mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
Preserve Slack form custody through replay and publication recovery
This commit is contained in:
1 parent
3d08c5a24d
commit
3cdec19def
8 files changed
+139
-32
No files matched your search
@@ -6,7 +6,7 @@ import { and, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SLACK_CHAT_BOT_SCOPES } from "@paperclipai/shared";
|
||||
import { activityLog, agentRuntimeState, agentTaskSessions, agentWakeupRequests, agents, applyPendingMigrations, authUsers,
|
||||
chatDeliveries, chatEndpoints, chatExternalPrincipals, companySecretBindings, chatIdentityLinks, chatSlackRegistrations, companies, companyMemberships,
|
||||
chatActions, chatDeliveries, chatEndpoints, chatExternalPrincipals, companySecretBindings, chatIdentityLinks, chatSlackRegistrations, companies, companyMemberships,
|
||||
companySecrets, companySkills, costEvents, financeEvents, heartbeatRunEvents, heartbeatRuns, issueComments, issues, toolApplications, toolConnections,
|
||||
closeCheckpointDb, closeFileStorageDb, closeLivenessDb, createDb } from "@paperclipai/db";
|
||||
import { databaseWorkPending, reconcileDatabaseWork, subscribeDatabaseWork } from "@paperclipai/db/work-signals";
|
||||
@@ -229,7 +229,16 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
expect(Date.parse(retained.nextAttemptAt!)).toBeGreaterThan(Date.now());
|
||||
expect(cloud.calls.slice(start).filter(call => call.enrollment?.endpointId === a)).toEqual([]);
|
||||
const retryAt = Date.parse(retained.nextAttemptAt!);
|
||||
expect(owner.nextPollAt()).toBe(retryAt);
|
||||
const formRetries = await db.select({ result: chatActions.result }).from(chatActions).where(and(
|
||||
eq(chatActions.companyId, companyId),
|
||||
sql`${chatActions.kind} in ('slack_form_owner','slack_form_grant','slack_form_session')`,
|
||||
sql`${chatActions.payload}->>'environment' = ${cloud.config.environment}`,
|
||||
sql`coalesce(${chatActions.payload}->'binding'->>'instanceId', ${chatActions.payload}->'enrollment'->>'instanceId') = ${cloud.config.instanceId}`,
|
||||
sql`${chatActions.result}->>'nextAttemptAt' is not null`));
|
||||
expect(formRetries.some(value => value.result?.failureCode === "form_owner_broker_unavailable")).toBe(true);
|
||||
const formDeadlines = formRetries.map(value => Date.parse(String(value.result?.nextAttemptAt)));
|
||||
expect(formDeadlines.every(Number.isFinite)).toBe(true);
|
||||
expect(owner.nextPollAt()).toBe(Math.min(retryAt, ...formDeadlines));
|
||||
releases.splice(0).forEach(release => release()); await Promise.all(heldLeases);
|
||||
pollTime = retryAt - 1;
|
||||
await owner.pollOnce();
|
||||
|
||||
@@ -266,5 +266,58 @@ if (process.env.SLACK_GATE_EXPECT_PRELOAD === "1" && !external) throw new Error(
|
||||
await completedWorker.pollOnce(); expect(lease).toHaveBeenCalledTimes(2); expect(completedWorker.nextPollAt()).toBeNull();
|
||||
await completedWorker.pollOnce(); expect(lease).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("bounded retained-consumer pages pass more than32 completed rows to discover an unfinished tail without dropping attention", async () => {
|
||||
await acceptSlackFormRetirementLocally(db, await row(), identity, compactJws);
|
||||
const retirementDigest = slackFormRetirementReceipt(binding, identity.environment, actorId).receiptId;
|
||||
const retirementProtocol = async (input: { operation: Record<string, unknown> }) => input.operation.refreshRetirementReceipt
|
||||
? { retirementReceiptJws: compactJws } : input.operation.acceptedRetirementReceipt
|
||||
? { acceptedRetirementDigest: retirementDigest } : { releasedRetirementDigest: retirementDigest };
|
||||
await transferSlackFormRetirement(db, await row(), identity, retirementProtocol);
|
||||
await transferSlackFormRetirement(db, await row(), identity, retirementProtocol);
|
||||
expect((await row()).result?.phase).toBe("transferred");
|
||||
expect((await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpointId)))[0]?.status).toBe("paused");
|
||||
const sessionId = randomUUID(), operationId = "c".repeat(64), deliveryId = `slack_form_${operationId}`, now = new Date().toISOString();
|
||||
const receipt = parseSlackFormFinalizedReceipt({ version: 1, kind: "slack_form_finalized", environment: identity.environment, binding,
|
||||
operationId, deliveryId, appReceiptId: sessionId, grantId: "grant", publicationId: "publication", interactionId: "interaction", userId: "UTEST",
|
||||
viewDigest: null, terminalDigest: "d".repeat(64), outcome: "no_effect", finalizedAt: now });
|
||||
const pair = generateKeyPairSync("ed25519"), kid = "session-canonical-control";
|
||||
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
const input = encode({ alg: "EdDSA", typ: "paperclip-connector-ack-receipt+jwt", kid }) + "." + encode({ v: 1, iss: "paperclip-cloud", aud: "paperclip-connector-ack-receipt/v1", sub: identity.instanceId, receipt });
|
||||
const receiptJws = input + "." + sign(null, Buffer.from(input), pair.privateKey).toString("base64url");
|
||||
const terminalIntent = { version: 1, binding, operationId, deliveryId, userId: "UTEST", grantId: "grant", publicationId: "publication", interactionId: "interaction",
|
||||
appReceiptId: sessionId, view: null, outcome: "no_effect", submitReceiptId: null, rejectionDigest: receipt.terminalDigest, encryptedEvidence: null };
|
||||
await db.insert(chatActions).values({ id: sessionId, companyId, endpointId, kind: "slack_form_session", providerActionId: `slack-form-session:${operationId}`,
|
||||
status: "failed", payload: { binding, environment: identity.environment, operationId, userId: "UTEST", grantId: "grant", publicationId: "publication", interactionId: "interaction" },
|
||||
result: { phase: "not_opened", terminalIntent,
|
||||
cloudProofAcceptance: { version: 1, binding, operationId, appReceiptId: sessionId, outcome: "no_effect", terminalDigest: receipt.terminalDigest, acceptedAt: now },
|
||||
formAck: { version: 1, phase: "gc_pending", leaseId: "exact-session-lease", deliveryId, receiptJws, receipt }, nextAttemptAt: now } });
|
||||
await transferSlackFormAckReceipt(db, { companyId, actionId: sessionId, instanceId: identity.instanceId,
|
||||
protocol: async () => ({ releasedAckDigest: slackFormFinalizedReceiptDigest(receipt) }) });
|
||||
const [completed] = await db.select().from(chatActions).where(and(eq(chatActions.id, sessionId), eq(chatActions.companyId, companyId)));
|
||||
if (!completed) throw new Error("Actual GC transition lost its session");
|
||||
for (let n = 1; n <= 33; n++) {
|
||||
const id = `00000000-0000-4000-8000-${n.toString(16).padStart(12, "0")}`, op = n.toString(16).padStart(64, "0"), delivery = `slack_form_${op}`;
|
||||
const historyReceipt = { ...receipt, operationId: op, deliveryId: delivery, appReceiptId: id };
|
||||
const body = encode({ alg: "EdDSA", typ: "paperclip-connector-ack-receipt+jwt", kid }) + "." + encode({ v: 1, iss: "paperclip-cloud", aud: "paperclip-connector-ack-receipt/v1", sub: identity.instanceId, receipt: historyReceipt });
|
||||
const historyJws = body + "." + sign(null, Buffer.from(body), pair.privateKey).toString("base64url");
|
||||
await db.insert(chatActions).values({ ...completed, id, providerActionId: `slack-form-session:${op}`,
|
||||
payload: { ...completed.payload, operationId: op }, result: { phase: "not_opened",
|
||||
terminalIntent: { ...terminalIntent, operationId: op, deliveryId: delivery, appReceiptId: id },
|
||||
cloudProofAcceptance: { version: 1, binding, operationId: op, appReceiptId: id, outcome: "no_effect", terminalDigest: receipt.terminalDigest, acceptedAt: now },
|
||||
formAck: { version: 1, phase: "transferred", leaseId: "exact-session-lease", deliveryId: delivery, receiptJws: historyJws, receipt: historyReceipt }, nextAttemptAt: null } });
|
||||
}
|
||||
const tailId = "ffffffff-ffff-4fff-8fff-ffffffffffff", tailOp = "f".repeat(64);
|
||||
await db.insert(chatActions).values({ id: tailId, companyId, endpointId, kind: "slack_form_session", status: "processing", providerActionId: `slack-form-session:${tailOp}`,
|
||||
payload: { binding, environment: identity.environment, operationId: tailOp, userId: "UTEST", grantId: "grant", publicationId: "publication", interactionId: "interaction" },
|
||||
result: { phase: "update_attempted", view: { id: "VTAIL", hash: "same-loading-hash", externalId: `pc-form-${tailOp}` } } });
|
||||
const connector = { instanceIdentity: () => identity };
|
||||
expect((await readSlackFormRetainedConsumer(db, connector)).owner).toEqual({ subject: "github-bot-events", companyId, binding, requiresDelivery: true });
|
||||
await db.insert(chatActions).values({ id: "00000000-0000-4000-8000-000000000000", companyId, endpointId, kind: "slack_form_session", status: "attention", providerActionId: "malformed-retained-page",
|
||||
payload: { binding: { instanceId: identity.instanceId }, environment: identity.environment }, result: {} });
|
||||
const withMalformed = await readSlackFormRetainedConsumer(db, connector);
|
||||
expect(withMalformed.owner).toMatchObject({ companyId, requiresDelivery: true });
|
||||
expect(withMalformed.attention).toContainEqual({ actionId: "00000000-0000-4000-8000-000000000000", code: "form_retained_owner_invalid" });
|
||||
expect(withMalformed.attention.length).toBeLessThanOrEqual(32);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { stageSlackFormSubmission } from "../slack/form-session.js";
|
||||
import { slackFormSubmissionEvidence } from "../slack/cloud-forms.js";
|
||||
import { slackFormOpenContext } from "../slack/cloud-forms.js";
|
||||
import { stageSlackFormSession, confirmSlackFormSessionUpdate } from "../slack/form-session.js";
|
||||
import { stageSlackFormOpenCallback, confirmSlackFormOpenCallback } from "../slack/form-open-callback.js";
|
||||
import { SlackCloudReceiptError } from "../slack/cloud-event.js";
|
||||
import type { CredentialMutationLeaseGuard } from "../../chat-credential-mutation-lease.js";
|
||||
import { notifyChatEndpointConfiguration } from "../configuration-work-notifications.js";
|
||||
@@ -1045,21 +1045,9 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ id: chatActions.id });
|
||||
if (cloudForm) {
|
||||
if (!lease || !cloudForm.environment) throw new SlackCloudReceiptError("form_credential_lease_unavailable", "retry");
|
||||
const held = await stageSlackFormSession(tx, { operation: cloudForm.operation, currentBinding: cloudForm.currentBinding,
|
||||
principalId: principal.principal.id, resolved, lease, environment: cloudForm.environment });
|
||||
cloudForm.sessionActionId = held.actionId;
|
||||
if (held.kind !== "update") return { kind: "duplicate" as const };
|
||||
if (!attempt) {
|
||||
const [retainedAttempt] = await tx.select().from(chatActions).where(and(eq(chatActions.companyId, record.endpoint.companyId),
|
||||
eq(chatActions.endpointId, record.endpoint.id), eq(chatActions.conversationId, conversation.id),
|
||||
eq(chatActions.principalId, principal.principal.id), eq(chatActions.kind, "question_form_open_attempt"),
|
||||
eq(chatActions.providerActionId, attemptProviderActionId))).for("update");
|
||||
if (!retainedAttempt || retainedAttempt.status !== "processing") throw new SlackCloudReceiptError("form_open_attempt_unresolved", "attention");
|
||||
return { kind: "ready" as const, attemptActionId: retainedAttempt.id, resolved };
|
||||
}
|
||||
}
|
||||
if (cloudForm) return stageSlackFormOpenCallback(tx, { context: cloudForm, lease, resolved,
|
||||
companyId: record.endpoint.companyId, endpointId: record.endpoint.id, conversationId: conversation.id,
|
||||
principalId: principal.principal.id, attemptProviderActionId, attemptActionId: attempt?.id ?? null });
|
||||
return attempt
|
||||
? {
|
||||
kind: "ready" as const,
|
||||
@@ -1124,12 +1112,8 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb
|
||||
if (event.provider === "discord") return deny(safelyKnown);
|
||||
return;
|
||||
}
|
||||
if (cloudForm) {
|
||||
if (!cloudForm.sessionActionId || !cloudForm.updatedView) throw new SlackCloudReceiptError("form_update_receipt_unavailable", "retry");
|
||||
const updated = await db.transaction(tx => confirmSlackFormSessionUpdate(tx, { companyId: record.endpoint.companyId,
|
||||
endpointId: record.endpoint.id, principalId: principal.principal.id, operationId: cloudForm.operation.id }, cloudForm.operation.view!, cloudForm.updatedView!.hash));
|
||||
if (!updated) throw new SlackCloudReceiptError("form_update_settlement_changed", "retry");
|
||||
}
|
||||
if (cloudForm) await db.transaction(tx => confirmSlackFormOpenCallback(tx, { context: cloudForm,
|
||||
companyId: record.endpoint.companyId, endpointId: record.endpoint.id, principalId: principal.principal.id }));
|
||||
if (attemptActionId) {
|
||||
const [settledAttempt] = await db
|
||||
.update(chatActions)
|
||||
|
||||
@@ -783,6 +783,7 @@ export function createChatPublicationWorker(db: Db, options: PublicationWorkerOp
|
||||
runtimeContext: currentPublicationRuntimeContext,
|
||||
})
|
||||
: null;
|
||||
const stageSlackForm = await options.prepareSlackFormPublication?.(authorizationClaim.endpoint, publication);
|
||||
const sent = await postSafePublication({
|
||||
endpoint: authorizationClaim.endpoint,
|
||||
conversation: authorizationClaim.conversation,
|
||||
@@ -859,7 +860,6 @@ export function createChatPublicationWorker(db: Db, options: PublicationWorkerOp
|
||||
}
|
||||
const { authorizationActionId } = authorizationClaim;
|
||||
const receiptRemovalActionIds: string[] = [];
|
||||
const stageSlackForm = await options.prepareSlackFormPublication?.(authorizationClaim.endpoint, publication);
|
||||
await db.transaction(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
const committedAt = new Date();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { completedSlackFormSessionReceipt } from "./form-idle-history.js";
|
||||
import { and, inArray, sql } from "drizzle-orm";
|
||||
import { and, gt, inArray, sql } from "drizzle-orm";
|
||||
import { chatActions, type Db } from "@paperclipai/db";
|
||||
import { projectSlackFormRetainedOwner, type SlackFormRetainedRow } from "./form-session.js";
|
||||
|
||||
@@ -39,9 +39,20 @@ export function selectSlackFormRetainedConsumer(rows: readonly SlackFormRetained
|
||||
export async function readSlackFormRetainedConsumer(db: Pick<Db, "select">, connector: unknown) {
|
||||
const identity = slackFormConnectorIdentity(connector);
|
||||
if (!identity) return { owner: null, attention: [] };
|
||||
const rows = await db.select().from(chatActions).where(and(
|
||||
inArray(chatActions.kind, ["slack_form_session", "slack_form_owner", "slack_form_grant"]),
|
||||
sql`coalesce(${chatActions.payload}->'binding'->>'instanceId', ${chatActions.payload}->'enrollment'->>'instanceId') = ${identity.instanceId}`))
|
||||
.orderBy(chatActions.id).limit(32);
|
||||
return selectSlackFormRetainedConsumer(rows, identity);
|
||||
let after: string | undefined;
|
||||
const attention: { actionId: string; code: string }[] = [];
|
||||
for (;;) {
|
||||
const rows = await db.select().from(chatActions).where(and(
|
||||
inArray(chatActions.kind, ["slack_form_session", "slack_form_owner", "slack_form_grant"]),
|
||||
sql`coalesce(${chatActions.payload}->'binding'->>'instanceId', ${chatActions.payload}->'enrollment'->>'instanceId') = ${identity.instanceId}`,
|
||||
after === undefined ? undefined : gt(chatActions.id, after)))
|
||||
.orderBy(chatActions.id).limit(32);
|
||||
const selected = selectSlackFormRetainedConsumer(rows, identity);
|
||||
attention.push(...selected.attention.slice(0, Math.max(0, 32 - attention.length)));
|
||||
if (selected.owner) return { owner: selected.owner, attention };
|
||||
if (rows.length < 32) return { owner: null, attention };
|
||||
const next = rows[rows.length - 1]?.id;
|
||||
if (!next || next === after) throw new Error("Slack retained consumer cursor did not advance");
|
||||
after = next;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { chatActions, type Db } from "@paperclipai/db";
|
||||
import type { CredentialMutationLeaseGuard } from "../../chat-credential-mutation-lease.js";
|
||||
import type { ResolvedChatQuestionFormOpen } from "../../chat-question-forms.js";
|
||||
import type { SlackFormOpenContext } from "./cloud-forms.js";
|
||||
import { SlackCloudReceiptError } from "./cloud-event.js";
|
||||
import { stageSlackFormSession, confirmSlackFormSessionUpdate } from "./form-session.js";
|
||||
|
||||
type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
type Scope = { companyId: string; endpointId: string; conversationId: string; principalId: string };
|
||||
export async function stageSlackFormOpenCallback(tx: Tx, input: Scope & {
|
||||
context: SlackFormOpenContext; resolved: ResolvedChatQuestionFormOpen; lease?: CredentialMutationLeaseGuard;
|
||||
attemptProviderActionId: string; attemptActionId: string | null;
|
||||
}): Promise<{ kind: "ready"; attemptActionId: string; resolved: ResolvedChatQuestionFormOpen } | { kind: "duplicate" }> {
|
||||
const { context, lease } = input;
|
||||
if (!lease || !context.environment) throw new SlackCloudReceiptError("form_credential_lease_unavailable", "retry");
|
||||
const held = await stageSlackFormSession(tx, { operation: context.operation, currentBinding: context.currentBinding,
|
||||
principalId: input.principalId, resolved: input.resolved, lease, environment: context.environment });
|
||||
context.sessionActionId = held.actionId;
|
||||
if (held.kind !== "update") return { kind: "duplicate" };
|
||||
if (input.attemptActionId) return { kind: "ready", attemptActionId: input.attemptActionId, resolved: input.resolved };
|
||||
const [attempt] = await tx.select().from(chatActions).where(and(eq(chatActions.companyId, input.companyId),
|
||||
eq(chatActions.endpointId, input.endpointId), eq(chatActions.conversationId, input.conversationId),
|
||||
eq(chatActions.principalId, input.principalId), eq(chatActions.kind, "question_form_open_attempt"),
|
||||
eq(chatActions.providerActionId, input.attemptProviderActionId))).for("update");
|
||||
if (!attempt || attempt.status !== "processing") throw new SlackCloudReceiptError("form_open_attempt_unresolved", "attention");
|
||||
return { kind: "ready", attemptActionId: attempt.id, resolved: input.resolved };
|
||||
}
|
||||
export async function confirmSlackFormOpenCallback(tx: Tx, input: Omit<Scope, "conversationId"> & { context: SlackFormOpenContext }): Promise<void> {
|
||||
const { context } = input;
|
||||
if (!context.sessionActionId || !context.updatedView || !context.operation.view) throw new SlackCloudReceiptError("form_update_receipt_unavailable", "retry");
|
||||
const updated = await confirmSlackFormSessionUpdate(tx, { companyId: input.companyId, endpointId: input.endpointId,
|
||||
principalId: input.principalId, operationId: context.operation.id }, context.operation.view, context.updatedView.hash);
|
||||
if (!updated) throw new SlackCloudReceiptError("form_update_settlement_changed", "retry");
|
||||
}
|
||||
@@ -242,7 +242,7 @@ export async function stageSlackFormPublication(tx: Tx, publicationId: string, i
|
||||
if (!open) return null;
|
||||
const resolved = await resolveChatQuestionFormOpen(tx, { companyId: endpoint.companyId, endpointId: endpoint.id,
|
||||
conversationId: publication.conversationId, interaction: form, openActionId: open.providerActionId });
|
||||
if (!resolved) return attention("form_grant_current_question_changed");
|
||||
if (!resolved) return null;
|
||||
return stageSlackFormGrant(tx, { binding, environment: owner.payload.environment, subject: owner.payload.subject, resolved });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { chatActions, chatEndpoints } from "@paperclipai/db";
|
||||
import { parseSlackFormBinding } from "./cloud-forms.js";
|
||||
import { SlackCloudReceiptError } from "./cloud-event.js";
|
||||
import { slackFormSetupRecord } from "./cloud-forms.js";
|
||||
import { chatPublications, type Db } from "@paperclipai/db";
|
||||
import { issueThreadInteractionService } from "../../issue-thread-interactions.js";
|
||||
@@ -12,6 +17,16 @@ export function createSlackFormPublicationStage(db: Db) {
|
||||
const interaction = (await issueThreadInteractionService(db).listForIssue(publication.issueId))
|
||||
.find(value => value.id === publication.payload.interactionId && value.companyId === endpoint.companyId && value.status === "pending");
|
||||
if (!interaction) return null;
|
||||
const [current] = await db.select().from(chatEndpoints).where(and(eq(chatEndpoints.id, endpoint.id), eq(chatEndpoints.companyId, endpoint.companyId))).limit(1);
|
||||
const setup = current ? slackFormSetupRecord(current.setup) : undefined;
|
||||
const binding = parseSlackFormBinding(setup?.slackCloudForms);
|
||||
const [owner] = await db.select().from(chatActions).where(and(eq(chatActions.companyId, endpoint.companyId), eq(chatActions.endpointId, endpoint.id),
|
||||
eq(chatActions.kind, "slack_form_owner"), sql`${chatActions.payload}->'binding' = ${JSON.stringify(binding)}::jsonb`, sql`${chatActions.result}->>'phase' = 'enrolled'`)).limit(1);
|
||||
if (!current || !["active", "verifying", "attention"].includes(current.status) || setup?.runtimeGeneration !== binding.runtimeGeneration
|
||||
|| current.publicId !== binding.publicId || current.connectionId !== binding.connectionId || binding.companyId !== endpoint.companyId
|
||||
|| binding.endpointId !== endpoint.id || setup?.slackCloudInstanceId !== binding.instanceId || owner?.payload.subject !== setup?.slackCloudSubject
|
||||
|| !isDeepStrictEqual(setup?.slackCloudForms, binding) || typeof owner?.payload.environment !== "string")
|
||||
throw new SlackCloudReceiptError("form_publication_enrollment_pending", "retry");
|
||||
return async tx => { await stageSlackFormPublication(tx, publication.id, interaction); };
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user