Skip to content

The open-source app everyone uses to manage agents at work

refactor(server): isolate publication recovery and Board sends (#16192)

Dottae43af9770a36
diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts
index e78333fbc7..099880c173 100644
--- a/server/src/services/chat-channels.ts
+++ b/server/src/services/chat-channels.ts
@@ -1,3 +1,6 @@
+import { createChatPublicationResolution } from "./chat-channels/publications/resolution.js";
+import { createChatPublicationRequests } from "./chat-channels/publications/requests.js";
+import { createTeamsBoardSendPreparation } from "./chat-channels/microsoft-teams/board-send-preparation.js";
import { createInboundWakeAuthority, inboundWakeScope } from "./chat-channels/inbound/wakeup-authorization.js";
import { createInboundWakeups } from "./chat-channels/inbound/wakeups.js";
import { createInboundWakeNotices } from "./chat-channels/inbound/wakeup-notices.js";
@@ -22,7 +25,7 @@ import type { LiveInboundMessage } from "./chat-channels/runtime-types.js";
import { DELIVERY_PROCESSING_STALE_MS, normalizedDeliveryThreadId, normalizedLifecycleEffect, deliveryReady, pendingInboundWakeupCondition, lifecycleRuntimeFence, normalizedLifecycleWithRuntimeFence } from "./chat-channels/inbound/delivery-ledger.js";
import { createChatMessageLifecycle } from "./chat-channels/inbound/lifecycle.js";
import { createChatConversationDeliveryQueue } from "./chat-channels/inbound/conversation-queue.js";
-import { publicationTransportOrderKey } from "./chat-channels/publications/order.js";
+
import { createChatPublicationTaskControl } from "./chat-channels/publications/task-control.js";
import { createChatPublicationTransport } from "./chat-channels/publications/transport.js";
import { createChatPublicationAuthorization } from "./chat-channels/publications/authorization.js";
@@ -58,9 +61,9 @@ import { slackTestMessageService } from "./connectors/slack/test-message.js";
import type { SlackSetupOptions } from "./connectors/slack/setup/registration.js";
import { createSetupProbes } from "./chat-channels/setup-probes.js";
-import { createChatActivity, publicationSummary } from "./chat-channels/activity.js";
-import { fileTransferProjectionColumns } from "./chat-channels/microsoft-teams/file-transfer-projection.js";
-import { createProviderEffects, providerEffectPayload, type ProviderEffectTarget } from "./chat-channels/provider-effects.js";
+import { createChatActivity } from "./chat-channels/activity.js";
+
+import { createProviderEffects, type ProviderEffectTarget } from "./chat-channels/provider-effects.js";
import { createTelegramCallbackNoticeAuthority } from "./chat-channels/telegram/callback-notices.js";
import { createOutboundAttachments } from "./chat-channels/outbound-attachments.js";
export { hydrateOutboundAttachment } from "./chat-channels/outbound-attachments.js";
@@ -105,7 +108,7 @@ import {
} from "./chat-channels/github/messages.js";
import { nextChatActionAt } from "./chat-action-work.js";
import type { ScheduledChatAction } from "./chat-work-notifications.js";
-import { notifyChatDeliveryWork, notifyChatPublicationWork, notifyChatActionWork } from "./chat-work-notifications.js";
+import { notifyChatDeliveryWork, notifyChatPublicationWork } from "./chat-work-notifications.js";
import { voiceSessionService } from "./voice/voice-session-service.js";
import { createSpekoProvider } from "./voice/speko-provider.js";
@@ -121,10 +124,6 @@ import { slackChatRegistrationService } from "./chat-slack-registration.js";
import { canPublishIssueToChatAudience } from "./authorization.js";
-import { mirrorSlackBoardComment } from "./slack-board-messages.js";
-
-import { assertSlackBoardWorkAllowed } from "./slack-board-resume.js";
-
import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js";
import { assertChatTaskCreationAccess, resolveChatExecutionDefaults } from "./chat-execution-defaults.js";
function githubPolicyRecord(value: unknown): Record<string, unknown> { return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}; }
@@ -169,16 +168,8 @@ import {
import type { Db } from "@paperclipai/db";
-import { agentWakeupRequests, agents, assets, chatActions, chatConversations, chatDeliveries, chatEndpointResources, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, chatMessageLinks, chatPublications, chatTeamsFileTransfers, companyMemberships, heartbeatRuns, issueComments, issueAttachments, issueThreadInteractions, issues, toolConnections } from "@paperclipai/db";
-import type {
- ChatEventKind,
- ChatEndpointSetupState,
- ChatProvider,
- ChatPublicationBatchStatus,
- ExternalChannelBindingSummary,
- SafeChatPublicationPayload,
- ToolCredentialSecretRef,
-} from "@paperclipai/shared";
+import { agentWakeupRequests, agents, chatActions, chatConversations, chatDeliveries, chatEndpointResources, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, chatMessageLinks, chatPublications, chatTeamsFileTransfers, companyMemberships, heartbeatRuns, issueComments, issueThreadInteractions, issues, toolConnections } from "@paperclipai/db";
+import type { ChatEventKind, ChatEndpointSetupState, ChatProvider, ExternalChannelBindingSummary, SafeChatPublicationPayload, ToolCredentialSecretRef } from "@paperclipai/shared";
import {
isUuidLike,
LOW_TRUST_REVIEW_PRESET,
@@ -190,21 +181,9 @@ import {
type TeamsFileTransferOptions,
} from "./chat-teams-file-transfers.js";
-import {
- projectChatFileTransfer,
- projectChatPublicationBatch,
-} from "./chat-publication-batches.js";
-
import { parseChatWebhookPublicBaseUrl } from "../chat-webhook-public-url.js";
-import {
- badRequest,
- HttpError,
- conflict,
- forbidden,
- notFound,
- unprocessable,
-} from "../errors.js";
+import { HttpError, conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { redactSensitiveText } from "../redaction.js";
import type { StorageService } from "../storage/types.js";
@@ -3690,766 +3669,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
}
}
- async function replayPublication(endpointId: string, publicationId: string) {
- const publication = await db
- .select()
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.id, publicationId),
- ),
- )
- .then((rows) => rows[0] ?? null);
- if (!publication) throw notFound("Publication not found");
- if (publication.state !== "failed") {
- throw conflict("Only a failed publication can be replayed", {
- code:
- publication.state === "delivery_unknown"
- ? "chat_publication_resolution_required"
- : "chat_publication_not_replayable",
- });
- }
- const interactionId = publication.payload.interactionId;
- const isInteractionPrompt =
- Boolean(interactionId) &&
- publication.idempotencyKey ===
- `interaction:${interactionId}:${publication.endpointId}`;
- if (isInteractionPrompt) {
- if (!publication.issueId || !interactionId) {
- throw conflict(
- "This interaction prompt is missing its authoritative task binding and cannot be replayed safely",
- { code: "chat_terminal_interaction_publication_not_replayable" },
- );
- }
- const interaction = await db
- .select({ status: issueThreadInteractions.status })
- .from(issueThreadInteractions)
- .where(
- and(
- eq(issueThreadInteractions.id, interactionId),
- eq(issueThreadInteractions.companyId, publication.companyId),
- eq(issueThreadInteractions.issueId, publication.issueId),
- ),
- )
- .then((rows) => rows[0] ?? null);
- if (!interaction || interaction.status !== "pending") {
- throw conflict(
- "A resolved interaction prompt cannot be replayed into the provider",
- { code: "chat_terminal_interaction_publication_not_replayable" },
- );
- }
- }
- const claimed = await db.transaction(async (tx) => {
- const current = await tx
- .select()
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.companyId, publication.companyId),
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.id, publication.id),
- ),
- )
- .for("update")
- .then((rows) => rows[0]);
- if (
- !current ||
- current.state !== publication.state ||
- current.attempts !== publication.attempts
- )
- return [];
- // Lock the publication before checking the transfer lane: issue() takes
- // the same lock, so a concurrent consent/upload cannot slip into replay.
- const transfer = await tx
- .select({ id: chatTeamsFileTransfers.id })
- .from(chatTeamsFileTransfers)
- .where(
- and(
- eq(chatTeamsFileTransfers.companyId, current.companyId),
- eq(chatTeamsFileTransfers.publicationId, current.id),
- ),
- )
- .then((rows) => rows[0]);
- if (transfer)
- throw conflict(
- "File delivery requires a stage-specific operator resolution",
- {
- code: "chat_file_transfer_resolution_required",
- },
- );
- await notifyChatPublicationWork(tx);
- return tx
- .update(chatPublications)
- .set({
- state: "retry",
- nextAttemptAt: new Date(),
- redactedError: null,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(chatPublications.id, publication.id),
- eq(chatPublications.state, publication.state),
- eq(chatPublications.attempts, publication.attempts),
- ),
- )
- .returning({ id: chatPublications.id });
- });
- if (!claimed.length) {
- throw conflict("This publication is already being replayed", {
- code: "chat_publication_replay_conflict",
- });
- }
- await processPendingPublications(1);
- }
-
- async function resolvePublication(
- endpointId: string,
- publicationId: string,
- action: "mark_delivered" | "retry_anyway" | "cancel",
- userId: string,
- fileTransfer?: {
- phase: import("@paperclipai/shared").ChatFileTransferPhase;
- version: number;
- },
- ) {
- const initialRecord = await endpointRecord(endpointId);
- if (!initialRecord) throw notFound("Chat endpoint not found");
- await withCredentialMutationLease(
- initialRecord.endpoint,
- (credentialLease) =>
- db.transaction(async (tx) => {
- await credentialLease.assertOwned(tx);
- const publication = await tx
- .select()
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.id, publicationId),
- ),
- )
- .for("update")
- .then((rows) => rows[0] ?? null);
- if (!publication) throw notFound("Publication not found");
- const transfer = await tx
- .select({
- id: chatTeamsFileTransfers.id,
- endpointId: chatTeamsFileTransfers.endpointId,
- conversationId: chatTeamsFileTransfers.conversationId,
- phase: chatTeamsFileTransfers.phase,
- version: chatTeamsFileTransfers.version,
- })
- .from(chatTeamsFileTransfers)
- .where(
- and(
- eq(chatTeamsFileTransfers.companyId, publication.companyId),
- eq(chatTeamsFileTransfers.publicationId, publication.id),
- ),
- )
- .then((rows) => rows[0]);
- if (transfer || fileTransfer) {
- const resolutionRequired = () =>
- conflict(
- "File delivery requires its current stage-specific resolution",
- { code: "chat_file_transfer_resolution_required" },
- );
- if (
- !transfer ||
- !fileTransfer ||
- publication.state !== "delivery_unknown" ||
- transfer.endpointId !== publication.endpointId ||
- transfer.conversationId !== publication.conversationId ||
- transfer.phase !== fileTransfer.phase ||
- transfer.version !== fileTransfer.version ||
- ![
- "consent_unknown",
- "upload_unknown",
- "file_info_unknown",
- "conflict",
- ].includes(transfer.phase)
- )
- throw resolutionRequired();
- let result;
- try {
- result = await teamsTransferProtocol({
- credentialLease,
- }).resolveInTransaction(tx, {
- companyId: publication.companyId,
- publicationId: publication.id,
- transferId: transfer.id,
- expectedVersion: fileTransfer.version,
- expectedPhase: fileTransfer.phase as
- | "consent_unknown"
- | "upload_unknown"
- | "file_info_unknown"
- | "conflict",
- action,
- });
- } catch (error) {
- if (
- error instanceof Error &&
- error.message ===
- "Teams file transfer authority or state changed"
- )
- throw resolutionRequired();
- throw error;
- }
- await logActivity(tx as unknown as Db, {
- companyId: publication.companyId,
- actorType: "user",
- actorId: userId,
- action: `chat.publication_${action}`,
- entityType: "chat_publication",
- entityId: publication.id,
- issueId: publication.issueId,
- details: {
- endpointId,
- conversationId: publication.conversationId,
- transferId: transfer.id,
- previousPhase: fileTransfer.phase,
- previousVersion: fileTransfer.version,
- nextPhase: result.phase,
- nextVersion: result.version,
- duplicateRiskAcknowledged: action === "retry_anyway",
- },
- });
- await credentialLease.assertOwned(tx);
- return;
- }
- if (publication.state !== "delivery_unknown") {
- throw conflict(
- "Only an unconfirmed publication needs an operator resolution",
- {
- code: "chat_publication_resolution_not_required",
- },
- );
- }
-
- const interactionId = publication.payload.interactionId;
- const isInteractionPrompt =
- Boolean(interactionId) &&
- publication.idempotencyKey ===
- `interaction:${interactionId}:${publication.endpointId}`;
- if (action === "retry_anyway" && isInteractionPrompt) {
- if (!publication.issueId || !interactionId) {
- throw conflict(
- "This interaction prompt is missing its authoritative task binding and cannot be retried safely",
- {
- code: "chat_terminal_interaction_publication_not_replayable",
- },
- );
- }
- const interaction = await tx
- .select({ status: issueThreadInteractions.status })
- .from(issueThreadInteractions)
- .where(
- and(
- eq(issueThreadInteractions.id, interactionId),
- eq(issueThreadInteractions.companyId, publication.companyId),
- eq(issueThreadInteractions.issueId, publication.issueId),
- ),
- )
- .then((rows) => rows[0] ?? null);
- if (!interaction || interaction.status !== "pending") {
- throw conflict(
- "A resolved interaction prompt cannot be retried with stale provider actions; mark it delivered or cancel it instead",
- {
- code: "chat_terminal_interaction_publication_not_replayable",
- },
- );
- }
- }
-
- if (
- initialRecord.endpoint.provider === "imessage-photon" &&
- action === "retry_anyway"
- ) {
- await tx
- .insert(chatActions)
- .values({
- companyId: publication.companyId,
- endpointId,
- conversationId: publication.conversationId,
- kind: "photon_publication_retry",
- providerActionId: `photon-retry:${publication.id}:${publication.attempts + 1}`,
- payload: {
- publicationId: publication.id,
- attempt: publication.attempts + 1,
- },
- result: { authorizedByUserId: userId },
- status: "processed",
- })
- .onConflictDoNothing();
- }
- const now = new Date();
- await notifyChatPublicationWork(tx);
- await tx
- .update(chatPublications)
- .set(
- action === "mark_delivered"
- ? {
- state: "published",
- publishedAt: now,
- nextAttemptAt: null,
- redactedError: null,
- updatedAt: now,
- }
- : action === "retry_anyway"
- ? {
- state: "retry",
- nextAttemptAt: now,
- redactedError: null,
- updatedAt: now,
- }
- : {
- state: "cancelled",
- nextAttemptAt: null,
- redactedError:
- "Cancelled by an operator after an unconfirmed provider delivery",
- updatedAt: now,
- },
- )
- .where(
- and(
- eq(chatPublications.id, publication.id),
- eq(chatPublications.state, "delivery_unknown"),
- ),
- );
- const receiptProviderActionId = `slack-file-receipt:${publication.id}:${publication.attempts}`;
- if (action === "mark_delivered") {
- await tx
- .update(chatActions)
- .set({
- result: sql`coalesce(${chatActions.result}, '{}'::jsonb) || jsonb_build_object(
- 'operatorConfirmedPublicationId', ${publication.id}::text,
- 'operatorConfirmedAttempt', ${publication.attempts}::integer,
- 'operatorConfirmedAt', ${now.toISOString()}::text
- )`,
- updatedAt: now,
- })
- .where(
- and(
- eq(chatActions.companyId, publication.companyId),
- eq(chatActions.endpointId, publication.endpointId),
- eq(chatActions.conversationId, publication.conversationId),
- eq(chatActions.kind, "slack_file_upload_receipt"),
- eq(chatActions.providerActionId, receiptProviderActionId),
- inArray(chatActions.status, [
- "received",
- "failed",
- "processing",
- ]),
- sql`(${chatActions.payload}->>'publicationId')::uuid = ${publication.id}`,
- sql`(${chatActions.payload}->>'publicationAttempt')::int = ${publication.attempts}`,
- ),
- );
- } else {
- await tx
- .update(chatActions)
- .set({
- status: "cancelled",
- result: {
- code:
- action === "retry_anyway"
- ? "slack_file_upload_receipt_retry_superseded"
- : "slack_file_upload_receipt_cancelled_by_operator",
- },
- updatedAt: now,
- })
- .where(
- and(
- eq(chatActions.companyId, publication.companyId),
- eq(chatActions.endpointId, publication.endpointId),
- eq(chatActions.conversationId, publication.conversationId),
- eq(chatActions.kind, "slack_file_upload_receipt"),
- eq(chatActions.providerActionId, receiptProviderActionId),
- inArray(chatActions.status, [
- "received",
- "failed",
- "processing",
- ]),
- sql`(${chatActions.payload}->>'publicationId')::uuid = ${publication.id}`,
- sql`(${chatActions.payload}->>'publicationAttempt')::int = ${publication.attempts}`,
- ),
- );
- }
- if (publication.idempotencyKey.startsWith("control:")) {
- await tx
- .update(chatActions)
- .set({
- status:
- action === "mark_delivered"
- ? "processed"
- : action === "retry_anyway"
- ? "issued"
- : "cancelled",
- result: {
- code:
- action === "mark_delivered"
- ? "task_control_marked_delivered_by_operator"
- : action === "retry_anyway"
- ? "task_control_retry_requested"
- : "task_control_cancelled_by_operator",
- },
- updatedAt: now,
- })
- .where(
- and(
- eq(chatActions.endpointId, publication.endpointId),
- eq(
- chatActions.providerActionId,
- `task-control-authorization:${publication.id}`,
- ),
- inArray(chatActions.status, [
- "issued",
- "processing",
- "delivery_unknown",
- ]),
- ),
- );
- }
- if (action === "mark_delivered") {
- await tx
- .update(chatEndpoints)
- .set({ lastPublicationAt: now, updatedAt: now })
- .where(eq(chatEndpoints.id, endpointId));
- await commitTaskControlCompletion(
- tx as unknown as Db,
- publication,
- now,
- );
- }
- await logActivity(tx as unknown as Db, {
- companyId: publication.companyId,
- actorType: "user",
- actorId: userId,
- action: `chat.publication_${action}`,
- entityType: "chat_publication",
- entityId: publication.id,
- issueId: publication.issueId,
- details: {
- endpointId,
- conversationId: publication.conversationId,
- previousState: "delivery_unknown",
- nextState:
- action === "mark_delivered"
- ? "published"
- : action === "retry_anyway"
- ? "retry"
- : "cancelled",
- duplicateRiskAccepted: action === "retry_anyway",
- },
- });
- await credentialLease.assertOwned(tx);
- }),
- );
- await processPendingPublications();
- }
-
- async function resolveProviderEffect(
- endpointId: string,
- actionId: string,
- resolution: "mark_delivered" | "retry_anyway" | "cancel",
- userId: string,
- ) {
- const initialRecord = await endpointRecord(endpointId);
- if (!initialRecord) throw notFound("Chat endpoint not found");
-
- if (resolution === "retry_anyway") {
- await withCredentialMutationLease(
- initialRecord.endpoint,
- async (credentialLease) => {
- const currentRecord = await endpointRecord(endpointId);
- if (
- !currentRecord ||
- !["verifying", "active"].includes(currentRecord.endpoint.status)
- ) {
- throw conflict(
- "The chat connection must be active before retrying this provider reply",
- {
- code: "chat_action_endpoint_unavailable",
- },
- );
- }
- await db.transaction(async (tx) => {
- await credentialLease.assertOwned(tx);
- const action = await tx
- .select()
- .from(chatActions)
- .where(
- and(
- eq(chatActions.endpointId, endpointId),
- eq(chatActions.id, actionId),
- eq(chatActions.kind, "provider_effect"),
- ),
- )
- .for("update")
- .then((rows) => rows[0] ?? null);
- if (!action) throw notFound("Provider action not found");
- if (action.status !== "delivery_unknown") {
- throw conflict(
- "Only an unconfirmed provider action needs operator resolution",
- {
- code: "chat_action_resolution_not_required",
- },
- );
- }
- const payload = providerEffectPayload(action.payload);
- if (!payload) {
- throw conflict("This provider action cannot be retried safely", {
- code: "chat_action_retry_context_missing",
- });
- }
- const delivery =
- payload.settleDelivery && action.deliveryId
- ? await tx
- .select({ state: chatDeliveries.state })
- .from(chatDeliveries)
- .where(
- and(
- eq(chatDeliveries.endpointId, endpointId),
- eq(chatDeliveries.id, action.deliveryId),
- ),
- )
- .for("update")
- .then((rows) => rows[0] ?? null)
- : null;
- if (payload.settleDelivery && action.deliveryId) {
- if (!delivery || delivery.state !== "failed") {
- throw conflict(
- "The provider action's delivery is no longer awaiting resolution",
- {
- code: "chat_action_delivery_resolution_conflict",
- },
- );
- }
- await notifyChatDeliveryWork(tx);
- await tx
- .update(chatDeliveries)
- .set({
- state: "processing",
- nextAttemptAt: null,
- redactedError: null,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(chatDeliveries.id, action.deliveryId),
- eq(chatDeliveries.state, "failed"),
- ),
- );
- }
- const now = new Date();
- await notifyChatActionWork(tx, "provider_effect");
- const [claimed] = await tx
- .update(chatActions)
- .set({
- status: "received",
- result: {
- ...(action.result ?? {}),
- code: "provider_effect_retry_requested",
- retryable: false,
- retryAt: null,
- },
- updatedAt: now,
- })
- .where(
- and(
- eq(chatActions.id, action.id),
- eq(chatActions.status, "delivery_unknown"),
- ),
- )
- .returning({ id: chatActions.id });
- if (!claimed) {
- throw conflict("This provider action is already being resolved", {
- code: "chat_action_resolution_conflict",
- });
- }
- await logActivity(tx as unknown as Db, {
- companyId: action.companyId,
- actorType: "user",
- actorId: userId,
- action: "chat.provider_effect_retry_anyway",
- entityType: "chat_action",
- entityId: action.id,
- details: {
- endpointId,
- conversationId: action.conversationId,
- deliveryId: action.deliveryId,
- previousState: "delivery_unknown",
- nextState: "received",
- duplicateRiskAccepted: true,
- },
- });
- });
- },
- );
- // The audited retry request is durable before the new transport claim.
- // Do not keep the endpoint mutation lease across provider I/O.
- await processProviderEffect(actionId);
- return;
- }
-
- await withCredentialMutationLease(
- initialRecord.endpoint,
- (credentialLease) =>
- db.transaction(async (tx) => {
- await credentialLease.assertOwned(tx);
- const action = await tx
- .select()
- .from(chatActions)
- .where(
- and(
- eq(chatActions.endpointId, endpointId),
- eq(chatActions.id, actionId),
- eq(chatActions.kind, "provider_effect"),
- ),
- )
- .for("update")
- .then((rows) => rows[0] ?? null);
- if (!action) throw notFound("Provider action not found");
- if (action.status !== "delivery_unknown") {
- throw conflict(
- "Only an unconfirmed provider action needs operator resolution",
- {
- code: "chat_action_resolution_not_required",
- },
- );
- }
- const payload = providerEffectPayload(action.payload);
- if (!payload) {
- throw conflict("This provider action cannot be resolved safely", {
- code: "chat_action_resolution_context_missing",
- });
- }
- const delivery =
- payload.settleDelivery && action.deliveryId
- ? await tx
- .select({ state: chatDeliveries.state })
- .from(chatDeliveries)
- .where(
- and(
- eq(chatDeliveries.endpointId, endpointId),
- eq(chatDeliveries.id, action.deliveryId),
- ),
- )
- .for("update")
- .then((rows) => rows[0] ?? null)
- : null;
- if (
- payload.settleDelivery &&
- action.deliveryId &&
- (!delivery || delivery.state !== "failed")
- ) {
- throw conflict(
- "The provider action's delivery is no longer awaiting resolution",
- {
- code: "chat_action_delivery_resolution_conflict",
- },
- );
- }
-
- const now = new Date();
- const nextStatus =
- resolution === "mark_delivered" ? "processed" : "cancelled";
- await notifyChatActionWork(tx, "provider_effect");
- const [resolved] = await tx
- .update(chatActions)
- .set({
- status: nextStatus,
- result: {
- ...(action.result ?? {}),
- code:
- resolution === "mark_delivered"
- ? "provider_effect_marked_delivered_by_operator"
- : "provider_effect_cancelled_by_operator",
- retryable: false,
- retryAt: null,
- },
- updatedAt: now,
- })
- .where(
- and(
- eq(chatActions.id, action.id),
- eq(chatActions.status, "delivery_unknown"),
- ),
- )
- .returning({ id: chatActions.id });
- if (!resolved) {
- throw conflict("This provider action is already being resolved", {
- code: "chat_action_resolution_conflict",
- });
- }
- if (payload.settleDelivery && action.deliveryId) {
- await notifyChatDeliveryWork(tx);
- await tx
- .update(chatDeliveries)
- .set(
- resolution === "mark_delivered"
- ? {
- state: "processed",
- processedAt: now,
- nextAttemptAt: null,
- redactedError: null,
- updatedAt: now,
- }
- : {
- state: "filtered",
- processedAt: now,
- nextAttemptAt: null,
- redactedError:
- "Cancelled by an operator after an unconfirmed provider reply",
- updatedAt: now,
- },
- )
- .where(
- and(
- eq(chatDeliveries.id, action.deliveryId),
- eq(chatDeliveries.state, "failed"),
- ),
- );
- }
- if (resolution === "mark_delivered") {
- if (payload.completeConversationId) {
- await tx
- .update(chatConversations)
- .set({ state: "completed", updatedAt: now })
- .where(
- and(
- eq(chatConversations.id, payload.completeConversationId),
- eq(chatConversations.endpointId, endpointId),
- ),
- );
- }
- await tx
- .update(chatEndpoints)
- .set({ lastEventAt: now, updatedAt: now })
- .where(eq(chatEndpoints.id, endpointId));
- }
- await logActivity(tx as unknown as Db, {
- companyId: action.companyId,
- actorType: "user",
- actorId: userId,
- action: `chat.provider_effect_${resolution}`,
- entityType: "chat_action",
- entityId: action.id,
- details: {
- endpointId,
- conversationId: action.conversationId,
- deliveryId: action.deliveryId,
- completeConversationId: payload.completeConversationId ?? null,
- previousState: "delivery_unknown",
- nextState: nextStatus,
- duplicateRiskAccepted: false,
- },
- });
- await credentialLease.assertOwned(tx);
- }),
- );
- }
-
async function resolveAction(
endpointId: string,
actionId: string,
@@ -4476,487 +3695,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
return resolveSlackTaskStart(endpointId, actionId, resolution, userId, initialRecord);
}
- async function getPublicationBatchStatus(
- endpointId: string,
- conversationId: string,
- publicationId: string,
- ): Promise<ChatPublicationBatchStatus> {
- if (![endpointId, conversationId, publicationId].every(isUuidLike)) {
- throw badRequest(
- "Valid endpoint, conversation, and publication IDs are required",
- );
- }
- const anchor = await db
- .select()
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.id, publicationId),
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.conversationId, conversationId),
- ),
- )
- .then((rows) => rows[0]);
- if (!anchor) throw notFound("Chat publication not found");
- // An explicit Board send and every durable text/file transport part share
- // its comment. Read all parts without Activity's history limit; never
- // advance the worker or replay a provider side effect from this GET.
- // Join public receipts and private transfer facts in one database snapshot.
- // A concurrent consent or file receipt cannot produce a mixed-time batch.
- const batch = await db
- .select({
- publication: chatPublications,
- transfer: fileTransferProjectionColumns,
- })
- .from(chatPublications)
- .leftJoin(
- chatTeamsFileTransfers,
- and(
- eq(chatTeamsFileTransfers.companyId, chatPublications.companyId),
- eq(chatTeamsFileTransfers.endpointId, chatPublications.endpointId),
- eq(
- chatTeamsFileTransfers.conversationId,
- chatPublications.conversationId,
- ),
- eq(chatTeamsFileTransfers.publicationId, chatPublications.id),
- ),
- )
- .where(
- and(
- eq(chatPublications.companyId, anchor.companyId),
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.conversationId, conversationId),
- anchor.commentId
- ? eq(chatPublications.commentId, anchor.commentId)
- : eq(chatPublications.id, anchor.id),
- ),
- )
- .orderBy(
- asc(chatPublications.createdAt),
- asc(publicationTransportOrderKey(chatPublications)),
- );
- if (!batch.length) throw notFound("Chat publication not found");
- return projectChatPublicationBatch(
- batch.map(({ publication, transfer }) =>
- projectChatFileTransfer(
- publicationSummary(publication),
- transfer?.publicationId ? transfer : undefined,
- ),
- ),
- );
- }
-
- async function publishComment(
- endpointId: string,
- conversationId: string,
- commentId: string,
- ) {
- const emailBoundary = await endpointRecord(endpointId);
- if (emailBoundary?.endpoint.publicationMode === "explicit")
- throw badRequest("Use an explicit email send action");
- const conversation = await db
- .select()
- .from(chatConversations)
- .where(
- and(
- eq(chatConversations.id, conversationId),
- eq(chatConversations.endpointId, endpointId),
- ),
- )
- .then((rows) => rows[0] ?? null);
- if (!conversation) throw notFound("Conversation not found");
- const comment = await db
- .select()
- .from(issueComments)
- .where(
- and(
- eq(issueComments.id, commentId),
- eq(issueComments.issueId, conversation.issueId),
- isNull(issueComments.deletedAt),
- ),
- )
- .then((rows) => rows[0] ?? null);
- if (!comment) throw notFound("Task comment not found");
- const [publication] = await db.transaction(async (tx) => {
- await notifyChatPublicationWork(tx);
- return tx
- .insert(chatPublications)
- .values({
- companyId: conversation.companyId,
- endpointId,
- conversationId,
- issueId: conversation.issueId,
- commentId,
- idempotencyKey: `explicit:${commentId}:${endpointId}`,
- payload: projectSafeChatPublication({
- classification: "external",
- source: "explicit_board_send",
- text: comment.body,
- }),
- state: "pending",
- })
- .onConflictDoNothing()
- .returning();
- });
- await processPendingPublications();
- const batch = await db
- .select()
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.companyId, conversation.companyId),
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.conversationId, conversationId),
- eq(chatPublications.commentId, commentId),
- ),
- )
- .orderBy(
- asc(chatPublications.createdAt),
- asc(publicationTransportOrderKey(chatPublications)),
- );
- return (
- batch.find((candidate) => candidate.state !== "published") ??
- batch.at(-1) ??
- publication
- );
- }
-
- async function publishBoardMessage(
- endpointId: string,
- conversationId: string,
- body: string,
- clientIdempotencyKey: string,
- userId: string,
- attachmentIds: string[] = [],
- ) {
- const emailBoundary = await endpointRecord(endpointId);
- if (emailBoundary?.endpoint.publicationMode === "explicit")
- throw badRequest("Use an explicit email send action");
- // Browser request IDs are only unique within the conversation that issued
- // them. Include that durable task boundary so a retried key from another
- // conversation can neither suppress its send nor return the first task's
- // publication.
- const idempotencyKey = `explicit-board:${endpointId}:${conversationId}:${clientIdempotencyKey}`;
- const rejectionActionId = `board-send-rejected:${conversationId}:${clientIdempotencyKey}`;
- const rejectionCode = "chat_board_send_attachments_already_bound";
- const rejectionDetails = (ids: string[]) => ({
- code: rejectionCode,
- endpointId,
- conversationId,
- idempotencyKey: clientIdempotencyKey,
- attachmentIds: ids,
- });
- const validRejectedIds = (value: unknown): value is string[] =>
- Array.isArray(value) &&
- value.length > 0 &&
- value.length <= 20 &&
- value.every((id) => typeof id === "string" && isUuidLike(id)) &&
- new Set(value).size === value.length;
- if (attachmentIds.length > 0) {
- const record = await endpointRecord(endpointId);
- if (
- record?.endpoint.provider === "microsoft-teams" &&
- record.endpoint.status === "active"
- ) {
- const [existing] = await db
- .select({ id: chatPublications.id })
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.companyId, record.endpoint.companyId),
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.conversationId, conversationId),
- eq(chatPublications.idempotencyKey, idempotencyKey),
- ),
- )
- .limit(1);
- // A cold service must not permanently choose the task-link fallback
- // merely because runtime reconciliation has not run yet. Initialize
- // outside all Board/source locks, then recheck the full scope below.
- // A repeated send identity needs only its existing durable receipt.
- const [rejected] = existing
- ? []
- : await db
- .select({ id: chatActions.id })
- .from(chatActions)
- .where(
- and(
- eq(chatActions.companyId, record.endpoint.companyId),
- eq(chatActions.endpointId, endpointId),
- eq(chatActions.providerActionId, rejectionActionId),
- ),
- )
- .limit(1);
- if (!existing && !rejected) await runtimeFor(record.endpoint);
- }
- }
- const publication = await db.transaction(async (tx) => {
- const conversation = await tx
- .select()
- .from(chatConversations)
- .where(
- and(
- eq(chatConversations.id, conversationId),
- eq(chatConversations.endpointId, endpointId),
- ),
- )
- .for("update")
- .then((rows) => rows[0] ?? null);
- if (!conversation) throw notFound("Conversation not found");
-
- const existing = await tx
- .select()
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.companyId, conversation.companyId),
- eq(chatPublications.idempotencyKey, idempotencyKey),
- ),
- )
- .then((rows) => rows[0] ?? null);
- if (existing) {
- const batch = await tx
- .select()
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.conversationId, conversationId),
- eq(chatPublications.commentId, existing.commentId!),
- ),
- )
- .orderBy(
- asc(chatPublications.createdAt),
- asc(publicationTransportOrderKey(chatPublications)),
- );
- return (
- batch.find((candidate) => candidate.state !== "published") ??
- batch.at(-1) ??
- existing
- );
- }
-
- const [rejected] = await tx
- .select()
- .from(chatActions)
- .where(
- and(
- eq(chatActions.companyId, conversation.companyId),
- eq(chatActions.endpointId, endpointId),
- eq(chatActions.providerActionId, rejectionActionId),
- ),
- )
- .limit(1);
- if (rejected) {
- const payload = rejected.payload;
- if (
- rejected.kind !== "board_send_rejected" ||
- rejected.status !== "processed" ||
- rejected.conversationId !== conversation.id ||
- payload.schemaVersion !== 1 ||
- payload.issueId !== conversation.issueId ||
- payload.idempotencyKey !== clientIdempotencyKey ||
- rejected.result?.code !== rejectionCode ||
- !validRejectedIds(payload.attachmentIds)
- ) {
- throw conflict("Board send rejection receipt is unavailable");
- }
- // The negative receipt is immutable, including when the caller retries
- // with different content or the previous owner comment was deleted.
- return { rejection: rejectionDetails(payload.attachmentIds) };
- }
-
- let comment: Awaited<
- ReturnType<ReturnType<typeof issueService>["addComment"]>
- >;
- try {
- // addComment inserts before binding attachments. Roll back that insert
- // in a savepoint, then commit only the exact terminal rejection below.
- comment = await tx.transaction((inner) =>
- issueService(inner as unknown as Db).addComment(
- conversation.issueId,
- body,
- { userId },
- { authorType: "user", attachmentIds },
- inner,
- ),
- );
- } catch (error) {
- const details =
- error instanceof HttpError &&
- error.status === 409 &&
- error.details &&
- typeof error.details === "object" &&
- !Array.isArray(error.details)
- ? (error.details as Record<string, unknown>)
- : null;
- if (
- details?.code !== "issue_comment_attachments_already_bound" ||
- details.companyId !== conversation.companyId ||
- details.issueId !== conversation.issueId ||
- !validRejectedIds(details.attachmentIds) ||
- !details.attachmentIds.every((id) => attachmentIds.includes(id))
- )
- throw error;
- const invalidIds = attachmentIds.filter((id) =>
- (details.attachmentIds as string[]).includes(id),
- );
- await tx.insert(chatActions).values({
- companyId: conversation.companyId,
- endpointId,
- conversationId,
- kind: "board_send_rejected",
- providerActionId: rejectionActionId,
- payload: {
- schemaVersion: 1,
- issueId: conversation.issueId,
- requestedByUserId: userId,
- idempotencyKey: clientIdempotencyKey,
- attachmentIds: invalidIds,
- },
- status: "processed",
- result: { code: rejectionCode },
- });
- return { rejection: rejectionDetails(invalidIds) };
- }
- if (emailBoundary?.endpoint.provider === "slack") {
- const [issue] = await tx.select().from(issues).where(and(eq(issues.id, conversation.issueId), eq(issues.companyId, conversation.companyId)));
- if (!issue) throw notFound("Task not found");
- await assertSlackBoardWorkAllowed(tx as unknown as Db, issue);
- await mirrorSlackBoardComment(tx, comment, { publicationKey: idempotencyKey, wakeAgent: true, endpointId, conversationId, attachmentIds });
- const [created] = await tx.select().from(chatPublications).where(and(eq(chatPublications.companyId, conversation.companyId), eq(chatPublications.idempotencyKey, idempotencyKey)));
- if (!created) throw conflict("This Slack task is no longer assigned to the connected agent");
- return created;
- }
- const attachedFiles = attachmentIds.length
- ? await tx
- .select({
- id: issueAttachments.id,
- originalFilename: assets.originalFilename,
- })
- .from(issueAttachments)
- .innerJoin(assets, eq(issueAttachments.assetId, assets.id))
- .where(
- and(
- eq(issueAttachments.companyId, conversation.companyId),
- eq(issueAttachments.issueId, conversation.issueId),
- eq(issueAttachments.issueCommentId, comment.id),
- inArray(issueAttachments.id, attachmentIds),
- ),
- )
- : [];
- const attachedFileById = new Map(
- attachedFiles.map((file) => [file.id, file]),
- );
- const orderedFiles = attachmentIds.map(
- (attachmentId) => attachedFileById.get(attachmentId)!,
- );
- const publicationCreatedAt = new Date();
- await notifyChatPublicationWork(tx);
- const [created] = await tx
- .insert(chatPublications)
- .values({
- companyId: conversation.companyId,
- endpointId,
- conversationId,
- issueId: conversation.issueId,
- commentId: comment.id,
- idempotencyKey,
- payload: projectSafeChatPublication({
- classification: "external",
- source: "explicit_board_send",
- text: comment.body,
- }),
- state: "pending",
- createdAt: publicationCreatedAt,
- updatedAt: publicationCreatedAt,
- })
- .returning();
- let terminalPublication = created;
- for (const [index, file] of orderedFiles.entries()) {
- const attachmentCreatedAt = new Date(
- publicationCreatedAt.getTime() + index + 1,
- );
- await notifyChatPublicationWork(tx);
- const [attachmentPublication] = await tx
- .insert(chatPublications)
- .values({
- companyId: conversation.companyId,
- endpointId,
- conversationId,
- issueId: conversation.issueId,
- commentId: comment.id,
- idempotencyKey: `${idempotencyKey}:attachment:${file.id}`,
- payload: projectSafeChatPublication({
- classification: "external",
- source: "explicit_board_send",
- text: `Shared ${file.originalFilename ?? "a file"}.`,
- attachmentIds: [file.id],
- }),
- state: "pending",
- createdAt: attachmentCreatedAt,
- updatedAt: attachmentCreatedAt,
- })
- .returning();
- await stageTeamsBoardFileIntent(
- tx,
- attachmentPublication,
- userId,
- conversation,
- );
- terminalPublication = attachmentPublication;
- }
- await logActivity(tx as unknown as Db, {
- companyId: conversation.companyId,
- actorType: "user",
- actorId: userId,
- action: "chat.publication_requested",
- entityType: "chat_publication",
- entityId: created.id,
- issueId: conversation.issueId,
- details: {
- endpointId,
- conversationId,
- commentId: comment.id,
- source: "explicit_board_send",
- },
- });
- return terminalPublication;
- });
- if ("rejection" in publication) {
- throw conflict(
- "Selected attachments are already bound to another comment",
- publication.rejection,
- );
- }
- if (emailBoundary?.endpoint.provider === "slack") await processPendingSlackBoardMessages();
- await processPendingPublications();
- const batch = publication.commentId
- ? await db
- .select()
- .from(chatPublications)
- .where(
- and(
- eq(chatPublications.endpointId, endpointId),
- eq(chatPublications.conversationId, conversationId),
- eq(chatPublications.commentId, publication.commentId),
- ),
- )
- .orderBy(
- asc(chatPublications.createdAt),
- asc(publicationTransportOrderKey(chatPublications)),
- )
- : [publication];
- // A multi-part send is successful only when every ordered publication is
- // published. Surface the first blocking row so the UI points operators at
- // the actual retry/duplicate-risk resolution instead of a later pending
- // attachment that cannot advance past it.
- return (
- batch.find((candidate) => candidate.state !== "published") ??
- batch.at(-1) ??
- publication
- );
- }
async function recordExactOutboundPublicationLink(...args: Parameters<ReturnType<typeof createChatPublicationTransport>["recordExactOutboundPublicationLink"]>) {
return publicationTransport.recordExactOutboundPublicationLink(...args);
}
@@ -5216,7 +3954,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
const { publicationEligibility } = publicationQueue;
const { unregisterSlackTaskAuthority } = createSlackTaskAuthorityRegistration(db, { authorizeInboundWakeup, resolveCredentials });
- return {
+ const { replayPublication, resolvePublication, resolveProviderEffect } = createChatPublicationResolution(db, { endpointRecord, withCredentialMutationLease, teamsTransferProtocol, commitTaskControlCompletion, processPendingPublications, processProviderEffect });
+ const { prepareTeamsBoardSend } = createTeamsBoardSendPreparation(db, { endpointRecord, runtimeFor });
+ const { getPublicationBatchStatus, publishComment, publishBoardMessage } = createChatPublicationRequests(db, { endpointRecord, stageTeamsBoardFileIntent, processPendingSlackBoardMessages, processPendingPublications, prepareTeamsBoardSend });
+return {
voice,
authorizeFastResponse,
slackRegistration,
diff --git a/server/src/services/chat-channels/imessage-photon/publication-retry.ts b/server/src/services/chat-channels/imessage-photon/publication-retry.ts
new file mode 100644
index 0000000000..9b36b2aa3f
--- /dev/null
+++ b/server/src/services/chat-channels/imessage-photon/publication-retry.ts
@@ -0,0 +1,21 @@
+import { chatActions } from "@paperclipai/db";
+import type { DbTransaction } from "../runtime-types.js";
+import type { chatPublications } from "@paperclipai/db";
+export async function recordPhotonPublicationRetry(tx: DbTransaction, endpointId: string, publication: typeof chatPublications.$inferSelect, userId: string): Promise<void> {
+ await tx
+ .insert(chatActions)
+ .values({
+ companyId: publication.companyId,
+ endpointId,
+ conversationId: publication.conversationId,
+ kind: "photon_publication_retry",
+ providerActionId: `photon-retry:${publication.id}:${publication.attempts + 1}`,
+ payload: {
+ publicationId: publication.id,
+ attempt: publication.attempts + 1,
+ },
+ result: { authorizedByUserId: userId },
+ status: "processed",
+ })
+ .onConflictDoNothing();
+}
diff --git a/server/src/services/chat-channels/microsoft-teams/board-send-preparation.ts b/server/src/services/chat-channels/microsoft-teams/board-send-preparation.ts
new file mode 100644
index 0000000000..d2d3431966
--- /dev/null
+++ b/server/src/services/chat-channels/microsoft-teams/board-send-preparation.ts
@@ -0,0 +1,48 @@
+import { and, eq } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { chatActions, chatPublications } from "@paperclipai/db";
+import type { EndpointRow, EndpointRecord } from "../runtime-types.js";
+import type { ChatEndpointRuntime } from "../../voice/voice-runtime.js";
+type BoardPreparationOptions = { endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>; runtimeFor: (endpoint: EndpointRow) => Promise<ChatEndpointRuntime> };
+export function createTeamsBoardSendPreparation(db: Db, options: BoardPreparationOptions) {
+ const { endpointRecord, runtimeFor } = options;
+ async function prepareTeamsBoardSend(endpointId: string, conversationId: string, idempotencyKey: string, rejectionActionId: string) {
+ const record = await endpointRecord(endpointId);
+ if (
+ record?.endpoint.provider === "microsoft-teams" &&
+ record.endpoint.status === "active"
+ ) {
+ const [existing] = await db
+ .select({ id: chatPublications.id })
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.companyId, record.endpoint.companyId),
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.conversationId, conversationId),
+ eq(chatPublications.idempotencyKey, idempotencyKey),
+ ),
+ )
+ .limit(1);
+ // A cold service must not permanently choose the task-link fallback
+ // merely because runtime reconciliation has not run yet. Initialize
+ // outside all Board/source locks, then recheck the full scope below.
+ // A repeated send identity needs only its existing durable receipt.
+ const [rejected] = existing
+ ? []
+ : await db
+ .select({ id: chatActions.id })
+ .from(chatActions)
+ .where(
+ and(
+ eq(chatActions.companyId, record.endpoint.companyId),
+ eq(chatActions.endpointId, endpointId),
+ eq(chatActions.providerActionId, rejectionActionId),
+ ),
+ )
+ .limit(1);
+ if (!existing && !rejected) await runtimeFor(record.endpoint);
+ }
+ }
+ return { prepareTeamsBoardSend };
+}
diff --git a/server/src/services/chat-channels/microsoft-teams/file-resolution.ts b/server/src/services/chat-channels/microsoft-teams/file-resolution.ts
new file mode 100644
index 0000000000..626ce928fc
--- /dev/null
+++ b/server/src/services/chat-channels/microsoft-teams/file-resolution.ts
@@ -0,0 +1,100 @@
+import type { chatPublications } from "@paperclipai/db";
+import { and, eq } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { chatTeamsFileTransfers } from "@paperclipai/db";
+import { conflict } from "../../../errors.js";
+import { logActivity } from "../../activity-log.js";
+import type { DbTransaction } from "../runtime-types.js";
+import type { CredentialMutationLeaseGuard } from "../../chat-credential-mutation-lease.js";
+import type { createTeamsFileDelivery } from "./file-delivery.js";
+import type { ChatFileTransferPhase } from "@paperclipai/shared";
+type FileResolutionInput = { endpointId: string; publication: typeof chatPublications.$inferSelect; action: "mark_delivered" | "retry_anyway" | "cancel"; userId: string; credentialLease: CredentialMutationLeaseGuard; fileTransfer?: { phase: ChatFileTransferPhase; version: number } };
+export async function resolveTeamsFilePublication(tx: DbTransaction, input: FileResolutionInput, teamsTransferProtocol: ReturnType<typeof createTeamsFileDelivery>["teamsTransferProtocol"]): Promise<boolean> {
+ const { endpointId, publication, action, userId, credentialLease, fileTransfer } = input;
+ const transfer = await tx
+ .select({
+ id: chatTeamsFileTransfers.id,
+ endpointId: chatTeamsFileTransfers.endpointId,
+ conversationId: chatTeamsFileTransfers.conversationId,
+ phase: chatTeamsFileTransfers.phase,
+ version: chatTeamsFileTransfers.version,
+ })
+ .from(chatTeamsFileTransfers)
+ .where(
+ and(
+ eq(chatTeamsFileTransfers.companyId, publication.companyId),
+ eq(chatTeamsFileTransfers.publicationId, publication.id),
+ ),
+ )
+ .then((rows) => rows[0]);
+ if (transfer || fileTransfer) {
+ const resolutionRequired = () =>
+ conflict(
+ "File delivery requires its current stage-specific resolution",
+ { code: "chat_file_transfer_resolution_required" },
+ );
+ if (
+ !transfer ||
+ !fileTransfer ||
+ publication.state !== "delivery_unknown" ||
+ transfer.endpointId !== publication.endpointId ||
+ transfer.conversationId !== publication.conversationId ||
+ transfer.phase !== fileTransfer.phase ||
+ transfer.version !== fileTransfer.version ||
+ ![
+ "consent_unknown",
+ "upload_unknown",
+ "file_info_unknown",
+ "conflict",
+ ].includes(transfer.phase)
+ )
+ throw resolutionRequired();
+ let result;
+ try {
+ result = await teamsTransferProtocol({
+ credentialLease,
+ }).resolveInTransaction(tx, {
+ companyId: publication.companyId,
+ publicationId: publication.id,
+ transferId: transfer.id,
+ expectedVersion: fileTransfer.version,
+ expectedPhase: fileTransfer.phase as
+ | "consent_unknown"
+ | "upload_unknown"
+ | "file_info_unknown"
+ | "conflict",
+ action,
+ });
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ error.message ===
+ "Teams file transfer authority or state changed"
+ )
+ throw resolutionRequired();
+ throw error;
+ }
+ await logActivity(tx as unknown as Db, {
+ companyId: publication.companyId,
+ actorType: "user",
+ actorId: userId,
+ action: `chat.publication_${action}`,
+ entityType: "chat_publication",
+ entityId: publication.id,
+ issueId: publication.issueId,
+ details: {
+ endpointId,
+ conversationId: publication.conversationId,
+ transferId: transfer.id,
+ previousPhase: fileTransfer.phase,
+ previousVersion: fileTransfer.version,
+ nextPhase: result.phase,
+ nextVersion: result.version,
+ duplicateRiskAcknowledged: action === "retry_anyway",
+ },
+ });
+ await credentialLease.assertOwned(tx);
+ return true;
+ }
+ return false;
+}
diff --git a/server/src/services/chat-channels/publications/requests.ts b/server/src/services/chat-channels/publications/requests.ts
new file mode 100644
index 0000000000..f97e3bc264
--- /dev/null
+++ b/server/src/services/chat-channels/publications/requests.ts
@@ -0,0 +1,467 @@
+import { publicationTransportOrderKey } from "./order.js";
+import { publicationSummary } from "../activity.js";
+import { fileTransferProjectionColumns } from "../microsoft-teams/file-transfer-projection.js";
+import { notifyChatPublicationWork } from "../../chat-work-notifications.js";
+import { and, asc, eq, inArray, isNull } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { assets, chatActions, chatConversations, chatPublications, chatTeamsFileTransfers, issueComments, issueAttachments } from "@paperclipai/db";
+import type { ChatPublicationBatchStatus } from "@paperclipai/shared";
+import { isUuidLike } from "@paperclipai/shared";
+import { projectChatFileTransfer, projectChatPublicationBatch } from "../../chat-publication-batches.js";
+import { badRequest, HttpError, conflict, notFound } from "../../../errors.js";
+import { logActivity } from "../../activity-log.js";
+import { issueService } from "../../issues.js";
+import { projectSafeChatPublication } from "../../chat-publication-projection.js";
+import type { EndpointRecord } from "../runtime-types.js";
+import type { createTeamsFileAuthority } from "../microsoft-teams/file-transfer-authority.js";
+import type { createChatPublicationQueue } from "./queue.js";
+import type { createSlackBoardMessages } from "../slack/board-messages.js";
+import type { createTeamsBoardSendPreparation } from "../microsoft-teams/board-send-preparation.js";
+import { stageSlackBoardSend } from "../slack/board-send.js";
+type RequestOptions = {
+ endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;
+ stageTeamsBoardFileIntent: ReturnType<typeof createTeamsFileAuthority>["stageTeamsBoardFileIntent"];
+ processPendingSlackBoardMessages: ReturnType<typeof createSlackBoardMessages>["processPendingSlackBoardMessages"];
+ processPendingPublications: ReturnType<typeof createChatPublicationQueue>["processPendingPublications"];
+ prepareTeamsBoardSend: ReturnType<typeof createTeamsBoardSendPreparation>["prepareTeamsBoardSend"];
+};
+export function createChatPublicationRequests(db: Db, options: RequestOptions) {
+ const { endpointRecord, stageTeamsBoardFileIntent, processPendingSlackBoardMessages, processPendingPublications, prepareTeamsBoardSend } = options;
+ async function getPublicationBatchStatus(
+ endpointId: string,
+ conversationId: string,
+ publicationId: string,
+ ): Promise<ChatPublicationBatchStatus> {
+ if (![endpointId, conversationId, publicationId].every(isUuidLike)) {
+ throw badRequest(
+ "Valid endpoint, conversation, and publication IDs are required",
+ );
+ }
+ const anchor = await db
+ .select()
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.id, publicationId),
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.conversationId, conversationId),
+ ),
+ )
+ .then((rows) => rows[0]);
+ if (!anchor) throw notFound("Chat publication not found");
+ // An explicit Board send and every durable text/file transport part share
+ // its comment. Read all parts without Activity's history limit; never
+ // advance the worker or replay a provider side effect from this GET.
+ // Join public receipts and private transfer facts in one database snapshot.
+ // A concurrent consent or file receipt cannot produce a mixed-time batch.
+ const batch = await db
+ .select({
+ publication: chatPublications,
+ transfer: fileTransferProjectionColumns,
+ })
+ .from(chatPublications)
+ .leftJoin(
+ chatTeamsFileTransfers,
+ and(
+ eq(chatTeamsFileTransfers.companyId, chatPublications.companyId),
+ eq(chatTeamsFileTransfers.endpointId, chatPublications.endpointId),
+ eq(
+ chatTeamsFileTransfers.conversationId,
+ chatPublications.conversationId,
+ ),
+ eq(chatTeamsFileTransfers.publicationId, chatPublications.id),
+ ),
+ )
+ .where(
+ and(
+ eq(chatPublications.companyId, anchor.companyId),
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.conversationId, conversationId),
+ anchor.commentId
+ ? eq(chatPublications.commentId, anchor.commentId)
+ : eq(chatPublications.id, anchor.id),
+ ),
+ )
+ .orderBy(
+ asc(chatPublications.createdAt),
+ asc(publicationTransportOrderKey(chatPublications)),
+ );
+ if (!batch.length) throw notFound("Chat publication not found");
+ return projectChatPublicationBatch(
+ batch.map(({ publication, transfer }) =>
+ projectChatFileTransfer(
+ publicationSummary(publication),
+ transfer?.publicationId ? transfer : undefined,
+ ),
+ ),
+ );
+ }
+
+ async function publishComment(
+ endpointId: string,
+ conversationId: string,
+ commentId: string,
+ ) {
+ const emailBoundary = await endpointRecord(endpointId);
+ if (emailBoundary?.endpoint.publicationMode === "explicit")
+ throw badRequest("Use an explicit email send action");
+ const conversation = await db
+ .select()
+ .from(chatConversations)
+ .where(
+ and(
+ eq(chatConversations.id, conversationId),
+ eq(chatConversations.endpointId, endpointId),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (!conversation) throw notFound("Conversation not found");
+ const comment = await db
+ .select()
+ .from(issueComments)
+ .where(
+ and(
+ eq(issueComments.id, commentId),
+ eq(issueComments.issueId, conversation.issueId),
+ isNull(issueComments.deletedAt),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (!comment) throw notFound("Task comment not found");
+ const [publication] = await db.transaction(async (tx) => {
+ await notifyChatPublicationWork(tx);
+ return tx
+ .insert(chatPublications)
+ .values({
+ companyId: conversation.companyId,
+ endpointId,
+ conversationId,
+ issueId: conversation.issueId,
+ commentId,
+ idempotencyKey: `explicit:${commentId}:${endpointId}`,
+ payload: projectSafeChatPublication({
+ classification: "external",
+ source: "explicit_board_send",
+ text: comment.body,
+ }),
+ state: "pending",
+ })
+ .onConflictDoNothing()
+ .returning();
+ });
+ await processPendingPublications();
+ const batch = await db
+ .select()
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.companyId, conversation.companyId),
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.conversationId, conversationId),
+ eq(chatPublications.commentId, commentId),
+ ),
+ )
+ .orderBy(
+ asc(chatPublications.createdAt),
+ asc(publicationTransportOrderKey(chatPublications)),
+ );
+ return (
+ batch.find((candidate) => candidate.state !== "published") ??
+ batch.at(-1) ??
+ publication
+ );
+ }
+
+ async function publishBoardMessage(
+ endpointId: string,
+ conversationId: string,
+ body: string,
+ clientIdempotencyKey: string,
+ userId: string,
+ attachmentIds: string[] = [],
+ ) {
+ const emailBoundary = await endpointRecord(endpointId);
+ if (emailBoundary?.endpoint.publicationMode === "explicit")
+ throw badRequest("Use an explicit email send action");
+ // Browser request IDs are only unique within the conversation that issued
+ // them. Include that durable task boundary so a retried key from another
+ // conversation can neither suppress its send nor return the first task's
+ // publication.
+ const idempotencyKey = `explicit-board:${endpointId}:${conversationId}:${clientIdempotencyKey}`;
+ const rejectionActionId = `board-send-rejected:${conversationId}:${clientIdempotencyKey}`;
+ const rejectionCode = "chat_board_send_attachments_already_bound";
+ const rejectionDetails = (ids: string[]) => ({
+ code: rejectionCode,
+ endpointId,
+ conversationId,
+ idempotencyKey: clientIdempotencyKey,
+ attachmentIds: ids,
+ });
+ const validRejectedIds = (value: unknown): value is string[] =>
+ Array.isArray(value) &&
+ value.length > 0 &&
+ value.length <= 20 &&
+ value.every((id) => typeof id === "string" && isUuidLike(id)) &&
+ new Set(value).size === value.length;
+ if (attachmentIds.length > 0) { await prepareTeamsBoardSend(endpointId, conversationId, idempotencyKey, rejectionActionId); }
+ const publication = await db.transaction(async (tx) => {
+ const conversation = await tx
+ .select()
+ .from(chatConversations)
+ .where(
+ and(
+ eq(chatConversations.id, conversationId),
+ eq(chatConversations.endpointId, endpointId),
+ ),
+ )
+ .for("update")
+ .then((rows) => rows[0] ?? null);
+ if (!conversation) throw notFound("Conversation not found");
+
+ const existing = await tx
+ .select()
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.companyId, conversation.companyId),
+ eq(chatPublications.idempotencyKey, idempotencyKey),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (existing) {
+ const batch = await tx
+ .select()
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.conversationId, conversationId),
+ eq(chatPublications.commentId, existing.commentId!),
+ ),
+ )
+ .orderBy(
+ asc(chatPublications.createdAt),
+ asc(publicationTransportOrderKey(chatPublications)),
+ );
+ return (
+ batch.find((candidate) => candidate.state !== "published") ??
+ batch.at(-1) ??
+ existing
+ );
+ }
+
+ const [rejected] = await tx
+ .select()
+ .from(chatActions)
+ .where(
+ and(
+ eq(chatActions.companyId, conversation.companyId),
+ eq(chatActions.endpointId, endpointId),
+ eq(chatActions.providerActionId, rejectionActionId),
+ ),
+ )
+ .limit(1);
+ if (rejected) {
+ const payload = rejected.payload;
+ if (
+ rejected.kind !== "board_send_rejected" ||
+ rejected.status !== "processed" ||
+ rejected.conversationId !== conversation.id ||
+ payload.schemaVersion !== 1 ||
+ payload.issueId !== conversation.issueId ||
+ payload.idempotencyKey !== clientIdempotencyKey ||
+ rejected.result?.code !== rejectionCode ||
+ !validRejectedIds(payload.attachmentIds)
+ ) {
+ throw conflict("Board send rejection receipt is unavailable");
+ }
+ // The negative receipt is immutable, including when the caller retries
+ // with different content or the previous owner comment was deleted.
+ return { rejection: rejectionDetails(payload.attachmentIds) };
+ }
+
+ let comment: Awaited<
+ ReturnType<ReturnType<typeof issueService>["addComment"]>
+ >;
+ try {
+ // addComment inserts before binding attachments. Roll back that insert
+ // in a savepoint, then commit only the exact terminal rejection below.
+ comment = await tx.transaction((inner) =>
+ issueService(inner as unknown as Db).addComment(
+ conversation.issueId,
+ body,
+ { userId },
+ { authorType: "user", attachmentIds },
+ inner,
+ ),
+ );
+ } catch (error) {
+ const details =
+ error instanceof HttpError &&
+ error.status === 409 &&
+ error.details &&
+ typeof error.details === "object" &&
+ !Array.isArray(error.details)
+ ? (error.details as Record<string, unknown>)
+ : null;
+ if (
+ details?.code !== "issue_comment_attachments_already_bound" ||
+ details.companyId !== conversation.companyId ||
+ details.issueId !== conversation.issueId ||
+ !validRejectedIds(details.attachmentIds) ||
+ !details.attachmentIds.every((id) => attachmentIds.includes(id))
+ )
+ throw error;
+ const invalidIds = attachmentIds.filter((id) =>
+ (details.attachmentIds as string[]).includes(id),
+ );
+ await tx.insert(chatActions).values({
+ companyId: conversation.companyId,
+ endpointId,
+ conversationId,
+ kind: "board_send_rejected",
+ providerActionId: rejectionActionId,
+ payload: {
+ schemaVersion: 1,
+ issueId: conversation.issueId,
+ requestedByUserId: userId,
+ idempotencyKey: clientIdempotencyKey,
+ attachmentIds: invalidIds,
+ },
+ status: "processed",
+ result: { code: rejectionCode },
+ });
+ return { rejection: rejectionDetails(invalidIds) };
+ }
+ if (emailBoundary?.endpoint.provider === "slack") { return stageSlackBoardSend(tx, { conversation, comment, idempotencyKey, endpointId, conversationId, attachmentIds }); }
+ const attachedFiles = attachmentIds.length
+ ? await tx
+ .select({
+ id: issueAttachments.id,
+ originalFilename: assets.originalFilename,
+ })
+ .from(issueAttachments)
+ .innerJoin(assets, eq(issueAttachments.assetId, assets.id))
+ .where(
+ and(
+ eq(issueAttachments.companyId, conversation.companyId),
+ eq(issueAttachments.issueId, conversation.issueId),
+ eq(issueAttachments.issueCommentId, comment.id),
+ inArray(issueAttachments.id, attachmentIds),
+ ),
+ )
+ : [];
+ const attachedFileById = new Map(
+ attachedFiles.map((file) => [file.id, file]),
+ );
+ const orderedFiles = attachmentIds.map(
+ (attachmentId) => attachedFileById.get(attachmentId)!,
+ );
+ const publicationCreatedAt = new Date();
+ await notifyChatPublicationWork(tx);
+ const [created] = await tx
+ .insert(chatPublications)
+ .values({
+ companyId: conversation.companyId,
+ endpointId,
+ conversationId,
+ issueId: conversation.issueId,
+ commentId: comment.id,
+ idempotencyKey,
+ payload: projectSafeChatPublication({
+ classification: "external",
+ source: "explicit_board_send",
+ text: comment.body,
+ }),
+ state: "pending",
+ createdAt: publicationCreatedAt,
+ updatedAt: publicationCreatedAt,
+ })
+ .returning();
+ let terminalPublication = created;
+ for (const [index, file] of orderedFiles.entries()) {
+ const attachmentCreatedAt = new Date(
+ publicationCreatedAt.getTime() + index + 1,
+ );
+ await notifyChatPublicationWork(tx);
+ const [attachmentPublication] = await tx
+ .insert(chatPublications)
+ .values({
+ companyId: conversation.companyId,
+ endpointId,
+ conversationId,
+ issueId: conversation.issueId,
+ commentId: comment.id,
+ idempotencyKey: `${idempotencyKey}:attachment:${file.id}`,
+ payload: projectSafeChatPublication({
+ classification: "external",
+ source: "explicit_board_send",
+ text: `Shared ${file.originalFilename ?? "a file"}.`,
+ attachmentIds: [file.id],
+ }),
+ state: "pending",
+ createdAt: attachmentCreatedAt,
+ updatedAt: attachmentCreatedAt,
+ })
+ .returning();
+ await stageTeamsBoardFileIntent(
+ tx,
+ attachmentPublication,
+ userId,
+ conversation,
+ );
+ terminalPublication = attachmentPublication;
+ }
+ await logActivity(tx as unknown as Db, {
+ companyId: conversation.companyId,
+ actorType: "user",
+ actorId: userId,
+ action: "chat.publication_requested",
+ entityType: "chat_publication",
+ entityId: created.id,
+ issueId: conversation.issueId,
+ details: {
+ endpointId,
+ conversationId,
+ commentId: comment.id,
+ source: "explicit_board_send",
+ },
+ });
+ return terminalPublication;
+ });
+ if ("rejection" in publication) {
+ throw conflict(
+ "Selected attachments are already bound to another comment",
+ publication.rejection,
+ );
+ }
+ if (emailBoundary?.endpoint.provider === "slack") await processPendingSlackBoardMessages();
+ await processPendingPublications();
+ const batch = publication.commentId
+ ? await db
+ .select()
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.conversationId, conversationId),
+ eq(chatPublications.commentId, publication.commentId),
+ ),
+ )
+ .orderBy(
+ asc(chatPublications.createdAt),
+ asc(publicationTransportOrderKey(chatPublications)),
+ )
+ : [publication];
+ // A multi-part send is successful only when every ordered publication is
+ // published. Surface the first blocking row so the UI points operators at
+ // the actual retry/duplicate-risk resolution instead of a later pending
+ // attachment that cannot advance past it.
+ return (
+ batch.find((candidate) => candidate.state !== "published") ??
+ batch.at(-1) ??
+ publication
+ );
+ }
+ return { getPublicationBatchStatus, publishComment, publishBoardMessage };
+}
diff --git a/server/src/services/chat-channels/publications/resolution.ts b/server/src/services/chat-channels/publications/resolution.ts
new file mode 100644
index 0000000000..a7841f225a
--- /dev/null
+++ b/server/src/services/chat-channels/publications/resolution.ts
@@ -0,0 +1,629 @@
+import { providerEffectPayload } from "../provider-effects.js";
+import { notifyChatDeliveryWork, notifyChatPublicationWork, notifyChatActionWork } from "../../chat-work-notifications.js";
+import { and, eq, inArray } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { chatActions, chatConversations, chatDeliveries, chatEndpoints, chatPublications, chatTeamsFileTransfers, issueThreadInteractions } from "@paperclipai/db";
+import { conflict, notFound } from "../../../errors.js";
+import { logActivity } from "../../activity-log.js";
+import type { EndpointRecord } from "../runtime-types.js";
+import type { chatCredentialMutationLease } from "../../chat-credential-mutation-lease.js";
+import type { createTeamsFileDelivery } from "../microsoft-teams/file-delivery.js";
+import type { createChatPublicationTaskControl } from "./task-control.js";
+import type { createChatPublicationQueue } from "./queue.js";
+import type { createProviderEffects } from "../provider-effects.js";
+import { resolveTeamsFilePublication } from "../microsoft-teams/file-resolution.js";
+import { recordPhotonPublicationRetry } from "../imessage-photon/publication-retry.js";
+import { resolveSlackFileReceipt } from "../slack/file-receipt-resolution.js";
+type ResolutionOptions = {
+ endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;
+ withCredentialMutationLease: ReturnType<typeof chatCredentialMutationLease>;
+ teamsTransferProtocol: ReturnType<typeof createTeamsFileDelivery>["teamsTransferProtocol"];
+ commitTaskControlCompletion: ReturnType<typeof createChatPublicationTaskControl>["commitTaskControlCompletion"];
+ processPendingPublications: ReturnType<typeof createChatPublicationQueue>["processPendingPublications"];
+ processProviderEffect: ReturnType<typeof createProviderEffects>["processProviderEffect"];
+};
+export function createChatPublicationResolution(db: Db, options: ResolutionOptions) {
+ const { endpointRecord, withCredentialMutationLease, teamsTransferProtocol, commitTaskControlCompletion, processPendingPublications, processProviderEffect } = options;
+ async function replayPublication(endpointId: string, publicationId: string) {
+ const publication = await db
+ .select()
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.id, publicationId),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (!publication) throw notFound("Publication not found");
+ if (publication.state !== "failed") {
+ throw conflict("Only a failed publication can be replayed", {
+ code:
+ publication.state === "delivery_unknown"
+ ? "chat_publication_resolution_required"
+ : "chat_publication_not_replayable",
+ });
+ }
+ const interactionId = publication.payload.interactionId;
+ const isInteractionPrompt =
+ Boolean(interactionId) &&
+ publication.idempotencyKey ===
+ `interaction:${interactionId}:${publication.endpointId}`;
+ if (isInteractionPrompt) {
+ if (!publication.issueId || !interactionId) {
+ throw conflict(
+ "This interaction prompt is missing its authoritative task binding and cannot be replayed safely",
+ { code: "chat_terminal_interaction_publication_not_replayable" },
+ );
+ }
+ const interaction = await db
+ .select({ status: issueThreadInteractions.status })
+ .from(issueThreadInteractions)
+ .where(
+ and(
+ eq(issueThreadInteractions.id, interactionId),
+ eq(issueThreadInteractions.companyId, publication.companyId),
+ eq(issueThreadInteractions.issueId, publication.issueId),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (!interaction || interaction.status !== "pending") {
+ throw conflict(
+ "A resolved interaction prompt cannot be replayed into the provider",
+ { code: "chat_terminal_interaction_publication_not_replayable" },
+ );
+ }
+ }
+ const claimed = await db.transaction(async (tx) => {
+ const current = await tx
+ .select()
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.companyId, publication.companyId),
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.id, publication.id),
+ ),
+ )
+ .for("update")
+ .then((rows) => rows[0]);
+ if (
+ !current ||
+ current.state !== publication.state ||
+ current.attempts !== publication.attempts
+ )
+ return [];
+ // Lock the publication before checking the transfer lane: issue() takes
+ // the same lock, so a concurrent consent/upload cannot slip into replay.
+ const transfer = await tx
+ .select({ id: chatTeamsFileTransfers.id })
+ .from(chatTeamsFileTransfers)
+ .where(
+ and(
+ eq(chatTeamsFileTransfers.companyId, current.companyId),
+ eq(chatTeamsFileTransfers.publicationId, current.id),
+ ),
+ )
+ .then((rows) => rows[0]);
+ if (transfer)
+ throw conflict(
+ "File delivery requires a stage-specific operator resolution",
+ {
+ code: "chat_file_transfer_resolution_required",
+ },
+ );
+ await notifyChatPublicationWork(tx);
+ return tx
+ .update(chatPublications)
+ .set({
+ state: "retry",
+ nextAttemptAt: new Date(),
+ redactedError: null,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(chatPublications.id, publication.id),
+ eq(chatPublications.state, publication.state),
+ eq(chatPublications.attempts, publication.attempts),
+ ),
+ )
+ .returning({ id: chatPublications.id });
+ });
+ if (!claimed.length) {
+ throw conflict("This publication is already being replayed", {
+ code: "chat_publication_replay_conflict",
+ });
+ }
+ await processPendingPublications(1);
+ }
+
+ async function resolvePublication(
+ endpointId: string,
+ publicationId: string,
+ action: "mark_delivered" | "retry_anyway" | "cancel",
+ userId: string,
+ fileTransfer?: {
+ phase: import("@paperclipai/shared").ChatFileTransferPhase;
+ version: number;
+ },
+ ) {
+ const initialRecord = await endpointRecord(endpointId);
+ if (!initialRecord) throw notFound("Chat endpoint not found");
+ await withCredentialMutationLease(
+ initialRecord.endpoint,
+ (credentialLease) =>
+ db.transaction(async (tx) => {
+ await credentialLease.assertOwned(tx);
+ const publication = await tx
+ .select()
+ .from(chatPublications)
+ .where(
+ and(
+ eq(chatPublications.endpointId, endpointId),
+ eq(chatPublications.id, publicationId),
+ ),
+ )
+ .for("update")
+ .then((rows) => rows[0] ?? null);
+ if (!publication) throw notFound("Publication not found");
+ if (await resolveTeamsFilePublication(tx, { endpointId, publication, action, userId, credentialLease, fileTransfer }, teamsTransferProtocol)) return;
+ if (publication.state !== "delivery_unknown") {
+ throw conflict(
+ "Only an unconfirmed publication needs an operator resolution",
+ {
+ code: "chat_publication_resolution_not_required",
+ },
+ );
+ }
+
+ const interactionId = publication.payload.interactionId;
+ const isInteractionPrompt =
+ Boolean(interactionId) &&
+ publication.idempotencyKey ===
+ `interaction:${interactionId}:${publication.endpointId}`;
+ if (action === "retry_anyway" && isInteractionPrompt) {
+ if (!publication.issueId || !interactionId) {
+ throw conflict(
+ "This interaction prompt is missing its authoritative task binding and cannot be retried safely",
+ {
+ code: "chat_terminal_interaction_publication_not_replayable",
+ },
+ );
+ }
+ const interaction = await tx
+ .select({ status: issueThreadInteractions.status })
+ .from(issueThreadInteractions)
+ .where(
+ and(
+ eq(issueThreadInteractions.id, interactionId),
+ eq(issueThreadInteractions.companyId, publication.companyId),
+ eq(issueThreadInteractions.issueId, publication.issueId),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (!interaction || interaction.status !== "pending") {
+ throw conflict(
+ "A resolved interaction prompt cannot be retried with stale provider actions; mark it delivered or cancel it instead",
+ {
+ code: "chat_terminal_interaction_publication_not_replayable",
+ },
+ );
+ }
+ }
+
+ if (
+ initialRecord.endpoint.provider === "imessage-photon" &&
+ action === "retry_anyway"
+ ) { await recordPhotonPublicationRetry(tx, endpointId, publication, userId); }
+ const now = new Date();
+ await notifyChatPublicationWork(tx);
+ await tx
+ .update(chatPublications)
+ .set(
+ action === "mark_delivered"
+ ? {
+ state: "published",
+ publishedAt: now,
+ nextAttemptAt: null,
+ redactedError: null,
+ updatedAt: now,
+ }
+ : action === "retry_anyway"
+ ? {
+ state: "retry",
+ nextAttemptAt: now,
+ redactedError: null,
+ updatedAt: now,
+ }
+ : {
+ state: "cancelled",
+ nextAttemptAt: null,
+ redactedError:
+ "Cancelled by an operator after an unconfirmed provider delivery",
+ updatedAt: now,
+ },
+ )
+ .where(
+ and(
+ eq(chatPublications.id, publication.id),
+ eq(chatPublications.state, "delivery_unknown"),
+ ),
+ );
+ await resolveSlackFileReceipt(tx, publication, action, now);
+ if (publication.idempotencyKey.startsWith("control:")) {
+ await tx
+ .update(chatActions)
+ .set({
+ status:
+ action === "mark_delivered"
+ ? "processed"
+ : action === "retry_anyway"
+ ? "issued"
+ : "cancelled",
+ result: {
+ code:
+ action === "mark_delivered"
+ ? "task_control_marked_delivered_by_operator"
+ : action === "retry_anyway"
+ ? "task_control_retry_requested"
+ : "task_control_cancelled_by_operator",
+ },
+ updatedAt: now,
+ })
+ .where(
+ and(
+ eq(chatActions.endpointId, publication.endpointId),
+ eq(
+ chatActions.providerActionId,
+ `task-control-authorization:${publication.id}`,
+ ),
+ inArray(chatActions.status, [
+ "issued",
+ "processing",
+ "delivery_unknown",
+ ]),
+ ),
+ );
+ }
+ if (action === "mark_delivered") {
+ await tx
+ .update(chatEndpoints)
+ .set({ lastPublicationAt: now, updatedAt: now })
+ .where(eq(chatEndpoints.id, endpointId));
+ await commitTaskControlCompletion(
+ tx as unknown as Db,
+ publication,
+ now,
+ );
+ }
+ await logActivity(tx as unknown as Db, {
+ companyId: publication.companyId,
+ actorType: "user",
+ actorId: userId,
+ action: `chat.publication_${action}`,
+ entityType: "chat_publication",
+ entityId: publication.id,
+ issueId: publication.issueId,
+ details: {
+ endpointId,
+ conversationId: publication.conversationId,
+ previousState: "delivery_unknown",
+ nextState:
+ action === "mark_delivered"
+ ? "published"
+ : action === "retry_anyway"
+ ? "retry"
+ : "cancelled",
+ duplicateRiskAccepted: action === "retry_anyway",
+ },
+ });
+ await credentialLease.assertOwned(tx);
+ }),
+ );
+ await processPendingPublications();
+ }
+
+ async function resolveProviderEffect(
+ endpointId: string,
+ actionId: string,
+ resolution: "mark_delivered" | "retry_anyway" | "cancel",
+ userId: string,
+ ) {
+ const initialRecord = await endpointRecord(endpointId);
+ if (!initialRecord) throw notFound("Chat endpoint not found");
+
+ if (resolution === "retry_anyway") {
+ await withCredentialMutationLease(
+ initialRecord.endpoint,
+ async (credentialLease) => {
+ const currentRecord = await endpointRecord(endpointId);
+ if (
+ !currentRecord ||
+ !["verifying", "active"].includes(currentRecord.endpoint.status)
+ ) {
+ throw conflict(
+ "The chat connection must be active before retrying this provider reply",
+ {
+ code: "chat_action_endpoint_unavailable",
+ },
+ );
+ }
+ await db.transaction(async (tx) => {
+ await credentialLease.assertOwned(tx);
+ const action = await tx
+ .select()
+ .from(chatActions)
+ .where(
+ and(
+ eq(chatActions.endpointId, endpointId),
+ eq(chatActions.id, actionId),
+ eq(chatActions.kind, "provider_effect"),
+ ),
+ )
+ .for("update")
+ .then((rows) => rows[0] ?? null);
+ if (!action) throw notFound("Provider action not found");
+ if (action.status !== "delivery_unknown") {
+ throw conflict(
+ "Only an unconfirmed provider action needs operator resolution",
+ {
+ code: "chat_action_resolution_not_required",
+ },
+ );
+ }
+ const payload = providerEffectPayload(action.payload);
+ if (!payload) {
+ throw conflict("This provider action cannot be retried safely", {
+ code: "chat_action_retry_context_missing",
+ });
+ }
+ const delivery =
+ payload.settleDelivery && action.deliveryId
+ ? await tx
+ .select({ state: chatDeliveries.state })
+ .from(chatDeliveries)
+ .where(
+ and(
+ eq(chatDeliveries.endpointId, endpointId),
+ eq(chatDeliveries.id, action.deliveryId),
+ ),
+ )
+ .for("update")
+ .then((rows) => rows[0] ?? null)
+ : null;
+ if (payload.settleDelivery && action.deliveryId) {
+ if (!delivery || delivery.state !== "failed") {
+ throw conflict(
+ "The provider action's delivery is no longer awaiting resolution",
+ {
+ code: "chat_action_delivery_resolution_conflict",
+ },
+ );
+ }
+ await notifyChatDeliveryWork(tx);
+ await tx
+ .update(chatDeliveries)
+ .set({
+ state: "processing",
+ nextAttemptAt: null,
+ redactedError: null,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(chatDeliveries.id, action.deliveryId),
+ eq(chatDeliveries.state, "failed"),
+ ),
+ );
+ }
+ const now = new Date();
+ await notifyChatActionWork(tx, "provider_effect");
+ const [claimed] = await tx
+ .update(chatActions)
+ .set({
+ status: "received",
+ result: {
+ ...(action.result ?? {}),
+ code: "provider_effect_retry_requested",
+ retryable: false,
+ retryAt: null,
+ },
+ updatedAt: now,
+ })
+ .where(
+ and(
+ eq(chatActions.id, action.id),
+ eq(chatActions.status, "delivery_unknown"),
+ ),
+ )
+ .returning({ id: chatActions.id });
+ if (!claimed) {
+ throw conflict("This provider action is already being resolved", {
+ code: "chat_action_resolution_conflict",
+ });
+ }
+ await logActivity(tx as unknown as Db, {
+ companyId: action.companyId,
+ actorType: "user",
+ actorId: userId,
+ action: "chat.provider_effect_retry_anyway",
+ entityType: "chat_action",
+ entityId: action.id,
+ details: {
+ endpointId,
+ conversationId: action.conversationId,
+ deliveryId: action.deliveryId,
+ previousState: "delivery_unknown",
+ nextState: "received",
+ duplicateRiskAccepted: true,
+ },
+ });
+ });
+ },
+ );
+ // The audited retry request is durable before the new transport claim.
+ // Do not keep the endpoint mutation lease across provider I/O.
+ await processProviderEffect(actionId);
+ return;
+ }
+
+ await withCredentialMutationLease(
+ initialRecord.endpoint,
+ (credentialLease) =>
+ db.transaction(async (tx) => {
+ await credentialLease.assertOwned(tx);
+ const action = await tx
+ .select()
+ .from(chatActions)
+ .where(
+ and(
+ eq(chatActions.endpointId, endpointId),
+ eq(chatActions.id, actionId),
+ eq(chatActions.kind, "provider_effect"),
+ ),
+ )
+ .for("update")
+ .then((rows) => rows[0] ?? null);
+ if (!action) throw notFound("Provider action not found");
+ if (action.status !== "delivery_unknown") {
+ throw conflict(
+ "Only an unconfirmed provider action needs operator resolution",
+ {
+ code: "chat_action_resolution_not_required",
+ },
+ );
+ }
+ const payload = providerEffectPayload(action.payload);
+ if (!payload) {
+ throw conflict("This provider action cannot be resolved safely", {
+ code: "chat_action_resolution_context_missing",
+ });
+ }
+ const delivery =
+ payload.settleDelivery && action.deliveryId
+ ? await tx
+ .select({ state: chatDeliveries.state })
+ .from(chatDeliveries)
+ .where(
+ and(
+ eq(chatDeliveries.endpointId, endpointId),
+ eq(chatDeliveries.id, action.deliveryId),
+ ),
+ )
+ .for("update")
+ .then((rows) => rows[0] ?? null)
+ : null;
+ if (
+ payload.settleDelivery &&
+ action.deliveryId &&
+ (!delivery || delivery.state !== "failed")
+ ) {
+ throw conflict(
+ "The provider action's delivery is no longer awaiting resolution",
+ {
+ code: "chat_action_delivery_resolution_conflict",
+ },
+ );
+ }
+
+ const now = new Date();
+ const nextStatus =
+ resolution === "mark_delivered" ? "processed" : "cancelled";
+ await notifyChatActionWork(tx, "provider_effect");
+ const [resolved] = await tx
+ .update(chatActions)
+ .set({
+ status: nextStatus,
+ result: {
+ ...(action.result ?? {}),
+ code:
+ resolution === "mark_delivered"
+ ? "provider_effect_marked_delivered_by_operator"
+ : "provider_effect_cancelled_by_operator",
+ retryable: false,
+ retryAt: null,
+ },
+ updatedAt: now,
+ })
+ .where(
+ and(
+ eq(chatActions.id, action.id),
+ eq(chatActions.status, "delivery_unknown"),
+ ),
+ )
+ .returning({ id: chatActions.id });
+ if (!resolved) {
+ throw conflict("This provider action is already being resolved", {
+ code: "chat_action_resolution_conflict",
+ });
+ }
+ if (payload.settleDelivery && action.deliveryId) {
+ await notifyChatDeliveryWork(tx);
+ await tx
+ .update(chatDeliveries)
+ .set(
+ resolution === "mark_delivered"
+ ? {
+ state: "processed",
+ processedAt: now,
+ nextAttemptAt: null,
+ redactedError: null,
+ updatedAt: now,
+ }
+ : {
+ state: "filtered",
+ processedAt: now,
+ nextAttemptAt: null,
+ redactedError:
+ "Cancelled by an operator after an unconfirmed provider reply",
+ updatedAt: now,
+ },
+ )
+ .where(
+ and(
+ eq(chatDeliveries.id, action.deliveryId),
+ eq(chatDeliveries.state, "failed"),
+ ),
+ );
+ }
+ if (resolution === "mark_delivered") {
+ if (payload.completeConversationId) {
+ await tx
+ .update(chatConversations)
+ .set({ state: "completed", updatedAt: now })
+ .where(
+ and(
+ eq(chatConversations.id, payload.completeConversationId),
+ eq(chatConversations.endpointId, endpointId),
+ ),
+ );
+ }
+ await tx
+ .update(chatEndpoints)
+ .set({ lastEventAt: now, updatedAt: now })
+ .where(eq(chatEndpoints.id, endpointId));
+ }
+ await logActivity(tx as unknown as Db, {
+ companyId: action.companyId,
+ actorType: "user",
+ actorId: userId,
+ action: `chat.provider_effect_${resolution}`,
+ entityType: "chat_action",
+ entityId: action.id,
+ details: {
+ endpointId,
+ conversationId: action.conversationId,
+ deliveryId: action.deliveryId,
+ completeConversationId: payload.completeConversationId ?? null,
+ previousState: "delivery_unknown",
+ nextState: nextStatus,
+ duplicateRiskAccepted: false,
+ },
+ });
+ await credentialLease.assertOwned(tx);
+ }),
+ );
+ }
+ return { replayPublication, resolvePublication, resolveProviderEffect };
+}
diff --git a/server/src/services/chat-channels/slack/board-send.ts b/server/src/services/chat-channels/slack/board-send.ts
new file mode 100644
index 0000000000..80abdfaae5
--- /dev/null
+++ b/server/src/services/chat-channels/slack/board-send.ts
@@ -0,0 +1,20 @@
+import type { issueService } from "../../issues.js";
+import { mirrorSlackBoardComment } from "../../slack-board-messages.js";
+import { assertSlackBoardWorkAllowed } from "../../slack-board-resume.js";
+import { and, eq } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { chatPublications, issues } from "@paperclipai/db";
+import { conflict, notFound } from "../../../errors.js";
+import type { DbTransaction } from "../runtime-types.js";
+import type { chatConversations } from "@paperclipai/db";
+type BoardSendInput = { conversation: typeof chatConversations.$inferSelect; comment: Awaited<ReturnType<ReturnType<typeof issueService>["addComment"]>>; idempotencyKey: string; endpointId: string; conversationId: string; attachmentIds: string[] };
+export async function stageSlackBoardSend(tx: DbTransaction, input: BoardSendInput) {
+ const { conversation, comment, idempotencyKey, endpointId, conversationId, attachmentIds } = input;
+ const [issue] = await tx.select().from(issues).where(and(eq(issues.id, conversation.issueId), eq(issues.companyId, conversation.companyId)));
+ if (!issue) throw notFound("Task not found");
+ await assertSlackBoardWorkAllowed(tx as unknown as Db, issue);
+ await mirrorSlackBoardComment(tx, comment, { publicationKey: idempotencyKey, wakeAgent: true, endpointId, conversationId, attachmentIds });
+ const [created] = await tx.select().from(chatPublications).where(and(eq(chatPublications.companyId, conversation.companyId), eq(chatPublications.idempotencyKey, idempotencyKey)));
+ if (!created) throw conflict("This Slack task is no longer assigned to the connected agent");
+ return created;
+}
diff --git a/server/src/services/chat-channels/slack/file-receipt-resolution.ts b/server/src/services/chat-channels/slack/file-receipt-resolution.ts
new file mode 100644
index 0000000000..7805683d6e
--- /dev/null
+++ b/server/src/services/chat-channels/slack/file-receipt-resolution.ts
@@ -0,0 +1,64 @@
+import { and, eq, inArray, sql } from "drizzle-orm";
+import { chatActions } from "@paperclipai/db";
+import type { DbTransaction } from "../runtime-types.js";
+import type { chatPublications } from "@paperclipai/db";
+export async function resolveSlackFileReceipt(tx: DbTransaction, publication: typeof chatPublications.$inferSelect, action: "mark_delivered" | "retry_anyway" | "cancel", now: Date): Promise<void> {
+ const receiptProviderActionId = `slack-file-receipt:${publication.id}:${publication.attempts}`;
+ if (action === "mark_delivered") {
+ await tx
+ .update(chatActions)
+ .set({
+ result: sql`coalesce(${chatActions.result}, '{}'::jsonb) || jsonb_build_object(
+ 'operatorConfirmedPublicationId', ${publication.id}::text,
+ 'operatorConfirmedAttempt', ${publication.attempts}::integer,
+ 'operatorConfirmedAt', ${now.toISOString()}::text
+ )`,
+ updatedAt: now,
+ })
+ .where(
+ and(
+ eq(chatActions.companyId, publication.companyId),
+ eq(chatActions.endpointId, publication.endpointId),
+ eq(chatActions.conversationId, publication.conversationId),
+ eq(chatActions.kind, "slack_file_upload_receipt"),
+ eq(chatActions.providerActionId, receiptProviderActionId),
+ inArray(chatActions.status, [
+ "received",
+ "failed",
+ "processing",
+ ]),
+ sql`(${chatActions.payload}->>'publicationId')::uuid = ${publication.id}`,
+ sql`(${chatActions.payload}->>'publicationAttempt')::int = ${publication.attempts}`,
+ ),
+ );
+ } else {
+ await tx
+ .update(chatActions)
+ .set({
+ status: "cancelled",
+ result: {
+ code:
+ action === "retry_anyway"
+ ? "slack_file_upload_receipt_retry_superseded"
+ : "slack_file_upload_receipt_cancelled_by_operator",
+ },
+ updatedAt: now,
+ })
+ .where(
+ and(
+ eq(chatActions.companyId, publication.companyId),
+ eq(chatActions.endpointId, publication.endpointId),
+ eq(chatActions.conversationId, publication.conversationId),
+ eq(chatActions.kind, "slack_file_upload_receipt"),
+ eq(chatActions.providerActionId, receiptProviderActionId),
+ inArray(chatActions.status, [
+ "received",
+ "failed",
+ "processing",
+ ]),
+ sql`(${chatActions.payload}->>'publicationId')::uuid = ${publication.id}`,
+ sql`(${chatActions.payload}->>'publicationAttempt')::int = ${publication.attempts}`,
+ ),
+ );
+ }
+}