Merge remote-tracking branch 'origin/master' into swarm-fin-tmp

* origin/master:
  perf(test): split chat-channels monolith into 16 suites and shrink PR chat shards 5 -> 2 (#22838)
  fix: Restore icon and appearance when rolling back an agent config revision (#19244)
  fix: Match originKindPrefix as a literal prefix by escaping LIKE wildcards (#19197)
This commit is contained in:
Dotta committed 2026-11-24 17:47:35 -06:00
commit a2decc65f3
46 files changed
+50785 -87946

No files matched your search

@@ -12,7 +12,7 @@ const output = path.resolve(process.argv[2] ?? mkdtempSync(path.join(tmpdir(), "
mkdirSync(output, { recursive: true });
assert.equal(existsSync(path.join(output, "pairs.jsonl")), false, "Use a fresh output directory");
const baseline = "82c033ed127d07862e6765aa4b69a3cf339bde81";
const integration = "server/src/__tests__/chat-channels.integration.test.ts";
const integration = "server/src/__tests__/chat-channels/telegram-media-and-recovery.integration.test.ts";
const git = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8" });
assert.equal(git("status", "--porcelain").trim(), "", "Commit fixture changes first; use an isolated checkout");
const original = readFileSync(path.join(root, integration), "utf8");
@@ -30,7 +30,7 @@ const benchmark = String.raw` it("measures equivalent completed accepted-respon
const { appendFileSync } = await import("node:fs");
const output = process.env.PAPERCLIP_PRESENTATION_BENCHMARK_OUTPUT;
if (!output) throw new Error("Benchmark output directory is required");
const { nativeResponsePresentationWork: baselineWork } = await import("../services/native-runtime/native-response-presentation-work.baseline.js");
const { nativeResponsePresentationWork: baselineWork } = await import("../../services/native-runtime/native-response-presentation-work.baseline.js");
const { createDatabaseResponseCapture, installDatabaseResponseCapture } = await import("@paperclipai/db/response-capture");
const schema = await import("@paperclipai/db");
appendFileSync(output + "/child-runtime.jsonl",
+1 -1
View File
@@ -34,7 +34,7 @@ const env = {
SLACK_GATE_PROCESS_LOG: process.env.SLACK_GATE_PROCESS_LOG,
};
const child = spawn(process.execPath, ['--require', guard, vitest, 'run',
'src/__tests__/chat-channels.integration.test.ts', '--testNamePattern', testNamePattern, '--maxWorkers=1', '--no-file-parallelism', `--execArgv=--require=${guard}`],
'src/__tests__/chat-channels/slack-protocol.integration.test.ts', '--testNamePattern', testNamePattern, '--maxWorkers=1', '--no-file-parallelism', `--execArgv=--require=${guard}`],
{ cwd: server, env, stdio: 'inherit' });
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));
child.on('error', error => { console.error(error); process.exitCode = 1; });
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { randomAgentAppearance } from "@paperclipai/shared";
import { configPatchFromSnapshot } from "../lib/agent-records.js";
const baseSnapshot = {
name: "Agent",
role: "engineer",
adapterType: "process",
budgetMonthlyCents: 0,
};
describe("configPatchFromSnapshot", () => {
it("restores icon and appearance from the snapshot", () => {
const appearance = randomAgentAppearance();
const patch = configPatchFromSnapshot({ ...baseSnapshot, icon: "bot", appearance });
expect(patch.icon).toBe("bot");
expect(patch.appearance).toEqual(appearance);
});
it("restores a null icon", () => {
expect(configPatchFromSnapshot({ ...baseSnapshot, icon: null }).icon).toBeNull();
});
it("leaves icon and appearance out when the snapshot lacks valid values", () => {
const patch = configPatchFromSnapshot({ ...baseSnapshot, icon: 5, appearance: { bad: true } });
expect(patch).not.toHaveProperty("icon");
expect(patch).not.toHaveProperty("appearance");
const legacy = configPatchFromSnapshot(baseSnapshot);
expect(legacy).not.toHaveProperty("icon");
expect(legacy).not.toHaveProperty("appearance");
});
});
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { eq, sql } from "drizzle-orm";
import { agents, companies, createDb } from "@paperclipai/db";
import { agentConfigRevisions, agents, companies, createDb } from "@paperclipai/db";
import { agentAppearanceSchema, appearanceForPalette, legacyAgentAppearance } from "@paperclipai/shared";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { agentService } from "../services/agents.js";
@@ -38,6 +38,49 @@ describe("persisted agent personas", () => {
const [row] = await db.select().from(agents).where(eq(agents.id, original.id));
expect(row.appearance).toEqual(appearance);
});
it("restores the revision's icon and appearance on rollback and records them in the rollback revision", async () => {
const service = agentService(db);
const appearance = appearanceForPalette("arctic-blue");
const newerAppearance = appearanceForPalette("cherry-pop");
const original = await createAgentLifecycle(db).requestHire(companyId, { name: "Restored persona", role: "engineer", adapterType: "process", icon: "bot", appearance });
await service.update(original.id, { title: "First" }, { recordRevision: { source: "test" } });
const [revision] = await service.listConfigRevisions(original.id);
await service.update(original.id, { title: "Second", icon: "brain", appearance: newerAppearance });
const restored = await service.rollbackConfigRevision(original.id, revision.id, {});
expect(restored).toMatchObject({ title: "First", icon: "bot", appearance });
const [row] = await db.select().from(agents).where(eq(agents.id, original.id));
expect(row).toMatchObject({ icon: "bot", appearance });
const [rollbackRevision] = await service.listConfigRevisions(original.id);
expect(rollbackRevision.source).toBe("rollback");
expect(rollbackRevision.changedKeys).toEqual(expect.arrayContaining(["icon", "appearance"]));
expect(rollbackRevision.afterConfig).toMatchObject({ title: "First", icon: "bot", appearance });
});
it("clears the icon when the rolled back revision recorded no icon", async () => {
const service = agentService(db);
const original = await createAgentLifecycle(db).requestHire(companyId, { name: "Iconless persona", role: "engineer", adapterType: "process", icon: null });
await service.update(original.id, { title: "First" }, { recordRevision: { source: "test" } });
const [revision] = await service.listConfigRevisions(original.id);
await service.update(original.id, { icon: "brain" });
const restored = await service.rollbackConfigRevision(original.id, revision.id, {});
expect(restored?.icon).toBeNull();
});
it.each([
["missing", (config: Record<string, unknown>) => {
const { icon: _icon, appearance: _appearance, ...rest } = config;
return rest;
}],
["invalid", (config: Record<string, unknown>) => ({ ...config, icon: 42, appearance: { paletteId: "not-a-palette" } })],
])("keeps the current icon and appearance when the revision's values are %s", async (kind, rewrite) => {
const service = agentService(db);
const newerAppearance = appearanceForPalette("cherry-pop");
const original = await createAgentLifecycle(db).requestHire(companyId, { name: `Older revision ${kind}`, role: "engineer", adapterType: "process", icon: "bot", appearance: appearanceForPalette("arctic-blue") });
await service.update(original.id, { title: "First" }, { recordRevision: { source: "test" } });
const [revision] = await service.listConfigRevisions(original.id);
await db.update(agentConfigRevisions).set({ afterConfig: rewrite(revision.afterConfig) }).where(eq(agentConfigRevisions.id, revision.id));
await service.update(original.id, { title: "Second", icon: "brain", appearance: newerAppearance });
const restored = await service.rollbackConfigRevision(original.id, revision.id, {});
expect(restored).toMatchObject({ title: "First", icon: "brain", appearance: newerAppearance });
});
it("backfills legacy IDs with exactly the same persisted identity as the runtime fallback", async () => {
const ids = Array.from({ length: 20 }, () => randomUUID());
await db.insert(agents).values(ids.map((id, i) => ({ id, companyId, name: `Legacy ${i}`, role: "engineer", appearance: null, icon: "bot" })));
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,817 @@
// Shared GitHub endpoint, webhook, and pre-ingress fixture helpers.
import { githubChatManagementService } from "../../services/chat-github-management.js";
import { syncGitHubBotTools } from "../../services/chat-github-tools.js";
import { createHmac, generateKeyPairSync, randomUUID } from "node:crypto";
import request from "supertest";
import { and, eq, sql } from "drizzle-orm";
import { beforeAll, expect, it, vi } from "vitest";
import { chatActions, chatDeliveries, chatEndpoints, chatSdkState, issues } from "@paperclipai/db";
import { type ChatChannelServiceOptions, type ChatChannelService } from "../../services/chat-channels.js";
import type { CreateChatSdkEndpointRuntimeOptions } from "../../services/chat-sdk-runtime.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { type TestDb, FakeEndpointRuntime, FakeChatSdkRuntime, makeThread, makeMessage } from "./providers.js";
import type { ChatChannelHarness } from "./harness.js";
export function createGitHubHarness(h: ChatChannelHarness) {
let db!: TestDb;
beforeAll(() => { db = h.db; });
const { seedCompany, readChatEndpointsById, createService, deliverMessage } = h;
function githubWebhookVerificationResponse(
service: ChatChannelService,
publicId: string,
webhookSecret: string,
providerDeliveryId = `github-setup-ping-${randomUUID()}`,
) {
const body = JSON.stringify({ zen: "Keep it logically awesome." });
const signature = createHmac("sha256", webhookSecret)
.update(body)
.digest("hex");
return service.handleWebhook(
publicId,
"github",
new Request(
`https://paperclip.example/api/chat-webhooks/${publicId}/github`,
{
method: "POST",
headers: {
"content-type": "application/json",
"x-github-delivery": providerDeliveryId,
"x-github-event": "ping",
"x-hub-signature-256": `sha256=${signature}`,
},
body,
},
),
);
}
async function recordGitHubWebhookVerification(
service: ChatChannelService,
publicId: string,
webhookSecret: string,
) {
const providerDeliveryId = `github-setup-ping-${randomUUID()}`;
const response = await githubWebhookVerificationResponse(
service,
publicId,
webhookSecret,
providerDeliveryId,
);
expect([200, 202]).toContain(response.status);
const action = await db
.select({ id: chatActions.id })
.from(chatActions)
.innerJoin(chatEndpoints, eq(chatEndpoints.id, chatActions.endpointId))
.where(
and(
eq(chatEndpoints.publicId, publicId),
eq(
chatActions.providerActionId,
`github_webhook_ingress:${providerDeliveryId}`,
),
),
)
.then((rows) => rows[0] ?? null);
if (action) {
await service.processPendingGitHubWebhookIngress(1, action.id);
}
await vi.waitFor(async () => {
const setup = await db
.select({ setup: chatEndpoints.setup })
.from(chatEndpoints)
.where(eq(chatEndpoints.publicId, publicId))
.then((rows) => rows[0]?.setup);
expect(setup).toMatchObject({ webhookVerifiedAt: expect.any(String) });
});
}
function signedGitHubWebhookRequest(input: {
delivery: string;
event: string;
payload: unknown;
webhookSecret: string;
url?: string;
}) {
const body = JSON.stringify(input.payload);
const signature = createHmac("sha256", input.webhookSecret)
.update(body)
.digest("hex");
return new Request(input.url ?? "https://paperclip.example/github", {
method: "POST",
headers: {
"content-type": "application/json",
"x-github-event": input.event,
"x-github-delivery": input.delivery,
"x-hub-signature-256": `sha256=${signature}`,
},
body,
});
}
async function configuredGitHubEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: Partial<
Pick<
ChatChannelServiceOptions,
| "deferWebhookProcessing"
| "githubWebhookAuthenticationBarrier"
| "githubWebhookReplayBarrier"
| "githubWebhookResponseBudgetMs"
| "publicBaseUrl"
| "webhookPublicBaseUrl"
| "scheduleDeferredWork"
| "setupSecretActivityLogger"
| "setupSecretCredentialPersistBarrier"
| "receiptReactionTransportBarrier"
| "storage"
>
> & { wakeup?: ChatChannelServiceOptions["heartbeat"]["wakeup"] } = {},
useVerifiedAppId = false,
registerWithManifest = false,
connectExistingApp = false,
interruptAppVault = false,
) {
let setupComplete = false;
const deferredSchedule = overrides.scheduleDeferredWork;
let installationId = 2468;
let additionalInstallationIds: number[] = [];
let installationAvailable = true;
let repositories = [
{
id: 97531,
full_name: "paperclipai/paperclip",
html_url: "https://github.com/paperclipai/paperclip",
owner: { id: 1357, login: "paperclipai" },
private: false,
},
];
let appPermissions: Record<string, string> = {
contents: "read",
checks: "write",
issues: "write",
metadata: "read",
pull_requests: "write",
};
let installationPermissions: Record<string, string> = {
contents: "read",
checks: "write",
issues: "write",
metadata: "read",
pull_requests: "write",
};
let appEvents = [
"pull_request",
"github_app_authorization",
"installation",
"installation_repositories",
"issue_comment",
"pull_request_review_comment",
];
const webhookSyncRequests: Array<Record<string, unknown>> = [];
let webhookSyncResponse: (() => Promise<Response>) | null = null;
let supplementalProviderFetch:
| ((
input: string | URL | Request,
init?: RequestInit,
) => Promise<Response | undefined>)
| null = null;
const appRegistrationId = Number.parseInt(
fixture.companyId.replaceAll("-", "").slice(0, 8),
16,
);
const privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 })
.privateKey.export({ type: "pkcs8", format: "pem" })
.toString();
const responseComments = new Map<number, { id: number; body: string; html_url: string; user: { login: string }; thread: string }>();
const responseWrites: Array<{ method: string; id: number; body: string }> = [];
let nextResponseId = 800000;
const providerFetch = (async (
input: string | URL | Request,
init?: RequestInit,
) => {
const url = String(input);
const supplemental = await supplementalProviderFetch?.(input, init);
if (supplemental) return supplemental;
const list = /\/repos\/paperclipai\/paperclip\/(issues|pulls)\/([1-9][0-9]*)\/comments(?:\?.*)?$/.exec(url);
const reply = /\/repos\/paperclipai\/paperclip\/pulls\/([1-9][0-9]*)\/comments\/[1-9][0-9]*\/replies$/.exec(url);
const item = /\/repos\/paperclipai\/paperclip\/(issues|pulls)\/comments\/([1-9][0-9]*)$/.exec(url);
if (item) {
const comment = responseComments.get(Number(item[2]));
if (!comment) return Response.json({ message: "Not Found" }, { status: 404 });
if (init?.method === "PATCH") {
comment.body = JSON.parse(String(init.body)).body;
responseWrites.push({ method: "PATCH", id: comment.id, body: comment.body });
}
return Response.json(comment);
}
if ((list || reply) && init?.method === "POST") {
const id = ++nextResponseId;
const thread = list ? `${list[1]}:${list[2]}` : `pulls:${reply![1]}`;
const body = JSON.parse(String(init.body)).body;
const comment = { id, body, thread, html_url: `https://github.com/paperclipai/paperclip/issues/${list?.[2] ?? reply![1]}#issuecomment-${id}`,
user: { login: `maya-${fixture.companyId.slice(0, 8)}[bot]` } };
responseComments.set(id, comment);
responseWrites.push({ method: "POST", id, body });
return Response.json(comment, { status: 201 });
}
if (list && (!init?.method || init.method === "GET")) return Response.json([...responseComments.values()].filter(row => row.thread === `${list[1]}:${list[2]}`));
if (url === "https://api.github.com/app/hook/config") {
expect(init?.method).toBe("PATCH");
const config = JSON.parse(String(init?.body)) as Record<
string,
unknown
>;
webhookSyncRequests.push(config);
if (webhookSyncResponse) return webhookSyncResponse();
return new Response(
JSON.stringify({
url: config.url,
content_type: config.content_type,
insecure_ssl: config.insecure_ssl,
}),
{ status: 200 },
);
}
if (url === "https://api.github.com/app") {
return new Response(
JSON.stringify({
id: appRegistrationId,
slug: `maya-${fixture.companyId.slice(0, 8)}`,
name: "Maya Paperclip",
owner: { login: "paperclipai" },
permissions: appPermissions,
events: appEvents,
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
}
if (url === `https://api.github.com/app/installations/${installationId}`)
return Response.json({ permissions: installationPermissions, suspended_at: null });
if (url === "https://api.github.com/app/installations?per_page=100") {
return new Response(
JSON.stringify(
installationAvailable
? [
{
id: installationId,
account: {
id: 1357,
login: "paperclipai",
type: "Organization",
},
permissions: installationPermissions,
suspended_at: null,
},
...additionalInstallationIds.map((id) => ({
id,
account: {
id: id + 10_000,
login: `additional-${id}`,
type: "Organization",
},
permissions: installationPermissions,
suspended_at: null,
})),
]
: [],
),
{ status: 200, headers: { "content-type": "application/json" } },
);
}
if (
url ===
`https://api.github.com/app/installations/${installationId}/access_tokens`
) {
return new Response(JSON.stringify({ token: "installation-token" }), {
status: 201,
headers: { "content-type": "application/json" },
});
}
if (
url ===
"https://api.github.com/installation/repositories?per_page=100&page=1"
) {
return new Response(JSON.stringify({ repositories }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
throw new Error(`Unexpected provider request: ${url}`);
}) as typeof globalThis.fetch;
const context = createService(
new FakeChatSdkRuntime(),
providerFetch,
deferredSchedule
? {
...overrides,
scheduleDeferredWork: (task) => {
if (setupComplete) deferredSchedule(task);
else setImmediate(task);
},
}
: overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "github",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in GitHub",
},
"owner-user",
);
const { webhookSecret } = await context.service.generateSetupSecret(
endpoint.id,
"owner-user",
);
await recordGitHubWebhookVerification(
context.service,
endpoint.publicId,
webhookSecret,
);
if (registerWithManifest)
await context.service.startGitHubRegistration(endpoint.id, "owner-user", "Maya");
if (connectExistingApp) {
const credentials = { appId: String(appRegistrationId), privateKey, webhookSecret };
if (interruptAppVault) {
// Fail the real vault write after App identity has been durably claimed.
await db.execute(sql.raw("CREATE FUNCTION github_wizard_fail_vault() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Simulated App vault failure'; END $$"));
await db.execute(sql.raw("CREATE TRIGGER github_wizard_fail_vault BEFORE INSERT ON company_secrets FOR EACH ROW WHEN (lower(NEW.key) LIKE '%privatekey%') EXECUTE FUNCTION github_wizard_fail_vault()"));
try {
await expect(context.service.storeGitHubApp(endpoint.id, "owner-user", credentials)).rejects.toThrow();
expect(await context.service.githubWizard.advance(endpoint.id, "owner-user")).toMatchObject({ state: "recovery" });
expect((await context.service.get(endpoint.id)).setup.github).toMatchObject({ initialSetupPending: true, initialRepositoryImportPending: true });
expect((await context.service.get(endpoint.id)).setup.github?.initialRepositoriesImported).not.toBe(true);
expect(await context.service.listResources(endpoint.id)).toHaveLength(0);
expect((await githubChatManagementService(db, providerFetch).configuration(endpoint.id, "owner-user")).revision).toBe(0);
} finally {
await db.execute(sql.raw("DROP TRIGGER github_wizard_fail_vault ON company_secrets"));
await db.execute(sql.raw("DROP FUNCTION github_wizard_fail_vault()"));
}
}
await context.service.storeGitHubApp(endpoint.id, "owner-user", credentials);
}
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: {
appId: useVerifiedAppId ? String(appRegistrationId) : "123456",
privateKey,
},
},
"owner-user",
);
if (!useVerifiedAppId) {
const [configured] = await readChatEndpointsById(endpoint.id);
// Legacy transport fixtures already have explicit tool authority. Do not
// save a review configuration: that would switch their admission model.
await db.transaction((tx) => syncGitHubBotTools(tx, configured!, "owner-user", true));
}
const resources = await context.service.listResources(endpoint.id);
if (!registerWithManifest && !connectExistingApp)
await context.service.replaceResources(endpoint.id, [
{ id: resources[0]!.id, enabled: true },
]);
setupComplete = true;
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive GitHub callbacks");
return {
...context,
endpoint,
callbacks,
webhookSecret,
providerFetch,
responseComments,
responseWrites,
webhookSyncRequests,
privateKey,
setSupplementalProviderFetch(value: typeof supplementalProviderFetch) {
supplementalProviderFetch = value;
},
setWebhookSyncResponse(value: (() => Promise<Response>) | null) {
webhookSyncResponse = value;
},
setInstallationId(value: number) {
installationId = value;
},
setAdditionalInstallationIds(value: number[]) {
additionalInstallationIds = value;
},
setInstallationAvailable(value: boolean) {
installationAvailable = value;
},
setRepositories(
value: Array<{
id: number;
full_name: string;
html_url: string;
owner: { id: number; login: string };
private: boolean;
}>,
) {
repositories = value;
},
setAppAccess(input: {
permissions?: Record<string, string>;
events?: string[];
}) {
if (input.permissions) appPermissions = input.permissions;
if (input.events) appEvents = input.events;
},
setInstallationAccess(permissions: Record<string, string>) {
installationPermissions = permissions;
},
};
}
async function deliverLegacyGitHubReceipt(
input: Parameters<typeof deliverMessage>[0], service: ChatChannelService,
) {
await deliverMessage(input);
const [delivery] = await db.select().from(chatDeliveries).where(and(
eq(chatDeliveries.endpointId, input.endpointId),
eq(chatDeliveries.providerEventId, `${input.thread.id}:${input.message.id}`),
));
if (!delivery) throw new Error("Expected admitted legacy GitHub delivery");
const fence = delivery.normalizedEvent.runtimeContext as { generation: number; credentialFingerprint: string };
const [action] = await db.insert(chatActions).values({ companyId: delivery.companyId,
endpointId: input.endpointId, deliveryId: delivery.id, kind: "receipt_reaction",
providerActionId: `receipt_reaction:${delivery.id}`, status: "received",
payload: { version: 1, operation: "add", threadId: input.thread.id, messageId: input.message.id,
reaction: "eyes", runtimeGeneration: fence.generation, credentialFingerprint: fence.credentialFingerprint },
}).returning();
await service.processPendingReceiptReactions(1, action.id);
}
function attachFakeGitHubIssueCommentWebhook(input: {
botUsername: string;
callbacks: CreateChatSdkEndpointRuntimeOptions["callbacks"];
endpointId: string;
runtime: FakeEndpointRuntime;
}) {
input.runtime.webhookHook = async (request) => {
const payload = (await request.clone().json()) as {
action?: unknown;
comment?: {
body?: unknown;
created_at?: unknown;
id?: unknown;
updated_at?: unknown;
user?: { id?: unknown; login?: unknown };
};
issue?: { number?: unknown; pull_request?: unknown };
repository?: {
full_name?: unknown;
name?: unknown;
owner?: { login?: unknown };
};
sender?: { id?: unknown; login?: unknown };
};
if (payload.action !== "created") return;
const fullName =
typeof payload.repository?.full_name === "string"
? payload.repository.full_name
: typeof payload.repository?.owner?.login === "string" &&
typeof payload.repository.name === "string"
? `${payload.repository.owner.login}/${payload.repository.name}`
: null;
const issueNumber = payload.issue?.number;
const messageId = payload.comment?.id;
const text = payload.comment?.body;
if (
!fullName ||
typeof issueNumber !== "number" ||
(typeof messageId !== "number" && typeof messageId !== "string") ||
typeof text !== "string"
) {
return;
}
const mentionNames = new Set([
input.botUsername,
input.botUsername.replace(/\[bot\]$/i, ""),
]);
const mentioned = [...mentionNames].some((identity) =>
new RegExp(
`(?<!\\w)@${identity.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`,
"i",
).test(text),
);
const thread = makeThread({
channelId: fullName,
id: payload.issue?.pull_request
? `github:${fullName}:${issueNumber}`
: `github:${fullName}:issue:${issueNumber}`,
name: fullName,
}).thread;
const message = makeMessage({
id: String(messageId),
raw: payload,
text,
mentioned,
userId: String(payload.sender?.id ?? payload.comment?.user?.id ?? "42"),
userName: String(
payload.sender?.login ?? payload.comment?.user?.login ?? "octocat",
),
});
const createdAt = payload.comment?.created_at;
if (typeof createdAt === "string")
message.metadata.dateSent = new Date(createdAt);
await deliverMessage({
callbacks: input.callbacks,
endpointId: input.endpointId,
message,
provider: "github",
thread,
trigger: mentioned ? "mention" : "unaddressed_message",
});
};
}
async function githubPreIngressRecoveryFixture(
event: "issue_comment" | "pull_request_review_comment" = "issue_comment",
replayBarrier?: ChatChannelServiceOptions["githubWebhookReplayBarrier"],
) {
const fixture = await seedCompany();
const deferred: Array<() => void> = [];
const configured = await configuredGitHubEndpoint(
fixture,
{
deferWebhookProcessing: true,
githubWebhookReplayBarrier: replayBarrier,
scheduleDeferredWork: (task) => deferred.push(task),
},
true,
);
const { service, endpoint, runtime, callbacks } = configured;
// Setup admission is covered separately. Recovery is intentionally only
// eligible for an active endpoint with an explicitly enabled repository.
await db
.update(chatEndpoints)
.set({ status: "active" })
.where(eq(chatEndpoints.id, endpoint.id));
const current = await service.get(endpoint.id);
const providerRuntime = runtime.endpoints.get(endpoint.id)!;
attachFakeGitHubIssueCommentWebhook({
botUsername: current.botUsername!,
callbacks,
endpointId: endpoint.id,
runtime: providerRuntime,
});
const guid = randomUUID();
const deliveryId = "9007199254740993";
const webhookUrl = `https://paperclip.example/api/chat-webhooks/${endpoint.publicId}/github`;
const createdAt = new Date(Date.now() - 30_000).toISOString();
const body = `@${current.botUsername} recover the original request ${randomUUID()}`;
const comment = {
id: 9191,
body,
created_at: createdAt,
updated_at: createdAt,
user: { id: 42, login: "octocat", type: "User" },
...(event === "issue_comment"
? {
issue_url:
"https://api.github.com/repos/paperclipai/paperclip/issues/91",
}
: {
pull_request_url:
"https://api.github.com/repos/paperclipai/paperclip/pulls/91",
}),
};
const payload = {
action: "created",
installation: { id: 2468 },
repository: {
id: 97531,
full_name: "paperclipai/paperclip",
name: "paperclip",
owner: { id: 1357, login: "paperclipai" },
},
...(event === "issue_comment"
? { issue: { id: 9190, number: 91 } }
: { pull_request: { id: 9190, number: 91 } }),
comment,
sender: { id: 42, login: "octocat", type: "User" },
};
const original = {
id: deliveryId,
guid,
delivered_at: createdAt,
redelivery: false,
status_code: 502 as number | null,
event,
action: "created",
installation_id: 2468,
repository_id: 97531,
throttled_at: null as string | null,
};
let deliveries = [original];
const extraDetails = new Map<
string,
{ summary: typeof original; payload: unknown }
>();
let historyHasMore = false;
let historyPage = 0;
let canonicalComment = { ...comment };
let beforeList: (() => Promise<void>) | undefined;
let beforePost: (() => Promise<void>) | undefined;
const requests: Array<{ method: string; pathname: string }> = [];
const posts: string[] = [];
const commentPath = `/repos/paperclipai/paperclip/${event === "issue_comment" ? "issues" : "pulls"}/comments/9191`;
// Emit the actual unsafe JSON numeric literal, not a string-only mock.
const json = (value: unknown) =>
new Response(
JSON.stringify(value).replaceAll(`"${deliveryId}"`, deliveryId),
{
status: 200,
headers: { "content-type": "application/json" },
},
);
configured.setSupplementalProviderFetch(async (input, init) => {
const url = new URL(String(input));
const method = init?.method ?? "GET";
const isRecovery =
url.pathname.startsWith("/app/hook/") ||
url.pathname === commentPath ||
url.pathname === "/installation/token";
if (!isRecovery) return undefined;
requests.push({ method, pathname: url.pathname });
if (url.pathname === "/app/hook/config" && method === "GET") {
return json({
url: webhookUrl,
content_type: "json",
insecure_ssl: "0",
});
}
if (url.pathname === "/app/hook/deliveries") {
await beforeList?.();
const response = json(deliveries);
if (historyHasMore)
response.headers.set(
"link",
`<https://api.github.com/app/hook/deliveries?per_page=100&cursor=page${++historyPage}>; rel="next"`,
);
return response;
}
if (url.pathname === `/app/hook/deliveries/${deliveryId}`) {
return json({
...original,
url: webhookUrl,
request: {
headers: { authorization: "private-provider-header-canary" },
payload,
},
response: { payload: "private-proxy-body-canary" },
});
}
const extra = extraDetails.get(
url.pathname.replace(/^\/app\/hook\/deliveries\//, ""),
);
if (extra)
return json({
...extra.summary,
url: webhookUrl,
request: { payload: extra.payload },
});
if (
url.pathname === `/app/hook/deliveries/${deliveryId}/attempts` &&
method === "POST"
) {
posts.push(url.pathname);
await beforePost?.();
return new Response(null, { status: 202 });
}
if (url.pathname === commentPath) return json(canonicalComment);
if (url.pathname === "/installation/token" && method === "DELETE")
return new Response(null, { status: 204 });
return undefined;
});
const checkpoint = () =>
db
.select()
.from(chatSdkState)
.where(
and(
eq(chatSdkState.endpointId, endpoint.id),
eq(chatSdkState.stateKey, "paperclip:github-webhook-recovery:v1"),
),
)
.then((rows) => rows[0]!);
const makeScanDue = async (includeOriginal = true) => {
const state = await checkpoint();
await db
.update(chatSdkState)
.set({
value: {
...(state.value as Record<string, unknown>),
...(includeOriginal
? { floor: new Date(Date.now() - 120_000).toISOString() }
: {}),
nextScanAt: new Date(Date.now() - 1_000).toISOString(),
},
})
.where(eq(chatSdkState.id, state.id));
};
const ingress = () =>
db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpoint.id),
eq(chatActions.providerActionId, `github_webhook_ingress:${guid}`),
),
)
.then((rows) => rows[0]);
const receipt = () =>
db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpoint.id),
eq(chatActions.providerActionId, `github_webhook_recovery:${guid}`),
),
)
.then((rows) => rows[0]);
const callback = (
webhookSecret = configured.webhookSecret,
incomingPayload: unknown = payload,
) =>
service.handleWebhook(
endpoint.publicId,
"github",
signedGitHubWebhookRequest({
delivery: guid,
event,
payload: incomingPayload,
webhookSecret,
url: webhookUrl,
}),
);
const initializedAt = Date.now();
await service.processFailedGitHubWebhookDeliveries(5, endpoint.id);
expect(requests).toEqual([]);
const initial = (await checkpoint()).value as Record<string, unknown>;
expect(initial).toMatchObject({
appId: current.botExternalId,
webhookUrl,
generation: expect.any(Number),
});
expect(Date.parse(String(initial.floor))).toBeGreaterThanOrEqual(
initializedAt,
);
expect(Date.parse(String(initial.nextScanAt))).toBeGreaterThanOrEqual(
initializedAt + 60_000,
);
return {
...configured,
fixture,
body,
guid,
deliveryId,
original,
payload,
providerRuntime,
requests,
posts,
checkpoint,
makeScanDue,
ingress,
receipt,
callback,
deferred,
setDeliveries(value: typeof deliveries) {
deliveries = value;
},
setDetail(summary: typeof original, incomingPayload: unknown) {
extraDetails.set(summary.id, { summary, payload: incomingPayload });
},
setHistoryHasMore(value: boolean) {
historyHasMore = value;
},
setCanonicalComment(value: Partial<typeof comment>) {
canonicalComment = { ...canonicalComment, ...value };
},
setBeforeList(value: typeof beforeList) {
beforeList = value;
},
setBeforePost(value: typeof beforePost) {
beforePost = value;
},
};
}
return { githubWebhookVerificationResponse, recordGitHubWebhookVerification, signedGitHubWebhookRequest, configuredGitHubEndpoint, deliverLegacyGitHubReceipt, attachFakeGitHubIssueCommentWebhook, githubPreIngressRecoveryFixture };
}
export type GitHubHarness = ReturnType<typeof createGitHubHarness>;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,957 @@
// Shared PostgreSQL lifecycle and endpoint seeding harness for chat-channel integration suites.
import { reconcilePersistedRuntimeServicesOnStartup, readWorkspaceRuntimeIdleWork } from "../../services/workspace-runtime.js";
import { conflict } from "../../errors.js";
import { readIdleLocalWork } from "../../services/idle-local-work.js";
import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js";
import { chatGitHubRegistrations, chatGitHubReviews } from "@paperclipai/db";
import { createHash, createHmac, randomUUID } from "node:crypto";
import { mkdirSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { Readable } from "node:stream";
import request from "supertest";
import { and, eq, inArray, notInArray, or, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest";
import { agents, agentWakeupRequests, authUsers, chatActions, chatConversations, chatDeliveries, chatEndpointLeases, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, chatMessageLinks, chatPublications, chatTeamsFileTransfers, companies, companyMemberships, createDb, applyPendingMigrations, closeCheckpointDb, closeFileStorageDb, closeLivenessDb, heartbeatRuns, issueComments, issues, principalPermissionGrants, toolConnections } from "@paperclipai/db";
import { type ChatProvider } from "@paperclipai/shared";
import type { Message, Thread } from "chat";
import { chatChannelService, type ChatChannelServiceOptions, type ChatChannelService } from "../../services/chat-channels.js";
import type { CreateChatSdkEndpointRuntimeOptions, ChatSdkMessageTrigger, ChatSdkRuntime } from "../../services/chat-sdk-runtime.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { issueService } from "../../services/issues.js";
import type { StorageService } from "../../storage/types.js";
import { resolveChatRunPresentationAuthorizationReason } from "../../services/chat-run-publications.js";
import { startEmbeddedPostgresTestDatabase } from "../helpers/embedded-postgres.js";
import { type TestDb, slackProtocolCapture, slackProtocolDatabaseUrl, externalTestDatabaseUrl, FakeChatSdkRuntime, uniqueDiscordApplicationId, fakeSlackFetch, fakeDiscordFetch, fakeTelegramFetch, chatSdkProvider, makeThread, makeMessage } from "./providers.js";
export function createChatChannelHarness() {
let db!: TestDb;
let tempDb: Awaited<
ReturnType<typeof startEmbeddedPostgresTestDatabase>
> | null = null;
const previousKeyFile = process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
const secretsTmpDir = path.join(
os.tmpdir(),
`paperclip-chat-channels-${randomUUID()}`,
);
beforeAll(async () => {
if (slackProtocolDatabaseUrl) await applyPendingMigrations(slackProtocolDatabaseUrl);
mkdirSync(secretsTmpDir, { recursive: true });
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = path.join(
secretsTmpDir,
"master.key",
);
if (!externalTestDatabaseUrl) {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-chat-channels-");
}
// Scheduler tests advance virtual time while PostgreSQL uses real I/O.
// Do not expire or time out its connections on those virtual clock jumps.
db = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString, {
idleTimeoutSeconds: 0, connectTimeoutSeconds: 0, maxLifetimeSeconds: 0,
...(externalTestDatabaseUrl ? { maxConnections: 4 } : {}),
});
// The composed local-probe inventory includes the workspace owner. Match
// server startup on this fresh fixture; never adopt or start a leftover.
const [runtimeState] = await db.execute<{ configured: boolean }>(sql`SELECT
EXISTS (SELECT 1 FROM workspace_runtime_services)
OR EXISTS (SELECT 1 FROM project_workspaces)
OR EXISTS (SELECT 1 FROM execution_workspaces) AS configured`);
expect(runtimeState.configured).toBe(false);
expect(await reconcilePersistedRuntimeServicesOnStartup(db)).toEqual({
reconciled: 0, adopted: 0, stopped: 0, backfilled: 0, restarted: 0,
restartFailed: 0, exposureReservationDrift: [],
});
expect(readWorkspaceRuntimeIdleWork()).toBe("none");
}, 90_000);
afterAll(async () => {
if (slackProtocolCapture && db) { await closeCheckpointDb(db, 1); await closeFileStorageDb(db, 1); await closeLivenessDb(db, 1); }
await db?.$client.end();
await tempDb?.cleanup();
if (previousKeyFile === undefined)
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
else process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = previousKeyFile;
rmSync(secretsTmpDir, { recursive: true, force: true });
});
// Services scan this file's shared database. Retire each case's fixtures
// after its assertions so another case (or shard order) cannot claim them.
const fixtureCompanies = new Set<string>();
const fixtureServices = new Set<ChatChannelService>();
afterEach(async () => {
try {
await Promise.all([...fixtureServices].map((service) => service.shutdown()));
} finally {
const companyIds = [...fixtureCompanies];
await retireFixtureState(companyIds);
if (companyIds.length > 0) {
// Pausing an endpoint does not remove its rows from global recovery
// selectors. After every assertion and worker shutdown, settle leftover
// fixture work so later cases cannot claim its leases or retry its I/O.
await db.update(chatActions).set({ status: "cancelled" })
.where(and(inArray(chatActions.companyId, companyIds), notInArray(chatActions.status, ["processed", "cancelled"])));
await db.update(chatDeliveries).set({ state: "failed", nextAttemptAt: null })
.where(and(inArray(chatDeliveries.companyId, companyIds), inArray(chatDeliveries.state, ["received", "processing", "retry"])));
await db.update(chatPublications).set({ state: "cancelled", nextAttemptAt: null })
.where(and(inArray(chatPublications.companyId, companyIds), inArray(chatPublications.state, ["pending", "awaiting_consent", "streaming", "retry"])));
}
fixtureServices.clear();
fixtureCompanies.clear();
}
});
async function retireFixtureState(companyIds: string[]) {
if (companyIds.length === 0) return;
// Verifying endpoints can also own receipts. Once a receipt is 60s old,
// another test's global sweep can reclaim it. Retire every live endpoint,
// then release synthetic lease owners after their services have stopped.
await db.update(chatEndpoints).set({ status: "paused" })
.where(and(inArray(chatEndpoints.companyId, companyIds), notInArray(chatEndpoints.status, ["archived", "revoked"])));
await db.delete(chatEndpointLeases)
.where(inArray(chatEndpointLeases.companyId, companyIds));
// The milestone scanner includes paused endpoints with active bindings.
await db.update(chatConversations).set({ state: "completed" })
.where(and(inArray(chatConversations.companyId, companyIds), inArray(chatConversations.state, ["active", "waiting"])));
}
const companyPrefixAttempts = 8;
const freshCompanyPrefix = () => `C${randomUUID().replaceAll("-", "").slice(0, 7).toUpperCase()}`;
async function seedCompany(nextIssuePrefix = freshCompanyPrefix, companyId: string = randomUUID()) {
const assignedAgentId = randomUUID();
const replacementAgentId = randomUUID();
let inserted = false;
// Retired fixtures retain company rows. Retry only the short-prefix unique
// conflict; every other database error must still fail the test immediately.
for (let attempt = 0; attempt < companyPrefixAttempts; attempt += 1) {
const [company] = await db.insert(companies).values({
id: companyId,
name: `Chat Test ${companyId.slice(0, 8)}`,
issuePrefix: nextIssuePrefix(),
requireBoardApprovalForNewAgents: false,
}).onConflictDoNothing({ target: companies.issuePrefix }).returning({ id: companies.id });
if (company) {
inserted = true;
fixtureCompanies.add(companyId);
break;
}
}
if (!inserted) throw new Error(`Could not allocate a chat fixture company prefix after ${companyPrefixAttempts} attempts`);
const now = new Date();
await db
.insert(authUsers)
.values({
id: "owner-user",
name: "Owner User",
email: "owner-user@example.com",
emailVerified: true,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing();
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: "owner-user",
status: "active",
membershipRole: "operator",
});
await db.insert(principalPermissionGrants).values({
companyId,
principalType: "user",
principalId: "owner-user",
permissionKey: "tools:manage_connections",
scope: null,
grantedByUserId: "owner-user",
});
await db.insert(agents).values([
{
id: assignedAgentId,
companyId,
name: "Maya",
role: "engineer",
status: "idle",
adapterType: "paperclip_runner",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
{
id: replacementAgentId,
companyId,
name: "Linus",
role: "engineer",
status: "idle",
adapterType: "paperclip_runner",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
]);
return { companyId, assignedAgentId, replacementAgentId };
}
function readChatConversationsByEndpointId(value: (typeof chatConversations.$inferSelect)["endpointId"]) {
return db.select().from(chatConversations).where(eq(chatConversations.endpointId, value));
}
function readChatEndpointsById(value: (typeof chatEndpoints.$inferSelect)["id"]) {
return db.select().from(chatEndpoints).where(eq(chatEndpoints.id, value));
}
function readIssueCommentsByIssueId(value: (typeof issueComments.$inferSelect)["issueId"]) {
return db.select().from(issueComments).where(eq(issueComments.issueId, value));
}
function readChatDeliveriesByEndpointId(value: (typeof chatDeliveries.$inferSelect)["endpointId"]) {
return db.select().from(chatDeliveries).where(eq(chatDeliveries.endpointId, value));
}
function readChatDeliveriesById(value: (typeof chatDeliveries.$inferSelect)["id"]) {
return db.select().from(chatDeliveries).where(eq(chatDeliveries.id, value));
}
function readHeartbeatRunsById(value: (typeof heartbeatRuns.$inferSelect)["id"]) {
return db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, value));
}
function readIssuesById(value: (typeof issues.$inferSelect)["id"]) {
return db.select().from(issues).where(eq(issues.id, value));
}
function readChatActionsById(value: (typeof chatActions.$inferSelect)["id"]) {
return db.select().from(chatActions).where(eq(chatActions.id, value));
}
function readChatGitHubReviewsByEndpointId(value: (typeof chatGitHubReviews.$inferSelect)["endpointId"]) {
return db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.endpointId, value));
}
function readChatPublicationsByEndpointId(value: (typeof chatPublications.$inferSelect)["endpointId"]) {
return db.select().from(chatPublications).where(eq(chatPublications.endpointId, value));
}
function readChatPublicationsById(value: (typeof chatPublications.$inferSelect)["id"]) {
return db.select().from(chatPublications).where(eq(chatPublications.id, value));
}
function readChatGitHubRegistrationsByEndpointId(value: (typeof chatGitHubRegistrations.$inferSelect)["endpointId"]) {
return db.select().from(chatGitHubRegistrations).where(eq(chatGitHubRegistrations.endpointId, value));
}
function readToolConnectionsById(value: (typeof toolConnections.$inferSelect)["id"]) {
return db.select().from(toolConnections).where(eq(toolConnections.id, value));
}
function readChatConversationsById(value: (typeof chatConversations.$inferSelect)["id"]) {
return db.select().from(chatConversations).where(eq(chatConversations.id, value));
}
function readIssuesByCompanyId(value: (typeof issues.$inferSelect)["companyId"]) {
return db.select().from(issues).where(eq(issues.companyId, value));
}
function readChatPublicationsByCommentId(value: NonNullable<(typeof chatPublications.$inferSelect)["commentId"]>) {
return db.select().from(chatPublications).where(eq(chatPublications.commentId, value));
}
function readChatActionsByProviderActionId(value: (typeof chatActions.$inferSelect)["providerActionId"]) {
return db.select().from(chatActions).where(eq(chatActions.providerActionId, value));
}
function readChatPublicationsByIdempotencyKey(value: (typeof chatPublications.$inferSelect)["idempotencyKey"]) {
return db.select().from(chatPublications).where(eq(chatPublications.idempotencyKey, value));
}
function readHeartbeatRunsByCompanyId(value: (typeof heartbeatRuns.$inferSelect)["companyId"]) {
return db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, value));
}
function readAgentWakeupRequestsById(value: (typeof agentWakeupRequests.$inferSelect)["id"]) {
return db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, value));
}
function readIssueCommentsByCompanyId(value: (typeof issueComments.$inferSelect)["companyId"]) {
return db.select().from(issueComments).where(eq(issueComments.companyId, value));
}
function readChatTeamsFileTransfersById(value: (typeof chatTeamsFileTransfers.$inferSelect)["id"]) {
return db.select().from(chatTeamsFileTransfers).where(eq(chatTeamsFileTransfers.id, value));
}
// A truthy return is not a durable scheduler receipt. These transport tests
// record the same exact receipt identity; real scheduling/coalescing is
// separately exercised by durable-chat-wakeup.test.ts against heartbeat.
function receiptBackedWakeup(
wakeup: ChatChannelServiceOptions["heartbeat"]["wakeup"],
): ChatChannelServiceOptions["heartbeat"]["wakeup"] {
return async (agentId, opts) => {
const result = await wakeup(agentId, opts);
const request = opts.durableChatRequest;
if (request && result !== null && result !== undefined) {
const [existing] = await db
.select({ id: agentWakeupRequests.id })
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, request.id));
if (existing) return result;
await db.transaction(async (tx) => {
await request.authorize(
tx as unknown as Parameters<typeof request.authorize>[0],
);
await tx
.insert(agentWakeupRequests)
.values({
id: request.id,
companyId: request.companyId,
agentId,
source: opts.source ?? "assignment",
triggerDetail: opts.triggerDetail,
reason: opts.reason,
payload: opts.payload,
requestedByActorType: opts.requestedByActorType,
requestedByActorId: opts.requestedByActorId,
idempotencyKey: request.idempotencyKey,
requestedAt: request.requestedAt,
status: "queued",
})
.onConflictDoNothing();
});
}
return result;
};
}
function createService(
runtime = new FakeChatSdkRuntime(),
providerFetch: typeof globalThis.fetch = fakeSlackFetch() as typeof globalThis.fetch,
overrides: Partial<
Pick<
ChatChannelServiceOptions,
| "credentialMutationLeaseRenewalIntervalMs"
| "deferWebhookProcessing"
| "discordGatewayEventBarrier"
| "discordGatewayMessageAdmissionBarrier"
| "discordRootThreadTransportBarrier"
| "discordGatewayLeaseRenewalIntervalMs"
| "discordGatewayLeaseTtlMs"
| "discordGatewayLeaseWaitMs"
| "githubWebhookAuthenticationBarrier"
| "githubWebhookReplayBarrier"
| "githubWebhookResponseBudgetMs"
| "publicationTransportPreparationBarrier"
| "renderSlackAvatar"
| "slackManaged"
| "publicBaseUrl"
| "webhookPublicBaseUrl"
| "nativeBotIdentityClaimBarrier"
| "confirmationResolutionPersistBarrier"
| "conversationLeaseRenewalIntervalMs"
| "questionFormOpenAuthorizationBarrier"
| "questionResolutionPersistBarrier"
| "reactionLinkPreflightBarrier"
| "reactionReplayConversationLockBarrier"
| "reactionReplayEndpointLockBarrier"
| "receiptReactionTransportBarrier"
| "resolveNativeQuestion"
| "renewCredentialMutationLease"
| "renewConversationDeliveryLease"
| "renewDiscordGatewayLease"
| "scheduleDeferredWork"
| "slackTaskAdmissionClaimBarrier"
| "slackSessionSyncSelectionBarrier"
| "setupSecretActivityLogger"
| "setupSecretCredentialPersistBarrier"
| "setupSecretFinalOwnershipBarrier"
| "setupTestActivationBarrier"
| "storage"
| "reachAuthorizationBarrier"
>
> & {
cancelRun?: NonNullable<
ChatChannelServiceOptions["heartbeat"]["cancelRun"]
>;
wakeup?: ChatChannelServiceOptions["heartbeat"]["wakeup"];
} = {},
) {
const {
cancelRun: cancelRunOverride,
wakeup: wakeupOverride,
...serviceOverrides
} = overrides;
const wakeup = vi.fn<ChatChannelServiceOptions["heartbeat"]["wakeup"]>(wakeupOverride ?? (async () => ({ accepted: true })));
const cancelRun = vi.fn<NonNullable<ChatChannelServiceOptions["heartbeat"]["cancelRun"]>>(
cancelRunOverride ?? (async () => ({ status: "cancelled" })),
);
const service = chatChannelService(db, {
fetch: providerFetch,
heartbeat: { cancelRun, wakeup: receiptBackedWakeup(wakeup) },
publicBaseUrl: "https://paperclip.example",
runtime: runtime as unknown as ChatSdkRuntime,
...serviceOverrides,
});
fixtureServices.add(service);
return { cancelRun, runtime, service, wakeup };
}
function createStorageService() {
const objects = new Map<string, Buffer>();
const putFile = vi.fn<StorageService["putFile"]>(async (input) => {
if (!Buffer.isBuffer(input.body)) throw new Error("Expected a buffered attachment body");
const objectKey = `${input.namespace}/${randomUUID()}-${input.originalFilename ?? "attachment"}`;
objects.set(objectKey, input.body);
return {
provider: "local_disk",
objectKey,
contentType: input.contentType,
byteSize: input.body.length,
sha256: createHash("sha256").update(input.body).digest("hex"),
originalFilename: input.originalFilename,
};
});
const storage: StorageService = {
provider: "local_disk",
putFile,
getObject: vi.fn(async (_companyId, objectKey) => {
const body = objects.get(objectKey);
if (!body) throw new Error(`Missing test object ${objectKey}`);
return {
stream: Readable.from([body]),
contentLength: body.length,
};
}),
headObject: vi.fn(async (_companyId, objectKey) => ({
exists: objects.has(objectKey),
contentLength: objects.get(objectKey)?.length,
})),
deleteObject: vi.fn(async (_companyId, objectKey) => {
objects.delete(objectKey);
}),
};
return { objects, putFile, storage };
}
async function retirePublicationFixture(
service: ChatChannelService,
endpointId: string,
) {
try {
await service.shutdown();
} finally {
// Workers scan the shared fixture database. Local shutdown alone leaves
// future retries/receipts eligible for the next test's service. Preserve
// their asserted audit state, but retire this endpoint after assertions.
await db
.update(chatEndpoints)
.set({ status: "paused" })
.where(
and(
eq(chatEndpoints.id, endpointId),
eq(chatEndpoints.status, "active"),
),
);
}
}
async function recordSlackUrlVerification(
service: ChatChannelService,
publicId: string,
signingSecret = "test-signing-secret",
) {
const response = await service.handleWebhook(
publicId,
"slack",
signedSlackWebhookRequest({
url: `https://paperclip.example/api/chat-webhooks/${publicId}/slack`,
contentType: "application/json",
body: JSON.stringify({ type: "url_verification", challenge: "verified-challenge" }),
signingSecret,
}),
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ challenge: "verified-challenge" });
}
function signedSlackWebhookRequest(input: {
url: string;
body: string;
contentType: string;
signingSecret?: string;
timestamp?: string;
}) {
const timestamp = input.timestamp ?? String(Math.floor(Date.now() / 1000));
const signature = createHmac(
"sha256",
input.signingSecret ?? "test-signing-secret",
)
.update(`v0:${timestamp}:${input.body}`)
.digest("hex");
return new Request(input.url, {
method: "POST",
headers: {
"content-type": input.contentType,
"x-slack-request-timestamp": timestamp,
"x-slack-signature": `v0=${signature}`,
},
body: input.body,
});
}
async function chatWakeContext(input: {
endpointId: string;
issueId: string;
provider: ChatProvider;
providerMessageId: string;
}) {
const wakeCommentId = await db
.select({ commentId: chatMessageLinks.commentId })
.from(chatMessageLinks)
.where(
and(
eq(chatMessageLinks.endpointId, input.endpointId),
eq(chatMessageLinks.providerMessageId, input.providerMessageId),
eq(chatMessageLinks.direction, "inbound"),
),
)
.then((rows) => rows[0]?.commentId ?? null);
if (!wakeCommentId) {
throw new Error(
`Expected inbound comment link ${input.providerMessageId}`,
);
}
return {
issueId: input.issueId,
source: `chat:${input.provider}`,
wakeCommentId,
wakeCommentIds: [wakeCommentId],
};
}
async function addSelectedChatFinal(input: {
agentId: string;
body: string;
companyId: string;
issueId: string;
runId: string;
}) {
const authorizationReason =
await resolveChatRunPresentationAuthorizationReason(db, {
companyId: input.companyId,
issueId: input.issueId,
runId: input.runId,
});
return issueService(db).addComment(
input.issueId,
input.body,
{ agentId: input.agentId, runId: input.runId },
{ authorType: "agent", authorizationReason },
);
}
async function qualifySetupRoundTrip(
service: ChatChannelService,
endpointId: string,
userId = "U-EXTERNAL",
) {
const endpoint = await service.get(endpointId);
let conversation: typeof chatConversations.$inferSelect | undefined;
await vi.waitFor(async () => {
conversation = await readChatConversationsByEndpointId(endpointId)
.then((rows) => rows.at(-1));
expect(conversation).toBeDefined();
});
if (!conversation) throw new Error("Expected setup conversation");
const fakeRuntime = service.runtime as unknown as FakeChatSdkRuntime;
const callbacks = fakeRuntime.configurations.get(endpointId)?.callbacks;
if (!callbacks) throw new Error("Expected setup callbacks");
const { thread } = makeThread({
id: conversation.externalThreadId,
channelId: conversation.externalConversationId,
isDM: conversation.isDirectMessage,
name: conversation.externalLabel,
});
const setupFollowUpMessageId = `setup-follow-up-${randomUUID()}`;
await callbacks.onMessage({
endpointId,
provider: chatSdkProvider(endpoint.provider),
thread,
message: makeMessage({
id: setupFollowUpMessageId,
text: "Setup follow-up",
mentioned: endpoint.provider === "slack",
userId,
}),
trigger:
endpoint.provider === "telegram"
? "direct_message"
: "subscribed_message",
});
const contextSnapshot = await chatWakeContext({
endpointId,
issueId: conversation.issueId,
provider: endpoint.provider,
providerMessageId: setupFollowUpMessageId,
});
const runId = randomUUID();
await db.insert(heartbeatRuns).values({
id: runId,
companyId: endpoint.companyId,
agentId: endpoint.assignedAgentId,
status: "succeeded",
contextSnapshot,
});
if (endpoint.provider === "github") {
// Generic transport fixtures supply a confirmed task-tool receipt.
// Real tool execution and provider I/O have separate integration tests.
await db.insert(chatActions).values({ companyId: endpoint.companyId, endpointId, conversationId: conversation.id,
kind: "github_review_publication", providerActionId: `github_publication:setup:${runId}`,
payload: { operation: "comment", session: { companyId: endpoint.companyId, agentId: endpoint.assignedAgentId, issueId: conversation.issueId, runId } },
status: "processed", result: { id: "setup-tool-reply", url: "https://github.com/test/setup-tool-reply" } });
} else {
await addSelectedChatFinal({
agentId: endpoint.assignedAgentId,
body: "Setup round trip complete",
companyId: endpoint.companyId,
issueId: conversation.issueId,
runId,
});
}
await service.processPendingPublications();
const providerRuntime = fakeRuntime.endpoints.get(endpointId);
if (providerRuntime) providerRuntime.posts.length = 0;
return setupFollowUpMessageId;
}
async function configuredSlackEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: { allowUnlinkedPeople?: boolean; linkedBoardUser?: boolean; requireAtMention?: boolean } & Partial<
Pick<
ChatChannelServiceOptions,
| "credentialMutationLeaseRenewalIntervalMs"
| "conversationLeaseRenewalIntervalMs"
| "deferWebhookProcessing"
| "fetch"
| "questionFormOpenAuthorizationBarrier"
| "questionResolutionPersistBarrier"
| "reactionLinkPreflightBarrier"
| "reactionReplayConversationLockBarrier"
| "reactionReplayEndpointLockBarrier"
| "receiptReactionTransportBarrier"
| "reachAuthorizationBarrier"
| "resolveNativeQuestion"
| "renewCredentialMutationLease"
| "renewConversationDeliveryLease"
| "scheduleDeferredWork"
| "slackTaskAdmissionClaimBarrier"
| "storage"
>
> & {
cancelRun?: NonNullable<
ChatChannelServiceOptions["heartbeat"]["cancelRun"]
>;
wakeup?: ChatChannelServiceOptions["heartbeat"]["wakeup"];
} = {},
) {
const context = createService(
new FakeChatSdkRuntime(),
overrides.fetch ?? (fakeSlackFetch() as typeof globalThis.fetch),
overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "slack",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in Slack",
},
"owner-user",
);
// Most transport fixtures exercise restricted guests explicitly. Production
// Slack creation defaults to linked accounts only (covered separately).
await context.service.update(endpoint.id, {
allowUnlinkedPeople: overrides.allowUnlinkedPeople ?? true,
// Existing transport tests explicitly exercise the optional unmentioned mode.
requireAtMention: overrides.requireAtMention ?? false,
}, "owner-user");
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: {
botToken: "xoxb-test-token",
signingSecret: "test-signing-secret",
},
},
"owner-user",
);
if (overrides.linkedBoardUser) {
const [principal] = await db.insert(chatExternalPrincipals).values({ companyId: fixture.companyId, provider: "slack", providerAccountId: "T-PAPERCLIP", externalId: "UBOARD" }).returning();
await db.insert(chatIdentityLinks).values({ companyId: fixture.companyId, endpointId: endpoint.id, principalId: principal.id, paperclipUserId: "owner-user", status: "linked", confirmedAt: new Date() });
}
await recordSlackUrlVerification(context.service, endpoint.publicId);
await context.service.configure(
endpoint.id,
{ action: "verify" },
"owner-user",
);
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive endpoint callbacks");
return { ...context, endpoint, callbacks };
}
async function configuredTeamsEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: Partial<
Pick<
ChatChannelServiceOptions,
| "deferWebhookProcessing"
| "githubWebhookAuthenticationBarrier"
| "githubWebhookResponseBudgetMs"
| "scheduleDeferredWork"
| "storage"
| "reachAuthorizationBarrier"
>
> = {},
) {
const context = createService(
new FakeChatSdkRuntime(),
(async () =>
new Response(JSON.stringify({ access_token: "teams-test-access" }), {
status: 200,
headers: { "content-type": "application/json" },
})) as typeof globalThis.fetch,
overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "microsoft-teams",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in Teams",
},
"owner-user",
);
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: {
clientId: randomUUID(),
tenantId: randomUUID(),
clientSecret: "teams-test-secret",
},
},
"owner-user",
);
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive Teams callbacks");
return { ...context, endpoint, callbacks };
}
async function configuredTelegramEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: Parameters<typeof createService>[2] = {},
) {
const context = createService(
new FakeChatSdkRuntime(),
fakeTelegramFetch() as typeof globalThis.fetch,
overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "telegram",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in Telegram",
},
"owner-user",
);
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: { botToken: "123456:telegram-interaction-test" },
},
"owner-user",
);
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive Telegram callbacks");
return { ...context, endpoint, callbacks };
}
async function configuredDiscordEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: Parameters<typeof createService>[2] = {},
) {
const applicationId = uniqueDiscordApplicationId();
const context = createService(
new FakeChatSdkRuntime(),
fakeDiscordFetch(applicationId) as typeof globalThis.fetch,
overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "discord",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in Discord",
},
"owner-user",
);
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: {
applicationId,
botToken: "discord-secret",
guildId: "1457808928258658549",
},
},
"owner-user",
);
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive Discord callbacks");
return { ...context, endpoint, callbacks };
}
async function recoverDiscordCommands(service: ChatChannelService) {
const onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
try {
await service.registerCommandWork(coordinator, () => true).ready;
expect(onError).not.toHaveBeenCalled();
} finally {
await coordinator.stop();
}
}
async function deliverMessage(input: {
callbacks: CreateChatSdkEndpointRuntimeOptions["callbacks"];
endpointId: string;
message: Message;
provider?: ChatProvider;
providerUpdateId?: number;
thread: Thread;
trigger: ChatSdkMessageTrigger;
}) {
await input.callbacks.onMessage({
endpointId: input.endpointId,
provider: chatSdkProvider(input.provider ?? "slack"),
providerUpdateId: input.providerUpdateId,
thread: input.thread,
message: input.message,
trigger: input.trigger,
});
}
async function waitForProcessedReceiptRemoval(
endpointId: string,
receipt: { threadId: string; messageId: string; emoji: string },
) {
// Publication settlement only schedules this non-critical provider I/O.
// A sweep skips an action already owned by a fresh processing worker.
const removals = await db
.select({
id: chatActions.id,
deliveryId: chatActions.deliveryId,
providerActionId: chatActions.providerActionId,
})
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpointId),
eq(chatActions.kind, "receipt_reaction"),
sql`${chatActions.payload}->>'operation' = 'remove'`,
sql`${chatActions.payload}->>'threadId' = ${receipt.threadId}`,
sql`${chatActions.payload}->>'messageId' = ${receipt.messageId}`,
sql`${chatActions.payload}->>'reaction' = ${receipt.emoji}`,
),
);
expect(removals).toHaveLength(1);
const removal = removals[0]!;
expect(removal.deliveryId).toEqual(expect.any(String));
expect(removal.providerActionId).toBe(
`receipt_reaction_remove:${removal.deliveryId}`,
);
await vi.waitFor(async () => {
await expect(
db
.select({ status: chatActions.status })
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpointId),
eq(chatActions.id, removal.id),
),
),
).resolves.toEqual([{ status: "processed" }]);
});
return removal.id;
}
async function registeredIdleProbeState() {
let state: string | undefined;
await readIdleLocalWork({ diagnostic: (reason, value) => { if (reason === "local.registered_probes") state = value; } });
return state;
}
async function linkLifecycleFixtureActor(input: {
companyId: string;
endpointId: string;
externalId: string;
}) {
const [principal] = await db
.select()
.from(chatExternalPrincipals)
.where(
and(
eq(chatExternalPrincipals.companyId, input.companyId),
eq(chatExternalPrincipals.externalId, input.externalId),
),
);
if (!principal) throw new Error("Expected original lifecycle principal");
await db.insert(chatIdentityLinks).values({
companyId: input.companyId,
endpointId: input.endpointId,
principalId: principal.id,
paperclipUserId: "owner-user",
status: "linked",
confirmedAt: new Date(),
});
await db
.update(chatEndpoints)
.set({ allowUnlinkedPeople: false })
.where(
and(
eq(chatEndpoints.companyId, input.companyId),
eq(chatEndpoints.id, input.endpointId),
),
);
return principal.id;
}
return {
get db(): TestDb { return db; },
get connectionString(): string { return externalTestDatabaseUrl ?? tempDb!.connectionString; },
fixtureCompanies, fixtureServices, retireFixtureState, companyPrefixAttempts, freshCompanyPrefix, seedCompany, readChatConversationsByEndpointId, readChatEndpointsById, readIssueCommentsByIssueId, readChatDeliveriesByEndpointId, readChatDeliveriesById, readHeartbeatRunsById, readIssuesById, readChatActionsById, readChatGitHubReviewsByEndpointId, readChatPublicationsByEndpointId, readChatPublicationsById, readChatGitHubRegistrationsByEndpointId, readToolConnectionsById, readChatConversationsById, readIssuesByCompanyId, readChatPublicationsByCommentId, readChatActionsByProviderActionId, readChatPublicationsByIdempotencyKey, readHeartbeatRunsByCompanyId, readAgentWakeupRequestsById, readIssueCommentsByCompanyId, readChatTeamsFileTransfersById, receiptBackedWakeup, createService, createStorageService, retirePublicationFixture, recordSlackUrlVerification, signedSlackWebhookRequest, chatWakeContext, addSelectedChatFinal, qualifySetupRoundTrip, configuredSlackEndpoint, configuredTeamsEndpoint, configuredTelegramEndpoint, configuredDiscordEndpoint, recoverDiscordCommands, deliverMessage, waitForProcessedReceiptRemoval, registeredIdleProbeState, linkLifecycleFixtureActor,
};
}
export type ChatChannelHarness = ReturnType<typeof createChatChannelHarness>;
@@ -0,0 +1,857 @@
// Shared fake chat provider runtimes, fetch mocks, and Express app builders.
import { resolveExternalTestDatabaseUrl } from "../helpers/external-test-database.js";
import { randomUUID } from "node:crypto";
import path from "node:path";
import express from "express";
import request from "supertest";
import { describe, vi } from "vitest";
import { agents, createDb } from "@paperclipai/db";
import { type ChatProvider } from "@paperclipai/shared";
import type { Attachment, Author, Message, Thread } from "chat";
import { errorHandler } from "../../middleware/index.js";
import { createChatWebhookDiagnostics, type ChatWebhookDiagnosticEvent } from "../../services/chat-webhook-diagnostics.js";
import { chatChannelRoutes, chatWebhookRoutes } from "../../routes/chat-channels.js";
import { type ChatChannelService } from "../../services/chat-channels.js";
import type { CreateChatSdkEndpointRuntimeOptions, ChatSdkEndpointRuntime, ChatSdkProvider } from "../../services/chat-sdk-runtime.js";
import type { TelegramDraftControl } from "../../services/chat-telegram-draft-stop.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { githubAttachmentLocator, rehydrateGitHubPublicAttachment } from "../../services/chat-github-attachments.js";
import { getEmbeddedPostgresTestSupport } from "../helpers/embedded-postgres.js";
export const historyTestDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_HISTORY_TEST_DATABASE_URL");
export const slackProtocolCapture = process.env.PAPERCLIP_SLACK_PROTOCOL_CAPTURE === "1";
export const slackProtocolDatabaseUrl = slackProtocolCapture ? resolveExternalTestDatabaseUrl("PAPERCLIP_SLACK_TEST_DATABASE_URL") : undefined;
if (slackProtocolCapture && !slackProtocolDatabaseUrl) throw new Error("Slack protocol capture requires an explicit dedicated test database");
export const externalTestDatabaseUrl = slackProtocolDatabaseUrl ?? historyTestDatabaseUrl ?? process.env.PAPERCLIP_TEST_DATABASE_URL;
export const embeddedPostgresSupport = externalTestDatabaseUrl
? { supported: true }
: await getEmbeddedPostgresTestSupport();
export const describeEmbeddedPostgres = embeddedPostgresSupport.supported
? describe
: describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping chat-channel integration tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
export type TestDb = ReturnType<typeof createDb>;
export class FakeEndpointRuntime {
readonly initialize = vi.fn(async () => {
await this.initializeHook?.(this.options.endpointId);
});
readonly shutdown = vi.fn(async () => undefined);
readonly posts: Array<{
threadId: string;
text: string;
attachments?: unknown[];
chunks?: string[];
files?: unknown[];
}> = [];
readonly edits: Array<{
threadId: string;
messageId: string;
text: string;
}> = [];
readonly editAttempts: Array<{
threadId: string;
messageId: string;
}> = [];
readonly reactions: Array<{
threadId: string;
messageId: string;
emoji: string;
}> = [];
readonly reactionErrors: Error[] = [];
readonly removedReactions: Array<{
threadId: string;
messageId: string;
emoji: string;
}> = [];
readonly removeReactionErrors: Error[] = [];
readonly rehydratedAttachmentDescriptors: unknown[] = [];
readonly postResultIds: string[] = [];
readonly slackFileReceiptLookups: Array<{
fileIds: string[];
threadId: string;
}> = [];
readonly slackFileReceiptResultIds: Array<string | null> = [];
slackFileReceiptCaptureRepeats = 1;
slackFilePublicationAttempts = 0;
slackFilePostAcceptanceError: Error | null = null;
slackFilePostAcceptanceHook: (() => Promise<void>) | undefined;
slackFileReceiptHook: (() => Promise<void>) | undefined;
readonly ensuredDiscordRootThreads: Array<{
channelId: string;
content: string;
messageId: string;
}> = [];
readonly recordedMicrosoftTeamsRoutes: Array<{
threadId: string;
serviceUrl: unknown;
}> = [];
private nextPostId = 0;
postError: Error | null = null;
editError: Error | null = null;
postHook: (() => Promise<void>) | undefined;
webhookHook: ((request: Request) => Promise<void>) | undefined;
webhookRequest: Request | null = null;
webhookResponse = new Response("accepted", {
status: 202,
headers: { "x-chat-test": "accepted" },
});
constructor(
private readonly options: CreateChatSdkEndpointRuntimeOptions,
private readonly attachmentBodies: Map<string, Buffer>,
private readonly initializeHook?: (endpointId: string) => Promise<void>,
) {}
get provider() {
return this.options.providerConfig.provider;
}
async handleWebhook(request: Request) {
this.webhookRequest = request;
await this.webhookHook?.(request);
return this.webhookResponse;
}
async ensureDiscordRootThread(input: {
channelId: string;
content: string;
messageId: string;
}) {
this.ensuredDiscordRootThreads.push(input);
}
async recordMicrosoftTeamsRoute(threadId: string, serviceUrl: unknown) {
this.recordedMicrosoftTeamsRoutes.push({ threadId, serviceUrl });
}
async postSlackFilePublication(
threadId: string,
message: unknown,
onUploadAccepted: (receipt: {
version: 1;
channelId: string;
fileIds: string[];
threadTs: string | null;
}) => Promise<void>,
) {
this.slackFilePublicationAttempts += 1;
await this.postHook?.();
if (this.postError) throw this.postError;
const parts = threadId.split(":");
const files =
message &&
typeof message === "object" &&
"files" in message &&
Array.isArray((message as { files?: unknown }).files)
? (message as { files: unknown[] }).files
: [];
for (
let attempt = 0;
attempt < this.slackFileReceiptCaptureRepeats;
attempt += 1
) {
await onUploadAccepted({
version: 1,
channelId: parts[1] ?? "",
fileIds: files.map((_, index) => `FTEST${index + 1}`),
threadTs: parts[2] || null,
});
}
await this.slackFilePostAcceptanceHook?.();
if (this.slackFilePostAcceptanceError) {
throw this.slackFilePostAcceptanceError;
}
const postHook = this.postHook;
this.postHook = undefined;
try {
return await this.thread(threadId).post(message);
} finally {
this.postHook = postHook;
}
}
async resolveSlackFileUploadReceipt(threadId: string, fileIds: string[]) {
this.slackFileReceiptLookups.push({
fileIds: [...fileIds],
threadId,
});
await this.slackFileReceiptHook?.();
return this.slackFileReceiptResultIds.shift() ?? null;
}
acceptsProviderScope(raw: unknown) {
if (this.options.providerConfig.provider !== "microsoft-teams") return true;
const expected = this.options.providerConfig.credentials.appTenantId;
if (!expected || !raw || typeof raw !== "object") return Boolean(!expected);
const payload = raw as {
conversation?: { tenantId?: unknown };
channelData?: { tenant?: { id?: unknown } };
recipient?: { isTargeted?: unknown };
};
if (payload.recipient?.isTargeted === true) return false;
const tenantIds = [
payload.conversation?.tenantId,
payload.channelData?.tenant?.id,
].filter((value): value is string => typeof value === "string");
return (
tenantIds.length > 0 && tenantIds.every((value) => value === expected)
);
}
async applySlackReceiptReaction(input: {
operation: "add" | "remove";
threadId: string;
messageId: string;
reaction: "eyes";
}) {
const adapter = this.thread(input.threadId).adapter;
if (input.operation === "add")
await adapter.addReaction(
input.threadId,
input.messageId,
input.reaction,
);
else
await adapter.removeReaction(
input.threadId,
input.messageId,
input.reaction,
);
}
async applyGitHubReceiptReaction(
input: Parameters<ChatSdkEndpointRuntime["applyGitHubReceiptReaction"]>[0],
assertCurrent: () => Promise<void>,
) {
await assertCurrent();
await this.applySlackReceiptReaction(input);
return input.githubReceipt ?? { botUserId: "9001", reactionId: "880012" };
}
async streamTelegramDraft(
threadId: string,
stream: AsyncIterable<string>,
control: TelegramDraftControl,
) {
if (!(await control.beforeDraft()) || !(await control.beforeFinal()))
return { paperclipDraftStopped: true as const };
return this.thread(threadId).post(stream);
}
thread(threadId: string) {
const parts = threadId.split(":");
const channelId =
this.options.providerConfig.provider === "discord"
? (parts[2] ?? threadId)
: (parts[1] ?? threadId);
const isTelegramDirectMessage =
this.options.providerConfig.provider === "telegram" &&
/^\d+$/.test(channelId);
return {
id: threadId,
channelId,
isDM: isTelegramDirectMessage || /^D[A-Z0-9-]*$/i.test(channelId),
channel: {
id: channelId,
name: "command-thread",
},
adapter: {
addReaction: async (
reactionThreadId: string,
messageId: string,
emoji: string,
) => {
const error = this.reactionErrors.shift();
if (error) throw error;
this.reactions.push({
threadId: reactionThreadId,
messageId,
emoji,
});
},
removeReaction: async (
reactionThreadId: string,
messageId: string,
emoji: string,
) => {
const error = this.removeReactionErrors.shift();
if (error) throw error;
this.removedReactions.push({
threadId: reactionThreadId,
messageId,
emoji,
});
},
editMessage: async (
editedThreadId: string,
messageId: string,
editedMessage: unknown,
) => {
this.editAttempts.push({ threadId: editedThreadId, messageId });
if (this.editError) throw this.editError;
if (this.postError) throw this.postError;
const text =
editedMessage &&
typeof editedMessage === "object" &&
"markdown" in editedMessage
? String((editedMessage as { markdown: unknown }).markdown)
: JSON.stringify(editedMessage);
this.edits.push({
threadId: editedThreadId,
messageId,
text,
});
return { id: messageId, threadId: editedThreadId };
},
},
startTyping: async () => undefined,
subscribe: async () => undefined,
post: async (message: unknown) => {
await this.postHook?.();
if (this.postError) throw this.postError;
let text: string;
let attachments: unknown[] | undefined;
let chunks: string[] | undefined;
let files: unknown[] | undefined;
if (typeof message === "string") text = message;
else if (
message &&
typeof message === "object" &&
Symbol.asyncIterator in message
) {
chunks = [];
for await (const chunk of message as AsyncIterable<unknown>)
chunks.push(String(chunk));
text = chunks.join("");
} else if (
message &&
typeof message === "object" &&
"markdown" in message
) {
text = String((message as { markdown: unknown }).markdown);
} else text = JSON.stringify(message);
if (
message &&
typeof message === "object" &&
"attachments" in message &&
Array.isArray((message as { attachments?: unknown }).attachments)
) {
attachments = (message as { attachments: unknown[] }).attachments;
}
if (
message &&
typeof message === "object" &&
"files" in message &&
Array.isArray((message as { files?: unknown }).files)
) {
files = (message as { files: unknown[] }).files;
}
this.posts.push({
threadId,
text,
...(attachments ? { attachments } : {}),
...(chunks ? { chunks } : {}),
...(files ? { files } : {}),
});
this.nextPostId += 1;
return {
id: this.postResultIds.shift() ?? `outbound-${this.nextPostId}`,
threadId,
};
},
};
}
attachmentRecoveryDescriptor(attachment: Attachment) {
if (this.options.providerConfig.provider === "github") {
const locator = githubAttachmentLocator(attachment);
return locator
? {
version: 1,
provider: "github",
attachment: { type: attachment.type, name: attachment.name },
locator,
}
: null;
}
const recoveryKey = attachment.fetchMetadata?.testRecoveryKey;
if (typeof recoveryKey !== "string") return null;
return {
version: 1,
provider: this.options.providerConfig.provider,
attachment: {
type: attachment.type,
name: attachment.name,
mimeType: attachment.mimeType,
size: attachment.size,
},
locator: { kind: "test_attachment", recoveryKey },
};
}
parseTelegramCommandMessage(raw: unknown): Message | null {
if (
this.options.providerConfig.provider !== "telegram" ||
!raw ||
typeof raw !== "object"
)
return null;
const document = (raw as { document?: Record<string, unknown> }).document;
const recoveryKey =
typeof document?.file_id === "string" ? document.file_id : null;
if (!recoveryKey || !document) return null;
return makeMessage({
id: `telegram-command:${recoveryKey}`,
text: "",
attachments: [
{
type: "file",
name:
typeof document.file_name === "string"
? document.file_name
: undefined,
mimeType:
typeof document.mime_type === "string"
? document.mime_type
: undefined,
size:
typeof document.file_size === "number"
? document.file_size
: undefined,
fetchMetadata: { testRecoveryKey: recoveryKey },
} as Attachment,
],
});
}
parseMicrosoftTeamsMessage(raw: unknown): Message | null {
if (
this.options.providerConfig.provider !== "microsoft-teams" ||
!raw ||
typeof raw !== "object"
)
return null;
const activity = raw as {
conversation?: { conversationType?: unknown; id?: unknown };
from?: { aadObjectId?: unknown; id?: unknown; name?: unknown };
id?: unknown;
serviceUrl?: unknown;
text?: unknown;
};
if (
typeof activity.id !== "string" ||
typeof activity.conversation?.id !== "string" ||
typeof activity.serviceUrl !== "string"
)
return null;
const conversationType = activity.conversation.conversationType;
const legacyIsDM = !activity.conversation.id.startsWith("19:");
const explicitIsDM = conversationType === "personal";
const includeConversationType =
(conversationType === "channel" ||
conversationType === "groupChat" ||
conversationType === "personal") &&
explicitIsDM !== legacyIsDM;
const threadId = [
"teams",
Buffer.from(activity.conversation.id).toString("base64url"),
...(includeConversationType ? [conversationType] : []),
].join(":");
const userId =
typeof activity.from?.id === "string" ? activity.from.id : "unknown";
const userName =
typeof activity.from?.name === "string" ? activity.from.name : userId;
return {
...makeMessage({
id: activity.id,
raw,
text: typeof activity.text === "string" ? activity.text : "",
userId,
userName,
}),
threadId,
} as Message;
}
rehydrateAttachment(
descriptor: unknown,
source?: { threadId: string; messageId: string },
): Attachment | null {
this.rehydratedAttachmentDescriptors.push(descriptor);
if (!descriptor || typeof descriptor !== "object") return null;
const value = descriptor as {
version?: unknown;
provider?: unknown;
attachment?: Attachment;
locator?: { kind?: unknown; recoveryKey?: unknown };
};
if (
this.options.providerConfig.provider === "github" &&
value.provider === "github" &&
value.version === 1 &&
source
) {
return rehydrateGitHubPublicAttachment(value.locator, source);
}
if (
value.version !== 1 ||
value.provider !== this.options.providerConfig.provider ||
value.locator?.kind !== "test_attachment" ||
typeof value.locator.recoveryKey !== "string" ||
!value.attachment
) {
return null;
}
const body = this.attachmentBodies.get(value.locator.recoveryKey);
if (!body) return null;
return {
...value.attachment,
fetchData: async () => body,
fetchMetadata: { testRecoveryKey: value.locator.recoveryKey },
} as Attachment;
}
async resolveGitHubAttachmentComment(
_request: { url: string; accept: string },
_signal: AbortSignal,
): Promise<unknown> {
return null;
}
}
export class FakeChatSdkRuntime {
readonly endpoints = new Map<string, FakeEndpointRuntime>();
readonly configurations = new Map<
string,
CreateChatSdkEndpointRuntimeOptions
>();
initializeHook: ((endpointId: string) => Promise<void>) | undefined;
replaceCount = 0;
constructor(readonly attachmentBodies: Map<string, Buffer> = new Map()) {}
get(endpointId: string) {
return this.endpoints.get(endpointId) ?? null;
}
hasUnsettledLifecycle() { return false; }
async replaceEndpoint(options: CreateChatSdkEndpointRuntimeOptions) {
this.replaceCount += 1;
this.configurations.set(options.endpointId, options);
const endpoint = new FakeEndpointRuntime(
options,
this.attachmentBodies,
this.initializeHook,
);
this.endpoints.set(options.endpointId, endpoint);
return endpoint;
}
async removeEndpoint(endpointId: string) {
const endpoint = this.endpoints.get(endpointId);
if (!endpoint) return false;
this.endpoints.delete(endpointId);
await endpoint.shutdown();
return true;
}
async shutdown() {
await Promise.all(
[...this.endpoints.values()].map(async (endpoint) => endpoint.shutdown()),
);
this.endpoints.clear();
}
}
export const TEST_SLACK_BOT_SCOPES =
"app_mentions:read,assistant:write,channels:history,channels:read,chat:write,commands,files:read,files:write,groups:history,groups:read,im:history,im:read,mpim:history,mpim:read,reactions:read,reactions:write,users:read";
export const discordApplicationPrefix = 1_400_000_000_000_000_000n +
BigInt(`0x${randomUUID().replaceAll("-", "").slice(0, 12)}`) * 1000n;
export let discordApplicationSequence = 0n;
export function uniqueDiscordApplicationId() {
discordApplicationSequence += 1n;
return (discordApplicationPrefix + discordApplicationSequence).toString();
}
export function fakeSlackFetch(botId = `U-BOT-${randomUUID()}`) {
return (input: string | URL | Request, init?: RequestInit) => {
const url = String(input);
const args = new URLSearchParams(String(init?.body ?? new URL(url).search));
if (url === "https://slack.com/api/auth.test") {
return Promise.resolve(
new Response(
JSON.stringify({
ok: true,
team_id: "T-PAPERCLIP",
team: "Paperclip Test",
user_id: botId,
user: `maya-${botId.slice(-8)}`,
}),
{
status: 200,
headers: {
"content-type": "application/json",
"x-oauth-scopes": TEST_SLACK_BOT_SCOPES,
},
},
),
);
}
if (url.startsWith("https://slack.com/api/conversations.list")) {
return Promise.resolve(
new Response(
JSON.stringify({
ok: true,
channels: [],
response_metadata: { next_cursor: "" },
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
}
if (url.startsWith("https://slack.com/api/conversations.info")) {
const channelId = args.get("channel");
return Promise.resolve(
new Response(
JSON.stringify({
ok: true,
channel: {
id: channelId,
name: channelId?.toLowerCase(),
is_member: true,
is_archived: false,
},
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
}
if (url === "https://slack.com/api/users.info") {
return Promise.resolve(Response.json({ ok: true, user: { id: args.get("user"), team_id: "T-PAPERCLIP" } }));
}
if (url === "https://slack.com/api/agents.sessions.setStatus") {
return Promise.resolve(Response.json({ ok: true }));
}
throw new Error(`Unexpected provider request: ${url}`);
};
}
export function fakeDiscordFetch(
applicationId: string,
guildId = "1457808928258658549",
) {
return async (input: string | URL | Request) => {
const path = new URL(String(input)).pathname;
const responses: Record<string, unknown> = {
"/api/v10/users/@me": {
id: applicationId,
username: `maya-${applicationId.slice(-8)}`,
global_name: "Maya",
bot: true,
},
"/api/v10/oauth2/applications/@me": {
id: applicationId,
name: "Maya",
flags: 1 << 18,
},
[`/api/v10/guilds/${guildId}`]: { id: guildId, name: "Clawd" },
[`/api/v10/guilds/${guildId}/members/${applicationId}`]: {
roles: ["222222222222222222"],
user: { id: applicationId },
},
[`/api/v10/guilds/${guildId}/roles`]: [
{ id: "222222222222222222", permissions: "309237763136" },
],
[`/api/v10/guilds/${guildId}/channels`]: [
{
id: "333333333333333333",
name: "agent-lab",
position: 1,
type: 0,
},
],
};
return new Response(JSON.stringify(responses[path]), {
status: path in responses ? 200 : 404,
headers: { "content-type": "application/json" },
});
};
}
export function fakeTelegramFetch(
botId = Number.parseInt(randomUUID().replaceAll("-", "").slice(0, 12), 16),
) {
return async (input: string | URL | Request) => {
const url = String(input);
if (url.endsWith("/getMe")) {
return new Response(
JSON.stringify({
ok: true,
result: {
id: botId,
username: `paperclip_${botId}_bot`,
first_name: "Paperclip Test",
},
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
}
if (url.endsWith("/getWebhookInfo")) {
return new Response(JSON.stringify({ ok: true, result: { url: "" } }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
if (
url.endsWith("/setWebhook") ||
url.endsWith("/setMyCommands") ||
url.endsWith("/deleteWebhook") ||
url.endsWith("/deleteMyCommands")
) {
return new Response(JSON.stringify({ ok: true, result: true }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
throw new Error(`Unexpected provider request: ${url}`);
};
}
export function chatSdkProvider(provider: ChatProvider): ChatSdkProvider {
if (provider === "agentmail" || provider === "speko") throw new Error(`${provider} has no Chat SDK runtime`);
return provider;
}
export function wizardStoreApp(service: ChatChannelService) {
return (
endpointId: string,
userId: string,
credentials: Record<string, string>,
managementContext?: Parameters<ChatChannelService["storeGitHubApp"]>[4],
) => service.storeGitHubApp(endpointId, userId, credentials, "manifest", managementContext);
}
export function makeThread(input: {
channelId: string;
id: string;
isDM?: boolean;
name?: string;
}) {
const addReaction = vi.fn(async () => undefined);
const startTyping = vi.fn(async () => undefined);
const subscribe = vi.fn(async () => undefined);
const postEphemeral = vi.fn(async (_user?: unknown, _message?: unknown, _options?: unknown) => ({
id: `thread-ephemeral-${randomUUID()}`,
threadId: input.id,
usedFallback: false,
}));
const post = vi.fn(async () => ({
id: `thread-post-${randomUUID()}`,
threadId: input.id,
}));
const thread = {
id: input.id,
channelId: input.channelId,
isDM: input.isDM ?? false,
channel: { id: input.channelId, name: input.name ?? input.channelId },
adapter: { addReaction },
startTyping,
subscribe,
post,
postEphemeral,
} as unknown as Thread;
return {
thread,
addReaction,
startTyping,
subscribe,
post,
postEphemeral,
};
}
export function makeMessage(input: {
attachments?: Attachment[];
id: string;
raw?: unknown;
text: string;
mentioned?: boolean;
userId?: string;
userName?: string;
}) {
return {
id: input.id,
raw: input.raw,
text: input.text,
isMention: input.mentioned ?? false,
attachments: input.attachments ?? [],
metadata: { dateSent: new Date(), edited: false },
author: {
userId: input.userId ?? "U-EXTERNAL",
userName: input.userName ?? "alex",
fullName: "Alex External",
isBot: false,
isMe: false,
isSystem: false,
} satisfies Author,
} as unknown as Message;
}
export function boardActor(companyId: string, userId = "owner-user") {
return {
type: "board" as const,
source: "session" as const,
userId,
isInstanceAdmin: false,
companyIds: [companyId],
memberships: [{ companyId, status: "active", membershipRole: "operator" }],
};
}
export function routesApp(
db: TestDb,
companyId: string,
service: ChatChannelService,
userId = "owner-user",
) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = boardActor(companyId, userId);
next();
});
app.use(
"/api",
chatChannelRoutes(db, {
heartbeat: { wakeup: async () => undefined },
service,
}),
);
app.use(errorHandler);
return app;
}
export function webhookApp(
service: ChatChannelService,
diagnostics?: (event: ChatWebhookDiagnosticEvent) => void,
) {
const app = express();
if (diagnostics) app.use(createChatWebhookDiagnostics({ emit: diagnostics }));
app.use(express.raw({ type: "*/*" }));
app.use(chatWebhookRoutes(service));
app.use(errorHandler);
return app;
}
@@ -0,0 +1,905 @@
// Shared retry and committed-response recovery fixture builders.
import { requestTaskRetry } from "../../services/task-retry.js";
import { withQueuedCommentIdsInWakePayload } from "../../services/issue-queued-comment-queue.js";
import { createSystemRecovery } from "../../services/system-recovery-state.js";
import { githubChatManagementService } from "../../services/chat-github-management.js";
import { githubResponseCommentService } from "../../services/chat-github-response-comments.js";
import { chatGitHubConfigurations } from "@paperclipai/db";
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, eq, sql } from "drizzle-orm";
import { beforeAll, expect, vi } from "vitest";
import { agents, agentWakeupRequests, chatActions, chatDeliveries, chatEndpointResources, chatExternalPrincipals, chatMessageLinks, chatPublications, completionContracts, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, issues, nativeRunResults, nativeRunFinalizations, environmentLeases } from "@paperclipai/db";
import { type ChatProvider } from "@paperclipai/shared";
import { errorHandler } from "../../middleware/index.js";
import { issueRoutes } from "../../routes/issues.js";
import { type ChatChannelService } from "../../services/chat-channels.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { heartbeatService } from "../../services/heartbeat.js";
import { githubPublicAttachmentsFromMessage } from "../../services/chat-github-attachments.js";
import * as attachmentEgress from "../../services/remote-http-fetch.js";
import type { PrpStructuredRunResult, PrpTerminalState } from "../../vendor/paperclip-runner/index.js";
import { finalizeNativeRun, repairCommittedNativeChatResponse } from "../../services/native-runtime/native-run-finalizer.js";
import { NativeRunCoordinatorStore } from "../../services/native-runtime/native-run-coordinator-store.js";
import { PaperclipControlPlanePort } from "../../services/native-runtime/paperclip-control-plane-port.js";
import { type TestDb, makeThread, makeMessage, boardActor } from "./providers.js";
import type { ChatChannelHarness } from "./harness.js";
import type { GitHubHarness } from "./github-harness.js";
export function createRetryFixtures(h: ChatChannelHarness, gh: GitHubHarness) {
let db!: TestDb;
beforeAll(() => { db = h.db; });
const { seedCompany, readChatConversationsByEndpointId, readIssuesById, readChatPublicationsByEndpointId, readAgentWakeupRequestsById, createStorageService, chatWakeContext, configuredSlackEndpoint, configuredTeamsEndpoint, configuredTelegramEndpoint, configuredDiscordEndpoint, deliverMessage, linkLifecycleFixtureActor } = h;
const { configuredGitHubEndpoint } = gh;
type SharedEndpointProgress = {
fixture: Awaited<ReturnType<typeof seedCompany>>;
configured: Awaited<ReturnType<typeof configuredTelegramEndpoint>> | Awaited<ReturnType<typeof configuredSlackEndpoint>>;
suffix: string;
};
async function failedChatRetryFixture(
provider: "slack" | "telegram" | "github",
externalActorId?: string,
linkedOriginalActor = false,
githubUnavailableFile = false,
currentGitHubPr = false,
shared?: SharedEndpointProgress,
) {
// Keep the policy under which the source was admitted. Inserting an
// upgraded GitHub policy after receipt correctly invalidates retry proof.
const context = await safeNativeProgressFixture(
provider,
shared?.suffix ?? "91",
"channel",
externalActorId,
linkedOriginalActor,
githubUnavailableFile,
false,
currentGitHubPr,
shared,
);
const [issue] = await readIssuesById(context.conversation.issueId);
const [action] = await db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.conversationId, context.conversation.id),
eq(chatActions.kind, "inbound_wakeup"),
),
);
const [receipt] = await readAgentWakeupRequestsById(action.id);
const runId = randomUUID();
await db.insert(heartbeatRuns).values({
id: runId,
companyId: context.fixture.companyId,
agentId: context.fixture.assignedAgentId,
status: "failed",
errorCode: "adapter_failed",
finishedAt: new Date(),
wakeupRequestId: receipt.id,
contextSnapshot: {
issueId: issue.id,
taskKey: issue.identifier,
source: `chat:${provider}`,
wakeCommentId: action.payload.commentId,
wakeCommentIds: [action.payload.commentId],
},
});
await db
.update(agentWakeupRequests)
.set({ status: "failed", runId })
.where(eq(agentWakeupRequests.id, receipt.id));
await db
.update(issues)
.set({
description: "ORIGINAL task, not the failed request",
status: "blocked",
executionRunId: null,
})
.where(eq(issues.id, issue.id));
return { ...context, issue, action, receipt, runId };
}
async function currentGitHubTaskRetryFixture(withPending = false, pendingCount = 1) {
const f = await failedChatRetryFixture("github", "42", true);
const companyId = f.fixture.companyId, issueId = f.issue.id;
await githubResponseCommentService(db, f.providerFetch).tryAcknowledge(f.action.deliveryId!);
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId,
nativePhase: "terminal_failure", runnerProfileJson: {} }).where(eq(heartbeatRuns.id, f.runId));
await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId: f.runId, phase: "terminal_failure" });
await db.insert(heartbeatRunEvents).values({ companyId, agentId: f.fixture.assignedAgentId, runId: f.runId,
seq: 1, eventType: "native.local_process_stopped", payload: { processPid: 999999999, processGroupId: null } });
let pending: typeof chatActions.$inferSelect | undefined;
if (withPending) {
for (let index = 0; index < pendingCount; index++) {
await deliverMessage({ callbacks: f.runtime.configurations.get(f.endpoint.id)!.callbacks,
endpointId: f.endpoint.id, provider: "github", thread: f.thread.thread,
message: makeMessage({ id: String(990092 + index), text: `@maya continue saved follow-up ${index}`, userId: "42", mentioned: true }),
trigger: "mention" });
const [{ source }] = await db.select({ source: chatActions }).from(chatActions)
.innerJoin(chatDeliveries, eq(chatDeliveries.id, chatActions.deliveryId)).where(and(
eq(chatActions.conversationId, f.conversation.id), eq(chatActions.kind, "inbound_wakeup"),
eq(chatDeliveries.providerEventId, `${f.thread.thread.id}:${990092 + index}`)));
pending ??= source;
await db.update(agentWakeupRequests).set({ status: "deferred_issue_execution", runId: null })
.where(eq(agentWakeupRequests.id, source.id));
await githubResponseCommentService(db, f.providerFetch).tryAcknowledge(source.deliveryId!);
}
}
const [originalDelivery] = await db.select().from(chatDeliveries).where(eq(chatDeliveries.id, f.action.deliveryId!));
await db.update(agents).set({ adapterType: "paperclip_runner", status: "running",
runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } })
.where(eq(agents.id, f.fixture.assignedAgentId));
await db.insert(heartbeatRuns).values({ companyId, agentId: f.fixture.assignedAgentId,
status: "running", startedAt: new Date() });
f.wakeup.mockImplementation(heartbeatService(db).wakeup);
return { ...f, pending, originalDelivery };
}
async function busyChatRetryHttpFixture(withPending = false) {
const f = await currentGitHubTaskRetryFixture(withPending);
const originalPublications = await readChatPublicationsByEndpointId(f.endpoint.id);
const { issueRoutes } = await import("../../routes/issues.js");
const companyId = f.fixture.companyId, issueId = f.issue.id;
const app = express();
app.use(express.json());
app.use((req, _res, next) => { req.actor = boardActor(companyId); next(); });
app.use("/api", issueRoutes(db, createStorageService().storage, { chatRunRetries: f.service }));
app.use(errorHandler);
let release = () => {};
const held = new Promise<void>(resolve => { release = resolve; });
let acquired = () => {};
const locked = new Promise<void>(resolve => { acquired = resolve; });
const holding = db.transaction(async tx => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`chat-identity:${companyId}:${f.action.principalId}`}, 0))`);
acquired();
await held;
});
await locked;
f.wakeup.mockClear();
return { ...f, app, companyId, issueId, originalPublications,
releaseIdentity: async () => { release(); await holding; } };
}
async function successfulGitHubQueuedInputFixture() {
const f = await currentGitHubTaskRetryFixture(true);
const companyId = f.fixture.companyId, issueId = f.issue.id;
const [saved] = await readAgentWakeupRequestsById(f.pending!.id);
await db.update(agentWakeupRequests).set({ payload: withQueuedCommentIdsInWakePayload(saved.payload,
[String(f.pending!.payload.commentId)]) }).where(eq(agentWakeupRequests.id, saved.id));
const contractId = randomUUID(), resultId = randomUUID();
await db.insert(completionContracts).values({ id: contractId, companyId, issueId, revision: 1,
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", risk: "standard",
completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal", contractJson: {},
canonicalSha256: contractId, createdByActorType: "system", createdByActorId: "test" });
await db.update(heartbeatRuns).set({ status: "succeeded", errorCode: null, nativePhase: "committed",
completionContractId: contractId }).where(eq(heartbeatRuns.id, f.runId));
const [result] = await db.insert(nativeRunResults).values({ id: resultId, companyId, issueId, runId: f.runId,
completionContractId: contractId, serverFingerprint: resultId, schemaStatus: "accepted", canonicalSha256: resultId,
resultJson: { terminal: { runTerminalState: "succeeded" }, summary: "Earlier review remains saved" } }).returning();
await db.update(nativeRunFinalizations).set({ phase: "committed", resultId }).where(eq(nativeRunFinalizations.runId, f.runId));
await db.update(agentWakeupRequests).set({ status: "completed" }).where(eq(agentWakeupRequests.id, f.receipt.id));
const input = { db, companyId, issueId, actorId: "owner-user", actorSource: "cloud_tenant",
observedRunId: f.runId, idempotencyKey: randomUUID(), prepareChatRetry: f.service.prepareFailedChatRunRetry };
return { ...f, input, result };
}
async function deferredFailedRetryNoticeFixture(wakeOnDemand = true) {
const context = await failedChatRetryFixture("telegram", undefined, true);
const companyId = context.fixture.companyId, issueId = context.issue.id, leaseId = randomUUID();
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId,
nativePhase: "terminal_failure", runnerProfileJson: {},
resultJson: { workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: {
schema: "paperclip.workspace-restore-recovery.v1", runId: context.runId, leaseIds: [leaseId],
} },
}).where(eq(heartbeatRuns.id, context.runId));
await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId: context.runId, phase: "terminal_failure" });
await db.insert(environmentLeases).values({ id: leaseId, companyId, issueId,
heartbeatRunId: context.runId, provider: "daytona", providerLeaseId: randomUUID(),
status: "pending_cleanup", cleanupStatus: "failed", leasePolicy: "retain_on_failure",
metadata: { remoteCwd: "/home/daytona/paperclip-workspace", pendingCleanupInFlight: false },
});
await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId,
kind: "active_run_watchdog", status: "resolved", ownerType: "system",
cause: "native_continuation_requires_reconciliation", fingerprint: randomUUID(),
nextAction: "Verify and preserve the retained source before continuing.",
evidence: { runId: context.runId, automaticRecovery: { replay: "blocked" },
workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [leaseId] },
historicalWorkspaceSource: { schema: "paperclip.historical-workspace-source.v1", runId: context.runId, leaseIds: [leaseId] },
systemRecovery: { ...createSystemRecovery(context.runId), state: "exhausted", attempts: 2, retriesUsed: 1,
attemptId: randomUUID(), firstFailureAt: Date.now() - 1000, deadlineAt: Date.now() + 60_000,
preservationOperationIds: [randomUUID()] },
},
});
const retry = await requestTaskRetry({ db, companyId, issueId, actorId: "owner-user",
actorSource: "cloud_tenant", observedRunId: context.runId, idempotencyKey: randomUUID(),
prepareChatRetry: context.service.prepareFailedChatRunRetry });
await db.update(agents).set({ adapterType: "paperclip_runner", status: "running",
runtimeConfig: { heartbeat: { wakeOnDemand, maxConcurrentRuns: 1 } },
}).where(eq(agents.id, context.fixture.assignedAgentId));
await db.insert(heartbeatRuns).values({ companyId, agentId: context.fixture.assignedAgentId,
status: "running", startedAt: new Date() });
context.wakeup.mockImplementation(heartbeatService(db).wakeup);
return { ...context, retry, admit: () => context.service.processFailedChatRunRetry(retry.chatActionId!) };
}
async function failedReviewedGitHubRetryFixture() {
const context = await failedChatRetryFixture("github");
await db
.update(issues)
.set({ status: "in_review" })
.where(eq(issues.id, context.issue.id));
await db
.update(heartbeatRuns)
.set({
errorCode: "setup_failed",
error: "reviewed_chat_execution_binding_not_authorized",
startedAt: new Date(Date.now() - 10),
finishedAt: new Date(),
// Admission captures the prior display/session identity before any
// execution starts. It is not evidence of a turn for this new run.
sessionIdBefore: "prior-provider-session",
})
.where(eq(heartbeatRuns.id, context.runId));
await db.insert(heartbeatRunEvents).values({
companyId: context.fixture.companyId,
agentId: context.fixture.assignedAgentId,
runId: context.runId,
seq: 1,
eventType: "error",
stream: "system",
level: "error",
message: "reviewed_chat_execution_binding_not_authorized",
});
return context;
}
async function safeNativeProgressFixture(
provider: ChatProvider,
suffix: string,
teamsSurface: "channel" | "personal" = "channel",
externalActorId?: string,
linkedOriginalActor = false,
githubUnavailableFile = false,
upgradedGitHub = true,
currentGitHubPr = false,
shared?: SharedEndpointProgress,
) {
const fixture = shared?.fixture ?? await seedCompany();
const configured = shared?.configured ?? (
provider === "slack"
? await configuredSlackEndpoint(fixture)
: provider === "github"
? await configuredGitHubEndpoint(
fixture,
githubUnavailableFile
? { storage: createStorageService().storage }
: {},
)
: provider === "discord"
? await configuredDiscordEndpoint(fixture)
: provider === "microsoft-teams"
? await configuredTeamsEndpoint(fixture)
: await configuredTelegramEndpoint(fixture));
const { callbacks, endpoint, runtime, service } = configured;
const telegramChatId = `77113${suffix.padStart(3, "0")}`;
const teamsConversationId = `19:safe-progress-${suffix}@thread.${teamsSurface === "channel" ? "tacv2" : "v2"}`;
const teamsServiceUrl = "https://smba.trafficmanager.net/amer/";
const messageId =
provider === "slack"
? `1789000${suffix}.100001`
: provider === "github"
? `9900${suffix}`
: provider === "discord"
? `55555555555556${suffix.padStart(3, "0")}`
: provider === "microsoft-teams"
? `17400000${suffix.padStart(5, "0")}`
: `${telegramChatId}:101`;
const thread =
provider === "slack"
? makeThread({
channelId: `C-SAFE-PROGRESS-${suffix}`,
id: `slack:C-SAFE-PROGRESS-${suffix}:${messageId}`,
name: `safe-progress-${suffix}`,
})
: provider === "github"
? makeThread({
channelId: currentGitHubPr ? "paperclipai/paperclip" : "github:paperclipai/paperclip",
id: currentGitHubPr ? `github:paperclipai/paperclip:${700 + Number(suffix)}` : `github:paperclipai/paperclip:issue:${700 + Number(suffix)}`,
name: "paperclipai/paperclip",
})
: provider === "discord"
? makeThread({
channelId: `33333333333334${suffix.padStart(3, "0")}`,
id: `discord:1457808928258658549:33333333333334${suffix.padStart(3, "0")}:${messageId}`,
name: `safe-progress-${suffix}`,
})
: provider === "microsoft-teams"
? makeThread({
channelId: `teams:${Buffer.from(teamsConversationId).toString("base64url")}:${Buffer.from(teamsServiceUrl).toString("base64url")}`,
id: `teams:${Buffer.from(`${teamsConversationId}${teamsSurface === "channel" ? `;messageid=${messageId}` : ""}`).toString("base64url")}:${Buffer.from(teamsServiceUrl).toString("base64url")}`,
isDM: teamsSurface === "personal",
name: `safe-progress-${suffix}`,
})
: makeThread({
channelId: telegramChatId,
id: `telegram:${telegramChatId}`,
isDM: true,
name: `safe-progress-${suffix}`,
});
if (provider === "microsoft-teams" && teamsSurface === "channel") {
await db.insert(chatEndpointResources).values({
companyId: fixture.companyId,
endpointId: endpoint.id,
type: "channel",
providerResourceId: teamsConversationId,
label: "Native progress channel",
availability: "available",
enabled: true,
});
}
if (linkedOriginalActor) {
const currentEndpoint = await service.get(endpoint.id);
const originalActorId =
externalActorId ??
(provider === "telegram" ? telegramChatId : "U-SAFE-PROGRESS");
await db.insert(chatExternalPrincipals).values({
companyId: fixture.companyId,
provider,
providerAccountId: currentEndpoint.providerAccountId!,
externalId: originalActorId,
kind: "user",
isBot: false,
});
await linkLifecycleFixtureActor({
companyId: fixture.companyId,
endpointId: endpoint.id,
externalId: originalActorId,
});
}
if (provider === "github" && currentGitHubPr) {
const config = await githubChatManagementService(db).configuration(endpoint.id, "owner-user");
await db.insert(chatGitHubConfigurations).values({ companyId: fixture.companyId, endpointId: endpoint.id,
configuration: { ...config.configuration, toolsEnabled: true, defaults: { ...config.configuration.defaults,
invocation: "mentions_only", events: [] } }, updatedByUserId: "owner-user" });
}
const sourceMessage = makeMessage({
id: messageId,
mentioned: !thread.thread.isDM,
text: thread.thread.isDM
? "Show safe progress"
: "@maya show safe progress",
userId:
externalActorId ??
(provider === "telegram" ? telegramChatId : "U-SAFE-PROGRESS"),
});
if (currentGitHubPr) sourceMessage.raw = { action: "created", installation: { id: 2468 },
repository: { id: 97531, full_name: "paperclipai/paperclip" }, issue: { number: 791, pull_request: {} },
sender: { id: 42, login: "octocat", type: "User" }, comment: { id: Number(messageId), body: sourceMessage.text, user: { id: 42 } } };
if (githubUnavailableFile) {
const url =
"https://github.com/user-attachments/files/31967808/private-current.txt";
sourceMessage.text = `@maya inspect only this exact file: [file](${url})`;
Object.assign(sourceMessage, { threadId: thread.thread.id });
sourceMessage.raw = {
type: "issue_comment",
threadType: "issue",
prNumber: 700 + Number(suffix),
repository: { full_name: "paperclipai/paperclip" },
comment: {
id: Number(messageId),
body: sourceMessage.text,
user: { id: 42 },
},
};
sourceMessage.formatted = {
type: "root",
children: [{ type: "link", url, children: [] }],
};
sourceMessage.attachments.push(
...githubPublicAttachmentsFromMessage(sourceMessage),
);
}
await deliverMessage({
callbacks,
endpointId: endpoint.id,
provider,
thread: thread.thread,
message: sourceMessage,
trigger: thread.thread.isDM ? "direct_message" : "mention",
});
const conversations = await readChatConversationsByEndpointId(endpoint.id);
const conversation = shared ? conversations.find(row => row.externalThreadId === thread.thread.id) : conversations[0];
if (!conversation) throw new Error("Expected safe-progress conversation");
const providerRuntime = runtime.endpoints.get(endpoint.id);
if (!providerRuntime) throw new Error("Expected safe-progress runtime");
if (provider === "github" && upgradedGitHub) {
// These fixtures exercise upgraded bots' tool-owned reply model.
const config = await githubChatManagementService(db).configuration(endpoint.id, "owner-user");
await db.insert(chatGitHubConfigurations).values({ companyId: fixture.companyId, endpointId: endpoint.id, configuration: config.configuration, updatedByUserId: "owner-user" });
}
const createRun = async (label: string) => {
const runId = randomUUID();
const baseCreatedAt = new Date(Date.now() - 60_000);
await db.insert(heartbeatRuns).values({
id: runId,
companyId: fixture.companyId,
agentId: fixture.assignedAgentId,
runtimeMode: "native",
status: "running",
contextSnapshot: await chatWakeContext({
endpointId: endpoint.id,
issueId: conversation.issueId,
provider,
providerMessageId: messageId,
}),
});
await db.insert(chatPublications).values({
companyId: fixture.companyId,
endpointId: endpoint.id,
conversationId: conversation.id,
issueId: conversation.issueId,
idempotencyKey: `run:${runId}:working:${endpoint.id}`,
payload: {
text: `Maya is working on ${label}…`,
progressState: "working",
},
state: "pending",
createdAt: baseCreatedAt,
updatedAt: baseCreatedAt,
});
await service.processPendingPublications(100);
return { baseCreatedAt, runId };
};
const addEvent = async (
run: Awaited<ReturnType<typeof createRun>>,
eventType = "item.completed",
seq = 1,
createdAt = new Date(run.baseCreatedAt.getTime() + 30_000 + seq),
) => {
await db.insert(heartbeatRunEvents).values({
companyId: fixture.companyId,
runId: run.runId,
agentId: fixture.assignedAgentId,
seq,
eventType,
message: "PRIVATE native event prose must stay in Paperclip",
payload: {
toolName: "secret_internal_tool",
arguments: { token: "PRIVATE-NATIVE-TOKEN" },
result: "PRIVATE-NATIVE-RESULT",
target: "PRIVATE-NATIVE-TARGET",
},
createdAt,
});
};
return {
addEvent,
conversation,
createRun,
endpoint,
fixture,
messageId,
providerRuntime,
runtime,
service,
thread,
wakeup: configured.wakeup,
providerFetch:
"providerFetch" in configured ? (configured.providerFetch as typeof globalThis.fetch) : undefined,
};
}
async function committedChatResponseRecoveryFixture(
provider: "slack" | "telegram" | "github",
format: "coordinator" | "port" = "coordinator",
githubUnavailableFile = false,
beforeAcceptance?: (
context: Awaited<ReturnType<typeof failedChatRetryFixture>>,
) => Promise<void>,
summary?: (issueId: string) => string,
finalize = true,
shared?: SharedEndpointProgress,
) {
const context = await failedChatRetryFixture(
provider,
provider === "github" ? "42" : undefined,
false,
githubUnavailableFile,
false,
shared,
);
if (provider === "github") {
const config = await githubChatManagementService(db).configuration(context.endpoint.id, "owner-user");
await db.insert(chatGitHubConfigurations).values({ companyId: context.fixture.companyId, endpointId: context.endpoint.id, configuration: config.configuration, updatedByUserId: "owner-user" });
}
await beforeAcceptance?.(context);
const contractId = randomUUID();
const sessionId = randomUUID();
const runnerId = randomUUID();
const contractSha256 = `recovered-response-${randomUUID()}`;
await db.insert(completionContracts).values({
id: contractId,
companyId: context.fixture.companyId,
issueId: context.issue.id,
revision: 1,
schemaVersion: "paperclip.completion-contract.v1",
policyVersion: "phase6-v3",
risk: "low",
completionAuthority: "agent_claim_policy",
incompleteCriteriaPolicy: "preserve_non_terminal",
contractJson: {
revision: "recovered-response-v1",
objective: "Answer the exact message",
criteria: [
{ id: "response", requirement: "Return the requested answer" },
],
},
canonicalSha256: contractSha256,
createdByActorType: "system",
createdByActorId: "test",
});
await db
.update(heartbeatRuns)
.set({
runtimeMode: "native",
nativeIssueId: context.issue.id,
nativeSessionId: sessionId,
runnerInstanceId: runnerId,
completionContractId: contractId,
completionContractSha256: contractSha256,
status: "failed",
errorCode: "adapter_failed",
error: "provider_transport_failed: checkpoint is quarantined",
finishedAt: new Date(),
processPid: 987654,
runnerProfileJson: {
sessionCheckpoint: { retainedEvidence: "do not alter" },
},
})
.where(eq(heartbeatRuns.id, context.runId));
await db
.update(issues)
.set({ status: "in_review", executionRunId: null })
.where(eq(issues.id, context.issue.id));
const result: PrpStructuredRunResult = {
schema: "paperclip.run_result.v1",
reportedWorkDisposition: "yielded",
summary:
summary?.(context.issue.id) ??
"This is the exact accepted answer. I will wait for your next message.",
completionClaim: {
contractRevision: "recovered-response-v1",
objectiveSatisfied: true,
criteria: [
{ criterionId: "response", status: "satisfied", evidenceRefs: [] },
],
remainingWork: [],
},
evidence: [],
verification: [],
attentionRequests: [],
artifacts: [],
continuation: {
kind: "response_wake",
summary: "Wait for the next authorized message.",
idempotencyKey: `wait:${context.runId}`,
},
};
const terminal: PrpTerminalState = {
schema: "paperclip.prp.terminal.v1",
turnTerminalState: "completed",
runTerminalState: "succeeded",
reportedWorkDisposition: "yielded",
workAssessmentId: randomUUID(),
statusDecisionId: randomUUID(),
};
const binding = {
companyId: context.fixture.companyId,
issueId: context.issue.id,
runId: context.runId,
agentId: context.fixture.assignedAgentId,
normalizedSessionId: sessionId,
runnerSourceInstanceId: runnerId,
completionContractId: contractId,
completionContractSha256: contractSha256,
completionContractRevision: "recovered-response-v1",
completionContractCriterionIds: ["response"],
};
if (format === "coordinator") {
await new NativeRunCoordinatorStore(db, binding).completeRun({
result,
terminal,
turnId: `turn-${context.runId}`,
});
} else {
const controlPlaneSourceInstanceId = `control-${context.runId}`;
const port = new PaperclipControlPlanePort(db, {
companyId: binding.companyId,
issueId: binding.issueId,
runId: binding.runId,
agentId: binding.agentId,
sessionId,
completionContractId: contractId,
completionContractSha256: contractSha256,
sourceInstanceId: runnerId,
controlPlaneSourceInstanceId,
});
await port.openRun({
identity: {
companyId: binding.companyId,
issueId: binding.issueId,
runId: binding.runId,
agentId: binding.agentId,
sessionId,
},
backendKind: "mock",
sourceInstanceId: runnerId,
});
await port.completeRun({
result,
terminal,
turnId: `turn-${context.runId}`,
});
await db.insert(heartbeatRunEvents).values({
companyId: binding.companyId,
agentId: binding.agentId,
runId: binding.runId,
seq: 1,
eventType: "run.result.accepted",
sourceInstanceId: controlPlaneSourceInstanceId,
payload: { prpEvent: { sourceKind: "control_plane" } },
});
}
const [acceptedRow] = await db
.select()
.from(nativeRunResults)
.where(eq(nativeRunResults.runId, context.runId));
const accepted = { resultId: acceptedRow.id };
if (finalize) await finalizeNativeRun({
db,
runId: context.runId,
workspaceFinalizeStatus: "succeeded",
});
const [coordinator] = await db
.select()
.from(nativeRunFinalizations)
.where(eq(nativeRunFinalizations.runId, context.runId));
if (finalize) expect(coordinator.phase).toBe("committed");
else expect(coordinator.phase).not.toBe("committed");
await db
.update(heartbeatRuns)
.set({
resultJson: {
finalResponse: "PRIVATE provider narration must not be recovered",
privateTrace: "PRIVATE tool arguments",
},
})
.where(eq(heartbeatRuns.id, context.runId));
const [beforeIssue] = await readIssuesById(context.issue.id);
const repair = () =>
repairCommittedNativeChatResponse(db, {
companyId: context.fixture.companyId,
issueId: context.issue.id,
runId: context.runId,
});
return {
...context,
accepted,
result,
terminal,
binding,
coordinator,
beforeIssue,
repair,
};
}
async function githubOmissionFixture(
unavailable = true,
beforeAcceptance?: Parameters<
typeof committedChatResponseRecoveryFixture
>[3],
summary?: Parameters<typeof committedChatResponseRecoveryFixture>[4],
) {
const egress = vi
.spyOn(attachmentEgress, "guardedRemoteHttpFetch")
.mockResolvedValue(
new Response("private file unavailable", { status: 404 }),
);
try {
const context = await committedChatResponseRecoveryFixture(
"github",
"coordinator",
unavailable,
beforeAcceptance,
summary,
);
return {
...context,
egress,
cleanup: async () => {
try {
await context.service.shutdown();
} finally {
egress.mockRestore();
}
},
};
} catch (error) {
egress.mockRestore();
throw error;
}
}
async function linkedCommittedResponseFailure(
context: Awaited<ReturnType<typeof committedChatResponseRecoveryFixture>>,
runId: string = context.runId,
messageId = "same-run-message",
) {
const [failure] = await db
.insert(chatPublications)
.values({
companyId: context.fixture.companyId,
endpointId: context.endpoint.id,
conversationId: context.conversation.id,
issueId: context.issue.id,
idempotencyKey: `run:${runId}:failed:${context.endpoint.id}`,
payload: {
text: "Maya stopped before completing this turn.",
progressState: "failed",
},
state: "published",
providerMessageId: messageId,
publishedAt: new Date(),
attempts: 1,
})
.returning();
await db.insert(chatMessageLinks).values({
companyId: context.fixture.companyId,
endpointId: context.endpoint.id,
conversationId: context.conversation.id,
publicationId: failure.id,
providerMessageId: messageId,
direction: "outbound",
});
return failure;
}
async function deferredChatQueueFixture(admissionFails = false, beforeAdmission?: (service: ChatChannelService) => Promise<void>, linkedBoardUser = false) {
const fixture = await seedCompany();
let ownerId: string | null = null;
const configured = await configuredSlackEndpoint(fixture, {
linkedBoardUser,
wakeup: async (agentId, opts) => {
if (admissionFails)
throw new Error("PRIVATE admission failure token=do-not-publish");
const request = opts.durableChatRequest!;
await db.transaction(async (tx) => {
await request.authorize(
tx as unknown as Parameters<typeof request.authorize>[0],
);
const [owner] = ownerId
? await tx
.select()
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, ownerId))
: [];
const existingContext = owner?.payload?._paperclipWakeContext as
Record<string, unknown> | undefined;
const commentIds = [
...(Array.isArray(existingContext?.wakeCommentIds)
? existingContext.wakeCommentIds
: []),
request.commentId,
];
const payload = {
...opts.payload,
_paperclipWakeContext: {
...opts.contextSnapshot,
wakeCommentIds: commentIds,
},
};
if (owner)
await tx
.update(agentWakeupRequests)
.set({ payload, coalescedCount: owner.coalescedCount + 1 })
.where(eq(agentWakeupRequests.id, owner.id));
await tx.insert(agentWakeupRequests).values({
id: request.id,
companyId: fixture.companyId,
agentId,
source: "assignment",
reason: "issue_execution_deferred",
status: owner ? "coalesced" : "deferred_issue_execution",
payload: owner
? { ...opts.payload, coalescedIntoWakeupRequestId: owner.id }
: payload,
requestedByActorType: request.requestedByActorType,
requestedByActorId: request.requestedByActorId,
requestedAt: request.requestedAt,
idempotencyKey: request.idempotencyKey,
});
ownerId ??= request.id;
});
return { accepted: true };
},
});
const thread = makeThread({
channelId: "CDEFERREDNOTICE",
id: "slack:CDEFERREDNOTICE:1999000.1",
});
const send = async (id = "1999000.1") =>
deliverMessage({
callbacks: configured.callbacks,
endpointId: configured.endpoint.id,
thread: thread.thread,
message: makeMessage({
id,
text: "@maya exact queued request",
userId: linkedBoardUser ? "UBOARD" : undefined,
mentioned: id === "1999000.1",
}),
trigger: id === "1999000.1" ? "mention" : "subscribed_message",
});
await beforeAdmission?.(configured.service);
await send();
const [conversation] = await readChatConversationsByEndpointId(configured.endpoint.id);
const [action] = await db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, configured.endpoint.id),
eq(chatActions.kind, "inbound_wakeup"),
),
);
const promote = async () => {
const [owner] = await readAgentWakeupRequestsById(ownerId!);
const runId = randomUUID();
const contextSnapshot = owner.payload!._paperclipWakeContext as Record<
string,
unknown
>;
await db.transaction(async (tx) => {
await tx.insert(heartbeatRuns).values({
id: runId,
companyId: fixture.companyId,
agentId: fixture.assignedAgentId,
status: "running",
runtimeMode: "native",
wakeupRequestId: owner.id,
contextSnapshot,
});
await tx
.update(agentWakeupRequests)
.set({ runId, status: "claimed" })
.where(eq(agentWakeupRequests.id, owner.id));
});
return runId;
};
return {
...configured,
action,
conversation,
fixture,
promote,
send,
thread,
};
}
return { failedChatRetryFixture, currentGitHubTaskRetryFixture, busyChatRetryHttpFixture, successfulGitHubQueuedInputFixture, deferredFailedRetryNoticeFixture, failedReviewedGitHubRetryFixture, safeNativeProgressFixture, committedChatResponseRecoveryFixture, githubOmissionFixture, linkedCommittedResponseFailure, deferredChatQueueFixture };
}
export type RetryFixtures = ReturnType<typeof createRetryFixtures>;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,726 @@
import { guardSlackFixtureNetwork } from "../helpers/slack-cloud/transport.js";
import { createChatRuntime } from "../../services/chat-runtime.js";
import { createHash, createHmac, randomUUID } from "node:crypto";
import path from "node:path";
import request from "supertest";
import { and, eq, like, or, sql } from "drizzle-orm";
import { beforeAll, expect, it, vi } from "vitest";
import { activityLog, authUsers, chatActions, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatPublications, chatSdkState, companyMemberships, issueQuestionResponseDeliveries, issueThreadInteractions } from "@paperclipai/db";
import { chatChannelService, type ChatChannelService } from "../../services/chat-channels.js";
import type { InternalSetupState } from "../../services/chat-channels/runtime-types.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { issueThreadInteractionService } from "../../services/issue-thread-interactions.js";
import { type TestDb, slackProtocolCapture, describeEmbeddedPostgres, fakeSlackFetch, makeThread, makeMessage } from "./providers.js";
import { createChatChannelHarness } from "./harness.js";
describeEmbeddedPostgres("chat channels: slack protocol", () => {
const h = createChatChannelHarness();
let db!: TestDb;
beforeAll(() => { db = h.db; });
const { fixtureServices, seedCompany, readChatDeliveriesByEndpointId, readIssueCommentsByCompanyId, receiptBackedWakeup, retirePublicationFixture, qualifySetupRoundTrip, configuredSlackEndpoint, deliverMessage } = h;
it("recovers the visible receipt exactly once after wake acceptance contention", async () => {
const fixture = await seedCompany();
const { callbacks, endpoint, runtime, service, wakeup } =
await configuredSlackEndpoint(fixture);
const first = makeThread({
channelId: "C-RECEIPT-RETRY",
id: "slack:C-RECEIPT-RETRY:1000.1",
name: "receipt-retry",
});
const message = makeMessage({
id: "1000.1",
text: "@maya acknowledge this after retry",
mentioned: true,
});
let releaseLock!: () => void;
let lockEntered!: () => void;
const holdLock = new Promise<void>((resolve) => {
releaseLock = resolve;
});
const entered = new Promise<void>((resolve) => {
lockEntered = resolve;
});
let lockTransaction: Promise<unknown> | undefined;
first.subscribe.mockImplementationOnce(async () => {
lockTransaction = db.transaction(async (tx) => {
await tx
.select({ id: chatEndpoints.id })
.from(chatEndpoints)
.where(eq(chatEndpoints.id, endpoint.id))
.for("update");
lockEntered();
await holdLock;
});
await entered;
});
try {
await expect(
deliverMessage({
callbacks,
endpointId: endpoint.id,
thread: first.thread,
message,
trigger: "mention",
}),
).rejects.toMatchObject({ cause: { code: "55P03" } });
expect(wakeup).not.toHaveBeenCalled();
expect(runtime.endpoints.get(endpoint.id)?.reactions).toEqual([]);
} finally {
releaseLock();
await lockTransaction;
}
await vi.waitFor(
async () => {
await service.processPendingDeliveries();
expect(wakeup).toHaveBeenCalledTimes(1);
expect(runtime.endpoints.get(endpoint.id)?.reactions).toEqual([
{ threadId: first.thread.id, messageId: message.id, emoji: "eyes" },
]);
},
{ timeout: 10_000 },
);
await service.processPendingDeliveries();
expect(wakeup).toHaveBeenCalledTimes(1);
expect(runtime.endpoints.get(endpoint.id)?.reactions).toHaveLength(1);
const [delivery] = await readChatDeliveriesByEndpointId(endpoint.id);
expect(delivery).toMatchObject({ state: "processed" });
expect(
await readIssueCommentsByCompanyId(fixture.companyId),
).toHaveLength(1);
await service.shutdown();
});
it.each(slackProtocolCapture ? ["warm", "command-delayed", "action-delayed", "submission-delayed"] as const : ["warm"] as const)("captures signed Slack forwarding protocol with registered owners (%s)", async mode => {
const network = guardSlackFixtureNetwork({ requirePreload: slackProtocolCapture });
let configured: Awaited<ReturnType<typeof configuredSlackEndpoint>> | undefined;
let routedService: ChatChannelService | undefined;
let actualRuntime: ReturnType<typeof createChatRuntime> | undefined;
let failure: { error: unknown } | undefined;
try {
const fixture = await seedCompany();
configured = await configuredSlackEndpoint(fixture);
const { callbacks, endpoint, runtime, service, wakeup } = configured;
actualRuntime = createChatRuntime();
const custody: Array<{ lane: string; elapsedMs: number; acknowledgedWithin3s: boolean; originalTimestamp: string | null }> = [];
const protocol: Array<{ method: string; triggerAgeMs?: number; outcome: string }> = [];
let triggerCreatedAt = 0;
const channelId = "C-SIGNED-MODAL";
const threadTs = "1788.100";
const externalUserId = `U-MODAL-${randomUUID()}`;
const channel = makeThread({
channelId,
id: `slack:${channelId}:${threadTs}`,
name: "signed-modal",
});
// Existing fixture helpers establish the endpoint, conversation and
// published question. From block_actions onward, signed envelopes pass
// through the real adapter/SDK/runtime and unmocked service callbacks.
// Provider HTTP and the scheduler remain deterministic test boundaries.
await deliverMessage({
callbacks,
endpointId: endpoint.id,
thread: channel.thread,
message: makeMessage({
id: threadTs,
text: "@maya collect deployment details",
mentioned: true,
userId: externalUserId,
}),
trigger: "mention",
});
await qualifySetupRoundTrip(service, endpoint.id, externalUserId);
await service.test(endpoint.id);
const [conversation] = await service.listConversations(endpoint.id);
if (!conversation) throw new Error("Expected signed modal conversation");
const [principal] = await db
.select()
.from(chatExternalPrincipals)
.where(
and(
eq(chatExternalPrincipals.companyId, fixture.companyId),
eq(chatExternalPrincipals.provider, "slack"),
eq(chatExternalPrincipals.externalId, externalUserId),
),
);
const linkedUserId = `signed-modal-user-${randomUUID()}`;
const now = new Date();
await db.insert(authUsers).values({
id: linkedUserId,
name: "Modal Operator",
email: `${linkedUserId}@example.com`,
emailVerified: true,
createdAt: now,
updatedAt: now,
});
await db.insert(companyMemberships).values({
companyId: fixture.companyId,
principalType: "user",
principalId: linkedUserId,
status: "active",
membershipRole: "operator",
});
const intent = await service.createLinkIntent(
endpoint.id,
principal.id,
1_800,
);
const identityToken = new URL(intent.confirmationUrl).searchParams.get(
"token",
);
if (!identityToken) throw new Error("Expected modal identity token");
await service.confirmIdentityLink(identityToken, linkedUserId);
const interaction = await issueThreadInteractionService(db).create(
{ id: conversation.issueId, companyId: fixture.companyId },
{
kind: "ask_user_questions",
continuationPolicy: "wake_assignee",
title: "Deployment details",
payload: {
version: 1,
title: "Deployment details",
submitLabel: "Continue",
questions: [
{
id: "environment",
prompt: "Where should I deploy?",
selectionMode: "single",
required: true,
allowOther: false,
options: [
{ id: "staging", label: "Staging" },
{ id: "production", label: "Production" },
],
},
{
id: "reason",
prompt: "What should the release note say?",
selectionMode: "single",
required: true,
allowOther: true,
options: [
{
id: "__paperclip_text__",
label: "Type an answer",
freeText: true,
},
],
},
],
},
},
{ agentId: fixture.assignedAgentId },
);
runtime.endpoints.get(endpoint.id)!.postResultIds.push("1788.200");
await service.processPendingPublications();
const publication = await db
.select()
.from(chatPublications)
.where(
and(
eq(chatPublications.endpointId, endpoint.id),
eq(chatPublications.conversationId, conversation.id),
),
)
.then((rows) =>
rows.find((row) => row.payload.interactionId === interaction.id),
);
const openAction = publication?.payload.card?.actions?.find(
(action) => action.type === "callback",
);
if (!publication?.providerMessageId || openAction?.type !== "callback") {
throw new Error("Expected published question form action");
}
const configuration = runtime.configurations.get(endpoint.id)!;
if (
configuration.providerConfig.provider !== "slack" ||
!callbacks.onModalSubmit
) {
throw new Error("Expected Slack provider and service modal callback");
}
const credentials = configuration.providerConfig.credentials;
type SlackView = {
callback_id: string;
private_metadata: string;
blocks: Array<{
block_id: string;
element: {
type: string;
action_id: string;
options?: Array<{ text: { text: string }; value: string }>;
};
}>;
};
const views: SlackView[] = [];
const exchangedTriggers = new Set<string>();
const providerMethods: string[] = [];
const unexpectedProviderMethods: string[] = [];
const providerErrors: unknown[] = [];
const providerTransport = vi.fn(async (config: { url: string; baseURL: string; data: string }) => {
const target = new URL(config.url, config.baseURL);
expect(target.hostname).toBe("127.0.0.1");
const params = new URLSearchParams(config.data);
const method = target.pathname.split("/").at(-1) ?? "";
providerMethods.push(method);
let result: unknown;
if (method === "conversations.replies") {
result = {
ok: true,
messages: [
{
type: "message",
ts: publication.providerMessageId,
thread_ts: threadTs,
channel: channelId,
user: credentials.botUserId,
text: "Deployment details",
},
],
};
} else if (method === "users.info") {
result = {
ok: true,
user: {
id: params.get("user"),
name: "maya",
real_name: "Maya",
is_bot: true,
profile: { display_name: "Maya" },
},
};
} else if (method === "conversations.info") {
result = { ok: true, channel: { id: channelId, name: "signed-modal", is_im: false } };
} else if (method === "chat.postEphemeral") {
result = { ok: true, message_ts: "1788.250" };
} else if (method === "views.open") {
const triggerAgeMs = Date.now() - triggerCreatedAt;
const trigger = params.get("trigger_id")!;
const expired = triggerAgeMs >= 3_000;
const reused = exchangedTriggers.has(trigger);
protocol.push({ method, triggerAgeMs, outcome: expired ? "trigger_expired" : reused ? "trigger_exchanged" : "opened" });
if (expired || reused) result = { ok: false, error: expired ? "trigger_expired" : "trigger_exchanged" };
else {
exchangedTriggers.add(trigger);
views.push(JSON.parse(params.get("view")!) as SlackView);
result = { ok: true, view: { id: "V-SIGNED-MODAL" } };
}
} else {
unexpectedProviderMethods.push(method);
result = { ok: false, error: "unexpected_test_provider_method" };
}
return { data: result, status: 200, statusText: "OK", headers: {}, config, request: { path: target.pathname } };
});
const onSubmit = vi.fn(callbacks.onModalSubmit);
const onAction = vi.fn(callbacks.onAction);
const onCommand = vi.fn(callbacks.onSlashCommand);
const replace = actualRuntime.replaceEndpoint.bind(actualRuntime);
vi.spyOn(actualRuntime, "replaceEndpoint").mockImplementation(async input => {
if (input.providerConfig.provider !== "slack") throw new Error("Unexpected fixture provider");
onSubmit.mockImplementation(input.callbacks.onModalSubmit!);
onAction.mockImplementation(input.callbacks.onAction!);
onCommand.mockImplementation(input.callbacks.onSlashCommand!);
const value = await replace({ ...input, logger: "silent",
callbacks: { ...input.callbacks, onModalSubmit: onSubmit, onAction, onSlashCommand: onCommand },
providerConfig: { ...input.providerConfig,
credentials: { ...input.providerConfig.credentials, apiUrl: "http://127.0.0.1:1/api/" } } });
const client = (value.getProviderAdapter() as unknown as { _client: {
axios: { defaults: { adapter: unknown } }; views: { open(options: unknown): Promise<unknown> };
} })._client;
const open = client.views.open.bind(client.views);
client.views.open = async options => {
try { return await open(options); } catch (error) { providerErrors.push(error); throw error; }
};
client.axios.defaults.adapter = providerTransport;
return value;
});
routedService = chatChannelService(db, { runtime: actualRuntime,
fetch: fakeSlackFetch() as typeof globalThis.fetch,
heartbeat: { wakeup: receiptBackedWakeup(wakeup) }, publicBaseUrl: "https://paperclip.example" });
fixtureServices.add(routedService);
const callbackUrl = `https://paperclip.example/api/chat-webhooks/${endpoint.publicId}/slack`;
const forward = async (request: Request, lane: string) => {
const startedAt = Date.now();
const originalTimestamp = request.headers.get("x-slack-request-timestamp");
const originalSignature = request.headers.get("x-slack-signature");
const originalBody = await request.clone().text();
if (mode === "command-delayed" && lane === "command" || mode === "action-delayed" && lane === "action" || mode === "submission-delayed" && lane === "invalid_submission")
await new Promise(resolve => setTimeout(resolve, 3_500)); // test-budget:allow-sleep: tests Slack 3s webhook acknowledgment deadline
const response = await routedService!.handleWebhook(endpoint.publicId, "slack", request);
const elapsedMs = Date.now() - startedAt;
custody.push({ lane, elapsedMs, acknowledgedWithin3s: elapsedMs < 3_000, originalTimestamp });
expect(request.headers.get("x-slack-request-timestamp")).toBe(originalTimestamp);
expect(request.headers.get("x-slack-signature")).toBe(originalSignature);
expect(originalSignature).toBe(`v0=${createHmac("sha256", credentials.signingSecret!).update(`v0:${originalTimestamp}:${originalBody}`).digest("hex")}`);
return response;
};
const signed = (payload: unknown) => {
const body = new URLSearchParams({
payload: JSON.stringify(payload),
}).toString();
const timestamp = String(Math.floor(Date.now() / 1_000));
const signature = createHmac("sha256", credentials.signingSecret!)
.update(`v0:${timestamp}:${body}`)
.digest("hex");
return new Request(callbackUrl, {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-slack-request-timestamp": timestamp,
"x-slack-signature": `v0=${signature}`,
},
body,
});
};
const wireUser = {
id: externalUserId,
username: "operator",
name: "Modal Operator",
};
const beforeEvidence = ((await db.select({ setup: chatEndpoints.setup }).from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)))[0]!.setup as InternalSetupState).slackCallbackSurfaces;
const invalidAuth = signed({ type: "block_actions", team: { id: "T-PAPERCLIP" }, user: wireUser, actions: [] });
invalidAuth.headers.set("x-slack-signature", `v0=${"0".repeat(64)}`);
expect((await routedService.handleWebhook(endpoint.publicId, "slack", invalidAuth)).status).toBe(401);
expect(onAction).not.toHaveBeenCalled();
expect(((await db.select({ setup: chatEndpoints.setup }).from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)))[0]!.setup as InternalSetupState).slackCallbackSurfaces).toEqual(beforeEvidence);
const commandBody = new URLSearchParams({ command: endpoint.setup.command!, text: "", user_id: externalUserId,
user_name: "operator", channel_id: channelId, team_id: "T-PAPERCLIP", trigger_id: "synthetic-command-trigger" }).toString();
const commandTimestamp = String(Math.floor(Date.now() / 1_000));
const commandRequest = new Request(callbackUrl, { method: "POST", headers: {
"content-type": "application/x-www-form-urlencoded", "x-slack-request-timestamp": commandTimestamp,
"x-slack-signature": `v0=${createHmac("sha256", credentials.signingSecret!).update(`v0:${commandTimestamp}:${commandBody}`).digest("hex")}`,
}, body: commandBody });
const commandResponse = await forward(commandRequest, "command");
expect(commandResponse.status).toBe(200);
expect(onCommand).toHaveBeenCalledOnce();
expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id),
eq(chatActions.kind, "provider_effect"), sql`${chatActions.providerActionId} like 'provider_effect:slash_notice:%'`)))
.toEqual([expect.objectContaining({ companyId: fixture.companyId, endpointId: endpoint.id,
payload: expect.objectContaining({ effect: "ephemeral_message", authorizationMode: "safe_notice", userId: externalUserId }) })]);
expect(custody.find(value => value.lane === "command")!.acknowledgedWithin3s).toBe(mode !== "command-delayed");
const actionPayload = {
type: "block_actions",
team: { id: "T-PAPERCLIP" },
user: wireUser,
channel: { id: channelId },
container: {
type: "message",
channel_id: channelId,
message_ts: publication.providerMessageId,
thread_ts: threadTs,
},
message: { ts: publication.providerMessageId, thread_ts: threadTs },
actions: [{ action_id: openAction.actionId, value: interaction.id }],
trigger_id: "synthetic-signed-modal-trigger",
};
const actionRequest = signed(actionPayload);
triggerCreatedAt = Date.now();
const opened = await forward(actionRequest, "action");
expect(opened.status).toBe(200);
if (mode === "action-delayed") {
expect(protocol).toEqual([{ method: "views.open", triggerAgeMs: expect.any(Number), outcome: "trigger_expired" }]);
expect(protocol[0]!.triggerAgeMs).toBeGreaterThanOrEqual(3_000);
expect(views).toHaveLength(0);
const attempts = await db.select().from(chatActions).where(and(
eq(chatActions.endpointId, endpoint.id), eq(chatActions.kind, "question_form_open_attempt"),
));
expect(attempts).toEqual([expect.objectContaining({ status: "failed", result: expect.objectContaining({ retryable: false }) })]);
const pending = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interaction.id));
expect(pending).toEqual([expect.objectContaining({ status: "pending" })]);
expect(await db.select().from(issueQuestionResponseDeliveries).where(eq(issueQuestionResponseDeliveries.interactionId, interaction.id))).toEqual([]);
await forward(signed(actionPayload), "duplicate_action");
expect(protocol).toHaveLength(1);
expect(onSubmit).not.toHaveBeenCalled();
expect(unexpectedProviderMethods).toEqual([]);
expect(providerErrors).toEqual([expect.objectContaining({ code: "slack_webapi_platform_error", data: expect.objectContaining({ error: "trigger_expired" }) })]);
await Promise.all(providerTransport.mock.results.map(result => result.value));
expect(custody.find(value => value.lane === "action")!.acknowledgedWithin3s).toBe(false);
const observed = (await db.select({ setup: chatEndpoints.setup }).from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)))[0]!.setup as InternalSetupState;
expect(observed.slackCallbackSurfaces?.interactivity?.url).toBe(callbackUrl);
expect(observed.slackCallbackSurfaces?.slashCommands?.url).toBe(callbackUrl);
if (process.env.PAPERCLIP_SLACK_PROTOCOL_CAPTURE === "1") console.info(JSON.stringify({ mode, protocol, custody }));
return;
}
expect(protocol[0]).toMatchObject({ method: "views.open", outcome: "opened" });
expect(protocol[0]!.triggerAgeMs).toBeLessThan(3_000);
expect(views).toHaveLength(1);
await forward(signed(actionPayload), "duplicate_action");
expect(protocol).toHaveLength(1);
expect(views).toHaveLength(1);
const view = views[0]!;
const metadata = JSON.parse(view.private_metadata) as {
c: string;
m: string;
};
expect(metadata).toEqual({ c: expect.any(String), m: view.callback_id });
const select = view.blocks.find(
(block) => block.element?.type === "radio_buttons",
)!;
const text = view.blocks.find(
(block) => block.element?.type === "plain_text_input",
)!;
const production = select.element.options!.find(
(option) => option.text.text === "Production",
)!;
expect(production.value).not.toBe("production");
const submit = (value: string) =>
signed({
type: "view_submission",
team: { id: "T-PAPERCLIP" },
user: wireUser,
view: {
id: "V-SIGNED-MODAL",
callback_id: view.callback_id,
private_metadata: view.private_metadata,
state: {
values: {
[select.block_id]: {
[select.element.action_id]: {
type: "radio_buttons",
selected_option: production,
},
},
[text.block_id]: {
[text.element.action_id]: { type: "plain_text_input", value },
},
},
},
},
});
const sdkContextRows = () =>
db
.select({ id: chatSdkState.id })
.from(chatSdkState)
.where(
and(
eq(chatSdkState.companyId, fixture.companyId),
eq(chatSdkState.endpointId, endpoint.id),
eq(
chatSdkState.stateKey,
`cache:${createHash("sha256").update(`modal-context:slack:${metadata.c}`).digest("hex")}`,
),
),
);
const submissionState = async () => ({
interactions: await db
.select()
.from(issueThreadInteractions)
.where(eq(issueThreadInteractions.id, interaction.id)),
tokens: await db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpoint.id),
eq(chatActions.providerActionId, view.callback_id),
),
),
deliveries: await db
.select()
.from(issueQuestionResponseDeliveries)
.where(
eq(issueQuestionResponseDeliveries.interactionId, interaction.id),
),
audits: await db
.select()
.from(activityLog)
.where(
and(
eq(activityLog.companyId, fixture.companyId),
eq(activityLog.entityId, conversation.issueId),
eq(activityLog.action, "issue.thread_interaction_answered"),
),
),
});
await expect(sdkContextRows()).resolves.toHaveLength(1);
const before = await submissionState();
expect(before.interactions).toEqual([
expect.objectContaining({ status: "pending" }),
]);
expect(before.tokens).toEqual([
expect.objectContaining({ status: "issued" }),
]);
expect(before.deliveries).toEqual([]);
expect(before.audits).toEqual([]);
const wakeupsBefore = wakeup.mock.calls.length;
const invalidStartedAt = Date.now();
const invalid = await forward(submit(""), "invalid_submission");
expect(custody.find(value => value.lane === "invalid_submission")!.acknowledgedWithin3s).toBe(mode !== "submission-delayed");
if (mode === "submission-delayed") expect(Date.now() - invalidStartedAt).toBeGreaterThanOrEqual(3_500);
expect(invalid.status).toBe(200);
expect(await invalid.json()).toEqual({
response_action: "errors",
errors: { [text.block_id]: "Enter a response" },
});
expect(onSubmit.mock.calls[0]![0].event).toMatchObject({
relatedThread: { id: conversation.externalThreadId },
relatedMessage: { id: publication.providerMessageId },
});
await expect(sdkContextRows()).resolves.toEqual([]);
expect(await submissionState()).toEqual(before);
expect(wakeup).toHaveBeenCalledTimes(wakeupsBefore);
const setRole = (membershipRole: "viewer" | "operator") =>
db
.update(companyMemberships)
.set({ membershipRole, updatedAt: new Date() })
.where(
and(
eq(companyMemberships.companyId, fixture.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, linkedUserId),
),
);
await setRole("viewer");
const denied = await forward(submit("Add regional failover"), "current_authority_submission");
expect(denied.status).toBe(200);
expect(await denied.json()).toEqual({
response_action: "errors",
errors: {
[select.block_id]:
"This form is no longer authorized. Close it and open the linked Paperclip task.",
},
});
expect(await submissionState()).toEqual(before);
expect(wakeup).toHaveBeenCalledTimes(wakeupsBefore);
const denials = await db
.select()
.from(chatDeliveries)
.where(
and(
eq(chatDeliveries.endpointId, endpoint.id),
sql`${chatDeliveries.normalizedEvent}->'modal'->>'code' = 'chat_modal_principal_not_authorized'`,
),
);
expect(denials).toHaveLength(1);
expect(denials[0]).toMatchObject({
state: "filtered",
conversationId: conversation.id,
});
await setRole("operator");
const corrected = await forward(submit(" Add regional failover "), "corrected_submission");
expect(corrected.status).toBe(200);
expect(await corrected.json()).toEqual({ response_action: "clear" });
await vi.waitFor(async () => {
expect(wakeup).toHaveBeenCalledTimes(wakeupsBefore + 1);
expect((await submissionState()).deliveries).toEqual([
expect.objectContaining({
status: "fallback_queued",
deliveryMode: "wake_fallback",
}),
]);
});
expect(wakeup).toHaveBeenLastCalledWith(
fixture.assignedAgentId,
expect.objectContaining({
idempotencyKey: `question-response:${interaction.id}`,
requestedByActorType: "user",
requestedByActorId: linkedUserId,
contextSnapshot: expect.objectContaining({
issueId: conversation.issueId,
interactionId: interaction.id,
source: "issue.interaction.respond",
}),
}),
);
const accepted = await submissionState();
expect(accepted.interactions).toEqual([
expect.objectContaining({
companyId: fixture.companyId,
issueId: conversation.issueId,
status: "answered",
resolvedByUserId: linkedUserId,
result: {
version: 1,
summaryMarkdown: null,
answers: [
{ questionId: "environment", optionIds: ["production"] },
{
questionId: "reason",
optionIds: [],
otherText: "Add regional failover",
},
],
},
}),
]);
expect(accepted.tokens).toEqual([
expect.objectContaining({
status: "processed",
conversationId: conversation.id,
principalId: principal.id,
result: {
code: "question_form_answered",
interactionId: interaction.id,
},
}),
]);
expect(accepted.deliveries).toHaveLength(1);
expect(accepted.audits).toEqual([
expect.objectContaining({
actorId: linkedUserId,
details: expect.objectContaining({
source: "external_chat_modal",
endpointId: endpoint.id,
conversationId: conversation.id,
publicationId: publication.id,
}),
}),
]);
const duplicate = await forward(submit(" Add regional failover "), "duplicate_submission");
expect(duplicate.status).toBe(200);
expect(await duplicate.json()).toEqual({ response_action: "clear" });
expect(await submissionState()).toEqual(accepted);
expect(wakeup).toHaveBeenCalledTimes(wakeupsBefore + 1);
expect(onSubmit).toHaveBeenCalledTimes(4);
for (const [event] of onSubmit.mock.calls.slice(1)) {
expect(event).toMatchObject({
endpointId: endpoint.id,
provider: "slack",
event: {
callbackId: view.callback_id,
privateMetadata: view.callback_id,
user: { userId: externalUserId },
},
});
expect(event.event.relatedThread).toBeUndefined();
expect(event.event.relatedMessage).toBeUndefined();
}
await expect(service.listConversations(endpoint.id)).resolves.toEqual([
expect.objectContaining({
id: conversation.id,
issueId: conversation.issueId,
externalThreadId: channel.thread.id,
}),
]);
expect(
providerMethods.filter((method) => method === "views.open"),
).toHaveLength(1);
expect(unexpectedProviderMethods).toEqual([]);
await Promise.all(providerTransport.mock.results.map(result => result.value));
expect(providerErrors).toEqual([]);
const observed = (await db.select({ setup: chatEndpoints.setup }).from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)))[0]!.setup as InternalSetupState;
expect(observed.slackCallbackSurfaces?.interactivity?.url).toBe(callbackUrl);
expect(observed.slackCallbackSurfaces?.slashCommands?.url).toBe(callbackUrl);
if (process.env.PAPERCLIP_SLACK_PROTOCOL_CAPTURE === "1") console.info(JSON.stringify({ mode, protocol, custody, invalidSubmission: "errors", correctedSubmission: "clear", answerDeliveries: accepted.deliveries.length }));
} catch (error) {
failure = { error };
throw error;
} finally {
const errors: unknown[] = [];
for (const cleanup of [
() => routedService?.shutdown(),
() => actualRuntime?.shutdown(),
() => configured ? retirePublicationFixture(configured.service, configured.endpoint.id) : undefined,
() => network.assertQuiet(),
() => network.restore(),
]) {
try { await cleanup(); } catch (error) { errors.push(error); }
}
if (errors.length) throw new AggregateError([...(failure ? [failure.error] : []), ...errors], "Slack protocol work or cleanup failed");
}
});
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,74 @@
import request from "supertest";
import { expect, it } from "vitest";
import { issues } from "@paperclipai/db";
import { issueRoutes } from "../routes/issues.js";
import { issueService } from "../services/issues.js";
import {
describeEmbeddedPostgres,
resetCompanyIssueFixtures,
routeApp,
seedCompanyWithBoardAccess,
useEmbeddedPostgres,
} from "./helpers/route-test-harness.js";
describeEmbeddedPostgres("issue origin kind prefix", () => {
const ctx = useEmbeddedPostgres("paperclip-origin-prefix-", {
resetEach: resetCompanyIssueFixtures,
});
for (const attention of [undefined, "blocked"] as const) {
for (const method of ["list", "count"] as const) {
it.each(["%", "_", "plugin:sample_", "plugin:sample%", "plugin:sample\\", "plugin:", ""])(
`${method} matches literal prefix %j with attention ${attention}`,
async (prefix) => {
const { companyId } = await seedCompanyWithBoardAccess(ctx.db, "Origin prefix");
const other = await seedCompanyWithBoardAccess(ctx.db, "Other origins");
const originKinds = [
"%literal", "_literal", "manual", "plugin:sample_task",
"plugin:sampleXtask", "plugin:sample%task", "plugin:sample\\task",
"plugin:sample_task:child", "plugin:other",
];
const rows = await ctx.db.insert(issues).values(originKinds.map((originKind) => ({
companyId, title: originKind, originKind, status: "blocked",
}))).returning();
await ctx.db.insert(issues).values({
companyId: other.companyId, title: "Other company", originKind: `${prefix}other`, status: "blocked",
});
const expected = rows.filter((row) => row.originKind!.startsWith(prefix));
const svc = issueService(ctx.db);
const filters = { originKindPrefix: prefix, attention, includeRoutineExecutions: true };
if (method === "count") {
expect(await svc.count(companyId, filters)).toBe(expected.length);
} else {
const result = await svc.list(companyId, filters);
expect(result.map((row) => row.id).sort()).toEqual(expected.map((row) => row.id).sort());
}
},
);
}
}
async function seedRepeatedPrefixRoute() {
const { companyId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Repeated origin prefix");
const [joined] = await ctx.db.insert(issues).values(["plugin:a,plugin:b", "plugin:a", "plugin:b"].map((originKind) => ({
companyId, title: originKind, originKind, status: "blocked",
}))).returning();
return { companyId, app: routeApp(ctx.db, actor, issueRoutes), joinedId: joined!.id };
}
it.each(["", "&attention=blocked"])("list route joins repeated prefixes with commas (%s)", async (attention) => {
const { companyId, app, joinedId } = await seedRepeatedPrefixRoute();
const res = await request(app)
.get(`/api/companies/${companyId}/issues?originKindPrefix=plugin:a&originKindPrefix=plugin:b${attention}`)
.expect(200);
expect((res.body as { id: string }[]).map((issue) => issue.id)).toEqual([joinedId]);
});
it("count route joins repeated prefixes with commas", async () => {
const { companyId, app } = await seedRepeatedPrefixRoute();
const res = await request(app)
.get(`/api/companies/${companyId}/issues/count?attention=blocked&originKindPrefix=plugin:a&originKindPrefix=plugin:b`)
.expect(200);
expect(res.body).toEqual(expect.objectContaining({ count: 1 }));
});
});
+46 -27
View File
@@ -7,54 +7,73 @@ import { expect, it } from "vitest";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
it("runs every active nested/parameterized fixture case exactly once through the real chat shard CLI", () => {
it("runs every split chat integration suite exactly once through the real chat shard CLI", () => {
const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "pc-shards-")));
try {
const tests = path.join(root, "server/src/__tests__");
mkdirSync(tests, { recursive: true });
const chatDir = path.join(root, "server/src/__tests__/chat-channels");
mkdirSync(chatDir, { recursive: true });
mkdirSync(path.join(root, "server/scripts"), { recursive: true });
symlinkSync(path.join(repoRoot, "node_modules"), path.join(root, "node_modules"), "junction");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ private: true }));
const rootPkg = JSON.parse(readFileSync(path.join(repoRoot, "package.json"), "utf8"));
writeFileSync(
path.join(root, "package.json"),
JSON.stringify({ private: true, ...(rootPkg.packageManager ? { packageManager: rootPkg.packageManager } : {}) }),
);
writeFileSync(path.join(root, "vitest.config.mjs"), `export default {
test: { projects: [{ test: { name: "@paperclipai/server", root: ${JSON.stringify(path.join(root, "server"))},
include: ["src/**/*.test.ts"], pool: "forks", maxWorkers: 1 } }] }
};`);
const trace = path.join(root, "executed.jsonl");
const fixture = path.join(tests, "chat-channels.integration.test.ts");
writeFileSync(fixture, `import { appendFileSync } from "node:fs";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
let active = false;
beforeEach(() => { expect(active).toBe(false); active = true; });
afterEach(() => { active = false; });
function record(id) { expect(active).toBe(true); appendFileSync(${JSON.stringify(trace)}, JSON.stringify(id) + "\\n"); }
it("top-level", () => record("top"));
it("second top-level", () => record("top-second"));
it("third top-level", () => record("top-third"));
describe("nested", () => {
it("first", () => record("nested-first"));
it("second", () => record("nested-second"));
it.each(["a", "b", "c", "d"])("parameter %s", (value) => record(value));
it.skip("intentionally skipped", () => { throw new Error("must stay skipped"); });
});`);
const fixtures: Array<[string, string[]]> = [
["alpha.integration.test.ts", ["alpha-1", "alpha-2"]],
["beta.integration.test.ts", ["beta-1", "beta-2"]],
["gamma.integration.test.ts", ["gamma-1"]],
];
for (const [fileName, cases] of fixtures) {
writeFileSync(
path.join(chatDir, fileName),
`import { appendFileSync } from "node:fs";
import { expect, it } from "vitest";
for (const id of ${JSON.stringify(cases)}) {
it(id, () => {
expect(id).toBeTruthy();
appendFileSync(${JSON.stringify(trace)}, JSON.stringify(id) + "\\n");
});
}
it.skip("intentionally skipped", () => { throw new Error("must stay skipped"); });`,
);
}
const run = (index: number, count: number) => spawnSync(process.execPath, [
path.join(repoRoot, "scripts/run-vitest-stable.mjs"), "--mode", "general", "--group", "general-chat",
"--shard-index", String(index), "--shard-count", String(count),
], { cwd: root, env: { ...process.env, CI: "true", PAPERCLIP_CI_PROFILE: "false" }, encoding: "utf8", timeout: 45_000, maxBuffer: 4 * 1024 * 1024 });
], {
cwd: root,
env: { ...process.env, CI: "true", PAPERCLIP_CI_PROFILE: "false", PAPERCLIP_TEST_POSTGRES_SHARED: "0" },
encoding: "utf8",
timeout: 45_000,
maxBuffer: 4 * 1024 * 1024,
});
for (const index of [0, 1]) {
const result = run(index, 2);
expect(result.error, result.stderr).toBeUndefined();
expect(result.status, result.stdout + result.stderr).toBe(0);
expect(result.stdout).toContain("exact filter coverage verified");
}
const executed = readFileSync(trace, "utf8").trim().split("\n").map((line) => JSON.parse(line));
expect(executed.sort()).toEqual(["a", "b", "c", "d", "nested-first", "nested-second", "top", "top-second", "top-third"]);
expect(executed.sort()).toEqual(["alpha-1", "alpha-2", "beta-1", "beta-2", "gamma-1"]);
// A real assertion failure must still fail the wrapper after successful
// collection and filter validation.
writeFileSync(fixture, 'import { it } from "vitest"; it("fails", () => { throw new Error("fixture failure"); });');
// Trailing empty shards exit cleanly without launching Vitest unfiltered.
const emptyShard = run(4, 5);
expect(emptyShard.error, emptyShard.stderr).toBeUndefined();
expect(emptyShard.status, emptyShard.stdout + emptyShard.stderr).toBe(0);
expect(emptyShard.stdout).toContain("running 0 of 3 suites");
// A real assertion failure must fail the wrapper.
writeFileSync(
path.join(chatDir, "alpha.integration.test.ts"),
'import { it } from "vitest"; it("fails", () => { throw new Error("fixture failure"); });',
);
const failed = run(0, 1);
expect(failed.error, failed.stderr).toBeUndefined();
expect(failed.stdout).toContain("exact filter coverage verified");
expect(failed.status).not.toBe(0);
expect(failed.stdout + failed.stderr).toContain("fixture failure");
} finally {
+4
View File
@@ -260,10 +260,14 @@ export function configPatchFromSnapshot(snapshot: unknown): Partial<typeof agent
throw unprocessable("Invalid revision snapshot: runtimeConfig");
}
const appearance = agentAppearanceSchema.safeParse(snapshot.appearance);
return {
name: snapshot.name,
role: snapshot.role,
title: typeof snapshot.title === "string" || snapshot.title === null ? snapshot.title : null,
...(typeof snapshot.icon === "string" || snapshot.icon === null ? { icon: snapshot.icon } : {}),
...(appearance.success ? { appearance: appearance.data } : {}),
reportsTo:
typeof snapshot.reportsTo === "string" || snapshot.reportsTo === null ? snapshot.reportsTo : null,
capabilities:
+7 -7
View File
@@ -2212,6 +2212,10 @@ function escapeLikePattern(value: string): string {
return value.replace(/[\\%_]/g, "\\$&");
}
function originKindPrefixCondition(prefix: string) {
return like(issues.originKind, `${escapeLikePattern(String(prefix))}%`);
}
export function clampIssueListLimit(limit: number): number {
return Math.min(ISSUE_LIST_MAX_LIMIT, Math.max(1, Math.floor(limit)));
}
@@ -6800,7 +6804,7 @@ async function blockedInboxIssueConditions(
if (filters?.originKind)
conditions.push(eq(issues.originKind, filters.originKind));
if (filters?.originKindPrefix)
conditions.push(like(issues.originKind, `${filters.originKindPrefix}%`));
conditions.push(originKindPrefixCondition(filters.originKindPrefix));
if (filters?.originId) conditions.push(eq(issues.originId, filters.originId));
if (filters?.hasPlanDocument !== undefined) {
conditions.push(
@@ -8720,9 +8724,7 @@ export function issueService(db: Db) {
if (filters?.originKind)
conditions.push(eq(issues.originKind, filters.originKind));
if (filters?.originKindPrefix)
conditions.push(
like(issues.originKind, `${filters.originKindPrefix}%`),
);
conditions.push(originKindPrefixCondition(filters.originKindPrefix));
if (filters?.originId)
conditions.push(eq(issues.originId, filters.originId));
if (filters?.hasPlanDocument !== undefined) {
@@ -9046,9 +9048,7 @@ export function issueService(db: Db) {
if (filters?.originKind)
conditions.push(eq(issues.originKind, filters.originKind));
if (filters?.originKindPrefix)
conditions.push(
like(issues.originKind, `${filters.originKindPrefix}%`),
);
conditions.push(originKindPrefixCondition(filters.originKindPrefix));
if (filters?.originId)
conditions.push(eq(issues.originId, filters.originId));
if (filters?.hasPlanDocument !== undefined) {