From 3a213ab987080150387c16e45b993eaf1435dc30 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:39:51 -0500 Subject: [PATCH] refactor(chat): extract resource reconciliation and availability (#15834) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip manages AI agents and their work. > - Chat resources control which provider destinations can admit that work. > - Inventory updates and lifecycle callbacks must preserve company scope and operator choices. > - These rules share a large service with runtime and credential ownership. > - This PR extracts resource reconciliation and its availability transaction. > - Reviewers can inspect resource changes together while the service retains runtime control. ## Linked Issues or Issue Description Refs #15823 (merged). Slice 2 of 5 now targets `master`. Remaining order: #15834 → #15836 → #15844 → #15845. ## What Changed - Extract shared resource inventory, audited selection and availability settlement from the large service. - Put GitHub repository parsing, rename/transfer repair, webhook recovery and listing in `github/resources.ts`. - Put Telegram group migration in `telegram/resources.ts`, using the coordinator's existing transaction and timestamp. - Put Slack labels, Teams IDs and Photon participant parsing in their channel folders. - Keep lease assertions, delivery settlement and the resource upsert between Telegram migration steps in the shared coordinator. - The shared module is 598 lines; provider resource modules total 409 lines. Update the dated plan with this reassessment. ## Verification - On updated master, 15 existing resource integration cases and one Telegram migration case passed before this folder move. The same 16 cases passed after. Other cases were excluded by the filter. - Eight moved declarations and three transaction blocks match the prior implementation. The GitHub provider guard remains in the caller. - Server TypeScript, module-boundary and whitespace checks passed. Rebuilt plugin SDK types after rebasing onto current master. - Historical browser shard 8 timed out on inbox retry; its unchanged [rerun passed](https://github.com/paperclipai/paperclip/actions/runs/38134430238/job/114457529315). [Original failure](https://github.com/paperclipai/paperclip/actions/runs/38134430238/job/114455332214). - Tests use local disposable databases and fixture provider transports. No live third-party execution is claimed. - Fresh Greptile review is 5/5 on `e914f532ca66c429125492c1723df38afc6e13d7`, with a successful check and no open review threads. - Final-stack `pnpm -r typecheck` and `pnpm build` passed at `57ec5ba94aecd860471f9b14db46f99120c7c790`. - All CI checks passed on `e914f532ca66c429125492c1723df38afc6e13d7`. - The final full-local-suite outcome for this cumulative stack is recorded in #15845; do not infer that gate from the focused tests above. ## Risks - Resource identity and migrations depend on lock and write order. Provider modules use the original transaction; statement order and credential fencing remain unchanged. - Shared selection and availability still contain provider dispatch predicates. They coordinate common state transitions and should remain shared. - Full local tests and current-revision CI remain required for a green handoff. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and repository tools. The exact runtime model ID and context-window size are not exposed in this session. No separate agent was used. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../2026-10-10-chat-channels-refactor.md | 47 + server/src/services/chat-channels.ts | 931 +----------------- .../chat-channels/github/resources.ts | 278 ++++++ .../imessage-photon/resources.ts | 14 + .../microsoft-teams/resources.ts | 3 + .../chat-channels/resource-reconciliation.ts | 598 +++++++++++ .../services/chat-channels/slack/resources.ts | 10 + .../chat-channels/telegram/resources.ts | 104 ++ 8 files changed, 1065 insertions(+), 920 deletions(-) create mode 100644 server/src/services/chat-channels/github/resources.ts create mode 100644 server/src/services/chat-channels/imessage-photon/resources.ts create mode 100644 server/src/services/chat-channels/microsoft-teams/resources.ts create mode 100644 server/src/services/chat-channels/resource-reconciliation.ts create mode 100644 server/src/services/chat-channels/slack/resources.ts create mode 100644 server/src/services/chat-channels/telegram/resources.ts diff --git a/doc/plans/2026-10-10-chat-channels-refactor.md b/doc/plans/2026-10-10-chat-channels-refactor.md index 711c6e6b125..2b6765a72ea 100644 --- a/doc/plans/2026-10-10-chat-channels-refactor.md +++ b/doc/plans/2026-10-10-chat-channels-refactor.md @@ -125,3 +125,50 @@ this slice to `paperclipai/paperclip`; subsequent extractions are not part of this PR. Review and final verification: [PR #15823](https://github.com/paperclipai/paperclip/pull/15823). + +## Authorized stacked continuation + +The user requested at least five stacked PRs on 2026-10-10. Continue the four +remaining boundaries in order, with each branch based on its predecessor. Keep +merge and deployment outside this series. Each PR carries its own current-head +verification and review results; do not transfer a prior head's pass to a new one. + +### Slice 2: resource reconciliation and availability + +The lifecycle handler also owns credential replacement, delivery claims and +runtime shutdown. Keep those responsibilities in the service. Extract the full +non-GitHub availability transaction, inventory reconciliation, repository rename +handling, provider ordering, resource listing and audited selection together. +The factory takes the database, endpoint lookup, existing credential lease +function, generation reader and error text limit. It creates no worker or cache. + +- Source: 38,633 lines / 1,491,422 bytes → 37,720 lines / 1,454,762 bytes. +- Destination: 947 lines / 39,584 bytes in `resource-reconciliation.ts`. +- Mechanical comparison: 14 declarations and the complete availability + transaction are unchanged; all other function bodies remain unchanged. +- Baseline: all three complete chat CI shards passed on predecessor `cbba30a526`. +- Local baseline and after selections could not start PostgreSQL and skipped + the suite. They are not passes. Server typecheck and module boundaries pass. +- Require complete chat CI on this slice before starting the next extraction. + +### 2026-10-12 channel-folder reassessment: slice 2 + +PR #15823 was merged at the user's request. Rebase this slice onto the merged +master, then retain the remaining four PRs for review in dependency order. + +- GitHub payload parsing, repository coordinate repair, webhook recovery, + repository pagination and bulk-selection entry points live in + `chat-channels/github/resources.ts`. +- Telegram migration preparation and conversation migration live in + `telegram/resources.ts`. They receive the existing transaction and timestamp; + the shared coordinator still upserts the destination between those steps. +- Slack fallback labels, Teams conversation IDs and Photon participant parsing + live in each provider's `resources.ts`. +- Shared inventory replacement, availability settlement and audited selection + retain their transaction and credential-lease ownership. Small provider + dispatch predicates remain next to the shared operation they select. +- All eight moved declarations and three transaction blocks retain their logic. + The GitHub provider guard stays in the caller. No factory starts background work. +- Existing public-service tests: 15 resource cases and the Telegram migration + case passed before; the same 16 cases passed after. The name filter excludes + unrelated cases. No live third-party provider calls were made. diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index 9716073c91f..a0b5c93324c 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -1,3 +1,8 @@ +import { createChatResourceReconciliation } from "./chat-channels/resource-reconciliation.js"; +import { githubRepositoryInventoryItemFromPayload } from "./chat-channels/github/resources.js"; +import { baseTeamsConversationId } from "./chat-channels/microsoft-teams/resources.js"; +import { slackResourceLabelIsFallback } from "./chat-channels/slack/resources.js"; +import { telegramResourceLabelIsFallback } from "./chat-channels/telegram/resources.js"; import { MAX_INBOUND_TEXT, stableExternalPrincipalId, @@ -53,7 +58,7 @@ import type { AgentAvatarRequest } from "./agent-avatars.js"; import { slackChatRegistrationService, slackRegistrationProjection } from "./chat-slack-registration.js"; import { chatSlackRegistrations } from "@paperclipai/db"; import { SLACK_CHAT_BOT_SCOPES } from "@paperclipai/shared"; -import { authorizationService, canActorReadIssuePrivacy, canPublishIssueToChatAudience } from "./authorization.js"; +import { canActorReadIssuePrivacy, canPublishIssueToChatAudience } from "./authorization.js"; import { withSlackBoardLease } from "./slack-board-lease.js"; import { mirrorSlackBoardComment, slackBoardReplyBindings } from "./slack-board-messages.js"; import { authorizeSlackBoardPublication } from "./slack-board-authority.js"; @@ -64,7 +69,7 @@ import { slackAuthorizationRevision } from "./connectors/slack-revision.js"; import { slackPublicationAllowed } from "./connectors/slack-access.js"; import { instanceSettingsService } from "./instance-settings.js"; import { registerSlackTaskAuthority, slackRunOrigin } from "./connectors/slack-authority.js"; -import { captureRunIdentity } from "./run-identity.js"; + import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js"; function githubPolicyRecord(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; } import { githubChatManagementService } from "./chat-github-management.js"; @@ -102,7 +107,7 @@ import { validateNativeQuestionResponseInput } from "./native-runtime/native-que import type { AskUserQuestionsAnswer, AskUserQuestionsInteraction, IssueThreadInteraction } from "@paperclipai/shared"; import { PhotonCloudClient, PhotonError, photonFailure, photonSharedIdentity, photonSharedScope } from "./photon/cloud.js"; import { PhotonChatAdapter, photonThreadId, photonReplyReference } from "./photon/adapter.js"; -import { photonChannelConfigurationSchema, type PhotonChannelConfiguration } from "@paperclipai/shared"; +import { photonChannelConfigurationSchema } from "@paperclipai/shared"; import type { LiveEvent as PhotonEvent } from "@photon-ai/advanced-imessage"; import { defaultSlackAppConfiguration } from "@paperclipai/shared"; import { @@ -346,14 +351,7 @@ import { restoreGitHubAttachmentLimitOmissions, } from "./chat-github-attachments.js"; import { getExternalChannelBindingSummary } from "./chat-channel-binding.js"; -import { - discoverDedicatedGitHubAppInstallation, - getSlackBotChannel, - listGitHubInstallationRepositories, - listSlackBotChannels, - type ChatProviderInventoryResult, - type ChatProviderResourceInventoryItem, -} from "./chat-provider-inventory.js"; +import { discoverDedicatedGitHubAppInstallation, getSlackBotChannel, listGitHubInstallationRepositories, listSlackBotChannels, type ChatProviderInventoryResult } from "./chat-provider-inventory.js"; import { discordMarkdownRequiresAttachment, listDiscordBotChannels, @@ -1623,10 +1621,6 @@ function microsoftTeamsServiceUrl(raw: unknown): string | null { return typeof value === "string" && value ? value : null; } -function baseTeamsConversationId(value: string): string { - return value.replace(/;messageid=[^;]+/i, ""); -} - function teamsThreadRootMessageId(threadId: string): string | null { const conversationId = teamsConversationId(threadId); if (!conversationId) return null; @@ -1656,28 +1650,6 @@ function canonicalProviderResourceId( return thread.channelId; } -function slackResourceLabelIsFallback( - providerResourceId: string, - label: string, -): boolean { - const candidate = label.trim(); - return ( - candidate === providerResourceId || - candidate === `slack:${providerResourceId}` - ); -} - -function telegramResourceLabelIsFallback( - providerResourceId: string, - label: string, -): boolean { - const candidate = label.trim(); - return ( - candidate === providerResourceId || - candidate === `telegram:${providerResourceId}` - ); -} - function providerResourceLabelFromThread( provider: ChatProvider, thread: Pick, @@ -2053,67 +2025,6 @@ function isSupportedTelegramWebhookBaseUrl(value: string | null): boolean { } } -function githubRepositoryInventoryItemFromPayload( - payload: unknown, -): ChatProviderResourceInventoryItem | null { - if (!payload || typeof payload !== "object" || Array.isArray(payload)) - return null; - const repository = (payload as { repository?: unknown }).repository; - if ( - !repository || - typeof repository !== "object" || - Array.isArray(repository) - ) - return null; - const value = repository as { - id?: unknown; - full_name?: unknown; - html_url?: unknown; - name?: unknown; - owner?: { id?: unknown; login?: unknown }; - private?: unknown; - }; - const repositoryId = - typeof value.id === "number" && Number.isSafeInteger(value.id) - ? String(value.id) - : typeof value.id === "string" && /^\d+$/.test(value.id) - ? value.id - : null; - const owner = - typeof value.owner?.login === "string" ? value.owner.login.trim() : ""; - const name = typeof value.name === "string" ? value.name.trim() : ""; - const fullName = - typeof value.full_name === "string" && value.full_name.includes("/") - ? value.full_name.trim() - : owner && name - ? `${owner}/${name}` - : ""; - if (!repositoryId || !fullName) return null; - const ownerId = - typeof value.owner?.id === "number" && Number.isSafeInteger(value.owner.id) - ? String(value.owner.id) - : typeof value.owner?.id === "string" && /^\d+$/.test(value.owner.id) - ? value.owner.id - : undefined; - return { - providerResourceId: fullName.toLowerCase(), - parentProviderResourceId: ownerId, - type: "repository", - label: fullName, - providerUrl: - typeof value.html_url === "string" && value.html_url.length > 0 - ? value.html_url - : `https://github.com/${fullName}`, - metadata: { - providerRepositoryId: repositoryId, - fullName, - ...(owner ? { owner } : {}), - private: value.private === true, - source: "provider_webhook", - }, - }; -} - function providerSetupState( endpoint: Pick< EndpointRow, @@ -6283,6 +6194,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { } const withCredentialMutationLease = chatCredentialMutationLease(db, options); + const { reconcileGitHubWebhookRepository, reconcileProviderResourceRows, listResources, listGitHubRepositories, replaceResources, toggleAllGitHubRepositories, hasNewerProcessedProviderLifecycleEffect, applyProviderAvailability } = createChatResourceReconciliation(db, { endpointRecord, withCredentialMutationLease, runtimeGeneration, maxErrorText: MAX_ERROR_TEXT }); async function generateSetupSecret( endpointId: string, @@ -6563,273 +6475,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { ); } - function githubRepositoryStableId( - item: ChatProviderResourceInventoryItem, - ): string | null { - const value = item.metadata?.providerRepositoryId; - return typeof value === "string" && /^\d+$/.test(value) ? value : null; - } - - async function upsertProviderResourceRow( - tx: DbTransaction, - endpoint: EndpointRow, - item: ChatProviderResourceInventoryItem, - ) { - const stableGitHubId = - endpoint.provider === "github" ? githubRepositoryStableId(item) : null; - if (stableGitHubId) { - await tx.execute( - sql`select pg_advisory_xact_lock(hashtextextended(${`chat-github-repository:${endpoint.id}:${stableGitHubId}`}, 0))`, - ); - const stableResource = await tx - .select() - .from(chatEndpointResources) - .where( - and( - eq(chatEndpointResources.companyId, endpoint.companyId), - eq(chatEndpointResources.endpointId, endpoint.id), - eq(chatEndpointResources.type, "repository"), - sql`${chatEndpointResources.metadata}->>'providerRepositoryId' = ${stableGitHubId}`, - ), - ) - .for("update") - .then((rows) => rows[0] ?? null); - if ( - stableResource && - stableResource.providerResourceId !== item.providerResourceId - ) { - const coordinateResource = await tx - .select() - .from(chatEndpointResources) - .where( - and( - eq(chatEndpointResources.companyId, endpoint.companyId), - eq(chatEndpointResources.endpointId, endpoint.id), - eq(chatEndpointResources.type, "repository"), - eq( - chatEndpointResources.providerResourceId, - item.providerResourceId, - ), - ), - ) - .for("update") - .then((rows) => rows[0] ?? null); - if (coordinateResource && coordinateResource.id !== stableResource.id) { - const coordinateConversation = await tx - .select({ id: chatConversations.id }) - .from(chatConversations) - .where( - and( - eq(chatConversations.endpointId, endpoint.id), - eq(chatConversations.resourceId, coordinateResource.id), - ), - ) - .limit(1) - .then((rows) => rows[0] ?? null); - if (coordinateConversation) { - throw conflict( - "GitHub repository identity is already bound to two coordinates", - { code: "chat_github_repository_identity_conflict" }, - ); - } - await tx - .delete(chatEndpointResources) - .where(eq(chatEndpointResources.id, coordinateResource.id)); - } - - const oldRepository = stableResource.providerResourceId; - const oldThreadPrefix = `github:${oldRepository}`; - const newThreadPrefix = `github:${item.providerResourceId}`; - const oldProviderUrl = `https://github.com/${oldRepository}`; - const newProviderUrl = `https://github.com/${item.providerResourceId}`; - await tx - .update(chatEndpointResources) - .set({ - providerResourceId: item.providerResourceId, - parentProviderResourceId: item.parentProviderResourceId ?? null, - label: item.label, - providerUrl: item.providerUrl ?? null, - availability: "available", - enabled: - stableResource.enabled || coordinateResource?.enabled === true, - metadata: item.metadata ?? {}, - updatedAt: new Date(), - }) - .where(eq(chatEndpointResources.id, stableResource.id)); - await tx - .update(chatConversations) - .set({ - externalConversationId: sql`case - when lower(${chatConversations.externalConversationId}) = ${oldRepository} then ${item.providerResourceId} - when lower(${chatConversations.externalConversationId}) = ${oldThreadPrefix} then ${newThreadPrefix} - else ${chatConversations.externalConversationId} - end`, - externalThreadId: sql`case - when lower(${chatConversations.externalThreadId}) = ${oldThreadPrefix} then ${newThreadPrefix} - when lower(${chatConversations.externalThreadId}) like ${`${oldThreadPrefix}:%`} - then ${newThreadPrefix} || substring( - ${chatConversations.externalThreadId} - from char_length(${oldThreadPrefix}) + 1 - ) - else ${chatConversations.externalThreadId} - end`, - externalLabel: item.label, - providerUrl: sql`case - when lower(${chatConversations.providerUrl}) like ${`${oldProviderUrl}/%`} - then ${newProviderUrl} || substring( - ${chatConversations.providerUrl} - from char_length(${oldProviderUrl}) + 1 - ) - else ${chatConversations.providerUrl} - end`, - updatedAt: new Date(), - }) - .where( - and( - eq(chatConversations.companyId, endpoint.companyId), - eq(chatConversations.endpointId, endpoint.id), - eq(chatConversations.resourceId, stableResource.id), - ), - ); - return { id: stableResource.id }; - } - } - - const [resource] = await tx - .insert(chatEndpointResources) - .values({ - companyId: endpoint.companyId, - endpointId: endpoint.id, - type: item.type, - providerResourceId: item.providerResourceId, - parentProviderResourceId: item.parentProviderResourceId ?? null, - label: item.label, - providerUrl: item.providerUrl ?? null, - availability: "available", - // Slack inventory contains only channels the bot has joined. Apply the - // invitation default on insert; conflict updates preserve operator choices. - enabled: - endpoint.provider === "slack" && - item.type === "channel" && - item.metadata?.creator !== endpoint.botExternalId, - metadata: item.metadata ?? {}, - }) - .onConflictDoUpdate({ - target: [ - chatEndpointResources.endpointId, - chatEndpointResources.type, - chatEndpointResources.providerResourceId, - ], - set: { - parentProviderResourceId: item.parentProviderResourceId ?? null, - label: item.label, - providerUrl: item.providerUrl ?? null, - availability: "available", - metadata: item.metadata ?? {}, - updatedAt: new Date(), - }, - }) - .returning({ id: chatEndpointResources.id }); - return resource ?? null; - } - - async function reconcileGitHubWebhookRepository( - endpoint: EndpointRow, - payload: unknown, - credentialLease: CredentialMutationLeaseGuard, - ) { - const item = githubRepositoryInventoryItemFromPayload(payload); - if (!item) return; - await db.transaction(async (tx) => { - await credentialLease.assertOwned(tx); - const resource = await upsertProviderResourceRow(tx, endpoint, item); - if (!resource) return; - // A correctly signed repository callback is current provider proof. Keep - // Paperclip's enabled choice, and reopen only conversations previously - // quarantined for provider availability loss. - await tx - .update(chatConversations) - .set({ state: "active", updatedAt: new Date() }) - .where( - and( - eq(chatConversations.companyId, endpoint.companyId), - eq(chatConversations.endpointId, endpoint.id), - eq(chatConversations.resourceId, resource.id), - eq(chatConversations.state, "unavailable"), - ), - ); - await credentialLease.assertOwned(tx); - }); - } - - async function reconcileProviderResourceRows( - endpoint: EndpointRow, - inventory: ChatProviderInventoryResult, - credentialLease: CredentialMutationLeaseGuard, - ) { - const resourceType = - endpoint.provider === "github" ? "repository" : "channel"; - const discovered = new Set( - inventory.resources.map((resource) => resource.providerResourceId), - ); - const absentAvailability = - endpoint.provider === "github" ? "removed" : "unavailable"; - await db.transaction(async (tx) => { - await credentialLease.assertOwned(tx); - for (const item of inventory.resources) { - const resource = await upsertProviderResourceRow(tx, endpoint, item); - if (resource) { - // Resource recovery reopens only bindings that Paperclip marked - // unavailable. Completed historical tasks stay completed. - await tx - .update(chatConversations) - .set({ state: "active", updatedAt: new Date() }) - .where( - and( - eq(chatConversations.companyId, endpoint.companyId), - eq(chatConversations.endpointId, endpoint.id), - eq(chatConversations.resourceId, resource.id), - eq(chatConversations.state, "unavailable"), - ), - ); - } - } - - const existing = await tx - .select({ - id: chatEndpointResources.id, - providerResourceId: chatEndpointResources.providerResourceId, - }) - .from(chatEndpointResources) - .where( - and( - eq(chatEndpointResources.companyId, endpoint.companyId), - eq(chatEndpointResources.endpointId, endpoint.id), - eq(chatEndpointResources.type, resourceType), - ), - ); - for (const resource of existing) { - if (discovered.has(resource.providerResourceId)) continue; - await tx - .update(chatEndpointResources) - .set({ availability: absentAvailability, updatedAt: new Date() }) - .where(eq(chatEndpointResources.id, resource.id)); - await tx - .update(chatConversations) - .set({ state: "unavailable", updatedAt: new Date() }) - .where( - and( - eq(chatConversations.companyId, endpoint.companyId), - eq(chatConversations.endpointId, endpoint.id), - eq(chatConversations.resourceId, resource.id), - inArray(chatConversations.state, ["active", "waiting"]), - ), - ); - } - await credentialLease.assertOwned(tx); - }); - } - async function hydrateSlackResourceLabel( endpointId: string, providerResourceId: string, @@ -23812,309 +23457,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { effect.kind === "endpoint" && (effect.availability === "attention" || effect.availability === "revoked"); - await db.transaction(async (tx) => { - await credentialLease.assertOwned(tx); - const now = new Date(); - if (staleResourceEffect) { - // Persisted provider-native ordering wins over request arrival or - // lease acquisition order. The older callback remains auditable, - // but cannot roll a resource or conversation back. - await tx - .update(chatEndpoints) - .set({ lastEventAt: now, updatedAt: now }) - .where(eq(chatEndpoints.id, currentEndpoint.id)); - await notifyChatDeliveryWork(tx); - await tx - .update(chatDeliveries) - .set({ - state: "processed", - processedAt: now, - redactedError: null, - nextAttemptAt: null, - updatedAt: now, - }) - .where(eq(chatDeliveries.id, claimed.id)); - return; - } - if (effect.kind === "resource") { - const providerResourceId = - currentEndpoint.provider === "microsoft-teams" - ? baseTeamsConversationId(effect.providerResourceId) - : effect.providerResourceId; - const previousProviderResourceId = - currentEndpoint.provider === "telegram" - ? effect.previousProviderResourceId - : undefined; - const previousResource = previousProviderResourceId - ? await tx - .select() - .from(chatEndpointResources) - .where( - and( - eq(chatEndpointResources.endpointId, currentEndpoint.id), - eq(chatEndpointResources.type, "chat"), - eq( - chatEndpointResources.providerResourceId, - previousProviderResourceId, - ), - ), - ) - .for("update") - .then((rows) => rows[0] ?? null) - : null; - const migratedLabel = - previousResource && - telegramResourceLabelIsFallback(providerResourceId, effect.label) - ? previousResource.label - : effect.label; - const migratedEnabled = previousResource?.enabled === true; - if ( - previousResource && - previousProviderResourceId !== providerResourceId - ) { - await tx - .update(chatEndpointResources) - .set({ - availability: "unavailable", - enabled: false, - metadata: { - ...previousResource.metadata, - source: "chat_migration", - migratedTo: providerResourceId, - }, - updatedAt: now, - }) - .where(eq(chatEndpointResources.id, previousResource.id)); - } - const preserveProviderLabel = - (currentEndpoint.provider === "slack" && - slackResourceLabelIsFallback( - providerResourceId, - migratedLabel, - )) || - (currentEndpoint.provider === "telegram" && - telegramResourceLabelIsFallback( - providerResourceId, - migratedLabel, - )); - const [resource] = await tx - .insert(chatEndpointResources) - .values({ - companyId: currentEndpoint.companyId, - endpointId: currentEndpoint.id, - type: effect.resourceType, - providerResourceId, - parentProviderResourceId: - effect.parentProviderResourceId ?? null, - label: migratedLabel, - providerUrl: effect.providerUrl ?? null, - availability: effect.availability, - enabled: - migratedEnabled || - (currentEndpoint.provider === "slack" && - effect.resourceType === "channel" && - effect.availability === "available"), - metadata: effect.metadata ?? {}, - }) - .onConflictDoUpdate({ - target: [ - chatEndpointResources.endpointId, - chatEndpointResources.type, - chatEndpointResources.providerResourceId, - ], - set: { - parentProviderResourceId: - effect.parentProviderResourceId ?? null, - ...(preserveProviderLabel ? {} : { label: migratedLabel }), - providerUrl: effect.providerUrl ?? null, - availability: effect.availability, - ...(previousProviderResourceId - ? { - enabled: sql`${chatEndpointResources.enabled} or ${migratedEnabled}`, - } - : {}), - metadata: effect.metadata ?? {}, - updatedAt: now, - }, - }) - .returning({ id: chatEndpointResources.id }); - if ( - resource && - previousResource && - previousProviderResourceId !== providerResourceId - ) { - const previousThreadPrefix = `telegram:${previousProviderResourceId}`; - const migratedThreadPrefix = `telegram:${providerResourceId}`; - await tx - .update(chatConversations) - .set({ - resourceId: resource.id, - // Telegram SDK threads use the namespaced channel id. Keep - // the migrated row in that canonical shape so the first - // reply from the replacement supergroup finds this same - // task instead of creating a second conversation. - externalConversationId: migratedThreadPrefix, - externalThreadId: sql`case - when ${chatConversations.externalThreadId} = ${previousThreadPrefix} then ${migratedThreadPrefix} - when ${chatConversations.externalThreadId} like ${`${previousThreadPrefix}:%`} - then ${migratedThreadPrefix} || substring( - ${chatConversations.externalThreadId} - from char_length(${previousThreadPrefix}) + 1 - ) - else ${chatConversations.externalThreadId} - end`, - externalLabel: migratedLabel, - state: "active", - updatedAt: now, - }) - .where( - and( - eq(chatConversations.companyId, currentEndpoint.companyId), - eq(chatConversations.endpointId, currentEndpoint.id), - eq(chatConversations.resourceId, previousResource.id), - ), - ); - } - if (resource) { - await tx - .update(chatConversations) - .set({ - state: - effect.availability === "available" - ? "active" - : "unavailable", - updatedAt: now, - }) - .where( - and( - eq(chatConversations.companyId, currentEndpoint.companyId), - eq(chatConversations.endpointId, currentEndpoint.id), - eq(chatConversations.resourceId, resource.id), - effect.availability === "available" - ? eq(chatConversations.state, "unavailable") - : inArray(chatConversations.state, ["active", "waiting"]), - ), - ); - } - await tx - .update(chatEndpoints) - .set({ lastEventAt: now, updatedAt: now }) - .where(eq(chatEndpoints.id, currentEndpoint.id)); - } else { - const reason = redactSensitiveText(effect.reason).slice( - 0, - MAX_ERROR_TEXT, - ); - if (effect.availability === "available") { - if ( - currentEndpoint.status !== "paused" && - currentEndpoint.status !== "archived" - ) { - const status = - currentEndpoint.setup.step === "complete" - ? "active" - : currentEndpoint.status === "attention" - ? "verifying" - : currentEndpoint.status; - if (status !== currentEndpoint.status) await notifyChatEndpointWork(tx); - await tx - .update(chatEndpoints) - .set({ - status, - healthMessage: - status === "active" - ? "Connected" - : "Waiting for a test conversation", - lastError: null, - lastEventAt: now, - updatedAt: now, - }) - .where(eq(chatEndpoints.id, currentEndpoint.id)); - await tx - .update(toolConnections) - .set({ - status: "active", - enabled: true, - healthStatus: "healthy", - healthMessage: "Connected", - lastError: null, - healthCheckedAt: now, - updatedAt: now, - }) - .where(eq(toolConnections.id, currentEndpoint.connectionId)); - } - } else { - await tx - .update(chatEndpoints) - .set({ - status: effect.availability, - healthMessage: reason, - lastError: reason, - lastEventAt: now, - setup: { - ...currentEndpoint.setup, - runtimeGeneration: - runtimeGeneration(currentEndpoint.setup) + 1, - } as InternalSetupState, - updatedAt: now, - }) - .where(eq(chatEndpoints.id, currentEndpoint.id)); - await tx - .update(toolConnections) - .set({ - status: "disabled", - enabled: false, - healthStatus: - effect.availability === "revoked" ? "failed" : "degraded", - healthMessage: reason, - lastError: reason, - healthCheckedAt: now, - updatedAt: now, - }) - .where(eq(toolConnections.id, currentEndpoint.connectionId)); - await tx - .update(chatEndpointResources) - .set({ availability: "unavailable", updatedAt: now }) - .where( - and( - eq( - chatEndpointResources.companyId, - currentEndpoint.companyId, - ), - eq(chatEndpointResources.endpointId, currentEndpoint.id), - ), - ); - await tx - .update(chatConversations) - .set({ state: "unavailable", updatedAt: now }) - .where( - and( - eq(chatConversations.companyId, currentEndpoint.companyId), - eq(chatConversations.endpointId, currentEndpoint.id), - inArray(chatConversations.state, ["active", "waiting"]), - ), - ); - } - } - await notifyChatDeliveryWork(tx); - await tx - .update(chatDeliveries) - .set({ - state: "processed", - processedAt: now, - redactedError: null, - nextAttemptAt: null, - updatedAt: now, - }) - .where( - and( - eq(chatDeliveries.id, claimed.id), - eq(chatDeliveries.state, "processing"), - eq(chatDeliveries.attempts, candidate.attempts + 1), - ), - ); - await credentialLease.assertOwned(tx); - }); + await applyProviderAvailability({ currentEndpoint, effect, credentialLease, staleResourceEffect, claimed, candidate }); stopRuntimeAfterLifecycle = endpointEffectStopsRuntime; }); } catch (error) { @@ -24210,43 +23553,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { return { ...normalized, runtimeContext }; } - async function hasNewerProcessedProviderLifecycleEffect( - endpoint: EndpointRow, - effect: Extract, - ): Promise { - const sequence = effect.providerOrder?.sequence; - const occurredAt = effect.providerOrder?.occurredAt; - if (!sequence && !occurredAt) return false; - const providerResourceId = - endpoint.provider === "microsoft-teams" - ? baseTeamsConversationId(effect.providerResourceId) - : effect.providerResourceId; - const newerOrder = sequence - ? sql`( - ${chatDeliveries.normalizedEvent}#>>'{lifecycle,providerOrder,sequence}' ~ '^[0-9]+([.][0-9]+)?$' - and (${chatDeliveries.normalizedEvent}#>>'{lifecycle,providerOrder,sequence}')::numeric > cast(${sequence} as numeric) - )` - : sql`( - nullif(${chatDeliveries.normalizedEvent}#>>'{lifecycle,providerOrder,occurredAt}', '')::timestamptz > cast(${occurredAt!} as timestamptz) - )`; - const newer = await db - .select({ id: chatDeliveries.id }) - .from(chatDeliveries) - .where( - and( - eq(chatDeliveries.endpointId, endpoint.id), - eq(chatDeliveries.state, "processed"), - inArray(chatDeliveries.eventKind, ["installation", "uninstallation"]), - sql`${chatDeliveries.normalizedEvent}#>>'{lifecycle,kind}' = 'resource'`, - sql`${chatDeliveries.normalizedEvent}#>>'{lifecycle,provider}' = ${effect.provider}`, - sql`${chatDeliveries.normalizedEvent}#>>'{lifecycle,providerResourceId}' = ${providerResourceId}`, - newerOrder, - ), - ) - .limit(1); - return newer.length > 0; - } - async function applyProviderLifecycleEffects( endpoint: EndpointRow, effects: ChatProviderLifecycleEffect[], @@ -27715,221 +27021,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { return reactionCount + rows.length; } - async function listResources(endpointId: string) { - const resources = await db - .select() - .from(chatEndpointResources) - .where( - and( - eq(chatEndpointResources.endpointId, endpointId), - ne(chatEndpointResources.type, "direct_message"), - ), - ) - .orderBy(asc(chatEndpointResources.label)); - return resources.map((resource) => ({ - ...resource, - participants: - resource.providerResourceId.startsWith("imessage-photon:") && - Array.isArray(resource.metadata.participants) - ? resource.metadata.participants.flatMap((participant) => { - const address = - participant && typeof participant === "object" - ? (participant as Record).address - : null; - return typeof address === "string" ? [address] : []; - }) - : undefined, - })); - } - - async function listGitHubRepositories( - endpointId: string, - query: { limit: number; offset: number; search: string }, - ) { - const record = await endpointRecord(endpointId); - if (!record || record.endpoint.provider !== "github") throw notFound("GitHub bot not found"); - const scope = and( - eq(chatEndpointResources.companyId, record.endpoint.companyId), - eq(chatEndpointResources.endpointId, endpointId), - eq(chatEndpointResources.type, "repository"), - ); - // Literal, case-insensitive substring search (%, _ and backslashes are - // ordinary characters). Counts always describe the entire connection. - const search = query.search - ? sql`strpos(lower(${chatEndpointResources.label}), lower(${query.search})) > 0` - : undefined; - const [rows, [counts]] = await Promise.all([ - db.select().from(chatEndpointResources).where(and(scope, search)) - .orderBy(asc(chatEndpointResources.label), asc(chatEndpointResources.id)) - .offset(query.offset).limit(query.limit + 1), - db.select({ - totalCount: sql`count(*)::integer`, - enabledCount: sql`count(*) filter (where ${chatEndpointResources.enabled})::integer`, - availableCount: sql`count(*) filter (where ${chatEndpointResources.availability} = 'available')::integer`, - }).from(chatEndpointResources).where(scope), - ]); - return { - items: rows.slice(0, query.limit), - nextOffset: rows.length > query.limit ? query.offset + query.limit : null, - totalCount: counts!.totalCount, - enabledCount: counts!.enabledCount, - availableCount: counts!.availableCount, - }; - } - - async function replaceResources( - endpointId: string, - updates: Array<{ id: string; enabled: boolean }>, - actorUserId?: string | null, - options?: { initialGitHubImport?: boolean }, - ) { - await updateResourceSelection(endpointId, updates, actorUserId, options); - return listResources(endpointId); - } - - async function toggleAllGitHubRepositories(endpointId: string, enabled: boolean, actorUserId?: string | null) { - await updateResourceSelection(endpointId, [], actorUserId, { allGitHubRepositoriesEnabled: enabled }); - return { success: true as const }; - } - - async function updateResourceSelection( - endpointId: string, - updates: Array<{ id: string; enabled: boolean }>, - actorUserId?: string | null, - options?: { initialGitHubImport?: boolean; allGitHubRepositoriesEnabled?: boolean }, - ) { - const initial = await endpointRecord(endpointId); - if (!initial) throw notFound("Chat endpoint not found"); - const bulk = options?.allGitHubRepositoriesEnabled !== undefined; - if (bulk && initial.endpoint.provider !== "github") throw badRequest("Only GitHub repositories support toggle all"); - if (updates.length === 0 && initial.endpoint.provider !== "github") return; - if (initial.endpoint.provider === "imessage-photon" && initial.endpoint.botExternalId?.startsWith("photon-project:") && updates.some((entry) => entry.enabled)) - throw unprocessable("Photon shared channels support direct messages only; groups cannot be enabled"); - await withCredentialMutationLease( - initial.endpoint, - async (credentialLease) => { - const ids = updates.map((entry) => entry.id); - const publications: ActivityPublication[] = []; - await db.transaction(async (tx) => { - await credentialLease.assertOwned(tx); - const [endpoint] = await tx - .select({ - companyId: chatEndpoints.companyId, - connectionId: chatEndpoints.connectionId, - provider: chatEndpoints.provider, - setup: chatEndpoints.setup, - }) - .from(chatEndpoints) - .where( - and( - eq(chatEndpoints.id, endpointId), - eq(chatEndpoints.companyId, initial.endpoint.companyId), - ), - ) - .for("no key update"); - if (!endpoint) throw notFound("Chat endpoint not found"); - if (options?.initialGitHubImport && endpoint.provider === "github" && (endpoint.setup.github?.repositorySelectionSaved || !endpoint.setup.github?.initialRepositoryImportPending)) return; - const rows = await tx - .select({ - id: chatEndpointResources.id, - availability: chatEndpointResources.availability, - enabled: chatEndpointResources.enabled, - }) - .from(chatEndpointResources) - .where( - and( - eq(chatEndpointResources.companyId, endpoint.companyId), - eq(chatEndpointResources.endpointId, endpointId), - bulk - ? and( - eq(chatEndpointResources.type, "repository"), - options!.allGitHubRepositoriesEnabled - ? eq(chatEndpointResources.availability, "available") - : undefined, - ) - : inArray(chatEndpointResources.id, ids), - ), - ) - .orderBy(asc(chatEndpointResources.id)) - .for("no key update"); - if (!bulk && rows.length !== new Set(ids).size) - throw unprocessable("Every resource must belong to this endpoint"); - const selectedUpdates = bulk - ? rows.map((row) => ({ id: row.id, enabled: options!.allGitHubRepositoriesEnabled! })) - : updates; - const availabilityById = new Map( - rows.map((row) => [row.id, row.availability]), - ); - // Validate every submitted grant, including intermediate duplicate - // entries. Netting below describes the audit, not new authority. - const unavailable = selectedUpdates.find( - (entry) => - entry.enabled && availabilityById.get(entry.id) !== "available", - ); - if (unavailable) - throw conflict( - "A destination must still be available from the provider before it can be enabled", - { code: "chat_resource_unavailable", resourceId: unavailable.id }, - ); - const finalEnabled = new Map( - selectedUpdates.map((entry) => [entry.id, entry.enabled]), - ); - const changes = rows - .filter((row) => row.enabled !== finalEnabled.get(row.id)) - .map((row) => ({ - resourceId: row.id, - before: { enabled: row.enabled }, - after: { enabled: finalEnabled.get(row.id)! }, - })); - if (bulk) { - // One atomic database update, independent of pagination/search and - // serialized with refresh, reconnect, and individual row changes. - await tx.update(chatEndpointResources) - .set({ enabled: options!.allGitHubRepositoriesEnabled!, updatedAt: new Date() }) - .where(and( - eq(chatEndpointResources.companyId, endpoint.companyId), - eq(chatEndpointResources.endpointId, endpointId), - eq(chatEndpointResources.type, "repository"), - options!.allGitHubRepositoriesEnabled - ? eq(chatEndpointResources.availability, "available") - : undefined, - )); - } else for (const entry of selectedUpdates) - await tx - .update(chatEndpointResources) - .set({ enabled: entry.enabled, updatedAt: new Date() }) - .where( - and( - eq(chatEndpointResources.companyId, endpoint.companyId), - eq(chatEndpointResources.endpointId, endpointId), - eq(chatEndpointResources.id, entry.id), - ), - ); - if (endpoint.provider === "github") - await tx.update(chatEndpoints).set({ setup: sql`jsonb_set(${chatEndpoints.setup}, '{github}', coalesce(${chatEndpoints.setup}->'github', '{}'::jsonb) || '{"repositorySelectionSaved":true,"initialRepositoryImportPending":false}'::jsonb)`, updatedAt: new Date() }).where(eq(chatEndpoints.id, endpointId)); - if (changes.length > 0 || (endpoint.provider === "github" && !endpoint.setup.github?.repositorySelectionSaved)) - await logActivity( - tx as unknown as Db, - { - companyId: endpoint.companyId, - actorType: "user", - actorId: actorUserId ?? "board", - action: "chat_endpoint.resources_updated", - entityType: "tool_connection", - entityId: endpoint.connectionId, - details: { endpointId, provider: endpoint.provider, changes }, - }, - publications, - ); - await credentialLease.assertOwned(tx); - }); - // A committed reach change is factual even if the outer lease's last - // check subsequently fails. Never publish an uncommitted activity. - for (const publication of publications) publishActivity(publication); - }, - ); - } - async function listPrincipals(endpointId: string) { const record = await endpointRecord(endpointId); if (!record) throw notFound("Chat endpoint not found"); diff --git a/server/src/services/chat-channels/github/resources.ts b/server/src/services/chat-channels/github/resources.ts new file mode 100644 index 00000000000..5abe2384cd2 --- /dev/null +++ b/server/src/services/chat-channels/github/resources.ts @@ -0,0 +1,278 @@ +import { and, asc, eq, sql } from "drizzle-orm"; +import { chatConversations, chatEndpointResources, chatEndpoints, type Db } from "@paperclipai/db"; +import { conflict, notFound } from "../../../errors.js"; +import type { CredentialMutationLeaseGuard } from "../../chat-credential-mutation-lease.js"; +import type { ChatProviderResourceInventoryItem } from "../../chat-provider-inventory.js"; +type EndpointRow = typeof chatEndpoints.$inferSelect; +type DbTransaction = Parameters[0]>[0]; + +export function githubRepositoryInventoryItemFromPayload( + payload: unknown, +): ChatProviderResourceInventoryItem | null { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) + return null; + const repository = (payload as { repository?: unknown }).repository; + if ( + !repository || + typeof repository !== "object" || + Array.isArray(repository) + ) + return null; + const value = repository as { + id?: unknown; + full_name?: unknown; + html_url?: unknown; + name?: unknown; + owner?: { id?: unknown; login?: unknown }; + private?: unknown; + }; + const repositoryId = + typeof value.id === "number" && Number.isSafeInteger(value.id) + ? String(value.id) + : typeof value.id === "string" && /^\d+$/.test(value.id) + ? value.id + : null; + const owner = + typeof value.owner?.login === "string" ? value.owner.login.trim() : ""; + const name = typeof value.name === "string" ? value.name.trim() : ""; + const fullName = + typeof value.full_name === "string" && value.full_name.includes("/") + ? value.full_name.trim() + : owner && name + ? `${owner}/${name}` + : ""; + if (!repositoryId || !fullName) return null; + const ownerId = + typeof value.owner?.id === "number" && Number.isSafeInteger(value.owner.id) + ? String(value.owner.id) + : typeof value.owner?.id === "string" && /^\d+$/.test(value.owner.id) + ? value.owner.id + : undefined; + return { + providerResourceId: fullName.toLowerCase(), + parentProviderResourceId: ownerId, + type: "repository", + label: fullName, + providerUrl: + typeof value.html_url === "string" && value.html_url.length > 0 + ? value.html_url + : `https://github.com/${fullName}`, + metadata: { + providerRepositoryId: repositoryId, + fullName, + ...(owner ? { owner } : {}), + private: value.private === true, + source: "provider_webhook", + }, + }; +} + +function githubRepositoryStableId( + item: ChatProviderResourceInventoryItem, +): string | null { + const value = item.metadata?.providerRepositoryId; + return typeof value === "string" && /^\d+$/.test(value) ? value : null; +} + +export async function reconcileGitHubRepositoryCoordinates(tx: DbTransaction, endpoint: EndpointRow, item: ChatProviderResourceInventoryItem) { + const stableGitHubId = + githubRepositoryStableId(item); + if (stableGitHubId) { + await tx.execute( + sql`select pg_advisory_xact_lock(hashtextextended(${`chat-github-repository:${endpoint.id}:${stableGitHubId}`}, 0))`, + ); + const stableResource = await tx + .select() + .from(chatEndpointResources) + .where( + and( + eq(chatEndpointResources.companyId, endpoint.companyId), + eq(chatEndpointResources.endpointId, endpoint.id), + eq(chatEndpointResources.type, "repository"), + sql`${chatEndpointResources.metadata}->>'providerRepositoryId' = ${stableGitHubId}`, + ), + ) + .for("update") + .then((rows) => rows[0] ?? null); + if ( + stableResource && + stableResource.providerResourceId !== item.providerResourceId + ) { + const coordinateResource = await tx + .select() + .from(chatEndpointResources) + .where( + and( + eq(chatEndpointResources.companyId, endpoint.companyId), + eq(chatEndpointResources.endpointId, endpoint.id), + eq(chatEndpointResources.type, "repository"), + eq( + chatEndpointResources.providerResourceId, + item.providerResourceId, + ), + ), + ) + .for("update") + .then((rows) => rows[0] ?? null); + if (coordinateResource && coordinateResource.id !== stableResource.id) { + const coordinateConversation = await tx + .select({ id: chatConversations.id }) + .from(chatConversations) + .where( + and( + eq(chatConversations.endpointId, endpoint.id), + eq(chatConversations.resourceId, coordinateResource.id), + ), + ) + .limit(1) + .then((rows) => rows[0] ?? null); + if (coordinateConversation) { + throw conflict( + "GitHub repository identity is already bound to two coordinates", + { code: "chat_github_repository_identity_conflict" }, + ); + } + await tx + .delete(chatEndpointResources) + .where(eq(chatEndpointResources.id, coordinateResource.id)); + } + + const oldRepository = stableResource.providerResourceId; + const oldThreadPrefix = `github:${oldRepository}`; + const newThreadPrefix = `github:${item.providerResourceId}`; + const oldProviderUrl = `https://github.com/${oldRepository}`; + const newProviderUrl = `https://github.com/${item.providerResourceId}`; + await tx + .update(chatEndpointResources) + .set({ + providerResourceId: item.providerResourceId, + parentProviderResourceId: item.parentProviderResourceId ?? null, + label: item.label, + providerUrl: item.providerUrl ?? null, + availability: "available", + enabled: + stableResource.enabled || coordinateResource?.enabled === true, + metadata: item.metadata ?? {}, + updatedAt: new Date(), + }) + .where(eq(chatEndpointResources.id, stableResource.id)); + await tx + .update(chatConversations) + .set({ + externalConversationId: sql`case + when lower(${chatConversations.externalConversationId}) = ${oldRepository} then ${item.providerResourceId} + when lower(${chatConversations.externalConversationId}) = ${oldThreadPrefix} then ${newThreadPrefix} + else ${chatConversations.externalConversationId} + end`, + externalThreadId: sql`case + when lower(${chatConversations.externalThreadId}) = ${oldThreadPrefix} then ${newThreadPrefix} + when lower(${chatConversations.externalThreadId}) like ${`${oldThreadPrefix}:%`} + then ${newThreadPrefix} || substring( + ${chatConversations.externalThreadId} + from char_length(${oldThreadPrefix}) + 1 + ) + else ${chatConversations.externalThreadId} + end`, + externalLabel: item.label, + providerUrl: sql`case + when lower(${chatConversations.providerUrl}) like ${`${oldProviderUrl}/%`} + then ${newProviderUrl} || substring( + ${chatConversations.providerUrl} + from char_length(${oldProviderUrl}) + 1 + ) + else ${chatConversations.providerUrl} + end`, + updatedAt: new Date(), + }) + .where( + and( + eq(chatConversations.companyId, endpoint.companyId), + eq(chatConversations.endpointId, endpoint.id), + eq(chatConversations.resourceId, stableResource.id), + ), + ); + return { id: stableResource.id }; + } + } + + return null; +} + +type GitHubResourceOptions = { + endpointRecord: (endpointId: string) => Promise<{ endpoint: EndpointRow } | null>; + upsertProviderResourceRow: (tx: DbTransaction, endpoint: EndpointRow, item: ChatProviderResourceInventoryItem) => Promise<{ id: string } | null>; + updateResourceSelection: (endpointId: string, updates: Array<{ id: string; enabled: boolean }>, actorUserId?: string | null, options?: { allGitHubRepositoriesEnabled?: boolean }) => Promise; +}; + +export function createGitHubResources(db: Db, options: GitHubResourceOptions) { + const { endpointRecord, upsertProviderResourceRow, updateResourceSelection } = options; + async function reconcileGitHubWebhookRepository( + endpoint: EndpointRow, + payload: unknown, + credentialLease: CredentialMutationLeaseGuard, + ) { + const item = githubRepositoryInventoryItemFromPayload(payload); + if (!item) return; + await db.transaction(async (tx) => { + await credentialLease.assertOwned(tx); + const resource = await upsertProviderResourceRow(tx, endpoint, item); + if (!resource) return; + // A correctly signed repository callback is current provider proof. Keep + // Paperclip's enabled choice, and reopen only conversations previously + // quarantined for provider availability loss. + await tx + .update(chatConversations) + .set({ state: "active", updatedAt: new Date() }) + .where( + and( + eq(chatConversations.companyId, endpoint.companyId), + eq(chatConversations.endpointId, endpoint.id), + eq(chatConversations.resourceId, resource.id), + eq(chatConversations.state, "unavailable"), + ), + ); + await credentialLease.assertOwned(tx); + }); + } + + async function listGitHubRepositories( + endpointId: string, + query: { limit: number; offset: number; search: string }, + ) { + const record = await endpointRecord(endpointId); + if (!record || record.endpoint.provider !== "github") throw notFound("GitHub bot not found"); + const scope = and( + eq(chatEndpointResources.companyId, record.endpoint.companyId), + eq(chatEndpointResources.endpointId, endpointId), + eq(chatEndpointResources.type, "repository"), + ); + // Literal, case-insensitive substring search (%, _ and backslashes are + // ordinary characters). Counts always describe the entire connection. + const search = query.search + ? sql`strpos(lower(${chatEndpointResources.label}), lower(${query.search})) > 0` + : undefined; + const [rows, [counts]] = await Promise.all([ + db.select().from(chatEndpointResources).where(and(scope, search)) + .orderBy(asc(chatEndpointResources.label), asc(chatEndpointResources.id)) + .offset(query.offset).limit(query.limit + 1), + db.select({ + totalCount: sql`count(*)::integer`, + enabledCount: sql`count(*) filter (where ${chatEndpointResources.enabled})::integer`, + availableCount: sql`count(*) filter (where ${chatEndpointResources.availability} = 'available')::integer`, + }).from(chatEndpointResources).where(scope), + ]); + return { + items: rows.slice(0, query.limit), + nextOffset: rows.length > query.limit ? query.offset + query.limit : null, + totalCount: counts!.totalCount, + enabledCount: counts!.enabledCount, + availableCount: counts!.availableCount, + }; + } + + async function toggleAllGitHubRepositories(endpointId: string, enabled: boolean, actorUserId?: string | null) { + await updateResourceSelection(endpointId, [], actorUserId, { allGitHubRepositoriesEnabled: enabled }); + return { success: true as const }; + } + return { reconcileGitHubWebhookRepository, listGitHubRepositories, toggleAllGitHubRepositories }; +} diff --git a/server/src/services/chat-channels/imessage-photon/resources.ts b/server/src/services/chat-channels/imessage-photon/resources.ts new file mode 100644 index 00000000000..b86a15c3e42 --- /dev/null +++ b/server/src/services/chat-channels/imessage-photon/resources.ts @@ -0,0 +1,14 @@ +import type { chatEndpointResources } from "@paperclipai/db"; + +export function imessageResourceParticipants(resource: typeof chatEndpointResources.$inferSelect) { + return resource.providerResourceId.startsWith("imessage-photon:") && + Array.isArray(resource.metadata.participants) + ? resource.metadata.participants.flatMap((participant) => { + const address = + participant && typeof participant === "object" + ? (participant as Record).address + : null; + return typeof address === "string" ? [address] : []; + }) + : undefined; +} diff --git a/server/src/services/chat-channels/microsoft-teams/resources.ts b/server/src/services/chat-channels/microsoft-teams/resources.ts new file mode 100644 index 00000000000..675245b00e5 --- /dev/null +++ b/server/src/services/chat-channels/microsoft-teams/resources.ts @@ -0,0 +1,3 @@ +export function baseTeamsConversationId(value: string): string { + return value.replace(/;messageid=[^;]+/i, ""); +} diff --git a/server/src/services/chat-channels/resource-reconciliation.ts b/server/src/services/chat-channels/resource-reconciliation.ts new file mode 100644 index 00000000000..ac0d1069d73 --- /dev/null +++ b/server/src/services/chat-channels/resource-reconciliation.ts @@ -0,0 +1,598 @@ +import { imessageResourceParticipants } from "./imessage-photon/resources.js"; +import { createGitHubResources, reconcileGitHubRepositoryCoordinates } from "./github/resources.js"; +import { baseTeamsConversationId } from "./microsoft-teams/resources.js"; +import { slackResourceLabelIsFallback } from "./slack/resources.js"; +import { telegramResourceLabelIsFallback, prepareTelegramResourceMigration, migrateTelegramResourceConversations } from "./telegram/resources.js"; +import { and, asc, eq, inArray, ne, sql } from "drizzle-orm"; +import { chatConversations, chatDeliveries, chatEndpointResources, chatEndpoints, toolConnections, type Db } from "@paperclipai/db"; +import type { ChatEndpointSetupState } from "@paperclipai/shared"; +import { badRequest, conflict, notFound, unprocessable } from "../../errors.js"; +import { redactSensitiveText } from "../../redaction.js"; +import { notifyChatDeliveryWork, notifyChatEndpointWork } from "../chat-work-notifications.js"; +import { logActivity, publishActivity, type ActivityPublication } from "../activity-log.js"; +import type { CredentialMutationLeaseGuard, chatCredentialMutationLease } from "../chat-credential-mutation-lease.js"; +import type { ChatProviderInventoryResult, ChatProviderResourceInventoryItem } from "../chat-provider-inventory.js"; +import type { ChatProviderLifecycleEffect } from "../chat-provider-lifecycle.js"; + +type EndpointRow = typeof chatEndpoints.$inferSelect; +type DbTransaction = Parameters[0]>[0]; +type InternalSetupState = ChatEndpointSetupState & { runtimeGeneration?: number }; + +type ResourceReconciliationOptions = { + endpointRecord: (endpointId: string) => Promise<{ endpoint: EndpointRow } | null>; + withCredentialMutationLease: ReturnType; + runtimeGeneration: (setup: ChatEndpointSetupState) => number; + maxErrorText: number; +}; + +export function createChatResourceReconciliation(db: Db, options: ResourceReconciliationOptions) { + const { endpointRecord, withCredentialMutationLease, runtimeGeneration, maxErrorText: MAX_ERROR_TEXT } = options; + + async function upsertProviderResourceRow( + tx: DbTransaction, + endpoint: EndpointRow, + item: ChatProviderResourceInventoryItem, + ) { + if (endpoint.provider === "github") { + const renamed = await reconcileGitHubRepositoryCoordinates(tx, endpoint, item); + if (renamed) return renamed; + } + + const [resource] = await tx + .insert(chatEndpointResources) + .values({ + companyId: endpoint.companyId, + endpointId: endpoint.id, + type: item.type, + providerResourceId: item.providerResourceId, + parentProviderResourceId: item.parentProviderResourceId ?? null, + label: item.label, + providerUrl: item.providerUrl ?? null, + availability: "available", + // Slack inventory contains only channels the bot has joined. Apply the + // invitation default on insert; conflict updates preserve operator choices. + enabled: + endpoint.provider === "slack" && + item.type === "channel" && + item.metadata?.creator !== endpoint.botExternalId, + metadata: item.metadata ?? {}, + }) + .onConflictDoUpdate({ + target: [ + chatEndpointResources.endpointId, + chatEndpointResources.type, + chatEndpointResources.providerResourceId, + ], + set: { + parentProviderResourceId: item.parentProviderResourceId ?? null, + label: item.label, + providerUrl: item.providerUrl ?? null, + availability: "available", + metadata: item.metadata ?? {}, + updatedAt: new Date(), + }, + }) + .returning({ id: chatEndpointResources.id }); + return resource ?? null; + } + + async function reconcileProviderResourceRows( + endpoint: EndpointRow, + inventory: ChatProviderInventoryResult, + credentialLease: CredentialMutationLeaseGuard, + ) { + const resourceType = + endpoint.provider === "github" ? "repository" : "channel"; + const discovered = new Set( + inventory.resources.map((resource) => resource.providerResourceId), + ); + const absentAvailability = + endpoint.provider === "github" ? "removed" : "unavailable"; + await db.transaction(async (tx) => { + await credentialLease.assertOwned(tx); + for (const item of inventory.resources) { + const resource = await upsertProviderResourceRow(tx, endpoint, item); + if (resource) { + // Resource recovery reopens only bindings that Paperclip marked + // unavailable. Completed historical tasks stay completed. + await tx + .update(chatConversations) + .set({ state: "active", updatedAt: new Date() }) + .where( + and( + eq(chatConversations.companyId, endpoint.companyId), + eq(chatConversations.endpointId, endpoint.id), + eq(chatConversations.resourceId, resource.id), + eq(chatConversations.state, "unavailable"), + ), + ); + } + } + + const existing = await tx + .select({ + id: chatEndpointResources.id, + providerResourceId: chatEndpointResources.providerResourceId, + }) + .from(chatEndpointResources) + .where( + and( + eq(chatEndpointResources.companyId, endpoint.companyId), + eq(chatEndpointResources.endpointId, endpoint.id), + eq(chatEndpointResources.type, resourceType), + ), + ); + for (const resource of existing) { + if (discovered.has(resource.providerResourceId)) continue; + await tx + .update(chatEndpointResources) + .set({ availability: absentAvailability, updatedAt: new Date() }) + .where(eq(chatEndpointResources.id, resource.id)); + await tx + .update(chatConversations) + .set({ state: "unavailable", updatedAt: new Date() }) + .where( + and( + eq(chatConversations.companyId, endpoint.companyId), + eq(chatConversations.endpointId, endpoint.id), + eq(chatConversations.resourceId, resource.id), + inArray(chatConversations.state, ["active", "waiting"]), + ), + ); + } + await credentialLease.assertOwned(tx); + }); + } + + async function listResources(endpointId: string) { + const resources = await db + .select() + .from(chatEndpointResources) + .where( + and( + eq(chatEndpointResources.endpointId, endpointId), + ne(chatEndpointResources.type, "direct_message"), + ), + ) + .orderBy(asc(chatEndpointResources.label)); + return resources.map((resource) => ({ + ...resource, + participants: imessageResourceParticipants(resource), + })); + } + + async function replaceResources( + endpointId: string, + updates: Array<{ id: string; enabled: boolean }>, + actorUserId?: string | null, + options?: { initialGitHubImport?: boolean }, + ) { + await updateResourceSelection(endpointId, updates, actorUserId, options); + return listResources(endpointId); + } + + async function updateResourceSelection( + endpointId: string, + updates: Array<{ id: string; enabled: boolean }>, + actorUserId?: string | null, + options?: { initialGitHubImport?: boolean; allGitHubRepositoriesEnabled?: boolean }, + ) { + const initial = await endpointRecord(endpointId); + if (!initial) throw notFound("Chat endpoint not found"); + const bulk = options?.allGitHubRepositoriesEnabled !== undefined; + if (bulk && initial.endpoint.provider !== "github") throw badRequest("Only GitHub repositories support toggle all"); + if (updates.length === 0 && initial.endpoint.provider !== "github") return; + if (initial.endpoint.provider === "imessage-photon" && initial.endpoint.botExternalId?.startsWith("photon-project:") && updates.some((entry) => entry.enabled)) + throw unprocessable("Photon shared channels support direct messages only; groups cannot be enabled"); + await withCredentialMutationLease( + initial.endpoint, + async (credentialLease) => { + const ids = updates.map((entry) => entry.id); + const publications: ActivityPublication[] = []; + await db.transaction(async (tx) => { + await credentialLease.assertOwned(tx); + const [endpoint] = await tx + .select({ + companyId: chatEndpoints.companyId, + connectionId: chatEndpoints.connectionId, + provider: chatEndpoints.provider, + setup: chatEndpoints.setup, + }) + .from(chatEndpoints) + .where( + and( + eq(chatEndpoints.id, endpointId), + eq(chatEndpoints.companyId, initial.endpoint.companyId), + ), + ) + .for("no key update"); + if (!endpoint) throw notFound("Chat endpoint not found"); + if (options?.initialGitHubImport && endpoint.provider === "github" && (endpoint.setup.github?.repositorySelectionSaved || !endpoint.setup.github?.initialRepositoryImportPending)) return; + const rows = await tx + .select({ + id: chatEndpointResources.id, + availability: chatEndpointResources.availability, + enabled: chatEndpointResources.enabled, + }) + .from(chatEndpointResources) + .where( + and( + eq(chatEndpointResources.companyId, endpoint.companyId), + eq(chatEndpointResources.endpointId, endpointId), + bulk + ? and( + eq(chatEndpointResources.type, "repository"), + options!.allGitHubRepositoriesEnabled + ? eq(chatEndpointResources.availability, "available") + : undefined, + ) + : inArray(chatEndpointResources.id, ids), + ), + ) + .orderBy(asc(chatEndpointResources.id)) + .for("no key update"); + if (!bulk && rows.length !== new Set(ids).size) + throw unprocessable("Every resource must belong to this endpoint"); + const selectedUpdates = bulk + ? rows.map((row) => ({ id: row.id, enabled: options!.allGitHubRepositoriesEnabled! })) + : updates; + const availabilityById = new Map( + rows.map((row) => [row.id, row.availability]), + ); + // Validate every submitted grant, including intermediate duplicate + // entries. Netting below describes the audit, not new authority. + const unavailable = selectedUpdates.find( + (entry) => + entry.enabled && availabilityById.get(entry.id) !== "available", + ); + if (unavailable) + throw conflict( + "A destination must still be available from the provider before it can be enabled", + { code: "chat_resource_unavailable", resourceId: unavailable.id }, + ); + const finalEnabled = new Map( + selectedUpdates.map((entry) => [entry.id, entry.enabled]), + ); + const changes = rows + .filter((row) => row.enabled !== finalEnabled.get(row.id)) + .map((row) => ({ + resourceId: row.id, + before: { enabled: row.enabled }, + after: { enabled: finalEnabled.get(row.id)! }, + })); + if (bulk) { + // One atomic database update, independent of pagination/search and + // serialized with refresh, reconnect, and individual row changes. + await tx.update(chatEndpointResources) + .set({ enabled: options!.allGitHubRepositoriesEnabled!, updatedAt: new Date() }) + .where(and( + eq(chatEndpointResources.companyId, endpoint.companyId), + eq(chatEndpointResources.endpointId, endpointId), + eq(chatEndpointResources.type, "repository"), + options!.allGitHubRepositoriesEnabled + ? eq(chatEndpointResources.availability, "available") + : undefined, + )); + } else for (const entry of selectedUpdates) + await tx + .update(chatEndpointResources) + .set({ enabled: entry.enabled, updatedAt: new Date() }) + .where( + and( + eq(chatEndpointResources.companyId, endpoint.companyId), + eq(chatEndpointResources.endpointId, endpointId), + eq(chatEndpointResources.id, entry.id), + ), + ); + if (endpoint.provider === "github") + await tx.update(chatEndpoints).set({ setup: sql`jsonb_set(${chatEndpoints.setup}, '{github}', coalesce(${chatEndpoints.setup}->'github', '{}'::jsonb) || '{"repositorySelectionSaved":true,"initialRepositoryImportPending":false}'::jsonb)`, updatedAt: new Date() }).where(eq(chatEndpoints.id, endpointId)); + if (changes.length > 0 || (endpoint.provider === "github" && !endpoint.setup.github?.repositorySelectionSaved)) + await logActivity( + tx as unknown as Db, + { + companyId: endpoint.companyId, + actorType: "user", + actorId: actorUserId ?? "board", + action: "chat_endpoint.resources_updated", + entityType: "tool_connection", + entityId: endpoint.connectionId, + details: { endpointId, provider: endpoint.provider, changes }, + }, + publications, + ); + await credentialLease.assertOwned(tx); + }); + // A committed reach change is factual even if the outer lease's last + // check subsequently fails. Never publish an uncommitted activity. + for (const publication of publications) publishActivity(publication); + }, + ); + } + + async function hasNewerProcessedProviderLifecycleEffect( + endpoint: EndpointRow, + effect: Extract, + ): Promise { + const sequence = effect.providerOrder?.sequence; + const occurredAt = effect.providerOrder?.occurredAt; + if (!sequence && !occurredAt) return false; + const providerResourceId = + endpoint.provider === "microsoft-teams" + ? baseTeamsConversationId(effect.providerResourceId) + : effect.providerResourceId; + const newerOrder = sequence + ? sql`( + ${chatDeliveries.normalizedEvent}#>>'{lifecycle,providerOrder,sequence}' ~ '^[0-9]+([.][0-9]+)?$' + and (${chatDeliveries.normalizedEvent}#>>'{lifecycle,providerOrder,sequence}')::numeric > cast(${sequence} as numeric) + )` + : sql`( + nullif(${chatDeliveries.normalizedEvent}#>>'{lifecycle,providerOrder,occurredAt}', '')::timestamptz > cast(${occurredAt!} as timestamptz) + )`; + const newer = await db + .select({ id: chatDeliveries.id }) + .from(chatDeliveries) + .where( + and( + eq(chatDeliveries.endpointId, endpoint.id), + eq(chatDeliveries.state, "processed"), + inArray(chatDeliveries.eventKind, ["installation", "uninstallation"]), + sql`${chatDeliveries.normalizedEvent}#>>'{lifecycle,kind}' = 'resource'`, + sql`${chatDeliveries.normalizedEvent}#>>'{lifecycle,provider}' = ${effect.provider}`, + sql`${chatDeliveries.normalizedEvent}#>>'{lifecycle,providerResourceId}' = ${providerResourceId}`, + newerOrder, + ), + ) + .limit(1); + return newer.length > 0; + } + + async function applyProviderAvailability(input: { + currentEndpoint: EndpointRow; + effect: ChatProviderLifecycleEffect; + credentialLease: CredentialMutationLeaseGuard; + staleResourceEffect: boolean; + claimed: Pick; + candidate: Pick; + }): Promise { + const { currentEndpoint, effect, credentialLease, staleResourceEffect, claimed, candidate } = input; + await db.transaction(async (tx) => { + await credentialLease.assertOwned(tx); + const now = new Date(); + if (staleResourceEffect) { + // Persisted provider-native ordering wins over request arrival or + // lease acquisition order. The older callback remains auditable, + // but cannot roll a resource or conversation back. + await tx + .update(chatEndpoints) + .set({ lastEventAt: now, updatedAt: now }) + .where(eq(chatEndpoints.id, currentEndpoint.id)); + await notifyChatDeliveryWork(tx); + await tx + .update(chatDeliveries) + .set({ + state: "processed", + processedAt: now, + redactedError: null, + nextAttemptAt: null, + updatedAt: now, + }) + .where(eq(chatDeliveries.id, claimed.id)); + return; + } + if (effect.kind === "resource") { + const providerResourceId = + currentEndpoint.provider === "microsoft-teams" + ? baseTeamsConversationId(effect.providerResourceId) + : effect.providerResourceId; + const previousProviderResourceId = + currentEndpoint.provider === "telegram" + ? effect.previousProviderResourceId + : undefined; + const { previousResource, migratedLabel, migratedEnabled } = await prepareTelegramResourceMigration( + tx, currentEndpoint, effect, providerResourceId, previousProviderResourceId, now, + ); + const preserveProviderLabel = + (currentEndpoint.provider === "slack" && + slackResourceLabelIsFallback( + providerResourceId, + migratedLabel, + )) || + (currentEndpoint.provider === "telegram" && + telegramResourceLabelIsFallback( + providerResourceId, + migratedLabel, + )); + const [resource] = await tx + .insert(chatEndpointResources) + .values({ + companyId: currentEndpoint.companyId, + endpointId: currentEndpoint.id, + type: effect.resourceType, + providerResourceId, + parentProviderResourceId: + effect.parentProviderResourceId ?? null, + label: migratedLabel, + providerUrl: effect.providerUrl ?? null, + availability: effect.availability, + enabled: + migratedEnabled || + (currentEndpoint.provider === "slack" && + effect.resourceType === "channel" && + effect.availability === "available"), + metadata: effect.metadata ?? {}, + }) + .onConflictDoUpdate({ + target: [ + chatEndpointResources.endpointId, + chatEndpointResources.type, + chatEndpointResources.providerResourceId, + ], + set: { + parentProviderResourceId: + effect.parentProviderResourceId ?? null, + ...(preserveProviderLabel ? {} : { label: migratedLabel }), + providerUrl: effect.providerUrl ?? null, + availability: effect.availability, + ...(previousProviderResourceId + ? { + enabled: sql`${chatEndpointResources.enabled} or ${migratedEnabled}`, + } + : {}), + metadata: effect.metadata ?? {}, + updatedAt: now, + }, + }) + .returning({ id: chatEndpointResources.id }); + if ( + resource && + previousResource && + previousProviderResourceId !== providerResourceId + ) { + await migrateTelegramResourceConversations(tx, currentEndpoint, previousResource, resource, previousProviderResourceId, providerResourceId, migratedLabel, now); + } + if (resource) { + await tx + .update(chatConversations) + .set({ + state: + effect.availability === "available" + ? "active" + : "unavailable", + updatedAt: now, + }) + .where( + and( + eq(chatConversations.companyId, currentEndpoint.companyId), + eq(chatConversations.endpointId, currentEndpoint.id), + eq(chatConversations.resourceId, resource.id), + effect.availability === "available" + ? eq(chatConversations.state, "unavailable") + : inArray(chatConversations.state, ["active", "waiting"]), + ), + ); + } + await tx + .update(chatEndpoints) + .set({ lastEventAt: now, updatedAt: now }) + .where(eq(chatEndpoints.id, currentEndpoint.id)); + } else { + const reason = redactSensitiveText(effect.reason).slice( + 0, + MAX_ERROR_TEXT, + ); + if (effect.availability === "available") { + if ( + currentEndpoint.status !== "paused" && + currentEndpoint.status !== "archived" + ) { + const status = + currentEndpoint.setup.step === "complete" + ? "active" + : currentEndpoint.status === "attention" + ? "verifying" + : currentEndpoint.status; + if (status !== currentEndpoint.status) await notifyChatEndpointWork(tx); + await tx + .update(chatEndpoints) + .set({ + status, + healthMessage: + status === "active" + ? "Connected" + : "Waiting for a test conversation", + lastError: null, + lastEventAt: now, + updatedAt: now, + }) + .where(eq(chatEndpoints.id, currentEndpoint.id)); + await tx + .update(toolConnections) + .set({ + status: "active", + enabled: true, + healthStatus: "healthy", + healthMessage: "Connected", + lastError: null, + healthCheckedAt: now, + updatedAt: now, + }) + .where(eq(toolConnections.id, currentEndpoint.connectionId)); + } + } else { + await tx + .update(chatEndpoints) + .set({ + status: effect.availability, + healthMessage: reason, + lastError: reason, + lastEventAt: now, + setup: { + ...currentEndpoint.setup, + runtimeGeneration: + runtimeGeneration(currentEndpoint.setup) + 1, + } as InternalSetupState, + updatedAt: now, + }) + .where(eq(chatEndpoints.id, currentEndpoint.id)); + await tx + .update(toolConnections) + .set({ + status: "disabled", + enabled: false, + healthStatus: + effect.availability === "revoked" ? "failed" : "degraded", + healthMessage: reason, + lastError: reason, + healthCheckedAt: now, + updatedAt: now, + }) + .where(eq(toolConnections.id, currentEndpoint.connectionId)); + await tx + .update(chatEndpointResources) + .set({ availability: "unavailable", updatedAt: now }) + .where( + and( + eq( + chatEndpointResources.companyId, + currentEndpoint.companyId, + ), + eq(chatEndpointResources.endpointId, currentEndpoint.id), + ), + ); + await tx + .update(chatConversations) + .set({ state: "unavailable", updatedAt: now }) + .where( + and( + eq(chatConversations.companyId, currentEndpoint.companyId), + eq(chatConversations.endpointId, currentEndpoint.id), + inArray(chatConversations.state, ["active", "waiting"]), + ), + ); + } + } + await notifyChatDeliveryWork(tx); + await tx + .update(chatDeliveries) + .set({ + state: "processed", + processedAt: now, + redactedError: null, + nextAttemptAt: null, + updatedAt: now, + }) + .where( + and( + eq(chatDeliveries.id, claimed.id), + eq(chatDeliveries.state, "processing"), + eq(chatDeliveries.attempts, candidate.attempts + 1), + ), + ); + await credentialLease.assertOwned(tx); + }); + } + + const { reconcileGitHubWebhookRepository, listGitHubRepositories, toggleAllGitHubRepositories } = createGitHubResources(db, { endpointRecord, upsertProviderResourceRow, updateResourceSelection }); + + return { reconcileGitHubWebhookRepository, reconcileProviderResourceRows, listResources, listGitHubRepositories, replaceResources, toggleAllGitHubRepositories, hasNewerProcessedProviderLifecycleEffect, applyProviderAvailability }; +} diff --git a/server/src/services/chat-channels/slack/resources.ts b/server/src/services/chat-channels/slack/resources.ts new file mode 100644 index 00000000000..1d7773f750a --- /dev/null +++ b/server/src/services/chat-channels/slack/resources.ts @@ -0,0 +1,10 @@ +export function slackResourceLabelIsFallback( + providerResourceId: string, + label: string, +): boolean { + const candidate = label.trim(); + return ( + candidate === providerResourceId || + candidate === `slack:${providerResourceId}` + ); +} diff --git a/server/src/services/chat-channels/telegram/resources.ts b/server/src/services/chat-channels/telegram/resources.ts new file mode 100644 index 00000000000..17bc3b39b52 --- /dev/null +++ b/server/src/services/chat-channels/telegram/resources.ts @@ -0,0 +1,104 @@ +import { and, eq, sql } from "drizzle-orm"; +import { chatConversations, chatEndpointResources, chatEndpoints, type Db } from "@paperclipai/db"; +import type { ChatProviderLifecycleEffect } from "../../chat-provider-lifecycle.js"; +type DbTransaction = Parameters[0]>[0]; +type EndpointRow = typeof chatEndpoints.$inferSelect; + +export function telegramResourceLabelIsFallback( + providerResourceId: string, + label: string, +): boolean { + const candidate = label.trim(); + return ( + candidate === providerResourceId || + candidate === `telegram:${providerResourceId}` + ); +} + +export async function prepareTelegramResourceMigration( + tx: DbTransaction, currentEndpoint: EndpointRow, + effect: Extract, + providerResourceId: string, previousProviderResourceId: string | undefined, now: Date, +) { + const previousResource = previousProviderResourceId + ? await tx + .select() + .from(chatEndpointResources) + .where( + and( + eq(chatEndpointResources.endpointId, currentEndpoint.id), + eq(chatEndpointResources.type, "chat"), + eq( + chatEndpointResources.providerResourceId, + previousProviderResourceId, + ), + ), + ) + .for("update") + .then((rows) => rows[0] ?? null) + : null; + const migratedLabel = + previousResource && + telegramResourceLabelIsFallback(providerResourceId, effect.label) + ? previousResource.label + : effect.label; + const migratedEnabled = previousResource?.enabled === true; + if ( + previousResource && + previousProviderResourceId !== providerResourceId + ) { + await tx + .update(chatEndpointResources) + .set({ + availability: "unavailable", + enabled: false, + metadata: { + ...previousResource.metadata, + source: "chat_migration", + migratedTo: providerResourceId, + }, + updatedAt: now, + }) + .where(eq(chatEndpointResources.id, previousResource.id)); + } + return { previousResource, migratedLabel, migratedEnabled }; +} + +export async function migrateTelegramResourceConversations( + tx: DbTransaction, currentEndpoint: EndpointRow, + previousResource: typeof chatEndpointResources.$inferSelect, + resource: { id: string }, previousProviderResourceId: string | undefined, + providerResourceId: string, migratedLabel: string, now: Date, +) { + const previousThreadPrefix = `telegram:${previousProviderResourceId}`; + const migratedThreadPrefix = `telegram:${providerResourceId}`; + await tx + .update(chatConversations) + .set({ + resourceId: resource.id, + // Telegram SDK threads use the namespaced channel id. Keep + // the migrated row in that canonical shape so the first + // reply from the replacement supergroup finds this same + // task instead of creating a second conversation. + externalConversationId: migratedThreadPrefix, + externalThreadId: sql`case + when ${chatConversations.externalThreadId} = ${previousThreadPrefix} then ${migratedThreadPrefix} + when ${chatConversations.externalThreadId} like ${`${previousThreadPrefix}:%`} + then ${migratedThreadPrefix} || substring( + ${chatConversations.externalThreadId} + from char_length(${previousThreadPrefix}) + 1 + ) + else ${chatConversations.externalThreadId} + end`, + externalLabel: migratedLabel, + state: "active", + updatedAt: now, + }) + .where( + and( + eq(chatConversations.companyId, currentEndpoint.companyId), + eq(chatConversations.endpointId, currentEndpoint.id), + eq(chatConversations.resourceId, previousResource.id), + ), + ); +}