mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
perf(ci): split 6 single-file Vitest stragglers across runner, chat, server, and serialized lanes (#22916)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Profiling live 8-core PR runs (`45592683902`, `45578886514`, `45591289735`, `45587659461`) showed that every single top Vitest critical-path straggler across all 4 Vitest lanes was caused by **single-file tail pinning**—one massive file running solo while 4–6 CPU cores sat idle—rather than insufficient shard counts: > - `Verify Paperclip Runner (vitest package 1/6)` (`245s` job): `runnerd-codex-transport.test.ts` = `190.9s` solo > - `Verify Paperclip Runner (vitest package 2/6)` (`236s` job): `runnerd-codex-transport-deadlines.test.ts` = `181.3s` solo > - `Verify Paperclip Runner (vitest package 3/6)` (`185s` job): `runnerd-codex-transport-settlement.test.ts` = `123.6s` solo > - `General tests (chat 1/2)` (`229s` job): `github-review-workflow.integration.test.ts` = `179.2s` solo > - `General tests (server 1/20)` (`209s` job): `connection-management.integration.test.ts` = `160.1s` solo > - `Verify serialized server suites (1/9)` (`190s` job): `issue-queued-comments-routes.test.ts` = `132.8s` solo > - Instead of bloating shard counts, this pull request splits those 6 single-file tails into 20 focused sibling suites (`<925 LOC` per new file) with shared non-test harness helpers so existing 8-core workers execute them in parallel, keeps all 6 original anchor filenames intact so every existing `maps/` and contract reference remains valid, and refreshes all 4 Vitest LPT duration manifests from live 8-core measurements. > - Every single original test case is preserved (`694/694` live pass across the 20 split suites, zero deleted assertions) while shaving `60–105s` off every Vitest lane's critical-path tail. ## Linked Issues or Issue Description Refs #22804 **What existing behavior does this improve?** Parallel wall-clock execution time of the slowest shards across `Verify Paperclip Runner (vitest package)`, `General tests (chat)`, `General tests (server)`, and `Verify serialized server suites`. **Subsystem affected** packages/paperclip-runner/, server/, and scripts/ — Vitest integration test layout, sequencer priorities, and LPT shard duration manifests **Current behavior** Six oversized test files (`123s–191s` solo each) pin the tail of the slowest shard in every Vitest lane while peer workers on the 8-core runner sit idle. **Proposed behavior** Split those 6 single-file stragglers into 20 parallelizable sibling suites (retaining all 6 original anchor filenames and extracting shared non-test harnesses) and refresh `packages/paperclip-runner/scripts/vitest-lane-durations.json`, `scripts/chat-shard-durations.json`, `scripts/general-server-shard-durations.json`, and `scripts/serialized-shard-durations.json` plus `packages/paperclip-runner/scripts/vitest-sequencer.mjs`. ## What Changed - **Split all 6 single-file stragglers (31 files changed: 11 modified, 20 new; every new file `<925 LOC`, 100% of test cases preserved):** 1. `packages/paperclip-runner/test/runnerd-codex-transport-deadlines.test.ts` (`181.3s` CI) → 3 files (`anchor` + `-lease-expiry` + `-cold-admission`, 9/9 tests) 2. `packages/paperclip-runner/test/runnerd-codex-transport-settlement.test.ts` (`123.6s` CI) → 2 files (`anchor` + `-settlement-revocation`, 19/19 tests) + 3 non-test support harnesses (`runnerd-settlement-assertions.ts`, `runnerd-settlement-harness.ts`, `runnerd-settlement-fixture.ts`) 3. `packages/paperclip-runner/test/runnerd-codex-transport.test.ts` (`190.9s` CI) → 4 files (`anchor` + `-backlog-proxy` + `-held-calls` + `-provider-turns`, 337/337 tests) 4. `server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts` (`179.2s` CI) → 4 files (`anchor` + `-finding-threads` + `-response-maintenance` + `-publications`, 89/89 tests) + `github-review-harness.ts` 5. `server/src/__tests__/connection-management.integration.test.ts` (`160.1s` CI) → 4 files (`anchor` + `-providers` + `-delegated-policy` + `-gateways`, 92/92 tests) + `helpers/connection-management-harness.ts` 6. `server/src/__tests__/issue-queued-comments-routes.test.ts` (`132.8s` CI) → 3 `*routes*` files (`anchor` + `-steering-routes` + `-dispatch-routes`, 148/148 tests, all matching `routeTestPattern` in the `serialized` lane) + `helpers/issue-queued-comments-harness.ts` - **Updated sequencer & LPT duration manifests:** - Updated `packages/paperclip-runner/scripts/vitest-sequencer.mjs` and refreshed `packages/paperclip-runner/scripts/vitest-lane-durations.json`, `scripts/chat-shard-durations.json`, `scripts/general-server-shard-durations.json`, and `scripts/serialized-shard-durations.json` from live 8-core PR run `45592683902` with exact `coverage` reconciliation. ## Verification - Live execution of all 20 split suites: **20/20 files, 694/694 tests PASS** (`deadlines` 9/9 in `81.1s` parallel, `settlement` 19/19 in `105.4s` parallel, `transport` 337/337 in `109.2s` parallel, `github-review` 89/89 under shared PG, `connection-management` 92/92 under shared PG, `issue-queued-comments` 148/148 under shared PG) - `node scripts/check-test-budget.mjs --base origin/master` — **PASS** (105 nightly suites, 11 test files checked, 0 violations) - `node scripts/check-maps.mjs` — **PASS** (35 areas, 192 capability IDs aligned) - `pnpm --filter @paperclipai/paperclip-runner exec tsc --noEmit` — **PASS** (0 errors) - `pnpm --filter @paperclipai/paperclip-runner exec vitest run scripts/vitest-sequencer.test.mjs` — **5/5 PASS** - `node --test` across `native-completion-source-contract`, `run-vitest-stable-shard`, `run-vitest-stable-pr-mode`, `runner-vitest-package-lanes`, `test-selection-pr-timings`, `test-selection-timings`, `e2e-shard`, `check-test-budget`, and `ci-plan` — **121/121 PASS** ## Risks - Low risk: all 6 original anchor filenames remain intact, zero `.github/**` or `CODEOWNERS` files are touched, zero cross-test-file imports were introduced (shared setup lives in non-test harness modules), and full CI will execute all 20 split suites live before merge. ## Model Used - Gemini 4 Neon (High) via Antigravity agent swarm (`vitest-runner`, `verifier`, `ci-pipeline`). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
371ece9375
commit
4aaa77e6fc
31 files changed
+8973
-7546
No files matched your search
@@ -0,0 +1,395 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { beforeAll, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
chatActions,
|
||||
chatConversations,
|
||||
chatDeliveries,
|
||||
chatIdentityLinks,
|
||||
chatPublications,
|
||||
companies,
|
||||
heartbeatRuns,
|
||||
issueComments,
|
||||
issues,
|
||||
toolInvocations,
|
||||
toolPolicies,
|
||||
} from "@paperclipai/db";
|
||||
import type { Thread } from "chat";
|
||||
// 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 { githubChatReviewService } from "../../services/chat-github-reviews.js";
|
||||
import { githubBotToolsForSession } from "../../services/chat-github-tools.js";
|
||||
import { buildPaperclipRuntimeMcpServers } from "../../services/heartbeat/run-preparation.js";
|
||||
import { createAssignedMcpTools } from "../../services/native-runtime/assigned-mcp-tools.js";
|
||||
import { createToolGatewayService } from "../../services/tool-gateway.js";
|
||||
import { initializeRunIdentity } from "../../services/run-identity.js";
|
||||
import { enqueueChatRunMilestones, githubRunReplyState } from "../../services/chat-run-publications.js";
|
||||
import { extractWakeCommentIds, heartbeatService } from "../../services/heartbeat.js";
|
||||
import { registerServerAdapter, runningProcesses, unregisterServerAdapter } from "../../adapters/index.js";
|
||||
import { type TestDb, describeEmbeddedPostgres, makeThread, makeMessage } from "./providers.js";
|
||||
import { createChatChannelHarness } from "./harness.js";
|
||||
import { createGitHubHarness } from "./github-harness.js";
|
||||
import { createGitHubReviewHarness } from "./github-review-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("chat channels: github review finding threads and fallbacks", () => {
|
||||
const h = createChatChannelHarness();
|
||||
let db!: TestDb;
|
||||
beforeAll(() => { db = h.db; });
|
||||
const gh = createGitHubHarness(h);
|
||||
const rev = createGitHubReviewHarness(h, gh);
|
||||
const {
|
||||
readChatConversationsByEndpointId,
|
||||
readIssueCommentsByIssueId,
|
||||
readIssuesById,
|
||||
readChatGitHubReviewsByEndpointId,
|
||||
readHeartbeatRunsByCompanyId,
|
||||
deliverMessage,
|
||||
} = h;
|
||||
const { signedGitHubWebhookRequest } = gh;
|
||||
const {
|
||||
reviewBotFixture,
|
||||
subscribedGitHubFixture,
|
||||
toolReplyFixture,
|
||||
publicationRetryFixture,
|
||||
} = rev;
|
||||
|
||||
describe("GitHub agent review finding threads and delivery fallbacks", () => {
|
||||
it.each([
|
||||
{ boardFollowUp: false, legacyOrigin: false },
|
||||
{ boardFollowUp: true, legacyOrigin: false },
|
||||
{ boardFollowUp: false, legacyOrigin: true },
|
||||
{ boardFollowUp: true, legacyOrigin: true },
|
||||
])("keeps GitHub review tools callable through a later native task gateway (board follow-up: $boardFollowUp, legacy origin: $legacyOrigin)", async ({ boardFollowUp, legacyOrigin }) => {
|
||||
vi.stubEnv("PAPERCLIP_API_URL", "https://paperclip.example.test");
|
||||
onTestFinished(() => { vi.unstubAllEnvs(); });
|
||||
const f = await publicationRetryFixture();
|
||||
const identity = await initializeRunIdentity(db, {
|
||||
companyId: f.companyId, runId: f.run.id, issueId: f.conversation.issueId!,
|
||||
responsibleUserId: "owner-user", messageIds: legacyOrigin ? [] : [String(f.run.contextSnapshot?.wakeCommentId)], cause: "instruction",
|
||||
});
|
||||
vi.stubGlobal("fetch", f.providerFetch);
|
||||
onTestFinished(() => { vi.unstubAllGlobals(); });
|
||||
const [agent] = await db.select().from(agents).where(eq(agents.id, f.assignedAgentId));
|
||||
const gateway = createToolGatewayService(db);
|
||||
const first = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: f.run.id });
|
||||
const firstTools = await createAssignedMcpTools({ gateway, gatewayPublicId: new URL(first[0].url).pathname.split("/").at(-1)!, bearerToken: first[0].token });
|
||||
expect(await firstTools.execute({ tool: "paperclip_search_assigned_tools", arguments: { query: "begin_review" } })).toMatchObject({ tools: expect.arrayContaining([expect.objectContaining({ name: expect.stringContaining("begin_review") })]) });
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const [later] = await db.insert(heartbeatRuns).values({
|
||||
companyId: f.companyId, agentId: f.assignedAgentId, status: "running", runtimeMode: "native",
|
||||
nativeIssueId: f.conversation.issueId, contextSnapshot: { wakeReason: "issue_monitor_due" },
|
||||
}).returning();
|
||||
const [boardMessage] = boardFollowUp ? await db.insert(issueComments).values({
|
||||
companyId: f.companyId, issueId: f.conversation.issueId!, authorType: "user", authorUserId: "owner-user", body: "Finish the review",
|
||||
}).returning() : [];
|
||||
await initializeRunIdentity(db, {
|
||||
companyId: f.companyId, runId: later.id, issueId: f.conversation.issueId!,
|
||||
responsibleUserId: "owner-user", parentContextId: identity.id, messageIds: boardMessage ? [boardMessage.id] : [], cause: "monitor",
|
||||
});
|
||||
const servers = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: later.id });
|
||||
expect(servers).toHaveLength(1);
|
||||
await expect(gateway.createSession({ companyId: f.companyId, agentId: f.assignedAgentId, runId: later.id, issueId: randomUUID() }))
|
||||
.rejects.toMatchObject({ reasonCode: "run_context_mismatch" });
|
||||
const assigned = await createAssignedMcpTools({ gateway, gatewayPublicId: new URL(servers[0].url).pathname.split("/").at(-1)!, bearerToken: servers[0].token });
|
||||
expect(await assigned.execute({ tool: "paperclip_search_assigned_tools", arguments: { query: "begin_review" } })).toMatchObject({ tools: expect.arrayContaining([expect.objectContaining({ name: expect.stringContaining("begin_review") })]) });
|
||||
const read = assigned.definitions().find(tool => String(tool.name).includes("read_pull_request"))!;
|
||||
expect(await assigned.execute({ tool: String(read.name), arguments: { section: "metadata" } })).toMatchObject({ data: { pull: { number: 418 } } });
|
||||
const begin = assigned.definitions().find(tool => String(tool.name).includes("begin_review"))!;
|
||||
await assigned.execute({ tool: String(begin.name), arguments: { reviewedCommit: f.head } });
|
||||
const submit = assigned.definitions().find(tool => String(tool.name).includes("submit_review"))!;
|
||||
expect(await assigned.execute({ tool: String(submit.name), arguments: f.assessment })).toMatchObject({ data: { status: "processed", score: 3 } });
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect([...f.responseComments.values()][0].body).toContain("Advisory review");
|
||||
await db.update(chatIdentityLinks).set({ status: "revoked" }).where(eq(chatIdentityLinks.endpointId, f.endpoint.id));
|
||||
await expect(assigned.execute({ tool: String(read.name), arguments: { section: "metadata" } })).rejects.toThrow();
|
||||
});
|
||||
|
||||
describe("replies in review finding threads behind an active run", () => {
|
||||
const pr = "github:paperclipai/paperclip:17044";
|
||||
async function findingThreadFixture() {
|
||||
vi.stubEnv("PAPERCLIP_API_URL", "https://paperclip.example.test");
|
||||
onTestFinished(() => { vi.unstubAllEnvs(); });
|
||||
const f = await subscribedGitHubFixture(pr);
|
||||
const adapterType = `github-finding-thread-test-${randomUUID()}`;
|
||||
const execute = vi.fn(async (_input: { runId: string; context: Record<string, unknown> }) => ({
|
||||
exitCode: 0, signal: null, timedOut: false, errorMessage: null, summary: "Answered the finding thread",
|
||||
}));
|
||||
registerServerAdapter({ type: adapterType, supportsLocalAgentJwt: false, execute,
|
||||
testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }) });
|
||||
const heartbeat = heartbeatService(db);
|
||||
const activeRunId = randomUUID();
|
||||
onTestFinished(async () => {
|
||||
runningProcesses.delete(activeRunId);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
unregisterServerAdapter(adapterType);
|
||||
});
|
||||
const issueId = f.conversation.issueId!;
|
||||
await db.update(companies).set({ defaultResponsibleUserId: "owner-user" }).where(eq(companies.id, f.companyId));
|
||||
await db.update(agents).set({ adapterType, runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } })
|
||||
.where(eq(agents.id, f.assignedAgentId));
|
||||
// Published findings bind their inline threads to the PR review task.
|
||||
const { id: _id, ...base } = f.conversation;
|
||||
const threads = await Promise.all(["4332012267", "4332012626"].map(async (commentId) => {
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: `${pr}:rc:${commentId}` }).thread;
|
||||
const [conversation] = await db.insert(chatConversations).values({ ...base, externalThreadId: thread.id,
|
||||
providerUrl: `https://github.com/paperclipai/paperclip/pull/17044#discussion_r${commentId}` }).returning();
|
||||
return { thread, conversation };
|
||||
}));
|
||||
// The review-request run still holds the task when the linked user replies.
|
||||
await db.insert(heartbeatRuns).values({ id: activeRunId, companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", startedAt: new Date(), contextSnapshot: { issueId, source: "chat:github" },
|
||||
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } });
|
||||
runningProcesses.set(activeRunId, { child: {} as never, graceSec: 0, processGroupId: null });
|
||||
await db.update(issues).set({ status: "in_review", executionRunId: activeRunId,
|
||||
executionAgentNameKey: "maya", executionLockedAt: new Date() }).where(eq(issues.id, issueId));
|
||||
f.wakeup.mockImplementation(heartbeat.wakeup);
|
||||
let messageId = 41950;
|
||||
const reply = (thread: Thread, text: string) => deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id,
|
||||
provider: "github", thread, trigger: "subscribed_message",
|
||||
message: makeMessage({ id: String(messageId++), text, userId: "42", userName: "octocat" }) });
|
||||
const commentFor = async (text: string) => (await readIssueCommentsByIssueId(issueId)).find((c) => c.body.includes(text))!.id;
|
||||
const finishActiveRun = async () => {
|
||||
runningProcesses.delete(activeRunId);
|
||||
await heartbeat.cancelRun(activeRunId, "Review request finished", { suppressImmediateRecovery: true });
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
};
|
||||
const followUpRuns = async () => (await readHeartbeatRunsByCompanyId(f.companyId))
|
||||
.filter((run) => run.id !== activeRunId && run.wakeupRequestId)
|
||||
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
||||
return { ...f, issueId, threads, execute, reply, commentFor, finishActiveRun, followUpRuns };
|
||||
}
|
||||
|
||||
it("answers each finding thread in its own run instead of one unattestable batch", async () => {
|
||||
const f = await findingThreadFixture();
|
||||
await f.reply(f.threads[0].thread, "First finding is intentional");
|
||||
await f.reply(f.threads[1].thread, "Second finding is fixed in the next commit");
|
||||
const first = await f.commentFor("First finding"), second = await f.commentFor("Second finding");
|
||||
await f.finishActiveRun();
|
||||
const runs = await f.followUpRuns();
|
||||
expect(runs.map((run) => ({ status: run.status, errorCode: run.errorCode, error: run.error })))
|
||||
.toEqual([{ status: "succeeded", errorCode: null, error: null }, { status: "succeeded", errorCode: null, error: null }]);
|
||||
expect(runs.map((run) => extractWakeCommentIds(run.contextSnapshot))).toEqual([[first], [second]]);
|
||||
expect(runs.map((run) => run.contextSnapshot?.chatConversationId))
|
||||
.toEqual(f.threads.map(({ conversation }) => conversation.id));
|
||||
expect(f.execute.mock.calls.map(([input]) => [input.context.paperclipExternalChatExecutionBound,
|
||||
extractWakeCommentIds(input.context)])).toEqual([[true, [first]], [true, [second]]]);
|
||||
});
|
||||
|
||||
it("still batches several replies in one finding thread into one attested run", async () => {
|
||||
const f = await findingThreadFixture();
|
||||
await f.reply(f.threads[0].thread, "First note on this finding");
|
||||
await f.reply(f.threads[0].thread, "Second note on this finding");
|
||||
const ids = [await f.commentFor("First note"), await f.commentFor("Second note")];
|
||||
await f.finishActiveRun();
|
||||
const runs = await f.followUpRuns();
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs[0]).toMatchObject({ status: "succeeded", errorCode: null });
|
||||
expect(extractWakeCommentIds(runs[0].contextSnapshot)).toEqual(ids);
|
||||
expect(f.execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("still denies each separated finding-thread run after the linked identity is revoked", async () => {
|
||||
const f = await findingThreadFixture();
|
||||
await f.reply(f.threads[0].thread, "First finding is intentional");
|
||||
await f.reply(f.threads[1].thread, "Second finding is fixed in the next commit");
|
||||
await db.update(chatIdentityLinks).set({ status: "revoked", revokedAt: new Date() })
|
||||
.where(eq(chatIdentityLinks.principalId, f.principal.id));
|
||||
await f.finishActiveRun();
|
||||
const runs = await f.followUpRuns();
|
||||
expect(runs.length).toBeGreaterThan(0);
|
||||
for (const run of runs) expect(run).toMatchObject({ status: "failed", errorCode: "setup_failed" });
|
||||
expect(f.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ label: "preserves an explicit shorter GitHub tool deadline and reconciles without duplicate publication", delayMs: 200, timeoutMs: 50 },
|
||||
])("recovers a durable GitHub publication receipt ($label)", async ({ delayMs, timeoutMs }) => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418", true);
|
||||
const head = "b".repeat(40);
|
||||
const checks: Record<string, unknown>[] = [];
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/pulls/418")) return Response.json({ number: 418, state: "open", draft: false,
|
||||
head: { sha: head }, base: { sha: "a".repeat(40), ref: "master" }, user: { id: 42, login: "octocat", type: "User" }, labels: [] });
|
||||
if (url.includes("/files?")) return Response.json([{ filename: "src/math.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" }]);
|
||||
if (url.includes("/check-runs?")) return Response.json({ check_runs: [] });
|
||||
if (url.includes("/check-runs") && init?.method) {
|
||||
checks.push(JSON.parse(String(init.body)));
|
||||
return Response.json({ id: 419, html_url: "https://github.com/checks/419" });
|
||||
}
|
||||
if (url.includes("/issues/comments/") && init?.method === "PATCH") {
|
||||
await new Promise(resolve => setTimeout(resolve, delayMs));
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
vi.stubGlobal("fetch", f.providerFetch);
|
||||
onTestFinished(() => { vi.unstubAllGlobals(); });
|
||||
const { createToolGatewayService } = await import("../../services/tool-gateway.js");
|
||||
const gateway = createToolGatewayService(db);
|
||||
const session = await gateway.createSession({ companyId: f.companyId, agentId: f.assignedAgentId, runId: f.run.id });
|
||||
const tools = await githubBotToolsForSession(db, f.session);
|
||||
const tool = tools.find(tool => tool.upstreamToolName === "submit_review")!;
|
||||
await githubChatReviewService(db, f.providerFetch).execute(f.session, "begin_review", { reviewedCommit: head });
|
||||
const assessment = { reviewedCommit: head, score: 5, complete: true,
|
||||
summary: "Reviewed the changed behavior and its callers. ".repeat(30),
|
||||
rationale: "Checked the mutation boundary and the client retry contract. ".repeat(30),
|
||||
coverage: { reviewedPaths: ["src/math.ts"], omittedPaths: [], limitations: [] }, findings: [] };
|
||||
const result = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment, timeoutMs })
|
||||
.then(value => ({ value }), error => ({ error }));
|
||||
await expect.poll(async () => {
|
||||
const [action] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_publication")));
|
||||
return action?.status;
|
||||
}, { timeout: 15_000 }).toBe("processed");
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect(f.responseWrites.map(write => write.method)).toEqual(["POST", "PATCH"]);
|
||||
expect(checks).toContainEqual(expect.objectContaining({ conclusion: "neutral", status: "completed" }));
|
||||
if (timeoutMs === undefined) {
|
||||
expect(result).toMatchObject({ value: { status: "completed", result: { data: { status: "processed", score: 5, conclusion: "neutral" } } } });
|
||||
} else {
|
||||
expect(result).toMatchObject({ error: { status: 504, reasonCode: "tool_timeout" } });
|
||||
}
|
||||
const writes = f.responseWrites.length;
|
||||
const replay = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment });
|
||||
expect(replay).toMatchObject({ result: { data: { status: "processed", score: 5, conclusion: "neutral" } } });
|
||||
const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, replay.invocationId));
|
||||
expect(invocation).toMatchObject({ status: "succeeded", errorCode: null, errorMessage: null });
|
||||
expect(f.responseWrites).toHaveLength(writes);
|
||||
}, 40_000);
|
||||
|
||||
it("rejects changed requests and revoked access before repeating an unstaged review", async () => {
|
||||
const f = await publicationRetryFixture();
|
||||
let metadataReads = 0;
|
||||
let unavailable = true;
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
if (String(input).endsWith("/pulls/418")) {
|
||||
metadataReads++;
|
||||
if (unavailable) throw new Error("Connection closed before PR metadata arrived");
|
||||
}
|
||||
return f.provider(input, init);
|
||||
});
|
||||
vi.stubGlobal("fetch", f.providerFetch);
|
||||
onTestFinished(() => { vi.unstubAllGlobals(); });
|
||||
const gateway = createToolGatewayService(db);
|
||||
const session = await gateway.createSession({ companyId: f.companyId, agentId: f.assignedAgentId, runId: f.run.id });
|
||||
const tool = (await githubBotToolsForSession(db, f.session)).find(tool => tool.upstreamToolName === "submit_review")!;
|
||||
const input = { sessionToken: session.token, tool: tool.name, parameters: f.assessment, idempotencyKey: "preflight-request" };
|
||||
await expect(gateway.executeTool(input)).rejects.toThrow("GitHub is temporarily unavailable");
|
||||
unavailable = false;
|
||||
const failedReads = metadataReads;
|
||||
await expect(gateway.executeTool({ ...input, parameters: { ...f.assessment, summary: "Changed assessment" } }))
|
||||
.rejects.toMatchObject({ reasonCode: "github_publication_unavailable" });
|
||||
expect(await f.action()).toBeUndefined();
|
||||
expect(metadataReads).toBe(failedReads);
|
||||
await db.insert(toolPolicies).values({ companyId: f.companyId, name: "Revoke review", policyType: "block", priority: 0,
|
||||
selectors: { catalogEntryId: tool.catalogEntryId! } });
|
||||
await expect(gateway.executeTool(input)).rejects.toThrow();
|
||||
expect(await f.action()).toBeUndefined();
|
||||
expect(metadataReads).toBe(failedReads);
|
||||
expect(f.responseWrites.map(write => write.method)).toEqual(["POST"]);
|
||||
});
|
||||
|
||||
it("retries an ambiguous GitHub edit without creating another comment", async () => {
|
||||
const f = await toolReplyFixture();
|
||||
let unavailable = true;
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
if (String(input).includes("/issues/comments/") && init?.method === "PATCH" && unavailable) throw new Error("Response lost");
|
||||
return undefined;
|
||||
});
|
||||
const service = githubChatReviewService(db, f.providerFetch);
|
||||
const result = await service.execute(f.session, "comment", { body: "Here is your answer", idempotencyKey: "retry-reply" });
|
||||
expect(result.status).toBe("failed");
|
||||
await expect(githubRunReplyState(db, { ...f.session, endpointId: f.endpoint.id })).resolves.toBe("unsettled");
|
||||
unavailable = false;
|
||||
const [action] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_publication")));
|
||||
await db.update(chatActions).set({ result: { ...action.result, retryAt: new Date(0).toISOString() } }).where(eq(chatActions.id, action.id));
|
||||
await service.processPending();
|
||||
expect(f.responseWrites.map(write => write.method)).toEqual(["POST", "PATCH"]);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
await expect(githubRunReplyState(db, { ...f.session, endpointId: f.endpoint.id })).resolves.toBe("confirmed");
|
||||
});
|
||||
|
||||
it.each(["none", "confirmed", "unsettled", "check_only", "different_run", "different_company", "wrong_agent", "denied", "ambiguous_exhausted", "cancelled_after_ambiguous", "missing_receipt"] as const)(
|
||||
"GitHub failure fallback respects exact tool delivery state: %s", async scenario => {
|
||||
const f = await toolReplyFixture();
|
||||
if (scenario !== "none") {
|
||||
await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: f.conversation.id,
|
||||
kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`,
|
||||
payload: { operation: scenario === "check_only" ? "assessment" : "comment", session: { ...f.session,
|
||||
...(scenario === "different_run" ? { runId: randomUUID() } : {}),
|
||||
...(scenario === "different_company" ? { companyId: randomUUID() } : {}),
|
||||
...(scenario === "wrong_agent" ? { agentId: f.replacementAgentId } : {}),
|
||||
} },
|
||||
status: scenario === "unsettled" ? "processing" : scenario === "denied" || scenario === "cancelled_after_ambiguous" ? "cancelled" : scenario === "ambiguous_exhausted" ? "failed" : "processed",
|
||||
result: scenario === "check_only" || scenario === "missing_receipt" ? {} : scenario === "denied" ? { code: "authorization_changed", attempts: 1 } : scenario === "cancelled_after_ambiguous" ? { code: "authorization_changed", attempts: 2 }
|
||||
: scenario === "ambiguous_exhausted" ? { code: "publication_failed", retryable: false, attempts: 8 }
|
||||
: { id: "41802", url: "https://github.com/paperclipai/paperclip/issues/418#issuecomment-41802" },
|
||||
});
|
||||
}
|
||||
const unresolved = ["unsettled", "ambiguous_exhausted", "cancelled_after_ambiguous", "missing_receipt"].includes(scenario);
|
||||
const expected = scenario === "confirmed" ? "confirmed" : unresolved ? "unsettled" : "none";
|
||||
await expect(githubRunReplyState(db, { ...f.session, endpointId: f.endpoint.id })).resolves.toBe(expected);
|
||||
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "test_runtime_failed" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
await enqueueChatRunMilestones(db); await f.service.processPendingPublications();
|
||||
await enqueueChatRunMilestones(db); await f.service.processPendingPublications();
|
||||
const posts = f.runtime.endpoints.get(f.endpoint.id)?.posts ?? [];
|
||||
expect(posts).toHaveLength(0);
|
||||
expect(f.responseWrites).toHaveLength(expected === "none" ? 2 : 1);
|
||||
if (expected === "none") expect(f.responseWrites[1]).toMatchObject({ method: "PATCH", body: expect.stringContaining("stopped before completing this turn") });
|
||||
const [fallback] = await db.select().from(chatPublications).where(and(eq(chatPublications.endpointId, f.endpoint.id),
|
||||
eq(chatPublications.idempotencyKey, `run:${f.run.id}:failed:${f.endpoint.id}`)));
|
||||
expect(fallback.state).toBe(expected === "none" ? "published" : "cancelled");
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["issues", "issue_comment", "pull_request_review_comment"])(
|
||||
"admits signed %s mentions with automation off, deduplicates and retains manual task authority", async (event) => {
|
||||
const f = await reviewBotFixture();
|
||||
const saved = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: saved.revision, configuration: { ...saved.configuration, defaults: { ...saved.configuration.defaults, invocation: "mentions_only", events: [], issueOpened: false }, repositories: { ...saved.configuration.repositories, "97531": { instructions: "Use repository-specific guidance" } } } }, "owner-user");
|
||||
const body = `@${f.endpoint.botUsername!.replace(/\[bot\]$/, "")} tell me a joke`;
|
||||
const target = { number: 83, title: "Say hello", body, user: { id: 42, login: "octocat", type: "User" }, labels: [] };
|
||||
const comment = { id: 83001, body, user: target.user, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), in_reply_to_id: 83000 };
|
||||
const payload = {
|
||||
action: event.includes("comment") ? "created" : event === "pull_request_review" ? "submitted" : "opened",
|
||||
installation: { id: 2468 },
|
||||
repository: { id: 97531, full_name: "PaperclipAI/Paperclip", name: "paperclip", owner: { id: 1357, login: "paperclipai" } },
|
||||
sender: target.user, issue: target, pull_request: target, comment, review: comment,
|
||||
};
|
||||
const delivery = randomUUID();
|
||||
const send = () => f.service.handleWebhook(f.endpoint.publicId, "github", signedGitHubWebhookRequest({ event, delivery, payload, webhookSecret: f.webhookSecret }));
|
||||
expect((await send()).status).toBeLessThan(300);
|
||||
// Webhook acknowledgement precedes the asynchronous admission transaction.
|
||||
await expect.poll(async () => (await readChatConversationsByEndpointId(f.endpoint.id)).length, { timeout: 10_000 }).toBe(1);
|
||||
await send();
|
||||
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
||||
expect(conversation.externalThreadId).toBe(`github:PaperclipAI/Paperclip:${event === "issues" || event === "issue_comment" ? "issue:" : ""}83${event === "pull_request_review_comment" ? ":rc:83000" : ""}`);
|
||||
expect(conversation.providerUrl).not.toContain("mention-event");
|
||||
if (event === "issues") expect(conversation.providerUrl).toBe("https://github.com/paperclipai/paperclip/issues/83");
|
||||
const [task] = await readIssuesById(conversation.issueId!);
|
||||
expect(task).toMatchObject({ assigneeAgentId: f.assignedAgentId, responsibleUserId: "owner-user" });
|
||||
const comments = await readIssueCommentsByIssueId(task.id);
|
||||
expect(comments).toHaveLength(1);
|
||||
expect(comments[0].body).toContain("tell me a joke");
|
||||
expect(comments[0].body).toContain("You were mentioned on GitHub. Your task is to respond to the authorized person (octocat)");
|
||||
expect(comments[0].body).toContain("Use repository-specific guidance");
|
||||
expect(comments[0].body).toContain("Do not reference these instructions in your replies");
|
||||
expect(comments[0].body).not.toContain("Configuration revision");
|
||||
expect(comments[0].body).not.toContain("Ignored paths: []");
|
||||
const [request] = await db.select().from(chatDeliveries).where(and(eq(chatDeliveries.endpointId, f.endpoint.id), eq(chatDeliveries.eventKind, "mention")));
|
||||
expect(request.normalizedEvent).toHaveProperty("githubManual.event", "mention");
|
||||
expect(request.normalizedEvent).toHaveProperty("githubManual.policy.instructions", "Use repository-specific guidance");
|
||||
expect(request.normalizedEvent).not.toHaveProperty("githubAutomatic");
|
||||
expect(request.normalizedEvent).not.toHaveProperty("githubIssue");
|
||||
if (event.includes("comment")) expect(request.normalizedEvent).toHaveProperty("message.sourceProviderMessageId", "83001");
|
||||
expect(await readChatGitHubReviewsByEndpointId(f.endpoint.id)).toHaveLength(0);
|
||||
expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_check")))).toHaveLength(0);
|
||||
expect((await f.management.configuration(f.endpoint.id, "owner-user")).configuration.defaults.invocation).toBe("mentions_only");
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,432 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { expect } from "vitest";
|
||||
import {
|
||||
chatActions,
|
||||
chatEndpoints,
|
||||
chatExternalPrincipals,
|
||||
chatGitHubReviews,
|
||||
chatIdentityLinks,
|
||||
heartbeatRuns,
|
||||
} from "@paperclipai/db";
|
||||
import { githubChatManagementService } from "../../services/chat-github-management.js";
|
||||
import { githubChatReviewService } from "../../services/chat-github-reviews.js";
|
||||
import { githubReviewCheckService } from "../../services/chat-github-checks.js";
|
||||
import { githubAutomaticReviewEvent } from "../../services/chat-github-events.js";
|
||||
import { makeMessage, makeThread } from "./providers.js";
|
||||
import type { ChatChannelHarness } from "./harness.js";
|
||||
import type { GitHubHarness } from "./github-harness.js";
|
||||
|
||||
export function createGitHubReviewHarness(h: ChatChannelHarness, gh: GitHubHarness) {
|
||||
const {
|
||||
seedCompany,
|
||||
readChatConversationsByEndpointId,
|
||||
readChatEndpointsById,
|
||||
readChatGitHubReviewsByEndpointId,
|
||||
chatWakeContext,
|
||||
deliverMessage,
|
||||
} = h;
|
||||
const { signedGitHubWebhookRequest, configuredGitHubEndpoint } = gh;
|
||||
|
||||
async function reviewBotFixture() {
|
||||
const db = h.db;
|
||||
const fixture = await seedCompany();
|
||||
const context = await configuredGitHubEndpoint(fixture, {}, true);
|
||||
const endpoint = await context.service.get(context.endpoint.id);
|
||||
const [principal] = await db
|
||||
.insert(chatExternalPrincipals)
|
||||
.values({
|
||||
companyId: fixture.companyId,
|
||||
provider: "github",
|
||||
providerAccountId: endpoint.providerAccountId!,
|
||||
externalId: "42",
|
||||
kind: "user",
|
||||
displayName: "Octocat",
|
||||
handle: "octocat",
|
||||
isBot: false,
|
||||
})
|
||||
.returning();
|
||||
await db.insert(chatIdentityLinks).values({
|
||||
companyId: fixture.companyId,
|
||||
endpointId: endpoint.id,
|
||||
principalId: principal.id,
|
||||
paperclipUserId: "owner-user",
|
||||
status: "linked",
|
||||
confirmedAt: new Date(),
|
||||
});
|
||||
const management = githubChatManagementService(db, context.providerFetch);
|
||||
const initial = await management.configuration(endpoint.id, "owner-user");
|
||||
await management.saveConfiguration(
|
||||
endpoint.id,
|
||||
{
|
||||
expectedRevision: initial.revision,
|
||||
configuration: { ...initial.configuration, toolsEnabled: true },
|
||||
},
|
||||
"owner-user",
|
||||
);
|
||||
await context.service.update(
|
||||
endpoint.id,
|
||||
{ allowGroupChats: true },
|
||||
"owner-user",
|
||||
);
|
||||
return { ...fixture, ...context, endpoint, principal, management };
|
||||
}
|
||||
|
||||
async function subscribedGitHubFixture(threadId = "github:paperclipai/paperclip:issue:419") {
|
||||
const f = await reviewBotFixture();
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: threadId }).thread;
|
||||
await deliverMessage({
|
||||
callbacks: f.callbacks,
|
||||
endpointId: f.endpoint.id,
|
||||
provider: "github",
|
||||
thread,
|
||||
trigger: "mention",
|
||||
message: makeMessage({
|
||||
id: "41901",
|
||||
text: `@${f.endpoint.botUsername} start this thread`,
|
||||
userId: "42",
|
||||
userName: "octocat",
|
||||
mentioned: true,
|
||||
}),
|
||||
});
|
||||
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
||||
return { ...f, thread, conversation };
|
||||
}
|
||||
|
||||
async function addPeerGitHubBot(f: Awaited<ReturnType<typeof reviewBotFixture>>) {
|
||||
const db = h.db;
|
||||
const peer = await f.service.create(
|
||||
f.companyId,
|
||||
{ provider: "github", assignedAgentId: f.assignedAgentId, name: "Gonzo" },
|
||||
"owner-user",
|
||||
);
|
||||
await db
|
||||
.update(chatEndpoints)
|
||||
.set({ botUsername: "gonzo[bot]", status: "active" })
|
||||
.where(eq(chatEndpoints.id, peer.id));
|
||||
return peer;
|
||||
}
|
||||
|
||||
async function toolReplyFixture(
|
||||
threadId = "github:paperclipai/paperclip:issue:418",
|
||||
reportOnly = false,
|
||||
findingCategories?: string[],
|
||||
) {
|
||||
const db = h.db;
|
||||
const f = await reviewBotFixture();
|
||||
if (reportOnly || findingCategories) {
|
||||
const config = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(
|
||||
f.endpoint.id,
|
||||
{
|
||||
expectedRevision: config.revision,
|
||||
configuration: {
|
||||
...config.configuration,
|
||||
defaults: {
|
||||
...config.configuration.defaults,
|
||||
...(reportOnly ? { ratingThreshold: null } : {}),
|
||||
...(findingCategories ? { findingCategories } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
"owner-user",
|
||||
);
|
||||
}
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: threadId }).thread;
|
||||
await deliverMessage({
|
||||
callbacks: f.callbacks,
|
||||
endpointId: f.endpoint.id,
|
||||
provider: "github",
|
||||
thread,
|
||||
trigger: "mention",
|
||||
message: makeMessage({
|
||||
id: "41801",
|
||||
text: "Are you there?",
|
||||
userId: "42",
|
||||
userName: "octocat",
|
||||
mentioned: true,
|
||||
}),
|
||||
});
|
||||
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
||||
const [run] = await db
|
||||
.insert(heartbeatRuns)
|
||||
.values({
|
||||
companyId: f.companyId,
|
||||
agentId: f.assignedAgentId,
|
||||
status: "running",
|
||||
runtimeMode: "native",
|
||||
contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id,
|
||||
issueId: conversation.issueId,
|
||||
provider: "github",
|
||||
providerMessageId: "41801",
|
||||
}),
|
||||
})
|
||||
.returning();
|
||||
const session = {
|
||||
companyId: f.companyId,
|
||||
agentId: f.assignedAgentId,
|
||||
issueId: conversation.issueId,
|
||||
runId: run.id,
|
||||
};
|
||||
return { ...f, conversation, run, session };
|
||||
}
|
||||
|
||||
async function publicationRetryFixture(findingCategories?: string[]) {
|
||||
const db = h.db;
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418", true, findingCategories);
|
||||
const head = "b".repeat(40);
|
||||
const inline: Array<{ id: number; body: string; html_url: string; user: { login: string } }> = [];
|
||||
const checks: Array<{ id: number; external_id: string; app: { id: number }; html_url: string }> = [];
|
||||
const writes: Array<{ path: string; method: string }> = [];
|
||||
const provider = async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/pulls/418")) {
|
||||
return Response.json({
|
||||
number: 418,
|
||||
state: "open",
|
||||
draft: false,
|
||||
head: { sha: head },
|
||||
base: { sha: "a".repeat(40), ref: "master" },
|
||||
user: { id: 42, login: "octocat", type: "User" },
|
||||
labels: [],
|
||||
});
|
||||
}
|
||||
if (url.includes("/files?")) {
|
||||
return Response.json([
|
||||
{ filename: "src/math.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" },
|
||||
]);
|
||||
}
|
||||
if (url.includes("/pulls/418/comments?")) return Response.json(inline);
|
||||
if (url.includes("/check-runs?")) return Response.json({ check_runs: checks });
|
||||
if (init?.method === "POST" && url.endsWith("/pulls/418/comments")) {
|
||||
writes.push({ path: url, method: init.method });
|
||||
const item = {
|
||||
id: 420 + inline.length,
|
||||
body: JSON.parse(String(init.body)).body,
|
||||
html_url: "https://github.com/acme/repo/pull/418#discussion_r420",
|
||||
user: { login: f.endpoint.botUsername! },
|
||||
};
|
||||
inline.push(item);
|
||||
return Response.json(item);
|
||||
}
|
||||
if (url.includes("/check-runs") && init?.method) {
|
||||
writes.push({ path: url, method: init.method });
|
||||
const body = JSON.parse(String(init.body));
|
||||
const check = checks[0] ?? {
|
||||
id: 419,
|
||||
external_id: body.external_id,
|
||||
app: { id: Number(f.endpoint.botExternalId) },
|
||||
html_url: "https://github.com/checks/419",
|
||||
};
|
||||
if (!checks.length) checks.push(check);
|
||||
return Response.json(check);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
f.setSupplementalProviderFetch(provider);
|
||||
const service = githubChatReviewService(db, f.providerFetch);
|
||||
await service.execute(f.session, "begin_review", { reviewedCommit: head });
|
||||
const assessment = {
|
||||
reviewedCommit: head,
|
||||
score: 3,
|
||||
complete: true,
|
||||
summary: "Advisory review",
|
||||
rationale: "Reviewed the file",
|
||||
coverage: { reviewedPaths: ["src/math.ts"], omittedPaths: [], limitations: [] },
|
||||
findings: [],
|
||||
};
|
||||
const action = async () =>
|
||||
(
|
||||
await db
|
||||
.select()
|
||||
.from(chatActions)
|
||||
.where(
|
||||
and(
|
||||
eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_review_publication"),
|
||||
),
|
||||
)
|
||||
)[0];
|
||||
return { ...f, service, head, assessment, provider, action, inline, checks, writes };
|
||||
}
|
||||
|
||||
async function reviewCheckWorkerFixture(status: "running" | "failed" = "failed") {
|
||||
const db = h.db;
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418");
|
||||
const config = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
const event = githubAutomaticReviewEvent(
|
||||
{
|
||||
action: "opened",
|
||||
repository: { id: 97531, full_name: "paperclipai/paperclip" },
|
||||
sender: { id: 42, login: "octocat" },
|
||||
pull_request: {
|
||||
number: 418,
|
||||
title: "Review",
|
||||
body: "",
|
||||
draft: false,
|
||||
base: { sha: "a".repeat(40), ref: "master" },
|
||||
head: { sha: "b".repeat(40) },
|
||||
user: { id: 42, login: "octocat" },
|
||||
labels: [],
|
||||
},
|
||||
},
|
||||
randomUUID(),
|
||||
)!;
|
||||
const [review] = await db
|
||||
.insert(chatGitHubReviews)
|
||||
.values({
|
||||
companyId: f.companyId,
|
||||
endpointId: f.endpoint.id,
|
||||
issueId: f.conversation.issueId!,
|
||||
runId: f.run.id,
|
||||
repositoryId: "97531",
|
||||
repository: event.repository,
|
||||
pullNumber: 418,
|
||||
headSha: event.headSha,
|
||||
deliveryId: event.deliveryId,
|
||||
configurationRevision: config.revision,
|
||||
policySnapshot: config.configuration.defaults,
|
||||
event,
|
||||
})
|
||||
.returning();
|
||||
await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const writes: Record<string, unknown>[] = [];
|
||||
const requests: string[] = [];
|
||||
let remoteHead = event.headSha;
|
||||
let unavailable = false;
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/pulls/418")) {
|
||||
requests.push(url);
|
||||
return Response.json({ head: { sha: remoteHead } });
|
||||
}
|
||||
if (url.includes("/check-runs?")) {
|
||||
requests.push(url);
|
||||
return Response.json({ check_runs: [] });
|
||||
}
|
||||
if (url.endsWith("/check-runs") && init?.method === "POST") {
|
||||
requests.push(url);
|
||||
if (unavailable) return Response.json({ message: "injected check outage" }, { status: 503 });
|
||||
writes.push(JSON.parse(String(init.body)));
|
||||
return Response.json({ id: 418, html_url: "https://github.com/checks/418" });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
const checks = githubReviewCheckService(db, f.providerFetch);
|
||||
const [endpoint] = await readChatEndpointsById(f.endpoint.id);
|
||||
const action = async () =>
|
||||
(
|
||||
await db
|
||||
.select()
|
||||
.from(chatActions)
|
||||
.where(
|
||||
and(
|
||||
eq(chatActions.endpointId, endpoint.id),
|
||||
eq(chatActions.kind, "github_review_check"),
|
||||
),
|
||||
)
|
||||
)[0];
|
||||
return {
|
||||
...f,
|
||||
event,
|
||||
review,
|
||||
endpoint,
|
||||
checks,
|
||||
writes,
|
||||
requests,
|
||||
action,
|
||||
enqueue: () => checks.enqueue(endpoint, event, true, "authorized"),
|
||||
setRemoteHead: (value: string) => {
|
||||
remoteHead = value;
|
||||
},
|
||||
setUnavailable: (value: boolean) => {
|
||||
unavailable = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function reviewProjectionFixture(cancelFirst = true) {
|
||||
const db = h.db;
|
||||
const f = await reviewBotFixture();
|
||||
const deliveryId = randomUUID();
|
||||
const payload = {
|
||||
action: "synchronize",
|
||||
installation: { id: 2468 },
|
||||
repository: {
|
||||
id: 97531,
|
||||
full_name: "paperclipai/paperclip",
|
||||
name: "paperclip",
|
||||
owner: { id: 1357, login: "paperclipai" },
|
||||
},
|
||||
sender: { id: 42, login: "octocat" },
|
||||
pull_request: {
|
||||
number: 82,
|
||||
title: "Rapid pushes",
|
||||
body: "",
|
||||
draft: false,
|
||||
base: { sha: "a".repeat(40), ref: "master" },
|
||||
head: { sha: "b".repeat(40) },
|
||||
user: { id: 42, login: "octocat", type: "User" },
|
||||
labels: [],
|
||||
},
|
||||
};
|
||||
f.setSupplementalProviderFetch(async (input) =>
|
||||
String(input).endsWith("/pulls/82")
|
||||
? Response.json({ ...payload.pull_request, head: { sha: "c".repeat(40) } })
|
||||
: undefined,
|
||||
);
|
||||
const checks = githubReviewCheckService(db, f.providerFetch);
|
||||
const [endpoint] = await readChatEndpointsById(f.endpoint.id);
|
||||
const event = githubAutomaticReviewEvent(payload, deliveryId)!;
|
||||
await checks.enqueue(endpoint, event, true, "authorized");
|
||||
const action = async () =>
|
||||
(
|
||||
await db
|
||||
.select()
|
||||
.from(chatActions)
|
||||
.where(
|
||||
and(
|
||||
eq(chatActions.endpointId, endpoint.id),
|
||||
eq(chatActions.kind, "github_review_check"),
|
||||
),
|
||||
)
|
||||
)[0];
|
||||
if (cancelFirst) await checks.processPending();
|
||||
const admit = async () => {
|
||||
expect(
|
||||
(
|
||||
await f.service.handleWebhook(
|
||||
endpoint.publicId,
|
||||
"github",
|
||||
signedGitHubWebhookRequest({
|
||||
event: "pull_request",
|
||||
delivery: deliveryId,
|
||||
payload,
|
||||
webhookSecret: f.webhookSecret,
|
||||
}),
|
||||
)
|
||||
).status,
|
||||
).toBeLessThan(300);
|
||||
await expect
|
||||
.poll(async () => (await readChatGitHubReviewsByEndpointId(endpoint.id)).length, {
|
||||
timeout: 10_000,
|
||||
})
|
||||
.toBe(1);
|
||||
return (await readChatGitHubReviewsByEndpointId(endpoint.id))[0];
|
||||
};
|
||||
const read = async (id: string) =>
|
||||
(await db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.id, id)))[0];
|
||||
return { ...f, endpoint, event, action, checks, admit, read };
|
||||
}
|
||||
|
||||
return {
|
||||
reviewBotFixture,
|
||||
subscribedGitHubFixture,
|
||||
addPeerGitHubBot,
|
||||
toolReplyFixture,
|
||||
publicationRetryFixture,
|
||||
reviewCheckWorkerFixture,
|
||||
reviewProjectionFixture,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, asc, eq } from "drizzle-orm";
|
||||
import { beforeAll, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import {
|
||||
chatActions,
|
||||
chatDeliveries,
|
||||
chatEndpoints,
|
||||
companySkills,
|
||||
heartbeatRuns,
|
||||
issueComments,
|
||||
issues,
|
||||
toolPolicies,
|
||||
} from "@paperclipai/db";
|
||||
// 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 { chatHistoryActionBlocks } from "../helpers/chat-history-proof.js";
|
||||
import { githubChatReviewService } from "../../services/chat-github-reviews.js";
|
||||
import { githubResponseCommentService } from "../../services/chat-github-response-comments.js";
|
||||
import { githubBotToolsForSession } from "../../services/chat-github-tools.js";
|
||||
import { resolveRunScopedMentionedSkillKeys } from "../../services/heartbeat/run-preparation.js";
|
||||
import { type TestDb, describeEmbeddedPostgres, makeThread, makeMessage } from "./providers.js";
|
||||
import { createChatChannelHarness } from "./harness.js";
|
||||
import { createGitHubHarness } from "./github-harness.js";
|
||||
import { createGitHubReviewHarness } from "./github-review-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("chat channels: github review publications", () => {
|
||||
const h = createChatChannelHarness();
|
||||
let db!: TestDb;
|
||||
beforeAll(() => { db = h.db; });
|
||||
const gh = createGitHubHarness(h);
|
||||
const rev = createGitHubReviewHarness(h, gh);
|
||||
const {
|
||||
seedCompany,
|
||||
readChatConversationsByEndpointId,
|
||||
readIssueCommentsByIssueId,
|
||||
readChatActionsById,
|
||||
readChatGitHubReviewsByEndpointId,
|
||||
chatWakeContext,
|
||||
deliverMessage,
|
||||
} = h;
|
||||
const {
|
||||
reviewBotFixture,
|
||||
subscribedGitHubFixture,
|
||||
addPeerGitHubBot,
|
||||
toolReplyFixture,
|
||||
publicationRetryFixture,
|
||||
} = rev;
|
||||
|
||||
describe("GitHub agent review publications", () => {
|
||||
it("loads only the current configured instruction skills, never provider links or another company", async () => {
|
||||
const f = await reviewBotFixture();
|
||||
const other = await seedCompany();
|
||||
const skill = async (name: string, companyId = f.companyId) => db.insert(companySkills).values({
|
||||
companyId, key: `company/${companyId}/${name}`, slug: name, name, markdown: `# ${name}`,
|
||||
}).returning().then((rows) => rows[0]);
|
||||
const common = await skill("common");
|
||||
const mention = await skill("mention");
|
||||
const next = await skill("next");
|
||||
const injected = await skill("injected");
|
||||
const foreign = await skill("foreign", other.companyId);
|
||||
// Use the production link format, including the slash picker identity.
|
||||
const { buildSkillMentionHref } = await import("@paperclipai/shared");
|
||||
const ref = (s: typeof common) => `[/skill](${buildSkillMentionHref(s.id, s.slug)})`;
|
||||
const saved = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: saved.revision, configuration: {
|
||||
...saved.configuration, defaults: { ...saved.configuration.defaults,
|
||||
instructions: `Use ${ref(common)}.`,
|
||||
prompts: { ...saved.configuration.defaults.prompts, mention: `Use ${ref(mention)}.`, opened: ref(injected) },
|
||||
},
|
||||
} }, "owner-user");
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: "github:paperclipai/paperclip:issue:419" }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41901", text: `@${f.endpoint.botUsername} ${ref(injected)}`, userId: "42", userName: "octocat", mentioned: true }) });
|
||||
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
||||
const [comment] = await readIssueCommentsByIssueId(conversation.issueId!);
|
||||
const args = { db, companyId: f.companyId, issueId: conversation.issueId!, commentIds: [comment.id] };
|
||||
expect(await resolveRunScopedMentionedSkillKeys(args)).toEqual([common.key, mention.key]);
|
||||
expect(comment.body).toContain(ref(common));
|
||||
expect(comment.body).toContain(ref(mention));
|
||||
expect(comment.body).toContain(ref(injected)); // Present as untrusted context, never assigned.
|
||||
expect(await resolveRunScopedMentionedSkillKeys({ ...args, companyId: other.companyId })).toEqual([]);
|
||||
const changed = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: changed.revision, configuration: {
|
||||
...changed.configuration, defaults: { ...changed.configuration.defaults, instructions: ref(next),
|
||||
prompts: { ...changed.configuration.defaults.prompts, comment: "Answer briefly." },
|
||||
},
|
||||
} }, "owner-user");
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "subscribed_message", message: makeMessage({ id: "41902", text: ref(injected), userId: "42", userName: "octocat" }) });
|
||||
const all = await readIssueCommentsByIssueId(conversation.issueId!).orderBy(asc(issueComments.createdAt));
|
||||
expect(all).toHaveLength(2);
|
||||
expect(await resolveRunScopedMentionedSkillKeys({ ...args, commentIds: [all[1].id] })).toEqual([next.key]);
|
||||
// A later event must not change the snapshot for a queued older wake.
|
||||
expect(await resolveRunScopedMentionedSkillKeys(args)).toEqual([common.key, mention.key]);
|
||||
expect(await resolveRunScopedMentionedSkillKeys({ ...args, commentIds: all.map((c) => c.id) })).toEqual(expect.arrayContaining([common.key, mention.key, next.key]));
|
||||
expect(await resolveRunScopedMentionedSkillKeys({ ...args, commentIds: [] })).toEqual([next.key]);
|
||||
const invalid = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: invalid.revision, configuration: {
|
||||
...invalid.configuration, defaults: { ...invalid.configuration.defaults, instructions: ref(foreign) },
|
||||
} }, "owner-user");
|
||||
// Instructions are captured on admission; changing configuration must
|
||||
// not change the already admitted wake above.
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "subscribed_message", message: makeMessage({ id: "41903", text: "Check again", userId: "42", userName: "octocat" }) });
|
||||
await expect(resolveRunScopedMentionedSkillKeys({ ...args, commentIds: [] })).rejects.toThrow("referenced skill is unavailable");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"github:paperclipai/paperclip:issue:419",
|
||||
"github:paperclipai/paperclip:419",
|
||||
"github:paperclipai/paperclip:419:rc:41899",
|
||||
])("suppresses subscribed GitHub comments for another connected bot in %s", async threadId => {
|
||||
const f = await subscribedGitHubFixture(threadId);
|
||||
await addPeerGitHubBot(f);
|
||||
const wakeCount = f.wakeup.mock.calls.length;
|
||||
const message = makeMessage({ id: "41902", text: "@GONZO[bot] tell me a joke", userId: "42", userName: "octocat" });
|
||||
const send = () => deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread: f.thread, trigger: "subscribed_message", message });
|
||||
await send(); await send();
|
||||
const rows = await db.select().from(chatDeliveries).where(and(eq(chatDeliveries.endpointId, f.endpoint.id), eq(chatDeliveries.providerEventId, `${threadId}:41902`)));
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ state: "filtered", principalId: null, redactedError: "GitHub message explicitly addresses a different recipient" });
|
||||
expect(rows[0].normalizedEvent).toHaveProperty("filtering.contentRetained", false);
|
||||
expect(JSON.stringify(rows[0].normalizedEvent)).not.toContain("tell me a joke");
|
||||
expect(await readIssueCommentsByIssueId(f.conversation.issueId!)).toHaveLength(1);
|
||||
expect(f.wakeup).toHaveBeenCalledTimes(wakeCount);
|
||||
expect(f.runtime.endpoints.get(f.endpoint.id)?.reactions).toEqual([]);
|
||||
expect(f.responseWrites).toHaveLength(1);
|
||||
expect(await f.service.listActivity(f.endpoint.id)).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ status: "filtered", detail: "GitHub message explicitly addresses a different recipient" }),
|
||||
]));
|
||||
});
|
||||
|
||||
it("admits a GitHub request explicitly addressed to both connected bots", async () => {
|
||||
const f = await subscribedGitHubFixture();
|
||||
await addPeerGitHubBot(f);
|
||||
const wakeCount = f.wakeup.mock.calls.length;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread: f.thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41902", text: `@gonzo @${f.endpoint.botUsername} both help`, userId: "42", userName: "octocat", mentioned: true }) });
|
||||
expect(await readIssueCommentsByIssueId(f.conversation.issueId!)).toHaveLength(2);
|
||||
expect(f.wakeup).toHaveBeenCalledTimes(wakeCount + 1);
|
||||
});
|
||||
|
||||
it("returns snapshot finding categories and publishes only accepted categories", async () => {
|
||||
const categories = ["custom-reliability"];
|
||||
const f = await publicationRetryFixture(categories);
|
||||
const begin = await f.service.execute(f.session, "begin_review", { reviewedCommit: f.head });
|
||||
expect(begin).toMatchObject({ findingCategories: categories });
|
||||
const config = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: config.revision,
|
||||
configuration: { ...config.configuration, defaults: { ...config.configuration.defaults, findingCategories: ["new-category"] } },
|
||||
}, "owner-user");
|
||||
expect(await f.service.execute(f.session, "begin_review", { reviewedCommit: f.head }))
|
||||
.toMatchObject({ findingCategories: categories });
|
||||
const finding = { key: "one", path: "src/math.ts", line: 1, side: "RIGHT", severity: "error", category: "invented", body: "Concrete issue" };
|
||||
await expect(f.service.execute(f.session, "submit_review", { ...f.assessment, findings: [finding] }, "bad-category"))
|
||||
.rejects.toThrow('Accepted finding categories: ["custom-reliability"]');
|
||||
expect(await f.action()).toBeUndefined();
|
||||
const result = await f.service.execute(f.session, "submit_review", { ...f.assessment,
|
||||
findings: [{ ...finding, category: categories[0] }],
|
||||
}, "accepted-category");
|
||||
expect(result).toMatchObject({ status: "processed" });
|
||||
const [review] = await readChatGitHubReviewsByEndpointId(f.endpoint.id);
|
||||
expect(review.assessment?.findings[0].category).toBe(categories[0]);
|
||||
expect((await f.action()).status).toBe("processed");
|
||||
expect(await chatHistoryActionBlocks(db, (await f.action()).id)).toBe(false);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
});
|
||||
|
||||
it("publishes one score heading when a newly configured bot submits a formatted summary", async () => {
|
||||
const f = await publicationRetryFixture();
|
||||
await db.update(chatEndpoints).set({ botDisplayName: "Fresh Review Bot" }).where(eq(chatEndpoints.id, f.endpoint.id));
|
||||
const submit = (await githubBotToolsForSession(db, f.session)).find(tool => tool.upstreamToolName === "submit_review")!;
|
||||
expect(submit.parametersSchema).toMatchObject({ properties: {
|
||||
summary: { description: expect.stringContaining("Review body only") },
|
||||
rationale: { description: expect.stringContaining("Do not repeat the summary") },
|
||||
} });
|
||||
const assessment = { ...f.assessment, summary: "## Fresh Review Bot — 2/5\n\n## Fresh Review Bot — 3/5\n\nAdvisory review\n\n### Findings\n\nKeep this section." };
|
||||
const result = await f.service.execute(f.session, "submit_review", assessment, "formatted-summary");
|
||||
expect(result).toMatchObject({ status: "processed", score: 3 });
|
||||
const body = [...f.responseComments.values()][0].body;
|
||||
expect(body).toMatch(/^## Fresh Review Bot — 3\/5\n\nAdvisory review/);
|
||||
expect(body.match(/^## Fresh Review Bot — /gm)).toHaveLength(1);
|
||||
expect(body).toContain("### Findings\n\nKeep this section.");
|
||||
expect(body).toContain(f.assessment.rationale);
|
||||
expect(body).toContain(`Reviewed commit: \`${f.head}\``);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
const [review] = await readChatGitHubReviewsByEndpointId(f.endpoint.id);
|
||||
expect(review.assessment?.summary).toBe(assessment.summary);
|
||||
});
|
||||
|
||||
it.each(["same_head", "new_head"] as const)("reuses one main GitHub PR comment across review requests: %s", async headCase => {
|
||||
const f = await publicationRetryFixture();
|
||||
await f.service.execute(f.session, "submit_review", f.assessment, "first-review");
|
||||
const originalId = [...f.responseComments.keys()][0];
|
||||
// Restart after a provider write whose shared receipt was lost. The
|
||||
// App-owned marker, rather than process memory, must recover the target.
|
||||
await db.update(chatActions).set({ result: null }).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_pr_response_comment")));
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41802", text: "Review again", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41802",
|
||||
}) }).returning();
|
||||
const session = { ...f.session, runId: next.id };
|
||||
const currentHead = headCase === "new_head" ? "c".repeat(40) : f.head;
|
||||
f.setSupplementalProviderFetch(async (input, init) => String(input).endsWith("/pulls/418")
|
||||
? Response.json({ number: 418, state: "open", draft: false, head: { sha: currentHead },
|
||||
base: { sha: "a".repeat(40), ref: "master" }, user: { id: 42, login: "octocat", type: "User" }, labels: [] })
|
||||
: f.provider(input, init));
|
||||
await f.service.execute(session, "begin_review", { reviewedCommit: currentHead });
|
||||
await f.service.execute(session, "submit_review", { ...f.assessment, reviewedCommit: currentHead, summary: "Second assessment" }, "second-review");
|
||||
expect([...f.responseComments.keys()]).toEqual([originalId]);
|
||||
expect(f.responseComments.get(originalId)?.body).toContain("Second assessment");
|
||||
expect(f.responseWrites.filter(write => write.method === "POST")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("ignores a review request addressed to an external GitHub bot", async () => {
|
||||
const f = await subscribedGitHubFixture("github:paperclipai/paperclip:419");
|
||||
const wakeCount = f.wakeup.mock.calls.length;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread: f.thread,
|
||||
trigger: "subscribed_message", message: makeMessage({ id: "41902", text: "@greptile review", userId: "42", userName: "octocat" }) });
|
||||
const [delivery] = await db.select().from(chatDeliveries).where(and(eq(chatDeliveries.endpointId, f.endpoint.id),
|
||||
eq(chatDeliveries.providerEventId, `${f.thread.id}:41902`)));
|
||||
expect(delivery.state).toBe("filtered");
|
||||
expect(f.wakeup).toHaveBeenCalledTimes(wakeCount);
|
||||
expect(await readIssueCommentsByIssueId(f.conversation.issueId!)).toHaveLength(1);
|
||||
expect(f.responseWrites).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reconciles a GitHub working comment when execution stops without a publication", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418");
|
||||
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "execution_finalization_deadline_exceeded" })
|
||||
.where(eq(heartbeatRuns.id, f.run.id));
|
||||
await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect([...f.responseComments.values()][0].body).toContain("stopped before completing");
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41802", text: "Review again", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect([...f.responseComments.values()][0].body).toContain("paused");
|
||||
});
|
||||
|
||||
it("recovers lost inline and check responses without duplicate GitHub publications", async () => {
|
||||
const f = await publicationRetryFixture();
|
||||
const lost = new Set<string>();
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
const response = await f.provider(input, init);
|
||||
if (init?.method === "POST" && /\/(?:comments|check-runs)$/.test(String(input)) && !lost.has(String(input))) {
|
||||
lost.add(String(input));
|
||||
throw new Error("Provider accepted the write but the response was lost");
|
||||
}
|
||||
return response;
|
||||
});
|
||||
const result = await f.service.execute(f.session, "submit_review", { ...f.assessment,
|
||||
findings: [{ key: "note", path: "src/math.ts", line: 1, side: "RIGHT", severity: "error", category: "correctness", body: "Example finding" }],
|
||||
}, "lost-receipts");
|
||||
expect(result).toMatchObject({ status: "processed", score: 3, conclusion: "neutral" });
|
||||
expect(f.inline).toHaveLength(1);
|
||||
expect(f.checks).toHaveLength(1);
|
||||
expect(f.writes.filter(write => write.method === "POST")).toHaveLength(2);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect((await f.action()).status).toBe("processed");
|
||||
}, 25_000);
|
||||
|
||||
it.each([503, 429])("automatically retries a transient GitHub review publication (HTTP %s)", async providerStatus => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418", true);
|
||||
const head = "b".repeat(40);
|
||||
let summaryAttempts = 0;
|
||||
const checks: Record<string, unknown>[] = [];
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/pulls/418")) return Response.json({ number: 418, state: "open", draft: false,
|
||||
head: { sha: head }, base: { sha: "a".repeat(40), ref: "master" }, user: { id: 42, login: "octocat", type: "User" }, labels: [] });
|
||||
if (url.includes("/files?")) return Response.json([{ filename: "src/math.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" }]);
|
||||
if (url.includes("/check-runs?")) return Response.json({ check_runs: [] });
|
||||
if (url.includes("/check-runs") && init?.method) {
|
||||
checks.push(JSON.parse(String(init.body)));
|
||||
return Response.json({ id: 419, html_url: "https://github.com/checks/419" });
|
||||
}
|
||||
if (url.includes("/issues/comments/") && init?.method === "PATCH" && ++summaryAttempts === 1)
|
||||
return new Response("Temporary provider failure", { status: providerStatus, headers: { "retry-after": "1" } });
|
||||
return undefined;
|
||||
});
|
||||
vi.stubGlobal("fetch", f.providerFetch);
|
||||
onTestFinished(() => { vi.unstubAllGlobals(); });
|
||||
const { createToolGatewayService } = await import("../../services/tool-gateway.js");
|
||||
const gateway = createToolGatewayService(db);
|
||||
const session = await gateway.createSession({ companyId: f.companyId, agentId: f.assignedAgentId, runId: f.run.id });
|
||||
const tool = (await githubBotToolsForSession(db, f.session)).find(tool => tool.upstreamToolName === "submit_review")!;
|
||||
await githubChatReviewService(db, f.providerFetch).execute(f.session, "begin_review", { reviewedCommit: head });
|
||||
const assessment = { reviewedCommit: head, score: 3, complete: true, summary: "Advisory review", rationale: "Reviewed the file",
|
||||
coverage: { reviewedPaths: ["src/math.ts"], omittedPaths: [], limitations: [] }, findings: [] };
|
||||
const idempotencyKey = randomUUID();
|
||||
const result = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment, idempotencyKey });
|
||||
expect(result).toMatchObject({ status: "completed", result: { data: { status: "processed", score: 3, conclusion: "neutral" } } });
|
||||
expect(summaryAttempts).toBe(2);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect(checks).toEqual([expect.objectContaining({ conclusion: "neutral", status: "completed" })]);
|
||||
const replay = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment, idempotencyKey });
|
||||
expect(replay).toMatchObject({ result: { data: { status: "processed", score: 3, conclusion: "neutral" } } });
|
||||
expect(summaryAttempts).toBe(2);
|
||||
const [action] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_publication")));
|
||||
expect(action).toMatchObject({ status: "processed" });
|
||||
expect((await readChatGitHubReviewsByEndpointId(f.endpoint.id))).toHaveLength(1);
|
||||
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: { ...assessment, score: 5 }, idempotencyKey }))
|
||||
.rejects.toMatchObject({ status: 409, reasonCode: "github_idempotency_conflict" });
|
||||
await db.insert(toolPolicies).values({ companyId: f.companyId, name: "Revoke review publication", policyType: "block", priority: 0,
|
||||
selectors: { catalogEntryId: tool.catalogEntryId! },
|
||||
});
|
||||
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment, idempotencyKey })).rejects.toThrow();
|
||||
expect(summaryAttempts).toBe(2);
|
||||
}, 25_000);
|
||||
});
|
||||
});
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
chatActions,
|
||||
chatDeliveries,
|
||||
heartbeatRuns,
|
||||
} from "@paperclipai/db";
|
||||
// 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 { githubResponseCommentService } from "../../services/chat-github-response-comments.js";
|
||||
import { type TestDb, describeEmbeddedPostgres, makeThread, makeMessage } from "./providers.js";
|
||||
import { createChatChannelHarness } from "./harness.js";
|
||||
import { createGitHubHarness } from "./github-harness.js";
|
||||
import { createGitHubReviewHarness } from "./github-review-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("chat channels: github review response maintenance", () => {
|
||||
const h = createChatChannelHarness();
|
||||
let db!: TestDb;
|
||||
beforeAll(() => { db = h.db; });
|
||||
const gh = createGitHubHarness(h);
|
||||
const rev = createGitHubReviewHarness(h, gh);
|
||||
const { readChatActionsById, chatWakeContext, deliverMessage } = h;
|
||||
const { publicationRetryFixture } = rev;
|
||||
|
||||
describe("GitHub agent review response maintenance", () => {
|
||||
it.each((["completed", "failed", "missing_decision", "comment_requested", "missing_semantic", "legacy", "uncommitted_native", "pending_publication", "missing_decision_then_missing", "uncommitted_then_failed", "malformed_null", "malformed_scalar", "malformed_schema", "malformed_action"] as const)
|
||||
.flatMap(scenario => ["external_chat_response_waiting", "preserved_result_status_unproven"].map(reason => ({ scenario, reason }))))(
|
||||
"keeps GitHub response maintenance truthful for a new request: $scenario ($reason)", async ({ scenario, reason }) => {
|
||||
const pendingPresentation = scenario.startsWith("missing_decision") || scenario.startsWith("uncommitted") || scenario.startsWith("malformed");
|
||||
const f = await publicationRetryFixture();
|
||||
await f.service.execute(f.session, "submit_review", f.assessment, "review-before-new-request");
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const originalId = [...f.responseComments.keys()][0];
|
||||
const originalBody = f.responseComments.get(originalId)!.body;
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "subscribed_message", message: makeMessage({ id: "41802", text: "Please handle this new request", userId: "42", userName: "octocat" }) });
|
||||
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: scenario === "failed" ? "failed" : "succeeded", runtimeMode: scenario === "legacy" ? "legacy" : "native",
|
||||
nativePhase: scenario.startsWith("uncommitted") ? "observed" : "committed", contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41802",
|
||||
}), resultJson: { finalizationPhase: "committed", finalizationReasonCode: reason,
|
||||
...(scenario === "missing_semantic" ? {} : { nativeResult: { schema: "paperclip.run_result.v1",
|
||||
reportedWorkDisposition: scenario === "completed" ? "completed" : "yielded",
|
||||
continuation: { kind: "response_wake", idempotencyKey: "new-request-wait" } } }),
|
||||
...(scenario.startsWith("missing_decision") ? {} : { presentationDecision: scenario === "malformed_null" ? null : scenario === "malformed_scalar" ? "pending" : {
|
||||
schema: scenario === "malformed_schema" ? "unknown" : "paperclip.run_presentation_decision.v1", chosenSource: "none",
|
||||
commentAction: scenario === "malformed_action" ? "unknown" : scenario === "comment_requested" ? "create" : "none", reasonCodes: ["yielded_control_plane_wait"] } }) } }).returning();
|
||||
if (scenario === "pending_publication") await db.insert(chatActions).values({ companyId: f.companyId,
|
||||
endpointId: f.endpoint.id, conversationId: f.conversation.id, kind: "github_review_publication",
|
||||
providerActionId: `github_publication:${randomUUID()}`, status: "processing",
|
||||
payload: { operation: "comment", session: { ...f.session, runId: next.id } } });
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
await responses.processPending();
|
||||
const [delivery] = await db.select().from(chatDeliveries).where(and(eq(chatDeliveries.endpointId, f.endpoint.id),
|
||||
eq(chatDeliveries.providerEventId, `${thread.id}:41802`)));
|
||||
const [response] = await db.select().from(chatActions).where(and(eq(chatActions.deliveryId, delivery.id),
|
||||
eq(chatActions.kind, "github_response_comment")));
|
||||
if (scenario === "pending_publication") {
|
||||
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
|
||||
expect(response.result?.final).not.toBe(true);
|
||||
// Waiting for the reply to settle spends no delivery retry.
|
||||
expect(response.status).toBe("processed");
|
||||
expect(response.result?.attempts).toBeUndefined();
|
||||
} else if (pendingPresentation) {
|
||||
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
|
||||
expect(response.result?.final).not.toBe(true);
|
||||
const pendingWrites = f.responseWrites.length;
|
||||
await responses.processPending();
|
||||
await expect(responses.failRun({ ...f.session, runId: next.id, endpointId: f.endpoint.id,
|
||||
body: "This turn ended without publishing a final response." })).rejects.toMatchObject({ status: 409 });
|
||||
expect(f.responseWrites).toHaveLength(pendingWrites);
|
||||
const failed = scenario === "uncommitted_then_failed";
|
||||
const missing = scenario === "missing_decision_then_missing";
|
||||
await db.update(heartbeatRuns).set({ status: failed ? "failed" : "succeeded",
|
||||
nativePhase: failed ? "failed" : "committed", resultJson: {
|
||||
...next.resultJson, finalizationPhase: failed ? "failed" : "committed",
|
||||
nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: missing ? "completed" : "yielded",
|
||||
continuation: missing ? null : { kind: "response_wake", idempotencyKey: "settled-request-wait" } },
|
||||
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none",
|
||||
commentAction: "none", reasonCodes: [missing ? "no_final_response" : "yielded_control_plane_wait"] },
|
||||
} }).where(eq(heartbeatRuns.id, next.id));
|
||||
await responses.processPending();
|
||||
// A status for the new request never replaces the published review.
|
||||
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
|
||||
expect((await readChatActionsById(response.id))[0]).toMatchObject({
|
||||
status: failed || missing ? "processed" : "cancelled", result: { final: true },
|
||||
});
|
||||
} else {
|
||||
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
|
||||
expect(response).toMatchObject({ status: "processed", result: { final: true, code: "published_response_kept" } });
|
||||
}
|
||||
const writes = f.responseWrites.length;
|
||||
await responses.processPending();
|
||||
expect(f.responseWrites).toHaveLength(writes);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,204 +1,58 @@
|
||||
import { chatHistoryActionBlocks } from "../helpers/chat-history-proof.js";
|
||||
import { registerGitHubReviewProjectionWork } from "../../services/chat-channels/github/review-projection-work.js";
|
||||
import { idleWorkSnapshot } from "../../services/task-admission.js";
|
||||
import { createSystemRecovery } from "../../services/system-recovery-state.js";
|
||||
import { remoteTerminationReceipt } from "../../services/remote-execution-termination.js";
|
||||
import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js";
|
||||
import { toolInvocations, toolPolicies } from "@paperclipai/db";
|
||||
import { githubChatManagementService } from "../../services/chat-github-management.js";
|
||||
import { githubChatReviewService } from "../../services/chat-github-reviews.js";
|
||||
import { githubResponseCommentService } from "../../services/chat-github-response-comments.js";
|
||||
import { githubReviewCheckService } from "../../services/chat-github-checks.js";
|
||||
import { githubAutomaticReviewEvent } from "../../services/chat-github-events.js";
|
||||
import { githubBotToolsForSession } from "../../services/chat-github-tools.js";
|
||||
import { buildPaperclipRuntimeMcpServers } from "../../services/heartbeat/run-preparation.js";
|
||||
import { createAssignedMcpTools } from "../../services/native-runtime/assigned-mcp-tools.js";
|
||||
import { createToolGatewayService } from "../../services/tool-gateway.js";
|
||||
import { initializeRunIdentity } from "../../services/run-identity.js";
|
||||
import { chatGitHubReviews } from "@paperclipai/db";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import request from "supertest";
|
||||
import { and, asc, eq, or } from "drizzle-orm";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { beforeAll, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, chatPublications, companies, companySkills, heartbeatRuns, issueComments, issueRecoveryActions, issues, nativeRunFinalizations, environmentLeases, workspaceOperations } from "@paperclipai/db";
|
||||
import type { Thread } from "chat";
|
||||
import {
|
||||
agents,
|
||||
agentWakeupRequests,
|
||||
chatActions,
|
||||
chatConversations,
|
||||
chatEndpoints,
|
||||
chatGitHubReviews,
|
||||
chatIdentityLinks,
|
||||
companies,
|
||||
environmentLeases,
|
||||
heartbeatRuns,
|
||||
issueComments,
|
||||
issueRecoveryActions,
|
||||
nativeRunFinalizations,
|
||||
} from "@paperclipai/db";
|
||||
// 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 { enqueueChatRunMilestones, githubRunReplyState } from "../../services/chat-run-publications.js";
|
||||
import { registerGitHubReviewProjectionWork } from "../../services/chat-channels/github/review-projection-work.js";
|
||||
import { idleWorkSnapshot } from "../../services/task-admission.js";
|
||||
import { createSystemRecovery } from "../../services/system-recovery-state.js";
|
||||
import { remoteTerminationReceipt } from "../../services/remote-execution-termination.js";
|
||||
import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js";
|
||||
import { githubReviewCheckService } from "../../services/chat-github-checks.js";
|
||||
import { extractWakeCommentIds, heartbeatService } from "../../services/heartbeat.js";
|
||||
import { resolveRunScopedMentionedSkillKeys } from "../../services/heartbeat/run-preparation.js";
|
||||
import { registerServerAdapter, runningProcesses, unregisterServerAdapter } from "../../adapters/index.js";
|
||||
import { runningProcesses } from "../../adapters/index.js";
|
||||
import { type TestDb, describeEmbeddedPostgres, FakeChatSdkRuntime, makeThread, makeMessage } from "./providers.js";
|
||||
import { createChatChannelHarness } from "./harness.js";
|
||||
import { createGitHubHarness } from "./github-harness.js";
|
||||
import { createGitHubReviewHarness } from "./github-review-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("chat channels: github review workflow", () => {
|
||||
const h = createChatChannelHarness();
|
||||
let db!: TestDb;
|
||||
beforeAll(() => { db = h.db; });
|
||||
const gh = createGitHubHarness(h);
|
||||
const { seedCompany, readChatConversationsByEndpointId, readChatEndpointsById, readIssueCommentsByIssueId, readIssuesById, readChatActionsById, readChatGitHubReviewsByEndpointId, readHeartbeatRunsByCompanyId, createService, chatWakeContext, deliverMessage } = h;
|
||||
const { signedGitHubWebhookRequest, configuredGitHubEndpoint } = gh;
|
||||
const rev = createGitHubReviewHarness(h, gh);
|
||||
const {
|
||||
readIssueCommentsByIssueId,
|
||||
readHeartbeatRunsByCompanyId,
|
||||
createService,
|
||||
deliverMessage,
|
||||
} = h;
|
||||
const {
|
||||
subscribedGitHubFixture,
|
||||
reviewCheckWorkerFixture,
|
||||
reviewProjectionFixture,
|
||||
} = rev;
|
||||
|
||||
describe("GitHub agent review workflow", () => {
|
||||
async function reviewBotFixture() {
|
||||
const fixture = await seedCompany();
|
||||
const context = await configuredGitHubEndpoint(fixture, {}, true);
|
||||
const endpoint = await context.service.get(context.endpoint.id);
|
||||
const [principal] = await db
|
||||
.insert(chatExternalPrincipals)
|
||||
.values({
|
||||
companyId: fixture.companyId,
|
||||
provider: "github",
|
||||
providerAccountId: endpoint.providerAccountId!,
|
||||
externalId: "42",
|
||||
kind: "user",
|
||||
displayName: "Octocat",
|
||||
handle: "octocat",
|
||||
isBot: false,
|
||||
})
|
||||
.returning();
|
||||
await db.insert(chatIdentityLinks).values({
|
||||
companyId: fixture.companyId,
|
||||
endpointId: endpoint.id,
|
||||
principalId: principal.id,
|
||||
paperclipUserId: "owner-user",
|
||||
status: "linked",
|
||||
confirmedAt: new Date(),
|
||||
});
|
||||
const management = githubChatManagementService(db, context.providerFetch);
|
||||
const initial = await management.configuration(endpoint.id, "owner-user");
|
||||
await management.saveConfiguration(
|
||||
endpoint.id,
|
||||
{
|
||||
expectedRevision: initial.revision,
|
||||
configuration: { ...initial.configuration, toolsEnabled: true },
|
||||
},
|
||||
"owner-user",
|
||||
);
|
||||
await context.service.update(
|
||||
endpoint.id,
|
||||
{ allowGroupChats: true },
|
||||
"owner-user",
|
||||
);
|
||||
return { ...fixture, ...context, endpoint, principal, management };
|
||||
}
|
||||
async function subscribedGitHubFixture(threadId = "github:paperclipai/paperclip:issue:419") {
|
||||
const f = await reviewBotFixture();
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: threadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41901", text: `@${f.endpoint.botUsername} start this thread`, userId: "42", userName: "octocat", mentioned: true }) });
|
||||
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
||||
return { ...f, thread, conversation };
|
||||
}
|
||||
async function addPeerGitHubBot(f: Awaited<ReturnType<typeof reviewBotFixture>>) {
|
||||
const peer = await f.service.create(f.companyId, { provider: "github", assignedAgentId: f.assignedAgentId, name: "Gonzo" }, "owner-user");
|
||||
await db.update(chatEndpoints).set({ botUsername: "gonzo[bot]", status: "active" }).where(eq(chatEndpoints.id, peer.id));
|
||||
return peer;
|
||||
}
|
||||
|
||||
async function toolReplyFixture(threadId = "github:paperclipai/paperclip:issue:418", reportOnly = false, findingCategories?: string[]) {
|
||||
const f = await reviewBotFixture();
|
||||
if (reportOnly || findingCategories) {
|
||||
const config = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: config.revision,
|
||||
configuration: { ...config.configuration, defaults: { ...config.configuration.defaults, ...(reportOnly ? { ratingThreshold: null } : {}), ...(findingCategories ? { findingCategories } : {}) } },
|
||||
}, "owner-user");
|
||||
}
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: threadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41801", text: "Are you there?", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id, issueId: conversation.issueId, provider: "github", providerMessageId: "41801",
|
||||
}) }).returning();
|
||||
const session = { companyId: f.companyId, agentId: f.assignedAgentId, issueId: conversation.issueId, runId: run.id };
|
||||
return { ...f, conversation, run, session };
|
||||
}
|
||||
|
||||
async function publicationRetryFixture(findingCategories?: string[]) {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418", true, findingCategories);
|
||||
const head = "b".repeat(40);
|
||||
const inline: Array<{ id: number; body: string; html_url: string; user: { login: string } }> = [];
|
||||
const checks: Array<{ id: number; external_id: string; app: { id: number }; html_url: string }> = [];
|
||||
const writes: Array<{ path: string; method: string }> = [];
|
||||
const provider = async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/pulls/418")) return Response.json({ number: 418, state: "open", draft: false,
|
||||
head: { sha: head }, base: { sha: "a".repeat(40), ref: "master" }, user: { id: 42, login: "octocat", type: "User" }, labels: [] });
|
||||
if (url.includes("/files?")) return Response.json([{ filename: "src/math.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" }]);
|
||||
if (url.includes("/pulls/418/comments?")) return Response.json(inline);
|
||||
if (url.includes("/check-runs?")) return Response.json({ check_runs: checks });
|
||||
if (init?.method === "POST" && url.endsWith("/pulls/418/comments")) {
|
||||
writes.push({ path: url, method: init.method });
|
||||
const item = { id: 420 + inline.length, body: JSON.parse(String(init.body)).body,
|
||||
html_url: "https://github.com/acme/repo/pull/418#discussion_r420", user: { login: f.endpoint.botUsername! } };
|
||||
inline.push(item);
|
||||
return Response.json(item);
|
||||
}
|
||||
if (url.includes("/check-runs") && init?.method) {
|
||||
writes.push({ path: url, method: init.method });
|
||||
const body = JSON.parse(String(init.body));
|
||||
const check = checks[0] ?? { id: 419, external_id: body.external_id, app: { id: Number(f.endpoint.botExternalId) }, html_url: "https://github.com/checks/419" };
|
||||
if (!checks.length) checks.push(check);
|
||||
return Response.json(check);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
f.setSupplementalProviderFetch(provider);
|
||||
const service = githubChatReviewService(db, f.providerFetch);
|
||||
await service.execute(f.session, "begin_review", { reviewedCommit: head });
|
||||
const assessment = { reviewedCommit: head, score: 3, complete: true, summary: "Advisory review", rationale: "Reviewed the file",
|
||||
coverage: { reviewedPaths: ["src/math.ts"], omittedPaths: [], limitations: [] }, findings: [] };
|
||||
const action = async () => (await db.select().from(chatActions).where(and(
|
||||
eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_publication"),
|
||||
)))[0];
|
||||
return { ...f, service, head, assessment, provider, action, inline, checks, writes };
|
||||
}
|
||||
|
||||
const passiveWait = (key: string) => ({ status: "succeeded" as const, runtimeMode: "native" as const, nativePhase: "committed", resultJson: {
|
||||
finalizationPhase: "committed", finalizationReasonCode: "external_chat_response_waiting",
|
||||
nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded",
|
||||
continuation: { kind: "response_wake", idempotencyKey: key } },
|
||||
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none",
|
||||
commentAction: "none", reasonCodes: ["yielded_control_plane_wait"] } } });
|
||||
|
||||
async function reviewCheckWorkerFixture(status: "running" | "failed" = "failed") {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418");
|
||||
const config = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
const event = githubAutomaticReviewEvent({ action: "opened", repository: { id: 97531, full_name: "paperclipai/paperclip" }, sender: { id: 42, login: "octocat" },
|
||||
pull_request: { number: 418, title: "Review", body: "", draft: false, base: { sha: "a".repeat(40), ref: "master" }, head: { sha: "b".repeat(40) }, user: { id: 42, login: "octocat" }, labels: [] } }, randomUUID())!;
|
||||
const [review] = await db.insert(chatGitHubReviews).values({ companyId: f.companyId, endpointId: f.endpoint.id,
|
||||
issueId: f.conversation.issueId!, runId: f.run.id, repositoryId: "97531", repository: event.repository, pullNumber: 418, headSha: event.headSha,
|
||||
deliveryId: event.deliveryId, configurationRevision: config.revision, policySnapshot: config.configuration.defaults, event }).returning();
|
||||
await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const writes: Record<string, unknown>[] = [], requests: string[] = [];
|
||||
let remoteHead = event.headSha, unavailable = false;
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/pulls/418")) { requests.push(url); return Response.json({ head: { sha: remoteHead } }); }
|
||||
if (url.includes("/check-runs?")) { requests.push(url); return Response.json({ check_runs: [] }); }
|
||||
if (url.endsWith("/check-runs") && init?.method === "POST") {
|
||||
requests.push(url);
|
||||
if (unavailable) return Response.json({ message: "injected check outage" }, { status: 503 });
|
||||
writes.push(JSON.parse(String(init.body)));
|
||||
return Response.json({ id: 418, html_url: "https://github.com/checks/418" });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
const checks = githubReviewCheckService(db, f.providerFetch);
|
||||
const [endpoint] = await readChatEndpointsById(f.endpoint.id);
|
||||
const action = async () => (await db.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id), eq(chatActions.kind, "github_review_check"))))[0];
|
||||
return { ...f, event, review, endpoint, checks, writes, requests, action,
|
||||
enqueue: () => checks.enqueue(endpoint, event, true, "authorized"),
|
||||
setRemoteHead: (value: string) => { remoteHead = value; }, setUnavailable: (value: boolean) => { unavailable = value; } };
|
||||
}
|
||||
|
||||
it("keeps GitHub review check history quiet and wakes from the real enqueue producer", async () => {
|
||||
const f = await reviewCheckWorkerFixture();
|
||||
const errors: unknown[] = [];
|
||||
@@ -224,36 +78,6 @@ describeEmbeddedPostgres("chat channels: github review workflow", () => {
|
||||
} finally { await coordinator.stop(); vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
async function reviewProjectionFixture(cancelFirst = true) {
|
||||
const f = await reviewBotFixture();
|
||||
const deliveryId = randomUUID();
|
||||
const payload = { action: "synchronize", installation: { id: 2468 },
|
||||
repository: { id: 97531, full_name: "paperclipai/paperclip", name: "paperclip", owner: { id: 1357, login: "paperclipai" } },
|
||||
sender: { id: 42, login: "octocat" },
|
||||
pull_request: { number: 82, title: "Rapid pushes", body: "", draft: false,
|
||||
base: { sha: "a".repeat(40), ref: "master" }, head: { sha: "b".repeat(40) },
|
||||
user: { id: 42, login: "octocat", type: "User" }, labels: [] } };
|
||||
f.setSupplementalProviderFetch(async input => String(input).endsWith("/pulls/82")
|
||||
? Response.json({ ...payload.pull_request, head: { sha: "c".repeat(40) } }) : undefined);
|
||||
const checks = githubReviewCheckService(db, f.providerFetch);
|
||||
const [endpoint] = await readChatEndpointsById(f.endpoint.id);
|
||||
const event = githubAutomaticReviewEvent(payload, deliveryId)!;
|
||||
await checks.enqueue(endpoint, event, true, "authorized");
|
||||
const action = async () => (await db.select().from(chatActions).where(and(
|
||||
eq(chatActions.endpointId, endpoint.id), eq(chatActions.kind, "github_review_check"))))[0];
|
||||
if (cancelFirst) await checks.processPending();
|
||||
const admit = async () => {
|
||||
expect((await f.service.handleWebhook(endpoint.publicId, "github", signedGitHubWebhookRequest({
|
||||
event: "pull_request", delivery: deliveryId, payload, webhookSecret: f.webhookSecret,
|
||||
}))).status).toBeLessThan(300);
|
||||
await expect.poll(async () => (await readChatGitHubReviewsByEndpointId(endpoint.id)).length,
|
||||
{ timeout: 10_000 }).toBe(1);
|
||||
return (await readChatGitHubReviewsByEndpointId(endpoint.id))[0];
|
||||
};
|
||||
const read = async (id: string) => (await db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.id, id)))[0];
|
||||
return { ...f, endpoint, event, action, checks, admit, read };
|
||||
}
|
||||
|
||||
it("wakes stale GitHub review projection repair from real admission and leaves settled history quiet", async () => {
|
||||
const f = await reviewProjectionFixture();
|
||||
const errors: unknown[] = [];
|
||||
@@ -439,683 +263,6 @@ describeEmbeddedPostgres("chat channels: github review workflow", () => {
|
||||
}, 40_000,
|
||||
);
|
||||
|
||||
it("loads only the current configured instruction skills, never provider links or another company", async () => {
|
||||
const f = await reviewBotFixture();
|
||||
const other = await seedCompany();
|
||||
const skill = async (name: string, companyId = f.companyId) => db.insert(companySkills).values({
|
||||
companyId, key: `company/${companyId}/${name}`, slug: name, name, markdown: `# ${name}`,
|
||||
}).returning().then((rows) => rows[0]);
|
||||
const common = await skill("common");
|
||||
const mention = await skill("mention");
|
||||
const next = await skill("next");
|
||||
const injected = await skill("injected");
|
||||
const foreign = await skill("foreign", other.companyId);
|
||||
// Use the production link format, including the slash picker identity.
|
||||
const { buildSkillMentionHref } = await import("@paperclipai/shared");
|
||||
const ref = (s: typeof common) => `[/skill](${buildSkillMentionHref(s.id, s.slug)})`;
|
||||
const saved = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: saved.revision, configuration: {
|
||||
...saved.configuration, defaults: { ...saved.configuration.defaults,
|
||||
instructions: `Use ${ref(common)}.`,
|
||||
prompts: { ...saved.configuration.defaults.prompts, mention: `Use ${ref(mention)}.`, opened: ref(injected) },
|
||||
},
|
||||
} }, "owner-user");
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: "github:paperclipai/paperclip:issue:419" }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41901", text: `@${f.endpoint.botUsername} ${ref(injected)}`, userId: "42", userName: "octocat", mentioned: true }) });
|
||||
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
||||
const [comment] = await readIssueCommentsByIssueId(conversation.issueId!);
|
||||
const args = { db, companyId: f.companyId, issueId: conversation.issueId!, commentIds: [comment.id] };
|
||||
expect(await resolveRunScopedMentionedSkillKeys(args)).toEqual([common.key, mention.key]);
|
||||
expect(comment.body).toContain(ref(common));
|
||||
expect(comment.body).toContain(ref(mention));
|
||||
expect(comment.body).toContain(ref(injected)); // Present as untrusted context, never assigned.
|
||||
expect(await resolveRunScopedMentionedSkillKeys({ ...args, companyId: other.companyId })).toEqual([]);
|
||||
const changed = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: changed.revision, configuration: {
|
||||
...changed.configuration, defaults: { ...changed.configuration.defaults, instructions: ref(next),
|
||||
prompts: { ...changed.configuration.defaults.prompts, comment: "Answer briefly." },
|
||||
},
|
||||
} }, "owner-user");
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "subscribed_message", message: makeMessage({ id: "41902", text: ref(injected), userId: "42", userName: "octocat" }) });
|
||||
const all = await readIssueCommentsByIssueId(conversation.issueId!).orderBy(asc(issueComments.createdAt));
|
||||
expect(all).toHaveLength(2);
|
||||
expect(await resolveRunScopedMentionedSkillKeys({ ...args, commentIds: [all[1].id] })).toEqual([next.key]);
|
||||
// A later event must not change the snapshot for a queued older wake.
|
||||
expect(await resolveRunScopedMentionedSkillKeys(args)).toEqual([common.key, mention.key]);
|
||||
expect(await resolveRunScopedMentionedSkillKeys({ ...args, commentIds: all.map((c) => c.id) })).toEqual(expect.arrayContaining([common.key, mention.key, next.key]));
|
||||
expect(await resolveRunScopedMentionedSkillKeys({ ...args, commentIds: [] })).toEqual([next.key]);
|
||||
const invalid = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: invalid.revision, configuration: {
|
||||
...invalid.configuration, defaults: { ...invalid.configuration.defaults, instructions: ref(foreign) },
|
||||
} }, "owner-user");
|
||||
// Instructions are captured on admission; changing configuration must
|
||||
// not change the already admitted wake above.
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "subscribed_message", message: makeMessage({ id: "41903", text: 'Check again', userId: "42", userName: "octocat" }) });
|
||||
await expect(resolveRunScopedMentionedSkillKeys({ ...args, commentIds: [] })).rejects.toThrow("referenced skill is unavailable");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"github:paperclipai/paperclip:issue:419",
|
||||
"github:paperclipai/paperclip:419",
|
||||
"github:paperclipai/paperclip:419:rc:41899",
|
||||
])("suppresses subscribed GitHub comments for another connected bot in %s", async threadId => {
|
||||
const f = await subscribedGitHubFixture(threadId);
|
||||
await addPeerGitHubBot(f);
|
||||
const wakeCount = f.wakeup.mock.calls.length;
|
||||
const message = makeMessage({ id: "41902", text: "@GONZO[bot] tell me a joke", userId: "42", userName: "octocat" });
|
||||
const send = () => deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread: f.thread, trigger: "subscribed_message", message });
|
||||
await send(); await send();
|
||||
const rows = await db.select().from(chatDeliveries).where(and(eq(chatDeliveries.endpointId, f.endpoint.id), eq(chatDeliveries.providerEventId, `${threadId}:41902`)));
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ state: "filtered", principalId: null, redactedError: "GitHub message explicitly addresses a different recipient" });
|
||||
expect(rows[0].normalizedEvent).toHaveProperty("filtering.contentRetained", false);
|
||||
expect(JSON.stringify(rows[0].normalizedEvent)).not.toContain("tell me a joke");
|
||||
expect(await readIssueCommentsByIssueId(f.conversation.issueId!)).toHaveLength(1);
|
||||
expect(f.wakeup).toHaveBeenCalledTimes(wakeCount);
|
||||
expect(f.runtime.endpoints.get(f.endpoint.id)?.reactions).toEqual([]);
|
||||
expect(f.responseWrites).toHaveLength(1);
|
||||
expect(await f.service.listActivity(f.endpoint.id)).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ status: "filtered", detail: "GitHub message explicitly addresses a different recipient" }),
|
||||
]));
|
||||
});
|
||||
|
||||
it("admits a GitHub request explicitly addressed to both connected bots", async () => {
|
||||
const f = await subscribedGitHubFixture();
|
||||
await addPeerGitHubBot(f);
|
||||
const wakeCount = f.wakeup.mock.calls.length;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread: f.thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41902", text: `@gonzo @${f.endpoint.botUsername} both help`, userId: "42", userName: "octocat", mentioned: true }) });
|
||||
expect(await readIssueCommentsByIssueId(f.conversation.issueId!)).toHaveLength(2);
|
||||
expect(f.wakeup).toHaveBeenCalledTimes(wakeCount + 1);
|
||||
});
|
||||
|
||||
it("returns snapshot finding categories and publishes only accepted categories", async () => {
|
||||
const categories = ["custom-reliability"];
|
||||
const f = await publicationRetryFixture(categories);
|
||||
const begin = await f.service.execute(f.session, "begin_review", { reviewedCommit: f.head });
|
||||
expect(begin).toMatchObject({ findingCategories: categories });
|
||||
const config = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: config.revision,
|
||||
configuration: { ...config.configuration, defaults: { ...config.configuration.defaults, findingCategories: ["new-category"] } },
|
||||
}, "owner-user");
|
||||
expect(await f.service.execute(f.session, "begin_review", { reviewedCommit: f.head }))
|
||||
.toMatchObject({ findingCategories: categories });
|
||||
const finding = { key: "one", path: "src/math.ts", line: 1, side: "RIGHT", severity: "error", category: "invented", body: "Concrete issue" };
|
||||
await expect(f.service.execute(f.session, "submit_review", { ...f.assessment, findings: [finding] }, "bad-category"))
|
||||
.rejects.toThrow('Accepted finding categories: ["custom-reliability"]');
|
||||
expect(await f.action()).toBeUndefined();
|
||||
const result = await f.service.execute(f.session, "submit_review", { ...f.assessment,
|
||||
findings: [{ ...finding, category: categories[0] }],
|
||||
}, "accepted-category");
|
||||
expect(result).toMatchObject({ status: "processed" });
|
||||
const [review] = await readChatGitHubReviewsByEndpointId(f.endpoint.id);
|
||||
expect(review.assessment?.findings[0].category).toBe(categories[0]);
|
||||
expect((await f.action()).status).toBe("processed");
|
||||
expect(await chatHistoryActionBlocks(db, (await f.action()).id)).toBe(false);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
});
|
||||
|
||||
it("publishes one score heading when a newly configured bot submits a formatted summary", async () => {
|
||||
const f = await publicationRetryFixture();
|
||||
await db.update(chatEndpoints).set({ botDisplayName: "Fresh Review Bot" }).where(eq(chatEndpoints.id, f.endpoint.id));
|
||||
const submit = (await githubBotToolsForSession(db, f.session)).find(tool => tool.upstreamToolName === "submit_review")!;
|
||||
expect(submit.parametersSchema).toMatchObject({ properties: {
|
||||
summary: { description: expect.stringContaining("Review body only") },
|
||||
rationale: { description: expect.stringContaining("Do not repeat the summary") },
|
||||
} });
|
||||
const assessment = { ...f.assessment, summary: "## Fresh Review Bot — 2/5\n\n## Fresh Review Bot — 3/5\n\nAdvisory review\n\n### Findings\n\nKeep this section." };
|
||||
const result = await f.service.execute(f.session, "submit_review", assessment, "formatted-summary");
|
||||
expect(result).toMatchObject({ status: "processed", score: 3 });
|
||||
const body = [...f.responseComments.values()][0].body;
|
||||
expect(body).toMatch(/^## Fresh Review Bot — 3\/5\n\nAdvisory review/);
|
||||
expect(body.match(/^## Fresh Review Bot — /gm)).toHaveLength(1);
|
||||
expect(body).toContain("### Findings\n\nKeep this section.");
|
||||
expect(body).toContain(f.assessment.rationale);
|
||||
expect(body).toContain(`Reviewed commit: \`${f.head}\``);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
const [review] = await readChatGitHubReviewsByEndpointId(f.endpoint.id);
|
||||
expect(review.assessment?.summary).toBe(assessment.summary);
|
||||
});
|
||||
|
||||
it.each((["completed", "failed", "missing_decision", "comment_requested", "missing_semantic", "legacy", "uncommitted_native", "pending_publication", "missing_decision_then_missing", "uncommitted_then_failed", "malformed_null", "malformed_scalar", "malformed_schema", "malformed_action"] as const)
|
||||
.flatMap(scenario => ["external_chat_response_waiting", "preserved_result_status_unproven"].map(reason => ({ scenario, reason }))))(
|
||||
"keeps GitHub response maintenance truthful for a new request: $scenario ($reason)", async ({ scenario, reason }) => {
|
||||
const pendingPresentation = scenario.startsWith("missing_decision") || scenario.startsWith("uncommitted") || scenario.startsWith("malformed");
|
||||
const f = await publicationRetryFixture();
|
||||
await f.service.execute(f.session, "submit_review", f.assessment, "review-before-new-request");
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const originalId = [...f.responseComments.keys()][0];
|
||||
const originalBody = f.responseComments.get(originalId)!.body;
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "subscribed_message", message: makeMessage({ id: "41802", text: "Please handle this new request", userId: "42", userName: "octocat" }) });
|
||||
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: scenario === "failed" ? "failed" : "succeeded", runtimeMode: scenario === "legacy" ? "legacy" : "native",
|
||||
nativePhase: scenario.startsWith("uncommitted") ? "observed" : "committed", contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41802",
|
||||
}), resultJson: { finalizationPhase: "committed", finalizationReasonCode: reason,
|
||||
...(scenario === "missing_semantic" ? {} : { nativeResult: { schema: "paperclip.run_result.v1",
|
||||
reportedWorkDisposition: scenario === "completed" ? "completed" : "yielded",
|
||||
continuation: { kind: "response_wake", idempotencyKey: "new-request-wait" } } }),
|
||||
...(scenario.startsWith("missing_decision") ? {} : { presentationDecision: scenario === "malformed_null" ? null : scenario === "malformed_scalar" ? "pending" : {
|
||||
schema: scenario === "malformed_schema" ? "unknown" : "paperclip.run_presentation_decision.v1", chosenSource: "none",
|
||||
commentAction: scenario === "malformed_action" ? "unknown" : scenario === "comment_requested" ? "create" : "none", reasonCodes: ["yielded_control_plane_wait"] } }) } }).returning();
|
||||
if (scenario === "pending_publication") await db.insert(chatActions).values({ companyId: f.companyId,
|
||||
endpointId: f.endpoint.id, conversationId: f.conversation.id, kind: "github_review_publication",
|
||||
providerActionId: `github_publication:${randomUUID()}`, status: "processing",
|
||||
payload: { operation: "comment", session: { ...f.session, runId: next.id } } });
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
await responses.processPending();
|
||||
const [delivery] = await db.select().from(chatDeliveries).where(and(eq(chatDeliveries.endpointId, f.endpoint.id),
|
||||
eq(chatDeliveries.providerEventId, `${thread.id}:41802`)));
|
||||
const [response] = await db.select().from(chatActions).where(and(eq(chatActions.deliveryId, delivery.id),
|
||||
eq(chatActions.kind, "github_response_comment")));
|
||||
if (scenario === "pending_publication") {
|
||||
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
|
||||
expect(response.result?.final).not.toBe(true);
|
||||
// Waiting for the reply to settle spends no delivery retry.
|
||||
expect(response.status).toBe("processed");
|
||||
expect(response.result?.attempts).toBeUndefined();
|
||||
} else if (pendingPresentation) {
|
||||
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
|
||||
expect(response.result?.final).not.toBe(true);
|
||||
const pendingWrites = f.responseWrites.length;
|
||||
await responses.processPending();
|
||||
await expect(responses.failRun({ ...f.session, runId: next.id, endpointId: f.endpoint.id,
|
||||
body: "This turn ended without publishing a final response." })).rejects.toMatchObject({ status: 409 });
|
||||
expect(f.responseWrites).toHaveLength(pendingWrites);
|
||||
const failed = scenario === "uncommitted_then_failed";
|
||||
const missing = scenario === "missing_decision_then_missing";
|
||||
await db.update(heartbeatRuns).set({ status: failed ? "failed" : "succeeded",
|
||||
nativePhase: failed ? "failed" : "committed", resultJson: {
|
||||
...next.resultJson, finalizationPhase: failed ? "failed" : "committed",
|
||||
nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: missing ? "completed" : "yielded",
|
||||
continuation: missing ? null : { kind: "response_wake", idempotencyKey: "settled-request-wait" } },
|
||||
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none",
|
||||
commentAction: "none", reasonCodes: [missing ? "no_final_response" : "yielded_control_plane_wait"] },
|
||||
} }).where(eq(heartbeatRuns.id, next.id));
|
||||
await responses.processPending();
|
||||
// A status for the new request never replaces the published review.
|
||||
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
|
||||
expect((await readChatActionsById(response.id))[0]).toMatchObject({
|
||||
status: failed || missing ? "processed" : "cancelled", result: { final: true },
|
||||
});
|
||||
} else {
|
||||
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
|
||||
expect(response).toMatchObject({ status: "processed", result: { final: true, code: "published_response_kept" } });
|
||||
}
|
||||
const writes = f.responseWrites.length;
|
||||
await responses.processPending();
|
||||
expect(f.responseWrites).toHaveLength(writes);
|
||||
});
|
||||
|
||||
it.each(["same_head", "new_head"] as const)("reuses one main GitHub PR comment across review requests: %s", async headCase => {
|
||||
const f = await publicationRetryFixture();
|
||||
await f.service.execute(f.session, "submit_review", f.assessment, "first-review");
|
||||
const originalId = [...f.responseComments.keys()][0];
|
||||
// Restart after a provider write whose shared receipt was lost. The
|
||||
// App-owned marker, rather than process memory, must recover the target.
|
||||
await db.update(chatActions).set({ result: null }).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_pr_response_comment")));
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41802", text: "Review again", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41802",
|
||||
}) }).returning();
|
||||
const session = { ...f.session, runId: next.id };
|
||||
const currentHead = headCase === "new_head" ? "c".repeat(40) : f.head;
|
||||
f.setSupplementalProviderFetch(async (input, init) => String(input).endsWith("/pulls/418")
|
||||
? Response.json({ number: 418, state: "open", draft: false, head: { sha: currentHead },
|
||||
base: { sha: "a".repeat(40), ref: "master" }, user: { id: 42, login: "octocat", type: "User" }, labels: [] })
|
||||
: f.provider(input, init));
|
||||
await f.service.execute(session, "begin_review", { reviewedCommit: currentHead });
|
||||
await f.service.execute(session, "submit_review", { ...f.assessment, reviewedCommit: currentHead, summary: "Second assessment" }, "second-review");
|
||||
expect([...f.responseComments.keys()]).toEqual([originalId]);
|
||||
expect(f.responseComments.get(originalId)?.body).toContain("Second assessment");
|
||||
expect(f.responseWrites.filter(write => write.method === "POST")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("ignores a review request addressed to an external GitHub bot", async () => {
|
||||
const f = await subscribedGitHubFixture("github:paperclipai/paperclip:419");
|
||||
const wakeCount = f.wakeup.mock.calls.length;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread: f.thread,
|
||||
trigger: "subscribed_message", message: makeMessage({ id: "41902", text: "@greptile review", userId: "42", userName: "octocat" }) });
|
||||
const [delivery] = await db.select().from(chatDeliveries).where(and(eq(chatDeliveries.endpointId, f.endpoint.id),
|
||||
eq(chatDeliveries.providerEventId, `${f.thread.id}:41902`)));
|
||||
expect(delivery.state).toBe("filtered");
|
||||
expect(f.wakeup).toHaveBeenCalledTimes(wakeCount);
|
||||
expect(await readIssueCommentsByIssueId(f.conversation.issueId!)).toHaveLength(1);
|
||||
expect(f.responseWrites).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reconciles a GitHub working comment when execution stops without a publication", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418");
|
||||
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "execution_finalization_deadline_exceeded" })
|
||||
.where(eq(heartbeatRuns.id, f.run.id));
|
||||
await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect([...f.responseComments.values()][0].body).toContain("stopped before completing");
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41802", text: "Review again", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect([...f.responseComments.values()][0].body).toContain("paused");
|
||||
});
|
||||
|
||||
it("recovers lost inline and check responses without duplicate GitHub publications", async () => {
|
||||
const f = await publicationRetryFixture();
|
||||
const lost = new Set<string>();
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
const response = await f.provider(input, init);
|
||||
if (init?.method === "POST" && /\/(?:comments|check-runs)$/.test(String(input)) && !lost.has(String(input))) {
|
||||
lost.add(String(input));
|
||||
throw new Error("Provider accepted the write but the response was lost");
|
||||
}
|
||||
return response;
|
||||
});
|
||||
const result = await f.service.execute(f.session, "submit_review", { ...f.assessment,
|
||||
findings: [{ key: "note", path: "src/math.ts", line: 1, side: "RIGHT", severity: "error", category: "correctness", body: "Example finding" }],
|
||||
}, "lost-receipts");
|
||||
expect(result).toMatchObject({ status: "processed", score: 3, conclusion: "neutral" });
|
||||
expect(f.inline).toHaveLength(1);
|
||||
expect(f.checks).toHaveLength(1);
|
||||
expect(f.writes.filter(write => write.method === "POST")).toHaveLength(2);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect((await f.action()).status).toBe("processed");
|
||||
}, 25_000);
|
||||
|
||||
it.each([503, 429])("automatically retries a transient GitHub review publication (HTTP %s)", async providerStatus => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418", true);
|
||||
const head = "b".repeat(40);
|
||||
let summaryAttempts = 0;
|
||||
const checks: Record<string, unknown>[] = [];
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/pulls/418")) return Response.json({ number: 418, state: "open", draft: false,
|
||||
head: { sha: head }, base: { sha: "a".repeat(40), ref: "master" }, user: { id: 42, login: "octocat", type: "User" }, labels: [] });
|
||||
if (url.includes("/files?")) return Response.json([{ filename: "src/math.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" }]);
|
||||
if (url.includes("/check-runs?")) return Response.json({ check_runs: [] });
|
||||
if (url.includes("/check-runs") && init?.method) {
|
||||
checks.push(JSON.parse(String(init.body)));
|
||||
return Response.json({ id: 419, html_url: "https://github.com/checks/419" });
|
||||
}
|
||||
if (url.includes("/issues/comments/") && init?.method === "PATCH" && ++summaryAttempts === 1)
|
||||
return new Response("Temporary provider failure", { status: providerStatus, headers: { "retry-after": "1" } });
|
||||
return undefined;
|
||||
});
|
||||
vi.stubGlobal("fetch", f.providerFetch);
|
||||
onTestFinished(() => { vi.unstubAllGlobals(); });
|
||||
const { createToolGatewayService } = await import("../../services/tool-gateway.js");
|
||||
const gateway = createToolGatewayService(db);
|
||||
const session = await gateway.createSession({ companyId: f.companyId, agentId: f.assignedAgentId, runId: f.run.id });
|
||||
const tool = (await githubBotToolsForSession(db, f.session)).find(tool => tool.upstreamToolName === "submit_review")!;
|
||||
await githubChatReviewService(db, f.providerFetch).execute(f.session, "begin_review", { reviewedCommit: head });
|
||||
const assessment = { reviewedCommit: head, score: 3, complete: true, summary: "Advisory review", rationale: "Reviewed the file",
|
||||
coverage: { reviewedPaths: ["src/math.ts"], omittedPaths: [], limitations: [] }, findings: [] };
|
||||
const idempotencyKey = randomUUID();
|
||||
const result = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment, idempotencyKey });
|
||||
expect(result).toMatchObject({ status: "completed", result: { data: { status: "processed", score: 3, conclusion: "neutral" } } });
|
||||
expect(summaryAttempts).toBe(2);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect(checks).toEqual([expect.objectContaining({ conclusion: "neutral", status: "completed" })]);
|
||||
const replay = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment, idempotencyKey });
|
||||
expect(replay).toMatchObject({ result: { data: { status: "processed", score: 3, conclusion: "neutral" } } });
|
||||
expect(summaryAttempts).toBe(2);
|
||||
const [action] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_publication")));
|
||||
expect(action).toMatchObject({ status: "processed" });
|
||||
expect((await readChatGitHubReviewsByEndpointId(f.endpoint.id))).toHaveLength(1);
|
||||
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: { ...assessment, score: 5 }, idempotencyKey }))
|
||||
.rejects.toMatchObject({ status: 409, reasonCode: "github_idempotency_conflict" });
|
||||
await db.insert(toolPolicies).values({ companyId: f.companyId, name: "Revoke review publication", policyType: "block", priority: 0,
|
||||
selectors: { catalogEntryId: tool.catalogEntryId! },
|
||||
});
|
||||
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment, idempotencyKey })).rejects.toThrow();
|
||||
expect(summaryAttempts).toBe(2);
|
||||
}, 25_000);
|
||||
|
||||
it.each([
|
||||
{ boardFollowUp: false, legacyOrigin: false },
|
||||
{ boardFollowUp: true, legacyOrigin: false },
|
||||
{ boardFollowUp: false, legacyOrigin: true },
|
||||
{ boardFollowUp: true, legacyOrigin: true },
|
||||
])("keeps GitHub review tools callable through a later native task gateway (board follow-up: $boardFollowUp, legacy origin: $legacyOrigin)", async ({ boardFollowUp, legacyOrigin }) => {
|
||||
vi.stubEnv("PAPERCLIP_API_URL", "https://paperclip.example.test");
|
||||
onTestFinished(() => { vi.unstubAllEnvs(); });
|
||||
const f = await publicationRetryFixture();
|
||||
const identity = await initializeRunIdentity(db, {
|
||||
companyId: f.companyId, runId: f.run.id, issueId: f.conversation.issueId!,
|
||||
responsibleUserId: "owner-user", messageIds: legacyOrigin ? [] : [String(f.run.contextSnapshot?.wakeCommentId)], cause: "instruction",
|
||||
});
|
||||
vi.stubGlobal("fetch", f.providerFetch);
|
||||
onTestFinished(() => { vi.unstubAllGlobals(); });
|
||||
const [agent] = await db.select().from(agents).where(eq(agents.id, f.assignedAgentId));
|
||||
const gateway = createToolGatewayService(db);
|
||||
const first = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: f.run.id });
|
||||
const firstTools = await createAssignedMcpTools({ gateway, gatewayPublicId: new URL(first[0].url).pathname.split("/").at(-1)!, bearerToken: first[0].token });
|
||||
expect(await firstTools.execute({ tool: "paperclip_search_assigned_tools", arguments: { query: "begin_review" } })).toMatchObject({ tools: expect.arrayContaining([expect.objectContaining({ name: expect.stringContaining("begin_review") })]) });
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const [later] = await db.insert(heartbeatRuns).values({
|
||||
companyId: f.companyId, agentId: f.assignedAgentId, status: "running", runtimeMode: "native",
|
||||
nativeIssueId: f.conversation.issueId, contextSnapshot: { wakeReason: "issue_monitor_due" },
|
||||
}).returning();
|
||||
const [boardMessage] = boardFollowUp ? await db.insert(issueComments).values({
|
||||
companyId: f.companyId, issueId: f.conversation.issueId!, authorType: "user", authorUserId: "owner-user", body: "Finish the review",
|
||||
}).returning() : [];
|
||||
await initializeRunIdentity(db, {
|
||||
companyId: f.companyId, runId: later.id, issueId: f.conversation.issueId!,
|
||||
responsibleUserId: "owner-user", parentContextId: identity.id, messageIds: boardMessage ? [boardMessage.id] : [], cause: "monitor",
|
||||
});
|
||||
const servers = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: later.id });
|
||||
expect(servers).toHaveLength(1);
|
||||
await expect(gateway.createSession({ companyId: f.companyId, agentId: f.assignedAgentId, runId: later.id, issueId: randomUUID() }))
|
||||
.rejects.toMatchObject({ reasonCode: "run_context_mismatch" });
|
||||
const assigned = await createAssignedMcpTools({ gateway, gatewayPublicId: new URL(servers[0].url).pathname.split("/").at(-1)!, bearerToken: servers[0].token });
|
||||
expect(await assigned.execute({ tool: "paperclip_search_assigned_tools", arguments: { query: "begin_review" } })).toMatchObject({ tools: expect.arrayContaining([expect.objectContaining({ name: expect.stringContaining("begin_review") })]) });
|
||||
const read = assigned.definitions().find(tool => String(tool.name).includes("read_pull_request"))!;
|
||||
expect(await assigned.execute({ tool: String(read.name), arguments: { section: "metadata" } })).toMatchObject({ data: { pull: { number: 418 } } });
|
||||
const begin = assigned.definitions().find(tool => String(tool.name).includes("begin_review"))!;
|
||||
await assigned.execute({ tool: String(begin.name), arguments: { reviewedCommit: f.head } });
|
||||
const submit = assigned.definitions().find(tool => String(tool.name).includes("submit_review"))!;
|
||||
expect(await assigned.execute({ tool: String(submit.name), arguments: f.assessment })).toMatchObject({ data: { status: "processed", score: 3 } });
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect([...f.responseComments.values()][0].body).toContain("Advisory review");
|
||||
await db.update(chatIdentityLinks).set({ status: "revoked" }).where(eq(chatIdentityLinks.endpointId, f.endpoint.id));
|
||||
await expect(assigned.execute({ tool: String(read.name), arguments: { section: "metadata" } })).rejects.toThrow();
|
||||
});
|
||||
|
||||
describe("replies in review finding threads behind an active run", () => {
|
||||
const pr = "github:paperclipai/paperclip:17044";
|
||||
async function findingThreadFixture() {
|
||||
vi.stubEnv("PAPERCLIP_API_URL", "https://paperclip.example.test");
|
||||
onTestFinished(() => { vi.unstubAllEnvs(); });
|
||||
const f = await subscribedGitHubFixture(pr);
|
||||
const adapterType = `github-finding-thread-test-${randomUUID()}`;
|
||||
const execute = vi.fn(async (_input: { runId: string; context: Record<string, unknown> }) => ({
|
||||
exitCode: 0, signal: null, timedOut: false, errorMessage: null, summary: "Answered the finding thread",
|
||||
}));
|
||||
registerServerAdapter({ type: adapterType, supportsLocalAgentJwt: false, execute,
|
||||
testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }) });
|
||||
const heartbeat = heartbeatService(db);
|
||||
const activeRunId = randomUUID();
|
||||
onTestFinished(async () => {
|
||||
runningProcesses.delete(activeRunId);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
unregisterServerAdapter(adapterType);
|
||||
});
|
||||
const issueId = f.conversation.issueId!;
|
||||
await db.update(companies).set({ defaultResponsibleUserId: "owner-user" }).where(eq(companies.id, f.companyId));
|
||||
await db.update(agents).set({ adapterType, runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } })
|
||||
.where(eq(agents.id, f.assignedAgentId));
|
||||
// Published findings bind their inline threads to the PR review task.
|
||||
const { id: _id, ...base } = f.conversation;
|
||||
const threads = await Promise.all(["4332012267", "4332012626"].map(async (commentId) => {
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: `${pr}:rc:${commentId}` }).thread;
|
||||
const [conversation] = await db.insert(chatConversations).values({ ...base, externalThreadId: thread.id,
|
||||
providerUrl: `https://github.com/paperclipai/paperclip/pull/17044#discussion_r${commentId}` }).returning();
|
||||
return { thread, conversation };
|
||||
}));
|
||||
// The review-request run still holds the task when the linked user replies.
|
||||
await db.insert(heartbeatRuns).values({ id: activeRunId, companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", startedAt: new Date(), contextSnapshot: { issueId, source: "chat:github" },
|
||||
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } });
|
||||
runningProcesses.set(activeRunId, { child: {} as never, graceSec: 0, processGroupId: null });
|
||||
await db.update(issues).set({ status: "in_review", executionRunId: activeRunId,
|
||||
executionAgentNameKey: "maya", executionLockedAt: new Date() }).where(eq(issues.id, issueId));
|
||||
f.wakeup.mockImplementation(heartbeat.wakeup);
|
||||
let messageId = 41950;
|
||||
const reply = (thread: Thread, text: string) => deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id,
|
||||
provider: "github", thread, trigger: "subscribed_message",
|
||||
message: makeMessage({ id: String(messageId++), text, userId: "42", userName: "octocat" }) });
|
||||
const commentFor = async (text: string) => (await readIssueCommentsByIssueId(issueId)).find((c) => c.body.includes(text))!.id;
|
||||
const finishActiveRun = async () => {
|
||||
runningProcesses.delete(activeRunId);
|
||||
await heartbeat.cancelRun(activeRunId, "Review request finished", { suppressImmediateRecovery: true });
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
};
|
||||
const followUpRuns = async () => (await readHeartbeatRunsByCompanyId(f.companyId))
|
||||
.filter((run) => run.id !== activeRunId && run.wakeupRequestId)
|
||||
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
||||
return { ...f, issueId, threads, execute, reply, commentFor, finishActiveRun, followUpRuns };
|
||||
}
|
||||
|
||||
it("answers each finding thread in its own run instead of one unattestable batch", async () => {
|
||||
const f = await findingThreadFixture();
|
||||
await f.reply(f.threads[0].thread, "First finding is intentional");
|
||||
await f.reply(f.threads[1].thread, "Second finding is fixed in the next commit");
|
||||
const first = await f.commentFor("First finding"), second = await f.commentFor("Second finding");
|
||||
await f.finishActiveRun();
|
||||
const runs = await f.followUpRuns();
|
||||
expect(runs.map((run) => ({ status: run.status, errorCode: run.errorCode, error: run.error })))
|
||||
.toEqual([{ status: "succeeded", errorCode: null, error: null }, { status: "succeeded", errorCode: null, error: null }]);
|
||||
expect(runs.map((run) => extractWakeCommentIds(run.contextSnapshot))).toEqual([[first], [second]]);
|
||||
expect(runs.map((run) => run.contextSnapshot?.chatConversationId))
|
||||
.toEqual(f.threads.map(({ conversation }) => conversation.id));
|
||||
expect(f.execute.mock.calls.map(([input]) => [input.context.paperclipExternalChatExecutionBound,
|
||||
extractWakeCommentIds(input.context)])).toEqual([[true, [first]], [true, [second]]]);
|
||||
});
|
||||
|
||||
it("still batches several replies in one finding thread into one attested run", async () => {
|
||||
const f = await findingThreadFixture();
|
||||
await f.reply(f.threads[0].thread, "First note on this finding");
|
||||
await f.reply(f.threads[0].thread, "Second note on this finding");
|
||||
const ids = [await f.commentFor("First note"), await f.commentFor("Second note")];
|
||||
await f.finishActiveRun();
|
||||
const runs = await f.followUpRuns();
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs[0]).toMatchObject({ status: "succeeded", errorCode: null });
|
||||
expect(extractWakeCommentIds(runs[0].contextSnapshot)).toEqual(ids);
|
||||
expect(f.execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("still denies each separated finding-thread run after the linked identity is revoked", async () => {
|
||||
const f = await findingThreadFixture();
|
||||
await f.reply(f.threads[0].thread, "First finding is intentional");
|
||||
await f.reply(f.threads[1].thread, "Second finding is fixed in the next commit");
|
||||
await db.update(chatIdentityLinks).set({ status: "revoked", revokedAt: new Date() })
|
||||
.where(eq(chatIdentityLinks.principalId, f.principal.id));
|
||||
await f.finishActiveRun();
|
||||
const runs = await f.followUpRuns();
|
||||
expect(runs.length).toBeGreaterThan(0);
|
||||
for (const run of runs) expect(run).toMatchObject({ status: "failed", errorCode: "setup_failed" });
|
||||
expect(f.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ label: "preserves an explicit shorter GitHub tool deadline and reconciles without duplicate publication", delayMs: 200, timeoutMs: 50 },
|
||||
])("recovers a durable GitHub publication receipt ($label)", async ({ delayMs, timeoutMs }) => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418", true);
|
||||
const head = "b".repeat(40);
|
||||
const checks: Record<string, unknown>[] = [];
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/pulls/418")) return Response.json({ number: 418, state: "open", draft: false,
|
||||
head: { sha: head }, base: { sha: "a".repeat(40), ref: "master" }, user: { id: 42, login: "octocat", type: "User" }, labels: [] });
|
||||
if (url.includes("/files?")) return Response.json([{ filename: "src/math.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" }]);
|
||||
if (url.includes("/check-runs?")) return Response.json({ check_runs: [] });
|
||||
if (url.includes("/check-runs") && init?.method) {
|
||||
checks.push(JSON.parse(String(init.body)));
|
||||
return Response.json({ id: 419, html_url: "https://github.com/checks/419" });
|
||||
}
|
||||
if (url.includes("/issues/comments/") && init?.method === "PATCH") {
|
||||
await new Promise(resolve => setTimeout(resolve, delayMs));
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
vi.stubGlobal("fetch", f.providerFetch);
|
||||
onTestFinished(() => { vi.unstubAllGlobals(); });
|
||||
const { createToolGatewayService } = await import("../../services/tool-gateway.js");
|
||||
const gateway = createToolGatewayService(db);
|
||||
const session = await gateway.createSession({ companyId: f.companyId, agentId: f.assignedAgentId, runId: f.run.id });
|
||||
const tools = await githubBotToolsForSession(db, f.session);
|
||||
const tool = tools.find(tool => tool.upstreamToolName === "submit_review")!;
|
||||
await githubChatReviewService(db, f.providerFetch).execute(f.session, "begin_review", { reviewedCommit: head });
|
||||
const assessment = { reviewedCommit: head, score: 5, complete: true,
|
||||
summary: "Reviewed the changed behavior and its callers. ".repeat(30),
|
||||
rationale: "Checked the mutation boundary and the client retry contract. ".repeat(30),
|
||||
coverage: { reviewedPaths: ["src/math.ts"], omittedPaths: [], limitations: [] }, findings: [] };
|
||||
const result = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment, timeoutMs })
|
||||
.then(value => ({ value }), error => ({ error }));
|
||||
await expect.poll(async () => {
|
||||
const [action] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_publication")));
|
||||
return action?.status;
|
||||
}, { timeout: 15_000 }).toBe("processed");
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
expect(f.responseWrites.map(write => write.method)).toEqual(["POST", "PATCH"]);
|
||||
expect(checks).toContainEqual(expect.objectContaining({ conclusion: "neutral", status: "completed" }));
|
||||
if (timeoutMs === undefined) {
|
||||
expect(result).toMatchObject({ value: { status: "completed", result: { data: { status: "processed", score: 5, conclusion: "neutral" } } } });
|
||||
} else {
|
||||
expect(result).toMatchObject({ error: { status: 504, reasonCode: "tool_timeout" } });
|
||||
}
|
||||
const writes = f.responseWrites.length;
|
||||
const replay = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: assessment });
|
||||
expect(replay).toMatchObject({ result: { data: { status: "processed", score: 5, conclusion: "neutral" } } });
|
||||
const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, replay.invocationId));
|
||||
expect(invocation).toMatchObject({ status: "succeeded", errorCode: null, errorMessage: null });
|
||||
expect(f.responseWrites).toHaveLength(writes);
|
||||
}, 40_000);
|
||||
|
||||
it("rejects changed requests and revoked access before repeating an unstaged review", async () => {
|
||||
const f = await publicationRetryFixture();
|
||||
let metadataReads = 0;
|
||||
let unavailable = true;
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
if (String(input).endsWith("/pulls/418")) {
|
||||
metadataReads++;
|
||||
if (unavailable) throw new Error("Connection closed before PR metadata arrived");
|
||||
}
|
||||
return f.provider(input, init);
|
||||
});
|
||||
vi.stubGlobal("fetch", f.providerFetch);
|
||||
onTestFinished(() => { vi.unstubAllGlobals(); });
|
||||
const gateway = createToolGatewayService(db);
|
||||
const session = await gateway.createSession({ companyId: f.companyId, agentId: f.assignedAgentId, runId: f.run.id });
|
||||
const tool = (await githubBotToolsForSession(db, f.session)).find(tool => tool.upstreamToolName === "submit_review")!;
|
||||
const input = { sessionToken: session.token, tool: tool.name, parameters: f.assessment, idempotencyKey: "preflight-request" };
|
||||
await expect(gateway.executeTool(input)).rejects.toThrow("GitHub is temporarily unavailable");
|
||||
unavailable = false;
|
||||
const failedReads = metadataReads;
|
||||
await expect(gateway.executeTool({ ...input, parameters: { ...f.assessment, summary: "Changed assessment" } }))
|
||||
.rejects.toMatchObject({ reasonCode: "github_publication_unavailable" });
|
||||
expect(await f.action()).toBeUndefined();
|
||||
expect(metadataReads).toBe(failedReads);
|
||||
await db.insert(toolPolicies).values({ companyId: f.companyId, name: "Revoke review", policyType: "block", priority: 0,
|
||||
selectors: { catalogEntryId: tool.catalogEntryId! } });
|
||||
await expect(gateway.executeTool(input)).rejects.toThrow();
|
||||
expect(await f.action()).toBeUndefined();
|
||||
expect(metadataReads).toBe(failedReads);
|
||||
expect(f.responseWrites.map(write => write.method)).toEqual(["POST"]);
|
||||
});
|
||||
|
||||
it("retries an ambiguous GitHub edit without creating another comment", async () => {
|
||||
const f = await toolReplyFixture();
|
||||
let unavailable = true;
|
||||
f.setSupplementalProviderFetch(async (input, init) => {
|
||||
if (String(input).includes("/issues/comments/") && init?.method === "PATCH" && unavailable) throw new Error("Response lost");
|
||||
return undefined;
|
||||
});
|
||||
const service = githubChatReviewService(db, f.providerFetch);
|
||||
const result = await service.execute(f.session, "comment", { body: "Here is your answer", idempotencyKey: "retry-reply" });
|
||||
expect(result.status).toBe("failed");
|
||||
await expect(githubRunReplyState(db, { ...f.session, endpointId: f.endpoint.id })).resolves.toBe("unsettled");
|
||||
unavailable = false;
|
||||
const [action] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_publication")));
|
||||
await db.update(chatActions).set({ result: { ...action.result, retryAt: new Date(0).toISOString() } }).where(eq(chatActions.id, action.id));
|
||||
await service.processPending();
|
||||
expect(f.responseWrites.map(write => write.method)).toEqual(["POST", "PATCH"]);
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
await expect(githubRunReplyState(db, { ...f.session, endpointId: f.endpoint.id })).resolves.toBe("confirmed");
|
||||
});
|
||||
|
||||
it.each(["none", "confirmed", "unsettled", "check_only", "different_run", "different_company", "wrong_agent", "denied", "ambiguous_exhausted", "cancelled_after_ambiguous", "missing_receipt"] as const)(
|
||||
"GitHub failure fallback respects exact tool delivery state: %s", async scenario => {
|
||||
const f = await toolReplyFixture();
|
||||
if (scenario !== "none") {
|
||||
await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: f.conversation.id,
|
||||
kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`,
|
||||
payload: { operation: scenario === "check_only" ? "assessment" : "comment", session: { ...f.session,
|
||||
...(scenario === "different_run" ? { runId: randomUUID() } : {}),
|
||||
...(scenario === "different_company" ? { companyId: randomUUID() } : {}),
|
||||
...(scenario === "wrong_agent" ? { agentId: f.replacementAgentId } : {}),
|
||||
} },
|
||||
status: scenario === "unsettled" ? "processing" : scenario === "denied" || scenario === "cancelled_after_ambiguous" ? "cancelled" : scenario === "ambiguous_exhausted" ? "failed" : "processed",
|
||||
result: scenario === "check_only" || scenario === "missing_receipt" ? {} : scenario === "denied" ? { code: "authorization_changed", attempts: 1 } : scenario === "cancelled_after_ambiguous" ? { code: "authorization_changed", attempts: 2 }
|
||||
: scenario === "ambiguous_exhausted" ? { code: "publication_failed", retryable: false, attempts: 8 }
|
||||
: { id: "41802", url: "https://github.com/paperclipai/paperclip/issues/418#issuecomment-41802" },
|
||||
});
|
||||
}
|
||||
const unresolved = ["unsettled", "ambiguous_exhausted", "cancelled_after_ambiguous", "missing_receipt"].includes(scenario);
|
||||
const expected = scenario === "confirmed" ? "confirmed" : unresolved ? "unsettled" : "none";
|
||||
await expect(githubRunReplyState(db, { ...f.session, endpointId: f.endpoint.id })).resolves.toBe(expected);
|
||||
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "test_runtime_failed" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
await enqueueChatRunMilestones(db); await f.service.processPendingPublications();
|
||||
await enqueueChatRunMilestones(db); await f.service.processPendingPublications();
|
||||
const posts = f.runtime.endpoints.get(f.endpoint.id)?.posts ?? [];
|
||||
expect(posts).toHaveLength(0);
|
||||
expect(f.responseWrites).toHaveLength(expected === "none" ? 2 : 1);
|
||||
if (expected === "none") expect(f.responseWrites[1]).toMatchObject({ method: "PATCH", body: expect.stringContaining("stopped before completing this turn") });
|
||||
const [fallback] = await db.select().from(chatPublications).where(and(eq(chatPublications.endpointId, f.endpoint.id),
|
||||
eq(chatPublications.idempotencyKey, `run:${f.run.id}:failed:${f.endpoint.id}`)));
|
||||
expect(fallback.state).toBe(expected === "none" ? "published" : "cancelled");
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["issues", "issue_comment", "pull_request_review_comment"])(
|
||||
"admits signed %s mentions with automation off, deduplicates and retains manual task authority", async (event) => {
|
||||
const f = await reviewBotFixture();
|
||||
const saved = await f.management.configuration(f.endpoint.id, "owner-user");
|
||||
await f.management.saveConfiguration(f.endpoint.id, { expectedRevision: saved.revision, configuration: { ...saved.configuration, defaults: { ...saved.configuration.defaults, invocation: "mentions_only", events: [], issueOpened: false }, repositories: { ...saved.configuration.repositories, "97531": { instructions: "Use repository-specific guidance" } } } }, "owner-user");
|
||||
const body = `@${f.endpoint.botUsername!.replace(/\[bot\]$/, "")} tell me a joke`;
|
||||
const target = { number: 83, title: "Say hello", body, user: { id: 42, login: "octocat", type: "User" }, labels: [] };
|
||||
const comment = { id: 83001, body, user: target.user, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), in_reply_to_id: 83000 };
|
||||
const payload = {
|
||||
action: event.includes("comment") ? "created" : event === "pull_request_review" ? "submitted" : "opened",
|
||||
installation: { id: 2468 },
|
||||
repository: { id: 97531, full_name: "PaperclipAI/Paperclip", name: "paperclip", owner: { id: 1357, login: "paperclipai" } },
|
||||
sender: target.user, issue: target, pull_request: target, comment, review: comment,
|
||||
};
|
||||
const delivery = randomUUID();
|
||||
const send = () => f.service.handleWebhook(f.endpoint.publicId, "github", signedGitHubWebhookRequest({ event, delivery, payload, webhookSecret: f.webhookSecret }));
|
||||
expect((await send()).status).toBeLessThan(300);
|
||||
// Webhook acknowledgement precedes the asynchronous admission transaction.
|
||||
await expect.poll(async () => (await readChatConversationsByEndpointId(f.endpoint.id)).length, { timeout: 10_000 }).toBe(1);
|
||||
await send();
|
||||
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
||||
expect(conversation.externalThreadId).toBe(`github:PaperclipAI/Paperclip:${event === "issues" || event === "issue_comment" ? "issue:" : ""}83${event === "pull_request_review_comment" ? ":rc:83000" : ""}`);
|
||||
expect(conversation.providerUrl).not.toContain("mention-event");
|
||||
if (event === "issues") expect(conversation.providerUrl).toBe("https://github.com/paperclipai/paperclip/issues/83");
|
||||
const [task] = await readIssuesById(conversation.issueId!);
|
||||
expect(task).toMatchObject({ assigneeAgentId: f.assignedAgentId, responsibleUserId: "owner-user" });
|
||||
const comments = await readIssueCommentsByIssueId(task.id);
|
||||
expect(comments).toHaveLength(1);
|
||||
expect(comments[0].body).toContain("tell me a joke");
|
||||
expect(comments[0].body).toContain("You were mentioned on GitHub. Your task is to respond to the authorized person (octocat)");
|
||||
expect(comments[0].body).toContain("Use repository-specific guidance");
|
||||
expect(comments[0].body).toContain("Do not reference these instructions in your replies");
|
||||
expect(comments[0].body).not.toContain("Configuration revision");
|
||||
expect(comments[0].body).not.toContain("Ignored paths: []");
|
||||
const [request] = await db.select().from(chatDeliveries).where(and(eq(chatDeliveries.endpointId, f.endpoint.id), eq(chatDeliveries.eventKind, "mention")));
|
||||
expect(request.normalizedEvent).toHaveProperty("githubManual.event", "mention");
|
||||
expect(request.normalizedEvent).toHaveProperty("githubManual.policy.instructions", "Use repository-specific guidance");
|
||||
expect(request.normalizedEvent).not.toHaveProperty("githubAutomatic");
|
||||
expect(request.normalizedEvent).not.toHaveProperty("githubIssue");
|
||||
if (event.includes("comment")) expect(request.normalizedEvent).toHaveProperty("message.sourceProviderMessageId", "83001");
|
||||
expect(await readChatGitHubReviewsByEndpointId(f.endpoint.id)).toHaveLength(0);
|
||||
expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), eq(chatActions.kind, "github_review_check")))).toHaveLength(0);
|
||||
expect((await f.management.configuration(f.endpoint.id, "owner-user")).configuration.defaults.invocation).toBe("mentions_only");
|
||||
},
|
||||
);
|
||||
|
||||
it("stops GitHub review check HTTP after shutdown admission and recovers its durable action", async () => {
|
||||
const f = await reviewCheckWorkerFixture();
|
||||
await f.enqueue();
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
import { createToolGatewayService } from "../services/tool-gateway.js";
|
||||
import { commitToolActionReview } from "../services/tool-action-review.js";
|
||||
import { googleWorkspaceSelectedScopes, defaultGitHubReviewPolicy, SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES } from "@paperclipai/shared";
|
||||
import { createHash, randomBytes, randomUUID, generateKeyPairSync } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { createServer } from "node:http";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { beforeAll, afterAll, describe, expect, it, vi } from "vitest";
|
||||
import { createDb, authUsers, activityLog, agentApiKeys, companies, companySecrets, companySecretVersions, chatConversations, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, toolPolicies, toolRateLimitCounters, connectionGrants, connectionGrantMembers, connectionGrantDelegations, toolAccessAuditEvents, toolOauthStates, issueThreadInteractions, connectionIntentDeliveries, agents, companyMemberships, heartbeatRuns, issues, principalPermissionGrants, projects, toolApplications, toolConnections, toolConnectionInstalls, aiConnectionPools, toolMcpGateways, toolMcpGatewayTokens, toolActionRequests, toolCatalogEntries, toolInvocations, toolCallEvents, toolProfileEntries, toolProfiles, toolProfileBindings, plugins, adapterAuthSessions, environments, routines, chatGitHubReviews } from "@paperclipai/db";
|
||||
import { findSatisfiedToolConnection, satisfiedConnectionIntentService } from "../services/satisfied-connection-intents.js";
|
||||
import { connectionManagementService, continuingConnectionManagement } from "../services/connection-management.js";
|
||||
import { aiConnectionService } from "../services/ai-connections.js";
|
||||
import { redactRunnerApiPayloads } from "../services/native-runtime/runner-api-log-redaction.js";
|
||||
import * as remoteEndpointGuard from "../services/remote-http-endpoint-guard.js";
|
||||
import * as remoteHttpFetch from "../services/remote-http-fetch.js";
|
||||
import * as runIdentity from "../services/run-identity.js";
|
||||
import * as connectionManagementModule from "../services/connection-management.js";
|
||||
import * as localBrowserLogin from "../services/local-ai-browser-login.js";
|
||||
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
|
||||
import { startRunnerApiTestServer } from "./helpers/runner-api-server.js";
|
||||
import { getServerAdapter, registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
|
||||
import { configureAgentLifecycle } from "../services/agent-lifecycle.js";
|
||||
import { agentService } from "../services/agents.js";
|
||||
import { accessService } from "../services/access.js";
|
||||
import { secretService } from "../services/secrets.js";
|
||||
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
|
||||
import type { AuthorizationActor } from "../services/authorization.js";
|
||||
import type { ConnectionManagementResource } from "../services/connection-management-policy.js";
|
||||
|
||||
vi.mock("../services/agent-lifecycle-driver.js", () => ({
|
||||
createLifecycleDriver: () => ({ requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" }),
|
||||
}));
|
||||
|
||||
vi.mock("../services/chat-channels/github/webhook-recovery-work.js", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("../services/chat-channels/github/webhook-recovery-work.js")>();
|
||||
return { ...original, registerGitHubWebhookRecoveryWork: (...args: Parameters<typeof original.registerGitHubWebhookRecoveryWork>) =>
|
||||
original.registerGitHubWebhookRecoveryWork(args[0], args[1], () => false) };
|
||||
});
|
||||
|
||||
import { createConnectionManagementHarness, type ConnectionManagementLifecycle, type ConnectionManagementProviderHandler, type ConnectionManagementServer } from "./helpers/connection-management-harness.js";
|
||||
|
||||
// All requests traverse the assembled server and production bearer middleware.
|
||||
// No req.actor injection or special permission grants establish access.
|
||||
describe("connection management delegated policy and profile access", () => {
|
||||
let server!: ConnectionManagementServer;
|
||||
let lifecycle!: ConnectionManagementLifecycle;
|
||||
let provider: ConnectionManagementProviderHandler | null = null;
|
||||
const harness = createConnectionManagementHarness(() => provider);
|
||||
beforeAll(() => {
|
||||
server = harness.server;
|
||||
lifecycle = harness.lifecycle;
|
||||
});
|
||||
const fixture = () => harness.fixture();
|
||||
|
||||
it.each(["none", "other-agent", "other-agent-no-access", "other-agent-allow-policy", "other-agent-explicit-grant", "other-agent-caller-ask", "other-agent-new-rate", "other-agent-new-shared-rate", "other-agent-new-rate-target-block", "other-agent-caller-rate", "other-agent-shared-rate", "other-agent-credential", "other-agent-credential-none", "other-agent-caller-revoked", "private-status", "agent", "user", "cancelled", "project-block", "rate-limit", "agent-rate-approval", "authorized-policy-edit"] as const)("keeps delegated test policy and approval continuation bounded (%s)", async revocation => {
|
||||
const f = await fixture();
|
||||
let targetAgentId = f.agentId;
|
||||
if (revocation.startsWith("other-agent")) {
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
const created = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/agents`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Test target", role: "engineer", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, permissions: {}, runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: false } } }) });
|
||||
const target = await created.json();
|
||||
expect(created.status, JSON.stringify(target)).toBe(201);
|
||||
targetAgentId = target.id;
|
||||
await lifecycle.process(targetAgentId);
|
||||
await vi.waitFor(async () => expect((await agentService(server.db).getById(targetAgentId))?.status).toBe("idle"));
|
||||
}
|
||||
const allowed = revocation === "none" || revocation === "other-agent" || revocation === "other-agent-caller-ask" || ["other-agent-new-rate", "other-agent-new-shared-rate"].includes(revocation);
|
||||
let calls = 0;
|
||||
const remote = createServer(async (req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(Buffer.from(chunk));
|
||||
const request = JSON.parse(Buffer.concat(chunks).toString() || "{}");
|
||||
let result: unknown;
|
||||
if (request.method === "initialize") result = { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "Fixture", version: "1" } };
|
||||
else if (request.method === "tools/call") { calls++; result = { content: [{ type: "text", text: "Fixture result" }] }; }
|
||||
else { res.writeHead(req.method === "DELETE" ? 204 : request.method === "notifications/initialized" ? 202 : 405); res.end(); return; }
|
||||
res.writeHead(200, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }));
|
||||
});
|
||||
await new Promise<void>(resolve => remote.listen(0, "127.0.0.1", resolve));
|
||||
const address = remote.address();
|
||||
if (!address || typeof address === "string") throw new Error("Fixture did not listen");
|
||||
const mcpUrl = `http://127.0.0.1:${address.port}/mcp`;
|
||||
const freezeRateClock = revocation.startsWith("other-agent-new-") || ["other-agent-caller-rate", "other-agent-shared-rate", "rate-limit", "agent-rate-approval"].includes(revocation);
|
||||
if (freezeRateClock) vi.useFakeTimers({ toFake: ["Date"] });
|
||||
try {
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Governed test", transport: "mcp_remote", authKind: "none", transportConfig: { url: mcpUrl } });
|
||||
await server.db.update(toolConnections).set({ healthStatus: "ok" }).where(eq(toolConnections.id, created.body.id));
|
||||
const [entry] = await server.db.insert(toolCatalogEntries).values({ companyId: f.companyId, applicationId: created.body.applicationId, connectionId: created.body.id,
|
||||
entryKind: "tool", name: "Fixture probe", toolName: "fixture_probe", inputSchema: { type: "object", properties: {} }, riskLevel: "read", isReadOnly: true, status: "active", versionHash: "fixture-v1" }).returning();
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/tools/apps/${created.body.id}/finish`, { enabledCatalogEntryIds: [entry.id], access: { agentIds: revocation.startsWith("other-agent") && !["other-agent-no-access", "other-agent-allow-policy", "other-agent-explicit-grant"].includes(revocation) ? [f.agentId, targetAgentId] : [targetAgentId] } })).toMatchObject({ status: 200 });
|
||||
const path = `/tool-connections/${created.body.id}/test-calls`;
|
||||
const body = { agentId: targetAgentId, runContext: { heartbeatRunId: randomUUID(), issueId: randomUUID(), projectId: randomUUID() }, toolName: "fixture_probe", parameters: {} };
|
||||
if (revocation === "other-agent-no-access") {
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Caller cannot use this tool", policyType: "block", selectors: { connectionId: created.body.id, agentId: f.agentId }, priority: 0 });
|
||||
for (const token of [f.key.token, f.jwt]) expect(await f.request("POST", path, body, token)).toMatchObject({ status: 200, body: { decision: "off", error: { reasonCode: "deny_policy_block" } } });
|
||||
expect(calls).toBe(0);
|
||||
return;
|
||||
}
|
||||
if (revocation === "other-agent-allow-policy" || revocation === "other-agent-explicit-grant") {
|
||||
if (revocation === "other-agent-allow-policy") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Caller authorized by policy", policyType: "allow", selectors: { connectionId: created.body.id, agentId: f.agentId }, priority: 0 });
|
||||
else await server.db.update(principalPermissionGrants).set({ scope: { connectionId: created.body.id } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:use")));
|
||||
const result = await f.request("POST", path, body, f.jwt);
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ status: 200, body: { decision: "allowed", result: { content: "Fixture result" } } });
|
||||
expect(calls).toBe(1);
|
||||
return;
|
||||
}
|
||||
if (revocation === "other-agent-credential" || revocation === "other-agent-credential-none") {
|
||||
await server.db.update(toolConnections).set({ authKind: revocation === "other-agent-credential-none" ? "none" : "api_key", credentialPolicy: "per_agent" }).where(eq(toolConnections.id, created.body.id));
|
||||
await server.db.insert(connectionGrants).values([f.agentId, targetAgentId].map(subjectAgentId => ({ companyId: f.companyId, connectionId: created.body.id, kind: "agent" as const, subjectAgentId, status: "active" as const })));
|
||||
expect(await f.request("POST", path, body, f.jwt)).toMatchObject({ status: 403, body: { reasonCode: "test_credential_identity_mismatch" } });
|
||||
expect(calls).toBe(0);
|
||||
return;
|
||||
}
|
||||
if (revocation === "other-agent-caller-rate" || revocation === "other-agent-shared-rate") {
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Caller rate", policyType: "rate_limit", selectors: { connectionId: created.body.id, ...(revocation === "other-agent-caller-rate" ? { agentId: f.agentId } : {}) }, config: { limit: 1, windowSeconds: 60, keyBy: revocation === "other-agent-caller-rate" ? ["agent", "tool"] : ["company", "tool"] } });
|
||||
const admitted = await f.request("POST", path, body, f.jwt);
|
||||
expect(admitted, JSON.stringify(admitted)).toMatchObject({ status: 200, body: { decision: "allowed", result: { content: "Fixture result" } } });
|
||||
expect(calls).toBe(1);
|
||||
expect(await f.request("POST", path, body, f.jwt)).toMatchObject({ status: 200, body: { decision: "off", error: { reasonCode: "rate_limited" } } });
|
||||
expect(calls).toBe(1);
|
||||
return;
|
||||
}
|
||||
for (const selectors of [{ connectionId: created.body.id, projectId: f.projectId }, { connectionId: created.body.id, issueId: f.issueId }]) {
|
||||
const [block] = await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Scoped test block", policyType: "block", selectors, priority: 1 }).returning();
|
||||
expect(await f.request("POST", path, body, f.jwt)).toMatchObject({ status: 200, body: { decision: "off" } });
|
||||
expect(calls).toBe(0);
|
||||
await server.db.delete(toolPolicies).where(eq(toolPolicies.id, block.id));
|
||||
}
|
||||
if (revocation === "rate-limit") {
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "One test per minute", policyType: "rate_limit", selectors: { connectionId: created.body.id }, config: { limit: 1, windowSeconds: 60, keyBy: ["agent", "tool"] } });
|
||||
expect(await f.request("POST", path, body, f.jwt)).toMatchObject({ status: 200, body: { decision: "allowed", result: { content: "Fixture result" } } });
|
||||
expect(calls).toBe(1);
|
||||
expect(await f.request("POST", path, body, f.jwt)).toMatchObject({ status: 200, body: { decision: "off", error: { reasonCode: "rate_limited" } } });
|
||||
expect(calls).toBe(1);
|
||||
return;
|
||||
}
|
||||
if (revocation === "agent-rate-approval") {
|
||||
await server.db.insert(toolPolicies).values([
|
||||
{ companyId: f.companyId, name: "One admitted call", policyType: "rate_limit", selectors: { connectionId: created.body.id }, priority: 0, config: { limit: 1, windowSeconds: 60, keyBy: ["agent", "tool"] } },
|
||||
{ companyId: f.companyId, name: "Approve admitted call", policyType: "require_approval", selectors: { connectionId: created.body.id }, priority: 1 },
|
||||
]);
|
||||
const session = await f.request("POST", "/tool-gateway/sessions", {}, f.jwt);
|
||||
expect(session, JSON.stringify(session)).toMatchObject({ status: 201 });
|
||||
const gatewayRequest = async (path: string, parameters?: unknown) => {
|
||||
const response = await fetch(server.apiUrl + "/api" + path, { method: parameters === undefined ? "GET" : "POST", headers: { "x-paperclip-tool-gateway-token": session.body.token, "Content-Type": "application/json" }, ...(parameters === undefined ? {} : { body: JSON.stringify(parameters) }) });
|
||||
return { status: response.status, body: await response.json() };
|
||||
};
|
||||
const listed = await gatewayRequest("/tool-gateway/tools");
|
||||
expect(listed).toMatchObject({ status: 200 });
|
||||
const tool = listed.body.find((item: { catalogEntryId: string }) => item.catalogEntryId === entry.id);
|
||||
expect(tool, JSON.stringify(listed.body)).toBeTruthy();
|
||||
const requested = await gatewayRequest("/tool-gateway/tools/call", { tool: tool.name, parameters: {}, idempotencyKey: "rate-approval" });
|
||||
expect(requested, JSON.stringify(requested)).toMatchObject({ status: 409, body: { reasonCode: "approval_required" } });
|
||||
expect(calls).toBe(0);
|
||||
expect(await f.request("POST", `/tool-gateway/action-requests/${requested.body.actionRequestId}/approve`, { companyId: f.companyId }, f.jwt)).toMatchObject({ status: 403 });
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
const response = await fetch(`${server.apiUrl}/api/tool-gateway/action-requests/${requested.body.actionRequestId}/approve`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
|
||||
expect(response.status, JSON.stringify(await response.json())).toBe(200);
|
||||
expect((await server.db.select().from(toolInvocations).where(eq(toolInvocations.id, requested.body.invocationId)))[0].status).toBe("succeeded");
|
||||
expect(calls).toBe(1);
|
||||
expect(await gatewayRequest("/tool-gateway/tools/call", { tool: tool.name, parameters: { anotherCall: true }, idempotencyKey: "next-rate-approval" })).toMatchObject({ status: 429, body: { reasonCode: "rate_limited" } });
|
||||
expect(calls).toBe(1);
|
||||
return;
|
||||
}
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Scoped test approval", policyType: "require_approval", selectors: { connectionId: created.body.id, issueId: f.issueId, ...(revocation === "other-agent-caller-ask" ? { agentId: f.agentId } : {}) }, priority: 1 });
|
||||
const pending = await f.request("POST", path, body, f.jwt);
|
||||
expect(pending, JSON.stringify(pending)).toMatchObject({ status: 200, body: { decision: "ask_first" } });
|
||||
const [saved] = await server.db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.body.invocationId));
|
||||
expect(saved).toMatchObject({ runId: f.runId, issueId: f.issueId, actorType: "agent", actorId: f.agentId, agentId: targetAgentId });
|
||||
expect(calls).toBe(0);
|
||||
if (revocation === "private-status") {
|
||||
const statusPath = `${path}/${pending.body.actionRequestId}`;
|
||||
expect(await f.request("GET", statusPath)).toMatchObject({ status: 200 });
|
||||
const [hidden] = await server.db.insert(issues).values({ companyId: f.companyId, title: "Private test task", visibility: "private", status: "in_progress", responsibleUserId: randomUUID() }).returning();
|
||||
await server.db.update(toolInvocations).set({ issueId: hidden.id }).where(eq(toolInvocations.id, saved.id));
|
||||
for (const token of [f.key.token, f.jwt]) expect(await f.request("GET", statusPath, undefined, token)).toMatchObject({ status: 403 });
|
||||
expect(calls).toBe(0);
|
||||
return;
|
||||
}
|
||||
const approvalPath = `/tool-gateway/action-requests/${pending.body.actionRequestId}/approve`;
|
||||
expect(await f.request("POST", approvalPath, { companyId: f.companyId }, f.jwt)).toMatchObject({ status: 403 });
|
||||
if (revocation === "authorized-policy-edit") {
|
||||
const policiesPath = `/companies/${f.companyId}/tools/policies`;
|
||||
const policy = await f.request("POST", policiesPath, { name: "Requested self-targeted access", policyType: "allow", priority: 0,
|
||||
selectors: { agentId: f.agentId, connectionId: created.body.id } }, f.jwt);
|
||||
expect(policy, JSON.stringify(policy)).toMatchObject({ status: 201 });
|
||||
expect(await f.request("POST", path, body, f.jwt)).toMatchObject({ status: 200, body: { decision: "allowed" } });
|
||||
expect(calls).toBe(1);
|
||||
expect(await f.request("POST", approvalPath, { companyId: f.companyId }, f.jwt)).toMatchObject({ status: 403 });
|
||||
await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_profiles")));
|
||||
expect(await f.request("PATCH", `${policiesPath}/${policy.body.id}`, { enabled: false }, f.jwt)).toMatchObject({ status: 403 });
|
||||
return;
|
||||
}
|
||||
await server.db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId));
|
||||
if (revocation === "agent") await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:use")));
|
||||
if (revocation === "user") for (const permission of ["tools:use", "tools:manage_connections"]) await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.companyId, f.companyId), eq(principalPermissionGrants.principalId, f.userId), eq(principalPermissionGrants.permissionKey, permission)));
|
||||
if (revocation === "cancelled") await server.db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, f.issueId));
|
||||
if (revocation === "other-agent-caller-revoked") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Caller access revoked", policyType: "block", selectors: { connectionId: created.body.id, agentId: f.agentId }, priority: 0 });
|
||||
if (revocation === "project-block") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New project block", policyType: "block", selectors: { connectionId: created.body.id, projectId: f.projectId }, priority: 0 });
|
||||
if (revocation.startsWith("other-agent-new-")) {
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New delegated test admission", policyType: "rate_limit",
|
||||
selectors: { connectionId: created.body.id, ...(revocation === "other-agent-new-shared-rate" ? {} : { agentId: f.agentId }) },
|
||||
priority: -2, config: { limit: 1, windowSeconds: 60, keyBy: revocation === "other-agent-new-shared-rate" ? ["company", "tool"] : ["agent", "tool"] } });
|
||||
if (revocation === "other-agent-new-rate") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New test target admission", policyType: "rate_limit",
|
||||
selectors: { connectionId: created.body.id, agentId: targetAgentId }, priority: -2,
|
||||
config: { limit: 1, windowSeconds: 60, keyBy: ["agent", "tool"] } });
|
||||
if (revocation === "other-agent-new-rate-target-block") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New test target block", policyType: "block",
|
||||
selectors: { connectionId: created.body.id, agentId: targetAgentId }, priority: -1 });
|
||||
}
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
const approve = () => fetch(server.apiUrl + "/api" + approvalPath, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
|
||||
const response = await approve();
|
||||
expect(response.status, JSON.stringify(await response.json())).toBe(revocation === "cancelled" ? 409 : 200);
|
||||
const [settled] = await server.db.select().from(toolInvocations).where(eq(toolInvocations.id, saved.id));
|
||||
if (revocation === "cancelled") expect(settled.status).not.toBe("succeeded");
|
||||
else expect(settled, JSON.stringify(settled)).toMatchObject({ status: allowed ? "succeeded" : "failed" });
|
||||
expect(calls).toBe(allowed ? 1 : 0);
|
||||
if (allowed) { expect((await approve()).status).toBe(200); expect(calls).toBe(1); }
|
||||
if (revocation.startsWith("other-agent-new-")) {
|
||||
const counters = await server.db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.companyId, f.companyId));
|
||||
expect(counters).toHaveLength(allowed ? revocation === "other-agent-new-shared-rate" ? 1 : 2 : 0);
|
||||
expect(counters.every(counter => counter.remaining === 0)).toBe(true);
|
||||
if (allowed) {
|
||||
expect(settled.policyExplanation?.consumedRateAdmissions).toHaveLength(1);
|
||||
expect(settled.policyExplanation?.delegatedCallerConsumedRateAdmissions).toHaveLength(1);
|
||||
const [nextRun] = await server.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId,
|
||||
status: "running", responsibleUserId: f.userId, contextSnapshot: { issueId: f.issueId } }).returning();
|
||||
const nextJwt = createLocalAgentJwt(f.agentId, f.companyId, "paperclip_runner", nextRun.id, f.userId)!;
|
||||
expect(await f.request("POST", path, body, nextJwt)).toMatchObject({ status: 200, body: { decision: "off", error: { reasonCode: "rate_limited" } } });
|
||||
expect(calls).toBe(1);
|
||||
}
|
||||
}
|
||||
} finally { if (freezeRateClock) vi.useRealTimers(); remote.closeAllConnections(); await new Promise<void>((resolve, reject) => remote.close(error => error ? reject(error) : resolve())); }
|
||||
});
|
||||
|
||||
it("completes concurrent run-authenticated profile finishing and policy writes without lock-order failures", async () => {
|
||||
const f = await fixture();
|
||||
const connection = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Concurrent management", transport: "mcp_remote", authKind: "none", transportConfig: { url: "https://1.1.1.1/mcp" } });
|
||||
const policy = await f.request("POST", `/companies/${f.companyId}/tools/policies`, { name: "Concurrent policy", policyType: "allow", selectors: { agentId: f.agentId } });
|
||||
expect(policy).toMatchObject({ status: 201 });
|
||||
const finishPath = `/companies/${f.companyId}/tools/apps/${connection.body.id}/finish`;
|
||||
const finish = { enabledCatalogEntryIds: [], access: { agentIds: [f.agentId] } };
|
||||
expect(await f.request("POST", finishPath, finish, f.jwt)).toMatchObject({ status: 200 });
|
||||
for (let round = 0; round < 3; round++) {
|
||||
const rows = await server.db.select({ id: toolPolicies.id }).from(toolPolicies).where(eq(toolPolicies.companyId, f.companyId));
|
||||
const results = await Promise.all([
|
||||
f.request("POST", `/companies/${f.companyId}/tools/policies/reorder`, { policyIds: rows.map(row => row.id) }, f.jwt),
|
||||
f.request("PATCH", `/companies/${f.companyId}/tools/policies/${policy.body.id}`, { description: `Round ${round}` }, f.jwt),
|
||||
f.request("POST", finishPath, finish, f.jwt),
|
||||
]);
|
||||
expect([200, 422]).toContain(results[0].status);
|
||||
expect(results.slice(1), JSON.stringify(results)).toEqual([expect.objectContaining({ status: 200 }), expect.objectContaining({ status: 200 })]);
|
||||
}
|
||||
expect((await server.db.select().from(toolPolicies).where(eq(toolPolicies.id, policy.body.id)))[0].description).toBe("Round 2");
|
||||
});
|
||||
|
||||
it("checks issue, routine, and gateway profile targets including retained bindings", async () => {
|
||||
const f = await fixture();
|
||||
const other = (await server.db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, f.companyId))).find(agent => agent.id !== f.agentId)!;
|
||||
const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "target-checks", name: "Target checks", entries: [] });
|
||||
const gatewayProfile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "gateway-target", name: "Gateway target", entries: [] });
|
||||
const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Target gateway", slug: "binding-target", profileId: gatewayProfile.body.id, agentId: other.id });
|
||||
expect(gateway, JSON.stringify(gateway)).toMatchObject({ status: 201 });
|
||||
const [issue] = await server.db.insert(issues).values({ companyId: f.companyId, title: "Other agent task", assigneeAgentId: other.id, status: "in_progress", responsibleUserId: f.userId }).returning();
|
||||
const [routine] = await server.db.insert(routines).values({ companyId: f.companyId, title: "Other agent routine", assigneeAgentId: other.id, responsibleUserId: f.userId }).returning();
|
||||
const [configurationGrant] = await server.db.select().from(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "agents:configure")));
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { ...configurationGrant.scope, targetAgentIds: [f.agentId] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "agents:configure")));
|
||||
const path = `/companies/${f.companyId}/tools/profiles/${profile.body.id}`;
|
||||
const ownBinding = await f.request("POST", `${path}/bind`, { targetType: "issue", targetId: f.issueId });
|
||||
expect(ownBinding, JSON.stringify(ownBinding)).toMatchObject({ status: 201 });
|
||||
expect(await f.request("POST", `${path}/unbind`, { targetType: "issue", targetId: f.issueId })).toMatchObject({ status: 200 });
|
||||
for (const target of [{ targetType: "project" as const, targetId: f.projectId }, { targetType: "issue" as const, targetId: issue.id }, { targetType: "routine" as const, targetId: routine.id }, { targetType: "gateway" as const, targetId: gateway.body.id }]) {
|
||||
expect(await f.request("POST", `${path}/bind`, target), JSON.stringify(target)).toMatchObject({ status: 403 });
|
||||
const [saved] = await server.db.insert(toolProfileBindings).values({ ...target, companyId: f.companyId, profileId: profile.body.id }).returning();
|
||||
expect(await f.request("PATCH", `/tool-profiles/${profile.body.id}`, { description: "Cannot edit retained target" })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("POST", `${path}/unbind`, target)).toMatchObject({ status: 403 });
|
||||
await server.db.delete(toolProfileBindings).where(eq(toolProfileBindings.id, saved.id));
|
||||
}
|
||||
await server.db.update(toolMcpGateways).set({ profileId: profile.body.id }).where(eq(toolMcpGateways.id, gateway.body.id));
|
||||
expect(await f.request("PATCH", `/tool-profiles/${profile.body.id}`, { description: "Cannot edit a gateway's retained profile" })).toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it("filters GitHub review history and detail by the linked task's private visibility", async () => {
|
||||
const f = await fixture();
|
||||
const endpoint = await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider: "github", assignedAgentId: f.agentId });
|
||||
const [privateIssue] = await server.db.insert(issues).values({ companyId: f.companyId, title: "Private review task", visibility: "private", status: "in_progress", responsibleUserId: randomUUID() }).returning();
|
||||
const [visible, hidden] = await server.db.insert(chatGitHubReviews).values([f.issueId, privateIssue.id].map((issueId, index) => ({ companyId: f.companyId, endpointId: endpoint.body.id,
|
||||
issueId, repositoryId: "42", repository: "fixture/repo", pullNumber: index + 1, headSha: "b".repeat(40), deliveryId: randomUUID(), configurationRevision: 1,
|
||||
policySnapshot: defaultGitHubReviewPolicy(), event: { event: "opened" as const, deliveryId: randomUUID(), repositoryId: "42", repository: "fixture/repo", pullNumber: index + 1,
|
||||
title: "Review", body: index ? "Private provider context" : "Public context", baseSha: "a".repeat(40), headSha: "b".repeat(40), baseBranch: "master", author: { id: "1", login: "fixture", isBot: false }, sender: { id: "1", login: "fixture" }, draft: false, labels: [] },
|
||||
}))).returning();
|
||||
const path = `/chat-endpoints/${endpoint.body.id}/github/reviews`;
|
||||
expect((await f.request("GET", path)).body.map((review: { id: string }) => review.id)).toEqual([visible.id]);
|
||||
expect(await f.request("GET", `${path}/${visible.id}`)).toMatchObject({ status: 200 });
|
||||
expect(await f.request("GET", `${path}/${hidden.id}`)).toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("keeps narrow policy create, update, reorder, and delete within their actual audiences", async () => {
|
||||
const f = await fixture();
|
||||
const other = (await server.db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, f.companyId))).find(agent => agent.id !== f.agentId)!;
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { targetAgentIds: [f.agentId] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "agents:configure")));
|
||||
const path = `/companies/${f.companyId}/tools/policies`;
|
||||
const created = await f.request("POST", path, { name: "Own target rule", policyType: "allow", selectors: { agentId: f.agentId } });
|
||||
expect(created, JSON.stringify(created)).toMatchObject({ status: 201 });
|
||||
expect(await f.request("PATCH", `${path}/${created.body.id}`, { description: "Retain the target" })).toMatchObject({ status: 200 });
|
||||
expect(await f.request("POST", `${path}/reorder`, { policyIds: [created.body.id] })).toMatchObject({ status: 200 });
|
||||
expect(await f.request("PATCH", `${path}/${created.body.id}`, { selectors: {} })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("PATCH", `${path}/${created.body.id}`, { selectors: { agentId: other.id } })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("POST", path, { name: "Company rule", policyType: "allow", selectors: {} })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("DELETE", `${path}/${created.body.id}`)).toMatchObject({ status: 200 });
|
||||
});
|
||||
|
||||
it("bounds and deduplicates resource selectors before per-resource database work", async () => {
|
||||
const f = await fixture();
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Bounded selector", transport: "mcp_remote", authKind: "none", transportConfig: { url: "https://1.1.1.1/mcp" } });
|
||||
let resourceReads = 0;
|
||||
const originalSelect = server.db.select.bind(server.db);
|
||||
const select = vi.spyOn(server.db, "select").mockImplementation(((selection: never) => {
|
||||
const builder = originalSelect(selection);
|
||||
const originalFrom = builder.from.bind(builder);
|
||||
builder.from = ((table: never) => {
|
||||
if (table === toolConnections || table === toolPolicies || table === toolCatalogEntries) resourceReads++;
|
||||
return originalFrom(table);
|
||||
}) as typeof builder.from;
|
||||
return builder;
|
||||
}) as unknown as typeof server.db.select);
|
||||
try {
|
||||
const path = `/companies/${f.companyId}/tools/policies`;
|
||||
const body = { name: "Bounded policy", policyType: "allow", selectors: { agentId: f.agentId, connectionIds: Array(5000).fill(created.body.id) } };
|
||||
expect(await f.request("POST", path, body)).toMatchObject({ status: 400 });
|
||||
expect(resourceReads).toBe(0);
|
||||
expect(await f.request("POST", path, { ...body, selectors: { ...body.selectors, connectionIds: Array(100).fill(created.body.id) } })).toMatchObject({ status: 201 });
|
||||
expect(resourceReads).toBeLessThan(20);
|
||||
resourceReads = 0;
|
||||
await accessService(server.db).ensureMembership(f.companyId, "user", f.userId, "operator", "suspended");
|
||||
expect(await f.request("POST", path, { ...body, selectors: { ...body.selectors, connectionIds: Array(100).fill(created.body.id) } })).toMatchObject({ status: 403 });
|
||||
expect(resourceReads).toBe(0);
|
||||
} finally { select.mockRestore(); }
|
||||
});
|
||||
|
||||
it("shares one run capture across a management read without caching authority across requests", async () => {
|
||||
const f = await fixture();
|
||||
for (let index = 0; index < 5; index++) expect(await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: `Read snapshot ${index}`, transport: "mcp_remote", authKind: "none", transportConfig: { url: "https://1.1.1.1/mcp" } })).toMatchObject({ status: 201 });
|
||||
const capture = vi.spyOn(runIdentity, "captureRunIdentity");
|
||||
try {
|
||||
const listed = await f.request("GET", `/companies/${f.companyId}/tools/connections`, undefined, f.jwt);
|
||||
expect(listed).toMatchObject({ status: 200 });
|
||||
expect(listed.body.connections).toHaveLength(5);
|
||||
expect(capture.mock.calls.length).toBeGreaterThan(0);
|
||||
expect(capture.mock.calls.length).toBeLessThanOrEqual(2);
|
||||
await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await f.request("GET", `/companies/${f.companyId}/tools/connections`, undefined, f.jwt)).toMatchObject({ status: 403 });
|
||||
} finally { capture.mockRestore(); }
|
||||
});
|
||||
|
||||
it("returns the same missing-resource response for foreign and absent connection IDs", async () => {
|
||||
const f = await fixture(), other = await fixture();
|
||||
const foreign = await other.request("POST", `/companies/${other.companyId}/tools/connections`, { name: "Other company", transport: "mcp_remote", authKind: "none", transportConfig: { url: "https://1.1.1.1/mcp" } });
|
||||
const hidden = await f.request("GET", `/tool-connections/${foreign.body.id}`);
|
||||
const absent = await f.request("GET", `/tool-connections/${randomUUID()}`);
|
||||
expect(hidden).toMatchObject({ status: 404 });
|
||||
expect(absent).toEqual(hidden);
|
||||
});
|
||||
|
||||
it("checks existing and proposed provider scope without treating generic metadata as provider authority", async () => {
|
||||
const f = await fixture();
|
||||
const payload = { name: "Scoped provider", transport: "mcp_remote", authKind: "none", config: { url: "https://1.1.1.1/mcp", provider: "fixture-one" } };
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, payload);
|
||||
expect(created.status).toBe(201);
|
||||
const untagged = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { ...payload, name: "Untagged", config: { url: "https://1.1.1.1/mcp" } });
|
||||
const application = await f.request("POST", `/companies/${f.companyId}/tools/applications`, { name: "Provider app", type: "rest_api", metadata: { sourceTemplateKey: "fixture-one" } });
|
||||
expect(application).toMatchObject({ status: 201 });
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { providers: ["fixture-one"] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await f.request("PATCH", `/tool-connections/${untagged.body.id}`, { name: "Spoofed label", provider: "fixture-one" })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/tools/applications`, { name: "Spoofed application", type: "rest_api", provider: "fixture-one", metadata: { sourceTemplateKey: "fixture-two" } })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("PATCH", `/tool-applications/${application.body.id}`, { name: "Same app provider" })).toMatchObject({ status: 200 });
|
||||
for (const metadata of [{ sourceTemplateKey: "fixture-two" }, {}]) expect(await f.request("PATCH", `/tool-applications/${application.body.id}`, { provider: "fixture-one", metadata })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("PATCH", `/tool-connections/${created.body.id}`, { name: "Still the same provider" })).toMatchObject({ status: 200 });
|
||||
for (const config of [{ url: "https://1.1.1.1/mcp", provider: "fixture-two" }, { url: "https://1.1.1.1/mcp" }]) expect(await f.request("PATCH", `/tool-connections/${created.body.id}`, { config })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/tools/connections`, { ...payload, name: "Caller-labelled provider" })).toMatchObject({ status: 403 });
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { purposes: ["tool"] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/ai-connections`, { provider: "openai", method: "api_key", name: "Wrong purpose", apiKey: "fixture", ownership: "personal", agentIds: [] })).toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it("hands generic app authentication to the saved setup without creating agent-bound OAuth state", async () => {
|
||||
const f = await fixture();
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, {
|
||||
name: "OAuth handoff fixture", transport: "mcp_remote", authKind: "oauth", credentialPolicy: "per_user", status: "draft",
|
||||
transportConfig: { url: "https://1.1.1.1/mcp" },
|
||||
});
|
||||
expect(created, JSON.stringify(created)).toMatchObject({ status: 201 });
|
||||
const path = `/tools/oauth/${created.body.id}/start`;
|
||||
const started = await f.request("POST", path, { asCurrentUser: true });
|
||||
expect(started, JSON.stringify(started)).toMatchObject({ status: 200, body: {
|
||||
expiresAt: null, requiredUserAction: { userId: f.userId, resource: { id: created.body.id } },
|
||||
} });
|
||||
// The agent links this in chat, so it is a relative app route, never the server's own origin.
|
||||
expect(started.body.authorizationUrl).toMatch(/^\/[^/]/);
|
||||
expect(started.body.requiredUserAction.setupPath).toBe(started.body.authorizationUrl);
|
||||
expect(new URL(started.body.authorizationUrl, "https://paperclip.example").searchParams.get("resume")).toBe(created.body.id);
|
||||
expect(await f.request("POST", path, { asCurrentUser: true })).toMatchObject({ status: 200, body: { authorizationUrl: started.body.authorizationUrl } });
|
||||
expect(await server.db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, created.body.id))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("delegates and revokes an owned credential with actual agent attribution", async () => {
|
||||
const f = await fixture();
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, {
|
||||
name: "Personal delegation fixture", transport: "mcp_remote", authKind: "none", credentialPolicy: "per_user",
|
||||
transportConfig: { url: "https://1.1.1.1/mcp" },
|
||||
});
|
||||
expect(created.status).toBe(201);
|
||||
// Provider fixture: a completed personal credential, not principal permissions.
|
||||
const [grant] = await server.db.insert(connectionGrants).values({ companyId: f.companyId,
|
||||
connectionId: created.body.id, kind: "user", subjectUserId: f.userId, status: "active",
|
||||
credentialSecretRefs: [], createdByUserId: f.userId,
|
||||
}).returning();
|
||||
const path = `/tool-connections/${created.body.id}/grants/${grant.id}/delegations`;
|
||||
const delegated = await f.request("POST", path, { agentId: f.agentId });
|
||||
expect(delegated, JSON.stringify(delegated)).toMatchObject({ status: 201 });
|
||||
expect(await f.request("POST", path, { agentId: f.agentId })).toMatchObject({ status: 201, body: { id: delegated.body.id } });
|
||||
expect(await f.request("DELETE", `${path}/${delegated.body.id}`)).toMatchObject({ status: 200 });
|
||||
expect(await server.db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, grant.id))).toHaveLength(0);
|
||||
const events = await server.db.select().from(toolAccessAuditEvents).where(eq(toolAccessAuditEvents.connectionId, created.body.id));
|
||||
expect(events).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ action: "connection_grant.delegated", actorType: "agent", actorId: f.agentId }),
|
||||
expect.objectContaining({ action: "connection_grant.delegation_revoked", actorType: "agent", actorId: f.agentId }),
|
||||
]));
|
||||
const activity = await server.db.select().from(activityLog).where(eq(activityLog.entityId, grant.id));
|
||||
expect(activity).toEqual(expect.arrayContaining([expect.objectContaining({ actorType: "agent", actorId: f.agentId, responsibleUserId: f.userId })]));
|
||||
});
|
||||
|
||||
it("saves the addressed user's Google service choices before handing off browser consent", async () => {
|
||||
const f = await fixture();
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Selected Google services", transport: "mcp_remote", authKind: "oauth", credentialPolicy: "per_user", status: "draft",
|
||||
config: { url: "https://1.1.1.1/mcp", sourceTemplateKey: "google-workspace", connectionMethodKey: "paperclip-workspace" } });
|
||||
expect(created, JSON.stringify(created)).toMatchObject({ status: 201 });
|
||||
const handoff = await f.request("POST", `/tools/oauth/${created.body.id}/start`, { asCurrentUser: true });
|
||||
expect(handoff, JSON.stringify(handoff)).toMatchObject({ status: 200, body: { expiresAt: null, requiredUserAction: { userId: f.userId } } });
|
||||
const [unselected] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.id));
|
||||
expect(unselected.config.workspaceSetup).toBeUndefined();
|
||||
const services = { gmail: "read" as const };
|
||||
const started = await f.request("POST", `/tools/oauth/${created.body.id}/start`, { asCurrentUser: true, workspaceServices: services });
|
||||
expect(started, JSON.stringify(started)).toMatchObject({ status: 200, body: { expiresAt: null, requiredUserAction: { userId: f.userId } } });
|
||||
const [saved] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.id));
|
||||
expect((saved.config.oauth as { pendingWorkspaceServiceRequests: Record<string, unknown> }).pendingWorkspaceServiceRequests).toEqual({
|
||||
[f.userId]: { requestedScopes: googleWorkspaceSelectedScopes(services), requestedAt: expect.any(String) },
|
||||
});
|
||||
const restored = await f.request("GET", `/tool-connections/${saved.id}`);
|
||||
expect(restored).toMatchObject({ status: 200, body: { config: { oauth: { pendingWorkspaceServiceRequests: {
|
||||
[f.userId]: { requestedScopes: googleWorkspaceSelectedScopes(services) },
|
||||
} } } } });
|
||||
expect(await server.db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, saved.id))).toHaveLength(0);
|
||||
expect(await f.request("POST", `/tools/oauth/${saved.id}/start`, { asCurrentUser: true })).toMatchObject({ status: 200, body: { authorizationUrl: started.body.authorizationUrl } });
|
||||
const [handedOff] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, saved.id));
|
||||
expect(handedOff.config.workspaceSetup).toBeUndefined();
|
||||
expect(handedOff.config.oauth).toEqual(saved.config.oauth);
|
||||
});
|
||||
|
||||
it("discovers and invokes connection APIs through default production native bindings", async () => {
|
||||
const f = await fixture();
|
||||
const definitions = await f.authority.definitions();
|
||||
const names = definitions.map(d => d.name);
|
||||
const context = await f.authority.execute({ tool: "get_task_context", callId: "configuration-guidance", arguments: {} });
|
||||
expect(JSON.stringify(context)).toContain("Standard agents can manage connections under their responsible user's authority");
|
||||
expect(JSON.stringify(definitions.find(d => d.name === "connections_search"))).toContain("search_api/call_api");
|
||||
expect(names).toEqual(expect.arrayContaining(["search_api", "call_api"]));
|
||||
const search = await f.authority.execute({ tool: "search_api", callId: "find-profile", arguments: { query: "create tools profiles", limit: 10 } });
|
||||
expect(JSON.stringify(search)).toContain("POST /api/companies/{companyId}/tools/profiles");
|
||||
const result = await f.authority.execute({ tool: "call_api", callId: "create-profile", arguments: { operationId: "POST /api/companies/{companyId}/tools/profiles", body: { profileKey: "native-profile", name: "Native profile", entries: [] } } });
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ status: 201, ok: true });
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,585 @@
|
||||
import { createToolGatewayService } from "../services/tool-gateway.js";
|
||||
import { commitToolActionReview } from "../services/tool-action-review.js";
|
||||
import { googleWorkspaceSelectedScopes, defaultGitHubReviewPolicy, SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES } from "@paperclipai/shared";
|
||||
import { createHash, randomBytes, randomUUID, generateKeyPairSync } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { createServer } from "node:http";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { beforeAll, afterAll, describe, expect, it, vi } from "vitest";
|
||||
import { createDb, authUsers, activityLog, agentApiKeys, companies, companySecrets, companySecretVersions, chatConversations, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, toolPolicies, toolRateLimitCounters, connectionGrants, connectionGrantMembers, connectionGrantDelegations, toolAccessAuditEvents, toolOauthStates, issueThreadInteractions, connectionIntentDeliveries, agents, companyMemberships, heartbeatRuns, issues, principalPermissionGrants, projects, toolApplications, toolConnections, toolConnectionInstalls, aiConnectionPools, toolMcpGateways, toolMcpGatewayTokens, toolActionRequests, toolCatalogEntries, toolInvocations, toolCallEvents, toolProfileEntries, toolProfiles, toolProfileBindings, plugins, adapterAuthSessions, environments, routines, chatGitHubReviews } from "@paperclipai/db";
|
||||
import { findSatisfiedToolConnection, satisfiedConnectionIntentService } from "../services/satisfied-connection-intents.js";
|
||||
import { connectionManagementService, continuingConnectionManagement } from "../services/connection-management.js";
|
||||
import { aiConnectionService } from "../services/ai-connections.js";
|
||||
import { redactRunnerApiPayloads } from "../services/native-runtime/runner-api-log-redaction.js";
|
||||
import * as remoteEndpointGuard from "../services/remote-http-endpoint-guard.js";
|
||||
import * as remoteHttpFetch from "../services/remote-http-fetch.js";
|
||||
import * as runIdentity from "../services/run-identity.js";
|
||||
import * as connectionManagementModule from "../services/connection-management.js";
|
||||
import * as localBrowserLogin from "../services/local-ai-browser-login.js";
|
||||
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
|
||||
import { startRunnerApiTestServer } from "./helpers/runner-api-server.js";
|
||||
import { getServerAdapter, registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
|
||||
import { configureAgentLifecycle } from "../services/agent-lifecycle.js";
|
||||
import { agentService } from "../services/agents.js";
|
||||
import { accessService } from "../services/access.js";
|
||||
import { secretService } from "../services/secrets.js";
|
||||
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
|
||||
import type { AuthorizationActor } from "../services/authorization.js";
|
||||
import type { ConnectionManagementResource } from "../services/connection-management-policy.js";
|
||||
|
||||
vi.mock("../services/agent-lifecycle-driver.js", () => ({
|
||||
createLifecycleDriver: () => ({ requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" }),
|
||||
}));
|
||||
|
||||
vi.mock("../services/chat-channels/github/webhook-recovery-work.js", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("../services/chat-channels/github/webhook-recovery-work.js")>();
|
||||
return { ...original, registerGitHubWebhookRecoveryWork: (...args: Parameters<typeof original.registerGitHubWebhookRecoveryWork>) =>
|
||||
original.registerGitHubWebhookRecoveryWork(args[0], args[1], () => false) };
|
||||
});
|
||||
|
||||
import { createConnectionManagementHarness, type ConnectionManagementLifecycle, type ConnectionManagementProviderHandler, type ConnectionManagementServer } from "./helpers/connection-management-harness.js";
|
||||
|
||||
// All requests traverse the assembled server and production bearer middleware.
|
||||
// No req.actor injection or special permission grants establish access.
|
||||
describe("connection management gateway tokens, AI accounts, and grant scopes", () => {
|
||||
let server!: ConnectionManagementServer;
|
||||
let lifecycle!: ConnectionManagementLifecycle;
|
||||
let provider: ConnectionManagementProviderHandler | null = null;
|
||||
const harness = createConnectionManagementHarness(() => provider);
|
||||
beforeAll(() => {
|
||||
server = harness.server;
|
||||
lifecycle = harness.lifecycle;
|
||||
});
|
||||
const fixture = () => harness.fixture();
|
||||
|
||||
async function legacyAgentIssuedGatewayToken(f: Awaited<ReturnType<typeof fixture>>, gatewayId: string, name: string) {
|
||||
const id = randomUUID(), token = `pcgw_${id}.${randomBytes(32).toString("base64url")}`;
|
||||
const [row] = await server.db.insert(toolMcpGatewayTokens).values({ id, companyId: f.companyId, gatewayId, name, tokenHash: createHash("sha256").update(token).digest("hex"),
|
||||
tokenPrefix: `pcgw_${id.slice(0, 8)}`, subjectType: "gateway_client", clientLabel: "fixture", allowedActions: ["tools/list", "tools/call", "resources/list", "resources/read", "prompts/list", "prompts/get"],
|
||||
responsibleUserId: f.userId, createdByAgentId: f.agentId }).returning();
|
||||
return { status: 201, body: { ...row, token } };
|
||||
}
|
||||
|
||||
it("lets agents create and revoke gateway client tokens without ever receiving a token value", async () => {
|
||||
const f = await fixture();
|
||||
const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "gateway-profile", name: "Gateway profile", entries: [] });
|
||||
expect(profile, JSON.stringify(profile)).toMatchObject({ status: 201 });
|
||||
const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Delegated gateway", slug: "delegated", profileId: profile.body.id });
|
||||
expect(gateway, JSON.stringify(gateway)).toMatchObject({ status: 201 });
|
||||
const body = { companyId: f.companyId, name: "Fixture client", clientLabel: "fixture", expiresAt: new Date(Date.now() + 3600000).toISOString() };
|
||||
const call = (callId: string, operationId: string, pathParams: Record<string, string>, payload: unknown) =>
|
||||
f.authority.execute({ tool: "call_api", callId, arguments: { operationId, pathParams, body: payload } }) as Promise<{ status: number; data: Record<string, unknown> }>;
|
||||
const tokenValue = /pcgw_[0-9a-f-]{36}\.[A-Za-z0-9_-]+/;
|
||||
const [company] = await server.db.select({ issuePrefix: companies.issuePrefix }).from(companies).where(eq(companies.id, f.companyId));
|
||||
const tokensPath = `/${company.issuePrefix}/apps/gateways/${gateway.body.id}/tokens`;
|
||||
expect(gateway.body).toMatchObject({ tokensPath, gatewayPath: `/${company.issuePrefix}/apps/gateways/${gateway.body.id}/overview` });
|
||||
|
||||
const created = await call("gateway-client-create", "POST /api/tool-gateway/gateways/{gatewayId}/tokens", { gatewayId: gateway.body.id }, body);
|
||||
expect(created, JSON.stringify(created)).toMatchObject({ status: 201, data: { name: "Fixture client", pendingReveal: true, tokensPath,
|
||||
tokenPrefix: expect.stringMatching(/^pcgw_[0-9a-f]{8}$/), createdByAgentId: f.agentId, responsibleUserId: f.userId,
|
||||
requiredUserAction: { kind: "reveal_credential", userId: f.userId, setupPath: tokensPath, resource: { type: "gateway_token", id: created.data.id, companyId: f.companyId } } } });
|
||||
expect(created.data).not.toHaveProperty("token");
|
||||
expect(JSON.stringify(created)).not.toMatch(tokenValue);
|
||||
const [pending] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, created.data.id as string));
|
||||
expect(pending).toMatchObject({ pendingReveal: true, createdByAgentId: f.agentId, responsibleUserId: f.userId, subjectType: "gateway_client", revokedAt: null });
|
||||
// Agents cannot reveal any value.
|
||||
const agentReveal = await call("gateway-client-reveal", "POST /api/tool-gateway/gateway-tokens/{tokenId}/reveal", { tokenId: created.data.id as string }, { companyId: f.companyId });
|
||||
expect(agentReveal, JSON.stringify(agentReveal)).toMatchObject({ status: 403, data: { reasonCode: "gateway_token_requires_person" } });
|
||||
expect(JSON.stringify(agentReveal)).not.toMatch(tokenValue);
|
||||
expect(await f.request("POST", `/tool-gateway/gateway-tokens/${created.data.id}/reveal`, { companyId: f.companyId })).toMatchObject({ status: 403 });
|
||||
|
||||
// The responsible person reveals the value exactly once, and it works.
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
const reveal = () => fetch(`${server.apiUrl}/api/tool-gateway/gateway-tokens/${created.data.id}/reveal`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
|
||||
const revealed = await reveal();
|
||||
expect(revealed.status).toBe(200);
|
||||
const value = await revealed.json() as { token: string; pendingReveal: boolean; id: string };
|
||||
expect(value).toMatchObject({ id: created.data.id, pendingReveal: false, token: expect.stringMatching(new RegExp(`^pcgw_${created.data.id}\\.`)) });
|
||||
expect(await reveal()).toMatchObject({ status: 409 });
|
||||
expect(await server.db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId), eq(activityLog.action, "tool_gateway.token_revealed"))))
|
||||
.toEqual([expect.objectContaining({ actorType: "user", actorId: f.userId, entityId: gateway.body.id, details: { tokenId: created.data.id } })]);
|
||||
const use = () => f.request("POST", `/mcp/gateways/${gateway.body.gatewayPublicId}`, { jsonrpc: "2.0", id: 1, method: "tools/list" }, value.token);
|
||||
expect(await use()).toMatchObject({ status: 200 });
|
||||
|
||||
// Agents keep delegated revoke.
|
||||
const revoked = await call("gateway-client-revoke", "POST /api/tool-gateway/gateway-tokens/{tokenId}/revoke", { tokenId: created.data.id as string }, { companyId: f.companyId });
|
||||
expect(revoked, JSON.stringify(revoked)).toMatchObject({ status: 200, data: { id: created.data.id, revokedAt: expect.any(String) } });
|
||||
expect((await use()).status).toBeGreaterThanOrEqual(400);
|
||||
|
||||
// A token revoked before reveal never gets a value.
|
||||
const unrevealed = await call("gateway-client-create-2", "POST /api/tool-gateway/gateways/{gatewayId}/tokens", { gatewayId: gateway.body.id }, { ...body, name: "Never revealed" });
|
||||
expect(unrevealed).toMatchObject({ status: 201 });
|
||||
expect(await call("gateway-client-revoke-2", "POST /api/tool-gateway/gateway-tokens/{tokenId}/revoke", { tokenId: unrevealed.data.id as string }, { companyId: f.companyId })).toMatchObject({ status: 200 });
|
||||
expect(await fetch(`${server.apiUrl}/api/tool-gateway/gateway-tokens/${unrevealed.data.id}/reveal`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) }))
|
||||
.toMatchObject({ status: 409 });
|
||||
|
||||
// A token that expired before reveal never gets a value.
|
||||
const expiring = await call("gateway-client-create-3", "POST /api/tool-gateway/gateways/{gatewayId}/tokens", { gatewayId: gateway.body.id }, { ...body, name: "Expired before reveal" });
|
||||
expect(expiring).toMatchObject({ status: 201 });
|
||||
await server.db.update(toolMcpGatewayTokens).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(toolMcpGatewayTokens.id, expiring.data.id as string));
|
||||
const expiredReveal = await fetch(`${server.apiUrl}/api/tool-gateway/gateway-tokens/${expiring.data.id}/reveal`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
|
||||
expect(expiredReveal.status).toBe(409);
|
||||
expect(await expiredReveal.json()).toMatchObject({ reasonCode: "gateway_token_expired" });
|
||||
const [stillPending] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, expiring.data.id as string));
|
||||
expect(stillPending).toMatchObject({ pendingReveal: true });
|
||||
|
||||
// Person callers keep receiving the value from create.
|
||||
const personal = await fetch(`${server.apiUrl}/api/tool-gateway/gateways/${gateway.body.id}/tokens`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
expect(personal.status).toBe(201);
|
||||
expect(await personal.json()).toMatchObject({ token: expect.stringMatching(/^pcgw_/), createdByUserId: f.userId, createdByAgentId: null, pendingReveal: false });
|
||||
});
|
||||
|
||||
it("reveals an agent-created gateway token value only to its responsible person", async () => {
|
||||
const f = await fixture();
|
||||
const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "gateway-profile", name: "Gateway profile", entries: [] });
|
||||
const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Delegated gateway", slug: "delegated", profileId: profile.body.id });
|
||||
const created = await f.request("POST", `/tool-gateway/gateways/${gateway.body.id}/tokens`, { companyId: f.companyId, name: "Fixture client", clientLabel: "fixture" });
|
||||
expect(created, JSON.stringify(created)).toMatchObject({ status: 201, body: { pendingReveal: true } });
|
||||
const otherId = `other-admin-${randomUUID()}`;
|
||||
await server.db.insert(authUsers).values({ id: otherId, name: "Other admin", email: `${otherId}@fixture.invalid`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() });
|
||||
const access = accessService(server.db);
|
||||
await access.ensureMembership(f.companyId, "user", otherId, "owner", "active");
|
||||
await access.ensureRoleDefaultGrants(f.companyId, otherId, "owner", otherId);
|
||||
const cookie = await server.humanSession(otherId);
|
||||
const reveal = await fetch(`${server.apiUrl}/api/tool-gateway/gateway-tokens/${created.body.id}/reveal`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
|
||||
expect(reveal.status).toBe(403);
|
||||
expect(await reveal.json()).toMatchObject({ reasonCode: "gateway_token_reveal_requires_responsible_person" });
|
||||
const [still] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, created.body.id));
|
||||
expect(still).toMatchObject({ pendingReveal: true });
|
||||
});
|
||||
|
||||
it("keeps durable agent-issued gateway client tokens bound to the issuer and responsible user", async () => {
|
||||
const f = await fixture();
|
||||
const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "gateway-profile", name: "Gateway profile", entries: [] });
|
||||
expect(profile, JSON.stringify(profile)).toMatchObject({ status: 201 });
|
||||
const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Delegated gateway", slug: "delegated", profileId: profile.body.id });
|
||||
expect(gateway, JSON.stringify(gateway)).toMatchObject({ status: 201 });
|
||||
const token = await legacyAgentIssuedGatewayToken(f, gateway.body.id, "Fixture client");
|
||||
const [saved] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, token.body.id));
|
||||
expect(saved).toMatchObject({ createdByAgentId: f.agentId, responsibleUserId: f.userId, subjectType: "gateway_client" });
|
||||
const use = () => f.request("POST", `/mcp/gateways/${gateway.body.gatewayPublicId}`, { jsonrpc: "2.0", id: 1, method: "tools/list" }, token.body.token);
|
||||
expect(await use()).toMatchObject({ status: 200 });
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { purpose: "tool" } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await use()).toMatchObject({ status: 200 });
|
||||
await server.db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId));
|
||||
expect(await use()).toMatchObject({ status: 200 });
|
||||
await server.db.update(companyMemberships).set({ status: "suspended" }).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, f.userId)));
|
||||
expect((await use()).status).toBeGreaterThanOrEqual(400);
|
||||
await server.db.update(companyMemberships).set({ status: "active" }).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, f.userId)));
|
||||
expect(await use()).toMatchObject({ status: 200 });
|
||||
await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect((await use()).status).toBeGreaterThanOrEqual(400);
|
||||
// Model the token FK's ON DELETE SET NULL state without deleting the
|
||||
// fixture's protected historical activity references to the agent.
|
||||
await server.db.update(toolMcpGatewayTokens).set({ createdByAgentId: null }).where(eq(toolMcpGatewayTokens.id, token.body.id));
|
||||
const [orphaned] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, token.body.id));
|
||||
expect(orphaned).toMatchObject({ createdByAgentId: null, responsibleUserId: f.userId });
|
||||
expect((await use()).status).toBeGreaterThanOrEqual(400);
|
||||
});
|
||||
|
||||
it.each(["block", "ask", "ask-board", "ask-revoked", "ask-rate", "ask-new-rate", "ask-new-shared-rate", "ask-new-rate-target-block", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked", "ask-one-connection", "ask-one-connection-recovery", "ask-one-connection-revoked", "rate", "shared-rate", "target-block", "credential"] as const)("intersects gateway issuer and target rules (%s)", async mode => {
|
||||
const f = await fixture();
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
const createdTarget = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/agents`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Gateway target", role: "engineer", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, permissions: {}, runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: false } } }) });
|
||||
const target = await createdTarget.json();
|
||||
expect(createdTarget.status).toBe(201);
|
||||
await lifecycle.process(target.id);
|
||||
await vi.waitFor(async () => expect((await agentService(server.db).getById(target.id))?.status).toBe("idle"));
|
||||
let calls = 0;
|
||||
const remote = createServer(async (req, res) => {
|
||||
let body = "";
|
||||
for await (const chunk of req) body += chunk;
|
||||
const rpc = JSON.parse(body || "{}");
|
||||
let result: unknown;
|
||||
if (rpc.method === "initialize") result = { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "Fixture", version: "1" } };
|
||||
else if (rpc.method === "tools/list") result = { tools: [{ name: "fixture_probe", inputSchema: { type: "object" } }] };
|
||||
else if (rpc.method === "tools/call") { calls++; result = { content: [{ type: "text", text: "Fixture gateway result" }] }; }
|
||||
else { res.writeHead(202); res.end(); return; }
|
||||
res.writeHead(200, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify({ jsonrpc: "2.0", id: rpc.id, result }));
|
||||
});
|
||||
await new Promise<void>(resolve => remote.listen(0, "127.0.0.1", resolve));
|
||||
const address = remote.address();
|
||||
if (!address || typeof address === "string") throw new Error("No fixture address");
|
||||
try {
|
||||
const connection = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Gateway policy fixture", transport: "mcp_remote", authKind: "none", transportConfig: { url: `http://127.0.0.1:${address.port}/mcp` } });
|
||||
expect(connection.status).toBe(201);
|
||||
await server.db.update(toolConnections).set({ healthStatus: "ok" }).where(eq(toolConnections.id, connection.body.id));
|
||||
const [entry] = await server.db.insert(toolCatalogEntries).values({ companyId: f.companyId, applicationId: connection.body.applicationId, connectionId: connection.body.id,
|
||||
entryKind: "tool", name: "Fixture probe", toolName: "fixture_probe", inputSchema: { type: "object" }, riskLevel: "read", isReadOnly: true, status: "active", versionHash: "fixture-v1" }).returning();
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/tools/apps/${connection.body.id}/finish`, { enabledCatalogEntryIds: [entry.id], access: { agentIds: [f.agentId, target.id] } })).toMatchObject({ status: 200 });
|
||||
const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "gateway-rules", name: "Gateway rules", entries: [{ selectorType: "connection", connectionId: connection.body.id }] });
|
||||
const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Cross-agent gateway", slug: "cross-agent", profileId: profile.body.id, agentId: target.id, issueId: f.issueId, projectId: f.projectId });
|
||||
expect(gateway, JSON.stringify(gateway)).toMatchObject({ status: 201 });
|
||||
const tokenBody = { companyId: f.companyId, name: "Issuer client", clientLabel: "fixture" };
|
||||
const token = mode === "ask-board" ? await (async () => {
|
||||
const response = await fetch(`${server.apiUrl}/api/tool-gateway/gateways/${gateway.body.id}/tokens`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify(tokenBody) });
|
||||
return { status: response.status, body: await response.json() };
|
||||
})() : await legacyAgentIssuedGatewayToken(f, gateway.body.id, tokenBody.name);
|
||||
expect(token, JSON.stringify(token)).toMatchObject({ status: 201 });
|
||||
const path = `/mcp/gateways/${gateway.body.gatewayPublicId}`;
|
||||
const rpc = (method: string, params?: unknown) => f.request("POST", path, { jsonrpc: "2.0", id: randomUUID(), method, ...(params ? { params } : {}) }, token.body.token);
|
||||
const listed = await rpc("tools/list");
|
||||
const tool = listed.body.result?.tools?.find((tool: { name: string }) => tool.name.includes("fixture-probe"));
|
||||
expect(tool, JSON.stringify(listed)).toBeTruthy();
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
const isRate = mode === "rate" || mode === "shared-rate";
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Gateway caller control", policyType: isRate ? "rate_limit" : mode.startsWith("ask") ? "require_approval" : mode === "credential" ? "allow" : "block",
|
||||
selectors: { connectionId: connection.body.id, ...(mode === "shared-rate" ? {} : { agentId: mode === "target-block" || mode === "ask-board" ? target.id : f.agentId }) }, priority: 0,
|
||||
...(isRate ? { config: { limit: 1, windowSeconds: 60, keyBy: mode === "shared-rate" ? ["company", "tool"] : ["agent", "tool"] } } : {}) });
|
||||
if (mode === "ask-rate") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "One issuer admission", policyType: "rate_limit", selectors: { connectionId: connection.body.id, agentId: f.agentId }, priority: -1, config: { limit: 1, windowSeconds: 60, keyBy: ["agent", "tool"] } });
|
||||
if (mode === "credential") {
|
||||
await server.db.update(toolConnections).set({ credentialPolicy: "per_agent" }).where(eq(toolConnections.id, connection.body.id));
|
||||
await server.db.insert(connectionGrants).values([f.agentId, target.id].map(subjectAgentId => ({ companyId: f.companyId, connectionId: connection.body.id, kind: "agent" as const, subjectAgentId, status: "active" as const })));
|
||||
}
|
||||
const called = await rpc("tools/call", { name: tool.name, arguments: {} });
|
||||
if (isRate) {
|
||||
expect(calls, JSON.stringify(called)).toBe(1);
|
||||
await rpc("tools/call", { name: tool.name, arguments: { another: true } });
|
||||
expect(calls).toBe(1);
|
||||
return;
|
||||
}
|
||||
expect(calls, JSON.stringify(called)).toBe(0);
|
||||
if (mode === "credential") {
|
||||
expect(JSON.stringify(called.body)).toContain("gateway_credential_identity_mismatch");
|
||||
return;
|
||||
}
|
||||
const [invocation] = await server.db.select().from(toolInvocations).where(eq(toolInvocations.gatewayId, gateway.body.id));
|
||||
expect(invocation).toMatchObject({ gatewayTokenId: token.body.id, actorId: mode === "ask-board" ? token.body.id : f.agentId, agentId: target.id, policyDecision: mode.startsWith("ask") ? "require_approval" : "deny" });
|
||||
if (!mode.startsWith("ask")) return;
|
||||
const [action] = await server.db.select().from(toolActionRequests).where(eq(toolActionRequests.invocationId, invocation.id));
|
||||
expect(action.requestedByAgentId).toBe(mode === "ask-board" ? null : f.agentId);
|
||||
if (mode.startsWith("ask-new-")) {
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New admission after review", policyType: "rate_limit",
|
||||
selectors: { connectionId: connection.body.id, ...(mode === "ask-new-shared-rate" ? {} : { agentId: f.agentId }) },
|
||||
priority: -2, config: { limit: 1, windowSeconds: 60, keyBy: mode === "ask-new-shared-rate" ? ["company", "tool"] : ["agent", "tool"] } });
|
||||
if (mode === "ask-new-rate") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New target admission", policyType: "rate_limit",
|
||||
selectors: { connectionId: connection.body.id, agentId: target.id }, priority: -1,
|
||||
config: { limit: 1, windowSeconds: 60, keyBy: ["agent", "tool"] } });
|
||||
if (mode === "ask-new-rate-target-block") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New target block", policyType: "block",
|
||||
selectors: { connectionId: connection.body.id, agentId: target.id }, priority: -1 });
|
||||
}
|
||||
if (mode === "ask-revoked") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Issuer blocked after review", policyType: "block", selectors: { connectionId: connection.body.id, agentId: f.agentId }, priority: -1 });
|
||||
if (mode === "ask-token-revoked") await server.db.update(toolMcpGatewayTokens).set({ revokedAt: new Date() }).where(eq(toolMcpGatewayTokens.id, token.body.id));
|
||||
if (mode === "ask-token-deleted") await server.db.delete(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, token.body.id));
|
||||
if (mode === "ask-token-scope") await server.db.update(toolMcpGatewayTokens).set({ allowedActions: ["tools/list"] }).where(eq(toolMcpGatewayTokens.id, token.body.id));
|
||||
if (mode === "ask-grant-revoked" || mode === "ask-one-connection-revoked") await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
const approvalDenied = ["ask-revoked", "ask-new-rate-target-block", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked", "ask-one-connection-revoked"].includes(mode);
|
||||
if (mode.startsWith("ask-one-connection")) {
|
||||
const limited = createDb(server.databaseUrl, { maxConnections: 1, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
||||
const service = createToolGatewayService(limited);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let attempt: Promise<unknown> | undefined;
|
||||
try {
|
||||
if (mode === "ask-one-connection-recovery") await commitToolActionReview(server.db, {
|
||||
companyId: f.companyId, actionRequestId: action.id, decision: "approved", actor: { userId: f.userId },
|
||||
});
|
||||
attempt = mode === "ask-one-connection-recovery" ? service.recoverApprovedActionReviews(f.companyId)
|
||||
: service.approveActionRequest({ companyId: f.companyId, actionRequestId: action.id, actor: { userId: f.userId } });
|
||||
void attempt.catch(() => undefined);
|
||||
const completed = Promise.race([attempt, new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error("Single-connection gateway approval did not settle")), 5000);
|
||||
})]);
|
||||
if (approvalDenied) await expect(completed).rejects.toMatchObject({ status: 403 });
|
||||
else await completed;
|
||||
expect((await limited.execute(sql`select 1 as available`))[0].available).toBe(1);
|
||||
} finally {
|
||||
clearTimeout(timer); await limited.$client.end({ timeout: 1 }); await attempt?.catch(() => undefined);
|
||||
}
|
||||
} else {
|
||||
const response = await fetch(`${server.apiUrl}/api/tool-gateway/action-requests/${action.id}/approve`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
|
||||
expect(response.status, JSON.stringify(await response.json())).toBe(approvalDenied ? 403 : 200);
|
||||
}
|
||||
expect(calls).toBe(approvalDenied ? 0 : 1);
|
||||
if (mode.startsWith("ask-new-")) {
|
||||
const counters = await server.db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.companyId, f.companyId));
|
||||
expect(counters).toHaveLength(approvalDenied ? 0 : mode === "ask-new-shared-rate" ? 1 : 2);
|
||||
expect(counters.every(counter => counter.remaining === 0)).toBe(true);
|
||||
if (!approvalDenied) {
|
||||
const [settled] = await server.db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id));
|
||||
expect(settled.policyExplanation?.consumedRateAdmissions).toHaveLength(1);
|
||||
expect(settled.policyExplanation?.delegatedCallerConsumedRateAdmissions).toHaveLength(1);
|
||||
}
|
||||
}
|
||||
if (["ask-rate", "ask-new-rate", "ask-new-shared-rate"].includes(mode)) {
|
||||
await rpc("tools/call", { name: tool.name, arguments: { another: true } });
|
||||
expect(calls).toBe(1);
|
||||
}
|
||||
} finally { vi.useRealTimers(); await new Promise<void>((resolve, reject) => remote.close(error => error ? reject(error) : resolve())); }
|
||||
});
|
||||
|
||||
it("requires retained profile authority to clear gateway bindings and connection audiences", async () => {
|
||||
const f = await fixture();
|
||||
const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "bound-profile", name: "Bound profile", entries: [] });
|
||||
expect(profile, JSON.stringify(profile)).toMatchObject({ status: 201 });
|
||||
const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Bound gateway", slug: "bound", profileId: profile.body.id, agentId: f.agentId });
|
||||
expect(gateway, JSON.stringify(gateway)).toMatchObject({ status: 201, body: { agentId: f.agentId } });
|
||||
await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_profiles")));
|
||||
expect(await f.request("PATCH", `/tool-gateway/gateways/${gateway.body.id}`, { companyId: f.companyId, agentId: null })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("GET", `/companies/${f.companyId}/tools/gateways`)).toMatchObject({ status: 200, body: { gateways: expect.arrayContaining([expect.objectContaining({ id: gateway.body.id, agentId: f.agentId })]) } });
|
||||
for (const audience of [{ allAgents: false }, { agentIds: [] }]) {
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/ai-connections`, {
|
||||
provider: "openai", method: "api_key", name: "No audience authority", apiKey: "unused-fixture-secret", ...audience,
|
||||
})).toMatchObject({ status: 403 });
|
||||
}
|
||||
});
|
||||
|
||||
it("requires access to saved and replacement gateway profiles and project bindings", async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "saved-scope", name: "Saved scope", entries: [] });
|
||||
const replacement = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "replacement-scope", name: "Replacement scope", entries: [] });
|
||||
expect(saved.status).toBe(201);
|
||||
expect(replacement.status).toBe(201);
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/tools/profiles/${saved.body.id}/bind`, { targetType: "project", targetId: f.projectId })).toMatchObject({ status: 201 });
|
||||
const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Scoped gateway", slug: "scoped", profileId: saved.body.id });
|
||||
expect(gateway.status).toBe(201);
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { profileIds: [replacement.body.id] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await f.request("PATCH", `/tool-gateway/gateways/${gateway.body.id}`, { companyId: f.companyId, profileId: replacement.body.id })).toMatchObject({ status: 403 });
|
||||
// A grant covering both sides permits the same requested change.
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { profileIds: [saved.body.id, replacement.body.id] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await f.request("PATCH", `/tool-gateway/gateways/${gateway.body.id}`, { companyId: f.companyId, profileId: replacement.body.id })).toMatchObject({ status: 200, body: { profileId: replacement.body.id } });
|
||||
expect(await f.request("PATCH", `/tool-gateway/gateways/${gateway.body.id}`, { companyId: f.companyId, projectId: f.projectId })).toMatchObject({ status: 200 });
|
||||
const nextProjectId = randomUUID();
|
||||
await server.db.insert(projects).values({ id: nextProjectId, companyId: f.companyId, name: "Replacement project" });
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { projectIds: [f.projectId] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_profiles")));
|
||||
expect(await f.request("PATCH", `/tool-gateway/gateways/${gateway.body.id}`, { companyId: f.companyId, projectId: nextProjectId })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("PATCH", `/tool-gateway/gateways/${gateway.body.id}`, { companyId: f.companyId, projectId: null })).toMatchObject({ status: 403 });
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { projectIds: [f.projectId, nextProjectId] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_profiles")));
|
||||
expect(await f.request("PATCH", `/tool-gateway/gateways/${gateway.body.id}`, { companyId: f.companyId, projectId: nextProjectId })).toMatchObject({ status: 200, body: { projectId: nextProjectId } });
|
||||
await server.db.update(principalPermissionGrants).set({ scope: null }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_profiles")));
|
||||
expect(await f.request("PATCH", `/tool-gateway/gateways/${gateway.body.id}`, { companyId: f.companyId, projectId: null })).toMatchObject({ status: 200, body: { projectId: null } });
|
||||
});
|
||||
|
||||
it("saves an AI account with fixture verification under the user's ownership and agent attribution", async () => {
|
||||
const f = await fixture();
|
||||
provider = async url => {
|
||||
if (url === "https://api.openai.com/v1/models") return Response.json({ data: [] });
|
||||
throw new Error("Unexpected AI fixture request");
|
||||
};
|
||||
registerServerAdapter({ ...getServerAdapter("paperclip_runner"), testEnvironment: async () => ({ adapterType: "paperclip_runner", status: "pass", checks: [], testedAt: new Date().toISOString() }) });
|
||||
try {
|
||||
const account = await f.request("POST", `/companies/${f.companyId}/ai-connections`, { provider: "openai", method: "api_key", name: "Fixture OpenAI", ownership: "personal", apiKey: "fixture-secret-do-not-return", agentIds: [f.agentId] });
|
||||
expect(account, JSON.stringify(account)).toMatchObject({ status: 201 });
|
||||
expect(JSON.stringify(account)).not.toContain("fixture-secret-do-not-return");
|
||||
const list = await f.request("GET", `/companies/${f.companyId}/ai-connections`);
|
||||
expect(list).toMatchObject({ status: 200, body: { currentUserId: f.userId } });
|
||||
const [row] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, account.body.connectionId));
|
||||
expect(row.createdByUserId).toBe(f.userId);
|
||||
const binding = { mode: "delegated", provider: "openai", method: "api_key", ...account.body };
|
||||
const bound = await f.request("PATCH", `/agents/${f.agentId}`, { runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: false }, aiConnection: binding } });
|
||||
expect(bound, JSON.stringify(bound)).toMatchObject({ status: 200 });
|
||||
await instanceSettingsService(server.db).updateExperimental({ enableAiConnectionRouters: true });
|
||||
const pluginKey = `fixture.router.${f.agentId}`;
|
||||
await server.db.insert(plugins).values({ pluginKey, packageName: pluginKey, version: "0.1.0", status: "ready", manifestJson: {
|
||||
id: pluginKey, apiVersion: 1, version: "0.1.0", displayName: "Fixture router", description: "Fixture", author: "Tests",
|
||||
categories: ["connector"], capabilities: ["ai.connections.route"], aiConnectionRouter: { name: "Fixture pool", description: "Use saved accounts" }, entrypoints: { worker: "worker.js" },
|
||||
} });
|
||||
const config = { name: "Fixture pool", enabled: true, mode: "round_robin", thresholdPercent: 90,
|
||||
members: [{ id: randomUUID(), binding, profile: { provider: "codex", model: "gpt-5.6-sol", effort: "low" } }] };
|
||||
const pool = await f.request("POST", `/companies/${f.companyId}/ai-connection-pools`, { pluginKey, config });
|
||||
expect(pool, JSON.stringify(pool)).toMatchObject({ status: 200, body: { revision: 1 } });
|
||||
const changed = await f.request("POST", `/companies/${f.companyId}/ai-connection-pools`, { pluginKey, id: pool.body.id, expectedRevision: 1, config: { ...config, name: "Changed pool" } });
|
||||
expect(changed, JSON.stringify(changed)).toMatchObject({ status: 200, body: { revision: 2 } });
|
||||
expect(await f.request("DELETE", `/companies/${f.companyId}/ai-connection-pools/${pool.body.id}`, { expectedRevision: 1 })).toMatchObject({ status: 409 });
|
||||
expect(await f.request("DELETE", `/companies/${f.companyId}/ai-connection-pools/${pool.body.id}`, { expectedRevision: 2 })).toMatchObject({ status: 200 });
|
||||
await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_profiles")));
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/ai-connections`, { provider: "openai", method: "api_key", name: "No sharing authority", ownership: "personal", apiKey: "fixture-secret", agentIds: [f.agentId] })).toMatchObject({ status: 403 });
|
||||
} finally { provider = null; unregisterServerAdapter("paperclip_runner"); }
|
||||
});
|
||||
|
||||
it("reads only the authorized Anthropic account identity through actual agent authentication", async () => {
|
||||
const f = await fixture();
|
||||
const account = await aiConnectionService(server.db).save(f.companyId, f.userId, {
|
||||
provider: "anthropic", method: "subscription", ownership: "personal", name: "Account identity fixture",
|
||||
loginSessionId: "fixture", agentIds: [f.agentId], allAgents: false,
|
||||
}, "selected-identity-credential");
|
||||
let calls = 0;
|
||||
provider = async (url, init) => {
|
||||
calls++;
|
||||
expect(url).toBe("https://api.anthropic.com/api/oauth/profile");
|
||||
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer selected-identity-credential");
|
||||
return Response.json({ account: { uuid: "private-seat", email: "avery@example.test" }, organization: { uuid: "private-org", name: "Example team" } });
|
||||
};
|
||||
const path = `/companies/${f.companyId}/ai-connections/${account.connectionId}/identity?grantId=${account.grantId}`;
|
||||
try {
|
||||
for (const token of [f.key.token, f.jwt]) {
|
||||
const response = await f.request("GET", path, undefined, token);
|
||||
expect(response).toMatchObject({ status: 200, body: { ...account, status: "available", accountLabel: "avery@example.test", organizationLabel: "Example team" } });
|
||||
for (const secret of ["selected-identity-credential", "private-seat", "private-org"]) expect(JSON.stringify(response)).not.toContain(secret);
|
||||
}
|
||||
expect(calls).toBe(2);
|
||||
expect((await f.request("GET", path.replace(f.companyId, f.foreignCompanyId))).status).toBe(403);
|
||||
expect((await f.request("GET", path.replace(account.grantId, randomUUID()))).status).toBe(404);
|
||||
expect(calls).toBe(2);
|
||||
await server.db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, account.grantId));
|
||||
expect(await f.request("GET", path)).toMatchObject({ status: 200, body: { status: "unavailable", errorCode: "connection_unavailable", accountLabel: null } });
|
||||
expect(calls).toBe(2);
|
||||
} finally { provider = null; }
|
||||
});
|
||||
|
||||
it("filters AI account and pool listings by the agent's resolved connection scope", async () => {
|
||||
const f = await fixture();
|
||||
provider = async url => {
|
||||
if (url === "https://api.openai.com/v1/models") return Response.json({ data: [] });
|
||||
throw new Error("Unexpected AI fixture request");
|
||||
};
|
||||
try {
|
||||
const accounts: { connectionId: string; grantId: string }[] = [];
|
||||
for (const name of ["Allowed account", "Outside agent scope"]) {
|
||||
const account = await f.request("POST", `/companies/${f.companyId}/ai-connections`, { provider: "openai", method: "api_key", name, ownership: "personal", apiKey: `fixture-${name}`, agentIds: [] });
|
||||
expect(account, JSON.stringify(account)).toMatchObject({ status: 201 });
|
||||
accounts.push(account.body);
|
||||
}
|
||||
await instanceSettingsService(server.db).updateExperimental({ enableAiConnectionRouters: true });
|
||||
const pluginKey = `fixture.scope.${f.agentId}`;
|
||||
await server.db.insert(plugins).values({ pluginKey, packageName: pluginKey, version: "0.1.0", status: "ready", manifestJson: {
|
||||
id: pluginKey, apiVersion: 1, version: "0.1.0", displayName: "Fixture router", description: "Fixture", author: "Tests",
|
||||
categories: ["connector"], capabilities: ["ai.connections.route"], aiConnectionRouter: { name: "Fixture pool", description: "Use saved accounts" }, entrypoints: { worker: "worker.js" },
|
||||
} });
|
||||
const savedPools: { id: string }[] = [];
|
||||
for (const account of accounts) {
|
||||
const pool = await f.request("POST", `/companies/${f.companyId}/ai-connection-pools`, { pluginKey, config: { name: `Pool ${account.connectionId}`, enabled: true, mode: "round_robin", thresholdPercent: 90,
|
||||
members: [{ id: randomUUID(), binding: { mode: "delegated", provider: "openai", method: "api_key", ...account }, profile: { provider: "codex", model: "gpt-5.6-sol", effort: "low" } }] } });
|
||||
expect(pool, JSON.stringify(pool)).toMatchObject({ status: 200 });
|
||||
savedPools.push(pool.body);
|
||||
}
|
||||
const path = `/companies/${f.companyId}/ai-connections?connectionId=${accounts[0].connectionId}`;
|
||||
expect((await f.request("GET", path)).body.connections).toHaveLength(2);
|
||||
expect((await f.request("GET", path)).body.pools).toHaveLength(2);
|
||||
for (const connectionIds of [[accounts[0].connectionId], [accounts[0].connectionId, ...savedPools.map(pool => pool.id)]]) {
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { connectionIds } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
for (const token of [f.key.token, f.jwt]) {
|
||||
const listed = await f.request("GET", path, undefined, token);
|
||||
expect(listed, JSON.stringify(listed)).toMatchObject({ status: 200 });
|
||||
expect(listed.body.connections.map((account: { id: string }) => account.id)).toEqual([accounts[0].connectionId]);
|
||||
expect(listed.body.pools.map((pool: { id: string }) => pool.id)).toEqual(connectionIds.length === 1 ? [] : [savedPools[0].id]);
|
||||
}
|
||||
}
|
||||
} finally { provider = null; }
|
||||
});
|
||||
|
||||
it("reuses a saved chat authentication request and resumes only while its authority remains valid", async () => {
|
||||
const f = await fixture();
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider: "github", assignedAgentId: f.agentId });
|
||||
expect(created.status).toBe(201);
|
||||
const path = `/chat-endpoints/${created.body.id}/github/identity/start`;
|
||||
const first = await f.request("POST", path, {}, f.jwt);
|
||||
expect(first, JSON.stringify(first)).toMatchObject({ status: 200, body: { interactionId: expect.any(String) } });
|
||||
const retry = await f.request("POST", path, {}, f.jwt);
|
||||
expect(retry.body.interactionId).toBe(first.body.interactionId);
|
||||
const [intent] = await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, first.body.interactionId));
|
||||
const [task] = await server.db.select().from(issues).where(eq(issues.id, f.issueId));
|
||||
expect(intent).toMatchObject({ addresseeUserId: f.userId, payload: { savedSetup: { endpointId: created.body.id, connectionId: created.body.connectionId } } });
|
||||
expect(await findSatisfiedToolConnection(server.db, task, intent)).toBeNull();
|
||||
// Healthy App credentials alone do not prove the addressee's identity.
|
||||
await server.db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId));
|
||||
await server.db.update(chatEndpoints).set({ status: "active", providerAccountId: "identity-fixture" }).where(eq(chatEndpoints.id, created.body.id));
|
||||
await server.db.update(toolConnections).set({ status: "active", enabled: true, healthStatus: "healthy" }).where(eq(toolConnections.id, created.body.connectionId));
|
||||
expect(await findSatisfiedToolConnection(server.db, task, intent)).toBeNull();
|
||||
await satisfiedConnectionIntentService(server.db).sweepPending();
|
||||
expect((await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, intent.id)))[0].status).toBe("pending");
|
||||
expect(await server.db.select().from(connectionIntentDeliveries).where(eq(connectionIntentDeliveries.interactionId, intent.id))).toEqual([]);
|
||||
const [principal] = await server.db.insert(chatExternalPrincipals).values({ companyId: f.companyId, provider: "github", providerAccountId: "identity-fixture", externalId: "1357" }).returning();
|
||||
const [link] = await server.db.insert(chatIdentityLinks).values({ companyId: f.companyId, endpointId: created.body.id, principalId: principal.id, paperclipUserId: f.userId, status: "pending" }).returning();
|
||||
for (const status of ["pending", "revoked", "expired"] as const) {
|
||||
await server.db.update(chatIdentityLinks).set({ status }).where(eq(chatIdentityLinks.id, link.id));
|
||||
expect(await findSatisfiedToolConnection(server.db, task, intent), status).toBeNull();
|
||||
}
|
||||
await server.db.update(chatIdentityLinks).set({ status: "linked", confirmedAt: new Date() }).where(eq(chatIdentityLinks.id, link.id));
|
||||
await server.db.update(chatIdentityLinks).set({ paperclipUserId: randomUUID() }).where(eq(chatIdentityLinks.id, link.id));
|
||||
expect(await findSatisfiedToolConnection(server.db, task, intent)).toBeNull();
|
||||
await server.db.update(chatIdentityLinks).set({ paperclipUserId: f.userId }).where(eq(chatIdentityLinks.id, link.id));
|
||||
await server.db.update(chatExternalPrincipals).set({ providerAccountId: "different-installation" }).where(eq(chatExternalPrincipals.id, principal.id));
|
||||
expect(await findSatisfiedToolConnection(server.db, task, intent)).toBeNull();
|
||||
await server.db.update(chatExternalPrincipals).set({ providerAccountId: "identity-fixture" }).where(eq(chatExternalPrincipals.id, principal.id));
|
||||
expect((await findSatisfiedToolConnection(server.db, task, intent))?.id).toBe(created.body.connectionId);
|
||||
expect(await findSatisfiedToolConnection(server.db, { ...task, status: "cancelled" }, intent)).toBeNull();
|
||||
await accessService(server.db).ensureMembership(f.companyId, "user", f.userId, "operator", "suspended");
|
||||
expect(await findSatisfiedToolConnection(server.db, task, intent)).toBeNull();
|
||||
await accessService(server.db).ensureMembership(f.companyId, "user", f.userId, "operator", "active");
|
||||
await satisfiedConnectionIntentService(server.db).sweepPending();
|
||||
const [delivery] = await server.db.select().from(connectionIntentDeliveries).where(eq(connectionIntentDeliveries.interactionId, intent.id));
|
||||
expect(delivery).toBeDefined();
|
||||
});
|
||||
|
||||
it("retains a restricted user's personal self-service without company management or spoofed ownership", async () => {
|
||||
const f = await fixture();
|
||||
await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalType, "user"), eq(principalPermissionGrants.principalId, f.userId)));
|
||||
provider = async url => {
|
||||
if (url === "https://api.openai.com/v1/models") return Response.json({ data: [] });
|
||||
throw new Error("Unexpected AI fixture request");
|
||||
};
|
||||
const payload = { provider: "openai", method: "api_key", name: "Personal", ownership: "personal", apiKey: "personal-fixture", agentIds: [], allAgents: false };
|
||||
try {
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/ai-connections`, { ...payload, ownership: "shared" })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/ai-connections`, { ...payload, responsibleUserId: randomUUID() })).toMatchObject({ status: 403 });
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/ai-connections`, payload)).toMatchObject({ status: 201 });
|
||||
} finally { provider = null; }
|
||||
});
|
||||
|
||||
it("rejects foreign personal metadata, missing responsible users and task-bridge keys", async () => {
|
||||
const f = await fixture();
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Foreign personal fixture", transport: "mcp_remote", authKind: "none", transportConfig: { url: "https://1.1.1.1/mcp" } });
|
||||
expect(created.status).toBe(201);
|
||||
await server.db.update(toolConnections).set({ credentialPolicy: "per_user", createdByUserId: randomUUID() }).where(eq(toolConnections.id, created.body.id));
|
||||
expect(await f.request("GET", `/tool-connections/${created.body.id}`)).toMatchObject({ status: 403 });
|
||||
const listed = await f.request("GET", `/companies/${f.companyId}/tools/connections`);
|
||||
expect(JSON.stringify(listed.body)).not.toContain("Foreign personal fixture");
|
||||
const [policy] = await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Private account rule", policyType: "block", selectors: { connectionIds: [created.body.id] } }).returning();
|
||||
expect(JSON.stringify((await f.request("GET", `/companies/${f.companyId}/tools/policies`)).body)).not.toContain(policy.id);
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/tools/policies`, { name: "Cannot edit foreign access", policyType: "allow", selectors: { agentId: f.agentId, connectionIds: [created.body.id] } })).toMatchObject({ status: 403 });
|
||||
|
||||
await server.db.update(agentApiKeys).set({ responsibleUserId: null }).where(eq(agentApiKeys.id, f.key.id));
|
||||
expect((await f.request("GET", `/companies/${f.companyId}/tools/gallery`)).status).toBeGreaterThanOrEqual(400);
|
||||
const g = await fixture();
|
||||
await server.db.update(agentApiKeys).set({ scopeConfig: { kind: "task_bridge", parentIssueId: g.issueId } }).where(eq(agentApiKeys.id, g.key.id));
|
||||
expect((await g.request("GET", `/companies/${g.companyId}/tools/gallery`)).status).toBeGreaterThanOrEqual(400);
|
||||
});
|
||||
|
||||
it("revalidates pending credential promotion after yielding without reviving cancelled work", async () => {
|
||||
const f = await fixture();
|
||||
const context = await connectionManagementService(server.db).authorize({ type: "agent", companyId: f.companyId,
|
||||
agentId: f.agentId, runId: f.runId, onBehalfOfUserId: f.userId }, "connections:configure",
|
||||
{ type: "connection_management", companyId: f.companyId, purpose: "ai", operation: "login" });
|
||||
const continuation = continuingConnectionManagement(context)!;
|
||||
await server.db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId));
|
||||
await expect(context.reauthorize()).rejects.toThrow();
|
||||
await expect(continuation.reauthorize()).resolves.toBeUndefined();
|
||||
await server.db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, f.issueId));
|
||||
await expect(continuation.reauthorize()).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("denies revoked agent grants and user authority, including shadow mode, without backfilling", async () => {
|
||||
const f = await fixture();
|
||||
await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await f.request("GET", `/companies/${f.companyId}/tools/gallery`)).toMatchObject({ status: 403 });
|
||||
const g = await fixture();
|
||||
await accessService(server.db).ensureMembership(g.companyId, "user", g.userId, "operator", "suspended");
|
||||
expect(await g.request("GET", `/companies/${g.companyId}/tools/gallery`)).toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it("enforces grant scopes, company isolation, effective trust, and Ask/Plan work modes", async () => {
|
||||
const f = await fixture();
|
||||
expect(await f.request("GET", `/companies/${f.foreignCompanyId}/tools/gallery`)).toMatchObject({ status: 403 });
|
||||
const owned = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Scoped fixture", transport: "mcp_remote", authKind: "none", transportConfig: { url: "https://1.1.1.1/mcp" } });
|
||||
expect(owned.status).toBe(201);
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { connectionIds: [owned.body.id], purposes: ["tool"], operations: ["GET /tool-connections/:connectionId"] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await f.request("GET", `/tool-connections/${owned.body.id}`)).toMatchObject({ status: 200 });
|
||||
expect(await f.request("PATCH", `/tool-connections/${owned.body.id}`, { name: "Beyond operation scope" })).toMatchObject({ status: 403 });
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { provider: "slack" } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider: "github", assignedAgentId: f.agentId })).toMatchObject({ status: 403 });
|
||||
const g = await fixture();
|
||||
for (const workMode of ["ask", "planning", "skill_test"]) {
|
||||
await server.db.update(issues).set({ workMode }).where(eq(issues.id, g.issueId));
|
||||
expect(await g.request("POST", `/companies/${g.companyId}/tools/profiles`, { name: "Forbidden" }, g.jwt)).toMatchObject({ status: 403 });
|
||||
}
|
||||
await server.db.update(issues).set({ workMode: "standard" }).where(eq(issues.id, g.issueId));
|
||||
await server.db.update(projects).set({ executionWorkspacePolicy: { authorizationPolicy: { trustPreset: "low_trust_review", lowTrustBoundary: { projectIds: [g.projectId] } } } }).where(eq(projects.id, g.projectId));
|
||||
expect(await g.request("POST", `/companies/${g.companyId}/tools/profiles`, { name: "Forbidden trust" }, g.jwt)).toMatchObject({ status: 403 });
|
||||
await server.db.update(agents).set({ permissions: { trustPreset: "low_trust_review", authorizationPolicy: { trustBoundary: { mode: "low_trust_review", projectIds: [g.projectId], rootIssueId: g.issueId } } } }).where(eq(agents.id, g.agentId));
|
||||
expect(await g.request("POST", `/companies/${g.companyId}/tools/profiles`, { name: "Forbidden agent trust" })).toMatchObject({ status: 403 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,640 @@
|
||||
import { createToolGatewayService } from "../services/tool-gateway.js";
|
||||
import { commitToolActionReview } from "../services/tool-action-review.js";
|
||||
import { googleWorkspaceSelectedScopes, defaultGitHubReviewPolicy, SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES } from "@paperclipai/shared";
|
||||
import { createHash, randomBytes, randomUUID, generateKeyPairSync } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { createServer } from "node:http";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { beforeAll, afterAll, describe, expect, it, vi } from "vitest";
|
||||
import { createDb, authUsers, activityLog, agentApiKeys, companies, companySecrets, companySecretVersions, chatConversations, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, toolPolicies, toolRateLimitCounters, connectionGrants, connectionGrantMembers, connectionGrantDelegations, toolAccessAuditEvents, toolOauthStates, issueThreadInteractions, connectionIntentDeliveries, agents, companyMemberships, heartbeatRuns, issues, principalPermissionGrants, projects, toolApplications, toolConnections, toolConnectionInstalls, aiConnectionPools, toolMcpGateways, toolMcpGatewayTokens, toolActionRequests, toolCatalogEntries, toolInvocations, toolCallEvents, toolProfileEntries, toolProfiles, toolProfileBindings, plugins, adapterAuthSessions, environments, routines, chatGitHubReviews } from "@paperclipai/db";
|
||||
import { findSatisfiedToolConnection, satisfiedConnectionIntentService } from "../services/satisfied-connection-intents.js";
|
||||
import { connectionManagementService, continuingConnectionManagement } from "../services/connection-management.js";
|
||||
import { aiConnectionService } from "../services/ai-connections.js";
|
||||
import { redactRunnerApiPayloads } from "../services/native-runtime/runner-api-log-redaction.js";
|
||||
import * as remoteEndpointGuard from "../services/remote-http-endpoint-guard.js";
|
||||
import * as remoteHttpFetch from "../services/remote-http-fetch.js";
|
||||
import * as runIdentity from "../services/run-identity.js";
|
||||
import * as connectionManagementModule from "../services/connection-management.js";
|
||||
import * as localBrowserLogin from "../services/local-ai-browser-login.js";
|
||||
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
|
||||
import { startRunnerApiTestServer } from "./helpers/runner-api-server.js";
|
||||
import { getServerAdapter, registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
|
||||
import { configureAgentLifecycle } from "../services/agent-lifecycle.js";
|
||||
import { agentService } from "../services/agents.js";
|
||||
import { accessService } from "../services/access.js";
|
||||
import { secretService } from "../services/secrets.js";
|
||||
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
|
||||
import type { AuthorizationActor } from "../services/authorization.js";
|
||||
import type { ConnectionManagementResource } from "../services/connection-management-policy.js";
|
||||
|
||||
vi.mock("../services/agent-lifecycle-driver.js", () => ({
|
||||
createLifecycleDriver: () => ({ requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" }),
|
||||
}));
|
||||
|
||||
vi.mock("../services/chat-channels/github/webhook-recovery-work.js", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("../services/chat-channels/github/webhook-recovery-work.js")>();
|
||||
return { ...original, registerGitHubWebhookRecoveryWork: (...args: Parameters<typeof original.registerGitHubWebhookRecoveryWork>) =>
|
||||
original.registerGitHubWebhookRecoveryWork(args[0], args[1], () => false) };
|
||||
});
|
||||
|
||||
import { createConnectionManagementHarness, type ConnectionManagementLifecycle, type ConnectionManagementProviderHandler, type ConnectionManagementServer } from "./helpers/connection-management-harness.js";
|
||||
|
||||
// All requests traverse the assembled server and production bearer middleware.
|
||||
// No req.actor injection or special permission grants establish access.
|
||||
describe("connection management Slack, GitHub, email, activity, and local-login providers", () => {
|
||||
let server!: ConnectionManagementServer;
|
||||
let lifecycle!: ConnectionManagementLifecycle;
|
||||
let provider: ConnectionManagementProviderHandler | null = null;
|
||||
const harness = createConnectionManagementHarness(() => provider);
|
||||
beforeAll(() => {
|
||||
server = harness.server;
|
||||
lifecycle = harness.lifecycle;
|
||||
});
|
||||
const fixture = () => harness.fixture();
|
||||
|
||||
it("persists meaningful Slack and GitHub endpoint configuration for the responsible user", async () => {
|
||||
const f = await fixture();
|
||||
for (const provider of ["slack", "github"]) {
|
||||
const result = await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider, assignedAgentId: f.agentId, name: `${provider} fixture`, ...(provider === "slack" ? { slackSetupMethod: "manual" } : {}) });
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ status: 201 });
|
||||
if (provider === "slack") {
|
||||
const patch = { requireAtMention: true, allowDirectMessages: false };
|
||||
const updated = await f.request("PATCH", `/chat-endpoints/${result.body.id}`, patch);
|
||||
expect(updated, JSON.stringify(updated)).toMatchObject({ status: 200, body: patch });
|
||||
} else {
|
||||
const current = await f.request("GET", `/chat-endpoints/${result.body.id}/github/configuration`);
|
||||
expect(current, JSON.stringify(current)).toMatchObject({ status: 200 });
|
||||
const body = { expectedRevision: current.body.revision, configuration: { ...current.body.configuration, memberAccess: "selected" } };
|
||||
const updated = await f.request("PUT", `/chat-endpoints/${result.body.id}/github/configuration`, body);
|
||||
expect(updated, JSON.stringify(updated)).toMatchObject({ status: 200, body: { revision: 1, configuration: { memberAccess: "selected" } } });
|
||||
expect(await f.request("PUT", `/chat-endpoints/${result.body.id}/github/configuration`, body)).toMatchObject({ status: 409 });
|
||||
const otherUserId = randomUUID();
|
||||
await accessService(server.db).ensureMembership(f.companyId, "user", otherUserId, "operator", "active");
|
||||
for (const token of [f.key.token, f.jwt]) {
|
||||
for (const field of ["responsible", "guest"]) {
|
||||
const configuration = structuredClone(updated.body.configuration);
|
||||
if (field === "responsible") configuration.responsibleUserId = otherUserId;
|
||||
else configuration.people.push({ kind: "guest", githubUserId: "42", login: "guest", sponsorUserId: otherUserId, permissionProfile: "restricted" });
|
||||
const denied = await f.request("PUT", `/chat-endpoints/${result.body.id}/github/configuration`, { expectedRevision: 1, configuration }, token);
|
||||
expect(denied, JSON.stringify(denied)).toMatchObject({ status: 403 });
|
||||
expect(JSON.stringify(denied.body)).toContain("task sponsor");
|
||||
}
|
||||
}
|
||||
expect((await f.request("GET", `/chat-endpoints/${result.body.id}/github/configuration`)).body).toMatchObject({ revision: 1, configuration: updated.body.configuration });
|
||||
const handoff = await f.request("POST", `/chat-endpoints/${result.body.id}/github/identity/start`, {});
|
||||
expect(handoff).toMatchObject({ status: 200, body: { requiredUserAction: { userId: f.userId, resource: { id: result.body.id } } } });
|
||||
}
|
||||
expect((await f.request("GET", `/chat-endpoints/${result.body.id}`)).body.sponsorUserId).toBe(f.userId);
|
||||
}
|
||||
});
|
||||
|
||||
it("configures Slack against provider fixtures and subjects test messages to the normal action policy", async () => {
|
||||
const f = await fixture();
|
||||
const botId = `U${f.agentId.replaceAll("-", "").toUpperCase()}`;
|
||||
const scopes = [...SLACK_CHAT_BOT_SCOPES, ...SLACK_BOT_TOOL_SCOPES];
|
||||
let sent = 0;
|
||||
let revokeDuringAuth = false;
|
||||
provider = async (url, init) => {
|
||||
if (url.endsWith("auth.test")) {
|
||||
if (revokeDuringAuth) await accessService(server.db).ensureMembership(f.companyId, "user", f.userId, "operator", "suspended");
|
||||
return Response.json({ ok: true, team_id: "TFIXTURE", team: "Fixture workspace", user_id: botId, user: "fixture-bot" }, { headers: { "x-oauth-scopes": scopes.join(",") } });
|
||||
}
|
||||
if (url.includes("conversations.list")) return Response.json({ ok: true, channels: [], response_metadata: { next_cursor: "" } });
|
||||
if (url.endsWith("users.info")) return Response.json({ ok: true, user: { id: new URLSearchParams(String(init?.body)).get("user") ?? "UHUMAN", team_id: "TFIXTURE", name: "Fixture user", is_bot: false, deleted: false } });
|
||||
if (url.endsWith("chat.postMessage")) { sent++; return Response.json({ ok: true, channel: "DTEST", ts: "1.000001" }); }
|
||||
if (url.endsWith("agents.sessions.setStatus")) return Response.json({ ok: true });
|
||||
throw new Error(`Unexpected Slack fixture operation: ${new URL(url).pathname}`);
|
||||
};
|
||||
try {
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider: "slack", assignedAgentId: f.agentId, slackSetupMethod: "manual" });
|
||||
const setupPath = `/chat-endpoints/${created.body.id}/setup`;
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
const configuredResponse = await fetch(server.apiUrl + "/api" + setupPath, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "configure", credentials: { botToken: "xoxb-fixture-token", signingSecret: "fixture-signing-secret" } }) });
|
||||
const configured = { status: configuredResponse.status, body: await configuredResponse.json() };
|
||||
expect(configured, JSON.stringify(configured)).toMatchObject({ status: 200 });
|
||||
expect(JSON.stringify(configured.body)).not.toContain("xoxb-fixture-token");
|
||||
const [configuredEndpoint] = await server.db.select().from(chatEndpoints).where(eq(chatEndpoints.id, created.body.id));
|
||||
await server.db.update(chatEndpoints).set({ status: "active", setup: { ...configuredEndpoint.setup, step: "complete", webhookVerifiedAt: new Date().toISOString() } }).where(eq(chatEndpoints.id, created.body.id));
|
||||
const [before] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
const botTokenRef = before.credentialSecretRefs.find(ref => ref.configPath === "credentials.botToken")!;
|
||||
const rebound = before.credentialSecretRefs.map(ref => ref.configPath === "credentials.signingSecret" ? { ...ref, secretId: botTokenRef.secretId } : ref);
|
||||
expect(await f.request("PATCH", `/tool-connections/${created.body.connectionId}`, { credentialSecretRefs: rebound }, f.jwt))
|
||||
.toMatchObject({ status: 403, body: { code: "chat_endpoint_credentials_require_setup" } });
|
||||
let credentialIntentId: string | undefined;
|
||||
for (const action of ["reconnect", "configure"] as const) for (const token of [f.key.token, f.jwt]) {
|
||||
const chosen = "agent-chosen-webhook-key";
|
||||
const handoff = await f.request("POST", setupPath, { action, credentials: { signingSecret: chosen } }, token);
|
||||
expect(handoff, JSON.stringify(handoff)).toMatchObject({ status: 200, body: { status: "needs_user_action", endpointId: created.body.id,
|
||||
requiredUserAction: { kind: "enter_credentials", userId: f.userId, resource: { id: created.body.id } } } });
|
||||
expect(JSON.stringify(handoff.body)).not.toContain(chosen);
|
||||
expect(handoff.body.requiredUserAction.setupPath).toContain("stage=credentials&reconnect=1");
|
||||
const entryLink = new URL(handoff.body.requiredUserAction.setupPath, server.apiUrl);
|
||||
expect.soft(entryLink.searchParams.get("credentialFields")).toBe("signingSecret");
|
||||
expect.soft(entryLink.searchParams.get("credentialMode")).toBe("all");
|
||||
if (token === f.jwt) {
|
||||
if (credentialIntentId) expect(handoff.body.interactionId).toBe(credentialIntentId);
|
||||
credentialIntentId = handoff.body.interactionId;
|
||||
}
|
||||
const [after] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
expect(after.credentialSecretRefs).toEqual(before.credentialSecretRefs);
|
||||
const signing = after.credentialSecretRefs.find(ref => ref.configPath === "credentials.signingSecret")!;
|
||||
expect(await secretService(server.db).resolveSecretValue(f.companyId, signing.secretId, "latest", {
|
||||
accessContext: { consumerType: "system", consumerId: "integration-fixture", actorType: "system" },
|
||||
})).toBe("fixture-signing-secret");
|
||||
}
|
||||
const [credentialIntent] = await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, credentialIntentId!));
|
||||
const [task] = await server.db.select().from(issues).where(eq(issues.id, f.issueId));
|
||||
const entryProof = (credentialIntent.payload as { savedSetup: { credentialEntry: { previousGenerations: Record<string, string>; requireAll: boolean } } }).savedSetup.credentialEntry;
|
||||
expect(entryProof).toEqual({ previousGenerations: { signingSecret: expect.any(String) }, requireAll: true });
|
||||
expect(await findSatisfiedToolConnection(server.db, task, credentialIntent)).toBeNull();
|
||||
await satisfiedConnectionIntentService(server.db).sweepPending();
|
||||
expect((await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, credentialIntentId!)))[0].status).toBe("pending");
|
||||
// Ordinary write-only bot-token repair remains delegated under current authority.
|
||||
expect(await f.request("POST", setupPath, { action: "reconnect", credentials: { botToken: "xoxb-fixture-token" } }, f.jwt)).toMatchObject({ status: 200, body: { id: created.body.id } });
|
||||
const healthy = async () => {
|
||||
await server.db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, created.body.id));
|
||||
await server.db.update(toolConnections).set({ status: "active", enabled: true, healthStatus: "healthy" }).where(eq(toolConnections.id, created.body.connectionId));
|
||||
};
|
||||
await healthy();
|
||||
expect(await findSatisfiedToolConnection(server.db, task, credentialIntent)).toBeNull();
|
||||
const humanReconnect = async (signingSecret: string) => {
|
||||
const response = await fetch(server.apiUrl + "/api" + setupPath, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "reconnect", credentials: { signingSecret, botToken: "xoxb-fixture-token" } }) });
|
||||
expect({ status: response.status, body: await response.json() }).toMatchObject({ status: 200 });
|
||||
};
|
||||
await humanReconnect("fixture-signing-secret");
|
||||
await healthy();
|
||||
expect(await findSatisfiedToolConnection(server.db, task, credentialIntent)).toBeNull();
|
||||
await humanReconnect("human-replacement-signing-secret");
|
||||
expect(await findSatisfiedToolConnection(server.db, task, credentialIntent)).toBeNull();
|
||||
const resumedRequest = await f.request("POST", setupPath, { action: "reconnect", credentials: { signingSecret: "agent-chosen-webhook-key" } }, f.jwt);
|
||||
expect(resumedRequest.body.interactionId).toBe(credentialIntentId);
|
||||
expect((await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, credentialIntentId!)))[0].payload)
|
||||
.toMatchObject({ savedSetup: { credentialEntry: entryProof } });
|
||||
await healthy();
|
||||
expect(await findSatisfiedToolConnection(server.db, task, credentialIntent)).toBeNull();
|
||||
const [repaired] = await server.db.select().from(chatEndpoints).where(eq(chatEndpoints.id, created.body.id));
|
||||
await server.db.update(chatEndpoints).set({ setup: { ...repaired.setup, webhookVerifiedAt: new Date().toISOString() } }).where(eq(chatEndpoints.id, created.body.id));
|
||||
expect((await findSatisfiedToolConnection(server.db, task, credentialIntent))?.id).toBe(created.body.connectionId);
|
||||
expect(await findSatisfiedToolConnection(server.db, { ...task, status: "cancelled" }, credentialIntent)).toBeNull();
|
||||
await accessService(server.db).ensureMembership(f.companyId, "user", f.userId, "operator", "suspended");
|
||||
expect(await findSatisfiedToolConnection(server.db, task, credentialIntent)).toBeNull();
|
||||
await accessService(server.db).ensureMembership(f.companyId, "user", f.userId, "operator", "active");
|
||||
await satisfiedConnectionIntentService(server.db).sweepPending();
|
||||
expect((await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, credentialIntentId!)))[0].status).toBe("expired");
|
||||
// Replacing complete credentials repairs unavailable old vault material.
|
||||
for (const state of ["disabled", "deleted", "unreadable"] as const) {
|
||||
const [connection] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
const signing = connection.credentialSecretRefs.find(ref => ref.configPath === "credentials.signingSecret")!;
|
||||
if (state === "unreadable") {
|
||||
await server.db.update(companySecrets).set({ status: "active" }).where(eq(companySecrets.id, signing.secretId));
|
||||
await server.db.update(companySecretVersions).set({ material: {} }).where(eq(companySecretVersions.secretId, signing.secretId));
|
||||
} else {
|
||||
await server.db.update(companySecrets).set({ status: state }).where(eq(companySecrets.id, signing.secretId));
|
||||
}
|
||||
const response = await fetch(server.apiUrl + "/api" + setupPath, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "reconnect", credentials: { signingSecret: `human-repair-${state}`, botToken: "xoxb-fixture-token" } }) });
|
||||
expect.soft({ status: response.status, body: await response.json() }, `repair ${state} signing secret`).toMatchObject({ status: 200 });
|
||||
if (response.status === 200) {
|
||||
const [current] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
const replacement = current.credentialSecretRefs.find(ref => ref.configPath === "credentials.signingSecret")!;
|
||||
expect(replacement.secretId).not.toBe(signing.secretId);
|
||||
expect(await secretService(server.db).resolveSecretValue(f.companyId, replacement.secretId, "latest", {
|
||||
accessContext: { consumerType: "system", consumerId: "integration-fixture", actorType: "system" },
|
||||
})).toBe(`human-repair-${state}`);
|
||||
}
|
||||
}
|
||||
// Unexpected resolver failures must abort before writing new references.
|
||||
const [beforeFault] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
const resolverFault = vi.spyOn(localEncryptedProvider, "resolveVersion").mockRejectedValue(new Error("Unexpected secret resolution failure"));
|
||||
try {
|
||||
const response = await fetch(server.apiUrl + "/api" + setupPath, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "reconnect", credentials: { signingSecret: "human-repair-unexpected", botToken: "xoxb-fixture-token" } }) });
|
||||
expect(response.status).toBe(500);
|
||||
expect((await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId)))[0].credentialSecretRefs).toEqual(beforeFault.credentialSecretRefs);
|
||||
} finally { resolverFault.mockRestore(); }
|
||||
// Identity is a provider fixture; production HTTP admission and policy remain real.
|
||||
const [principal] = await server.db.insert(chatExternalPrincipals).values({ companyId: f.companyId, provider: "slack", providerAccountId: "TFIXTURE", externalId: "UHUMAN", isBot: false }).returning();
|
||||
await server.db.insert(chatIdentityLinks).values({ companyId: f.companyId, endpointId: created.body.id, principalId: principal.id, paperclipUserId: f.userId, status: "linked", confirmedAt: new Date() });
|
||||
await server.db.update(chatEndpoints).set({ status: "active", allowDirectMessages: true }).where(eq(chatEndpoints.id, created.body.id));
|
||||
const [deny] = await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Test messages off", policyType: "block", selectors: { connectionId: created.body.connectionId }, priority: 1 }).returning();
|
||||
const testPath = `/chat-endpoints/${created.body.id}/slack/test-message`;
|
||||
const denied = await f.request("POST", testPath, { requestId: randomUUID() });
|
||||
expect(denied, JSON.stringify(denied)).toMatchObject({ status: 403 });
|
||||
expect(sent).toBe(0);
|
||||
await server.db.update(toolPolicies).set({ policyType: "allow" }).where(eq(toolPolicies.id, deny.id));
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "One Slack setup send", policyType: "rate_limit", selectors: { connectionId: created.body.connectionId }, priority: 0, config: { limit: 1, windowSeconds: 60, keyBy: ["agent", "tool"] } });
|
||||
const requestId = randomUUID();
|
||||
const tested = await f.request("POST", testPath, { requestId });
|
||||
expect(tested, JSON.stringify(tested)).toMatchObject({ status: 200, body: { status: "sent" } });
|
||||
expect(await f.request("POST", testPath, { requestId })).toMatchObject({ status: 200 });
|
||||
expect(await f.request("POST", testPath, { requestId: randomUUID() })).toMatchObject({ status: 403, body: { details: { reasonCode: "rate_limited" } } });
|
||||
expect(await f.request("POST", testPath, { requestId: randomUUID(), slackUserId: "UOTHER" })).toMatchObject({ status: 403 });
|
||||
expect(sent).toBe(1);
|
||||
vi.useRealTimers();
|
||||
const [beforeRevocation] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
revokeDuringAuth = true;
|
||||
expect(await f.request("POST", setupPath, { action: "reconnect", credentials: { botToken: "xoxb-fixture-token" } }, f.jwt)).toMatchObject({ status: 403 });
|
||||
expect((await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId)))[0].credentialSecretRefs)
|
||||
.toEqual(beforeRevocation.credentialSecretRefs);
|
||||
} finally { vi.useRealTimers(); provider = null; }
|
||||
});
|
||||
|
||||
it.each(["linked", "invitation"] as const)("checks caller and target policy for delegated Slack %s sends", async recipient => {
|
||||
for (const mode of ["caller-block", "caller-ask", "caller-rate", "target-block", "target-rate", "shared-rate"] as const) {
|
||||
const f = await fixture();
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
const targetResponse = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/agents`, {
|
||||
method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Slack target", role: "engineer", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" },
|
||||
permissions: {}, runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: false } } }),
|
||||
});
|
||||
const target = await targetResponse.json();
|
||||
expect(targetResponse.status, JSON.stringify(target)).toBe(201);
|
||||
await lifecycle.process(target.id);
|
||||
await vi.waitFor(async () => expect((await agentService(server.db).getById(target.id))?.status).toBe("idle"));
|
||||
let sends = 0;
|
||||
const workspaceId = `T${f.companyId.replaceAll("-", "").toUpperCase()}`;
|
||||
const scopes = [...SLACK_CHAT_BOT_SCOPES, ...SLACK_BOT_TOOL_SCOPES];
|
||||
provider = async (url, init) => {
|
||||
if (url.endsWith("auth.test")) return Response.json({ ok: true, team_id: workspaceId, team: "Delegated fixture", user_id: `U${target.id.replaceAll("-", "").toUpperCase()}`, user: "fixture-bot" }, { headers: { "x-oauth-scopes": scopes.join(",") } });
|
||||
if (url.includes("conversations.list")) return Response.json({ ok: true, channels: [], response_metadata: { next_cursor: "" } });
|
||||
if (url.endsWith("users.info")) return Response.json({ ok: true, user: { id: new URLSearchParams(String(init?.body)).get("user"), team_id: workspaceId, name: "Fixture user", is_bot: false, deleted: false } });
|
||||
if (url.endsWith("chat.postMessage")) { sends++; return Response.json({ ok: true, channel: "DTEST", ts: "1.000001" }); }
|
||||
if (url.endsWith("agents.sessions.setStatus")) return Response.json({ ok: true });
|
||||
throw new Error(`Unexpected Slack fixture operation: ${new URL(url).pathname}`);
|
||||
};
|
||||
try {
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider: "slack", assignedAgentId: target.id, slackSetupMethod: "manual" });
|
||||
expect(created, JSON.stringify(created)).toMatchObject({ status: 201 });
|
||||
const configured = await fetch(`${server.apiUrl}/api/chat-endpoints/${created.body.id}/setup`, {
|
||||
method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "configure", credentials: { botToken: `xoxb-${target.id}`, signingSecret: "fixture-signing-secret" } }),
|
||||
});
|
||||
expect({ status: configured.status, body: await configured.json() }).toMatchObject({ status: 200 });
|
||||
await server.db.update(chatEndpoints).set({ status: "active", allowDirectMessages: true }).where(eq(chatEndpoints.id, created.body.id));
|
||||
await server.db.update(toolConnections).set({ status: "active", enabled: true, healthStatus: "healthy" }).where(eq(toolConnections.id, created.body.connectionId));
|
||||
if (recipient === "linked") {
|
||||
const [principal] = await server.db.insert(chatExternalPrincipals).values({ companyId: f.companyId, provider: "slack", providerAccountId: workspaceId, externalId: "UHUMAN", isBot: false }).returning();
|
||||
await server.db.insert(chatIdentityLinks).values({ companyId: f.companyId, endpointId: created.body.id, principalId: principal.id, paperclipUserId: f.userId, status: "linked", confirmedAt: new Date() });
|
||||
}
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Slack fixture access", policyType: "allow", selectors: { connectionId: created.body.connectionId }, priority: 2 });
|
||||
const rate = mode.endsWith("rate");
|
||||
await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: mode, policyType: rate ? "rate_limit" : mode === "caller-ask" ? "require_approval" : "block",
|
||||
selectors: { connectionId: created.body.connectionId, ...(mode === "shared-rate" ? {} : { agentId: mode.startsWith("caller") ? f.agentId : target.id }) }, priority: 0,
|
||||
...(rate ? { config: { limit: 1, windowSeconds: 60, keyBy: mode === "shared-rate" ? ["company", "tool"] : ["agent", "tool"] } } : {}),
|
||||
});
|
||||
const path = `/chat-endpoints/${created.body.id}/slack/test-message`;
|
||||
if (rate) {
|
||||
// Keep both calls in one rate window even when CI crosses a minute boundary.
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
// Shared buckets admit one actual send, while each principal's own
|
||||
// limit also prevents the next send. Neither may consume twice.
|
||||
expect(await f.request("POST", path, { requestId: randomUUID(), slackUserId: "UHUMAN" }, f.jwt), mode)
|
||||
.toMatchObject({ status: 200, body: { status: recipient === "linked" ? "sent" : "connection_pending" } });
|
||||
expect(sends, mode).toBe(1);
|
||||
}
|
||||
for (const token of [f.key.token, f.jwt]) {
|
||||
const denied = await f.request("POST", path, { requestId: randomUUID(), slackUserId: "UHUMAN" }, token);
|
||||
expect(denied, `${mode}: ${JSON.stringify(denied)}`).toMatchObject({ status: 403, body: { details: { reasonCode: rate ? "rate_limited" : mode === "caller-ask" ? "requires_approval_policy" : "deny_policy_block" } } });
|
||||
if (mode === "caller-ask") expect(denied.body.details.requiredUserAction).toMatchObject({ kind: "approve" });
|
||||
}
|
||||
expect(sends, mode).toBe(rate ? 1 : 0);
|
||||
const audit = await server.db.select().from(toolAccessAuditEvents).where(eq(toolAccessAuditEvents.companyId, f.companyId));
|
||||
expect(audit.some(event => event.details.agentId === f.agentId && event.actorId === f.agentId), mode).toBe(true);
|
||||
} finally { vi.useRealTimers(); provider = null; }
|
||||
}
|
||||
}, 90_000);
|
||||
|
||||
it("imports a GitHub App and discovers repositories against provider fixtures", async () => {
|
||||
const f = await fixture();
|
||||
const permissions = { contents: "read", issues: "write", metadata: "read", pull_requests: "write" };
|
||||
const appId = 100000 + Number.parseInt(f.agentId.slice(0, 6), 16);
|
||||
const privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
||||
provider = async (url, init) => {
|
||||
const path = new URL(url).pathname;
|
||||
if (path === "/login/oauth/access_token") return Response.json({ access_token: "fixture-personal-token" });
|
||||
if (path === "/user") return Response.json({ id: 1357, login: "fixture-person" });
|
||||
if (path === "/user/installations") return Response.json({ installations: [{ id: 2468, app_id: appId }] });
|
||||
if (path === "/app") return Response.json({ id: appId, slug: `fixture-${f.agentId.slice(0, 8)}`, name: "Fixture App", owner: { login: "fixture" }, permissions,
|
||||
events: ["pull_request", "github_app_authorization", "installation", "installation_repositories", "issue_comment", "pull_request_review_comment"] });
|
||||
if (path === "/app/hook/config") return Response.json(init?.body ? JSON.parse(String(init.body)) : { url: "https://paperclip.fixture.invalid", content_type: "json", insecure_ssl: "0" });
|
||||
if (path === "/app/installations") return Response.json([{ id: 2468, account: { id: 1357, login: "fixture", type: "Organization" }, permissions, suspended_at: null }]);
|
||||
if (path === "/app/installations/2468") return Response.json({ permissions, suspended_at: null });
|
||||
if (path === "/app/installations/2468/access_tokens") return Response.json({ token: "fixture-installation-token" }, { status: 201 });
|
||||
if (path === "/installation/repositories") return Response.json({ repositories: [{ id: 42, name: "repo", full_name: "fixture/repo", private: true, owner: { login: "fixture" }, html_url: "https://github.com/fixture/repo" }] });
|
||||
throw new Error(`Unexpected GitHub fixture operation: ${path}`);
|
||||
};
|
||||
try {
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider: "github", assignedAgentId: f.agentId });
|
||||
expect(await f.request("POST", `/chat-endpoints/${created.body.id}/github/registration`, { name: `fixture-${f.agentId.slice(0, 8)}` })).toMatchObject({ status: 200 });
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
const humanRequest = (path: string, method = "GET", body?: unknown, session = cookie) => fetch(server.apiUrl + path, {
|
||||
method, redirect: "manual", headers: { cookie: session, "Content-Type": "application/json", origin: server.apiUrl },
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
const appCredentials = { appId: String(appId), privateKey, webhookSecret: "fixture-webhook-secret", clientId: "fixture-client", clientSecret: "fixture-secret" };
|
||||
expect(await f.request("POST", `/chat-endpoints/${created.body.id}/github/app`, appCredentials)).toMatchObject({ status: 200, body: { status: "needs_user_action" } });
|
||||
const importHandoff = await f.request("POST", `/chat-endpoints/${created.body.id}/github/app`, {}, f.jwt);
|
||||
expect(importHandoff).toMatchObject({ status: 200, body: { requiredUserAction: { kind: "enter_credentials", userId: f.userId } } });
|
||||
expect.soft(importHandoff.body.requiredUserAction.setupPath).toContain("stage=credentials");
|
||||
expect.soft(importHandoff.body.requiredUserAction.setupPath).not.toContain("reconnect=1");
|
||||
const privateKeyHandoff = await f.request("POST", `/chat-endpoints/${created.body.id}/setup`, { action: "configure", credentials: { privateKey } }, f.jwt);
|
||||
expect.soft(privateKeyHandoff, JSON.stringify(privateKeyHandoff)).toMatchObject({ status: 200, body: { requiredUserAction: { kind: "enter_credentials" } } });
|
||||
if (privateKeyHandoff.status === 200) {
|
||||
const entryLink = new URL(privateKeyHandoff.body.requiredUserAction.setupPath, server.apiUrl);
|
||||
expect.soft(entryLink.searchParams.get("credentialFields")).toBe("privateKey");
|
||||
expect.soft(entryLink.searchParams.get("credentialMode")).toBe("all");
|
||||
expect(privateKeyHandoff.body.interactionId).not.toBe(importHandoff.body.interactionId);
|
||||
const retry = await f.request("POST", `/chat-endpoints/${created.body.id}/setup`, { action: "configure", credentials: { privateKey } }, f.jwt);
|
||||
expect(retry.body.interactionId).toBe(privateKeyHandoff.body.interactionId);
|
||||
}
|
||||
expect((await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId)))[0].credentialSecretRefs).toEqual([]);
|
||||
const imported = await humanRequest(`/api/chat-endpoints/${created.body.id}/github/app`, "POST", appCredentials);
|
||||
expect(imported.status).toBe(200);
|
||||
expect(JSON.stringify(await imported.json())).not.toContain("PRIVATE KEY");
|
||||
const refreshed = await f.request("POST", `/chat-endpoints/${created.body.id}/github/repositories/refresh`, {});
|
||||
expect(refreshed, JSON.stringify(refreshed)).toMatchObject({ status: 200 });
|
||||
expect(JSON.stringify(refreshed.body)).toContain("fixture/repo");
|
||||
expect(await f.request("POST", `/chat-endpoints/${created.body.id}/github/verify`, {})).toMatchObject({ status: 200 });
|
||||
await server.db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, created.body.id));
|
||||
await server.db.update(toolConnections).set({ status: "active", enabled: true, healthStatus: "healthy" }).where(eq(toolConnections.id, created.body.connectionId));
|
||||
const identityHandoff = await f.request("POST", `/chat-endpoints/${created.body.id}/github/identity/start`, {}, f.jwt);
|
||||
expect(identityHandoff).toMatchObject({ status: 200, body: { requiredUserAction: { kind: "confirm_identity" } } });
|
||||
const [identityIntent] = await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, identityHandoff.body.interactionId));
|
||||
const [identityTask] = await server.db.select().from(issues).where(eq(issues.id, f.issueId));
|
||||
expect(await findSatisfiedToolConnection(server.db, identityTask, identityIntent)).toBeNull();
|
||||
const start = await humanRequest(`/api/chat-endpoints/${created.body.id}/github/identity/start`, "POST", {});
|
||||
const started = await start.json();
|
||||
expect(started, JSON.stringify(started)).toHaveProperty("authorizationUrl");
|
||||
const state = new URL(started.authorizationUrl).searchParams.get("state")!;
|
||||
const callback = `/api/chat-github/identity/callback?state=${encodeURIComponent(state)}&code=fixture-code`;
|
||||
const other = await fixture();
|
||||
const otherCookie = await server.humanSession(other.userId);
|
||||
expect((await humanRequest(callback, "GET", undefined, otherCookie)).status).toBe(403);
|
||||
expect((await humanRequest(callback)).status).toBe(303);
|
||||
expect((await humanRequest(callback)).status).toBe(403);
|
||||
expect(await findSatisfiedToolConnection(server.db, identityTask, identityIntent)).toBeNull();
|
||||
const confirmed = await humanRequest(`/api/chat-endpoints/${created.body.id}/github/identity/confirm`, "POST", { githubUserId: "1357" });
|
||||
expect(confirmed.status, JSON.stringify(await confirmed.json())).toBe(200);
|
||||
const [endpoint] = await server.db.select().from(chatEndpoints).where(eq(chatEndpoints.id, created.body.id));
|
||||
await server.db.update(chatEndpoints).set({ status: "active", setup: { ...endpoint.setup, webhookVerifiedAt: new Date().toISOString() } }).where(eq(chatEndpoints.id, endpoint.id));
|
||||
await server.db.update(toolConnections).set({ status: "active", enabled: true, healthStatus: "healthy" }).where(eq(toolConnections.id, created.body.connectionId));
|
||||
expect((await findSatisfiedToolConnection(server.db, identityTask, identityIntent))?.id).toBe(created.body.connectionId);
|
||||
const credentialHandoff = await f.request("POST", `/chat-endpoints/${created.body.id}/setup`, { action: "reconnect", credentials: { webhookSecret: "agent-chosen-key" } }, f.jwt);
|
||||
expect(credentialHandoff).toMatchObject({ status: 200, body: { requiredUserAction: { kind: "enter_credentials" } } });
|
||||
const entryLink = new URL(credentialHandoff.body.requiredUserAction.setupPath, server.apiUrl);
|
||||
expect(entryLink.searchParams.get("reconnect")).toBe("1");
|
||||
expect.soft(entryLink.searchParams.get("credentialFields")).toBe("webhookSecret");
|
||||
expect.soft(entryLink.searchParams.get("credentialMode")).toBe("all");
|
||||
const entryOptionsResponse = await humanRequest(`/api/connection-intents/${credentialHandoff.body.interactionId}/setup-options`);
|
||||
const entryOptions = await entryOptionsResponse.json();
|
||||
expect.soft(entryOptions.chatSetup.path).toBe(credentialHandoff.body.requiredUserAction.setupPath);
|
||||
const [entryIntent] = await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, credentialHandoff.body.interactionId));
|
||||
const [entryTask] = await server.db.select().from(issues).where(eq(issues.id, f.issueId));
|
||||
expect(await findSatisfiedToolConnection(server.db, entryTask, entryIntent)).toBeNull();
|
||||
const repairedResponse = await humanRequest(`/api/chat-endpoints/${created.body.id}/setup`, "POST", { action: "reconnect", credentials: { webhookSecret: "human-replacement-webhook" } });
|
||||
expect(repairedResponse.status).toBe(200);
|
||||
const [repairedConnection] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
for (const [field, value] of [["privateKey", privateKey], ["clientSecret", "fixture-secret"], ["webhookSecret", "human-replacement-webhook"]]) {
|
||||
const ref = repairedConnection.credentialSecretRefs.find(ref => ref.configPath === `credentials.${field}`)!;
|
||||
expect(await secretService(server.db).resolveSecretValue(f.companyId, ref.secretId, "latest", {
|
||||
accessContext: { consumerType: "system", consumerId: "integration-fixture", actorType: "system" },
|
||||
})).toBe(value);
|
||||
}
|
||||
expect(await findSatisfiedToolConnection(server.db, entryTask, entryIntent)).toBeNull();
|
||||
const [repairedEndpoint] = await server.db.select().from(chatEndpoints).where(eq(chatEndpoints.id, created.body.id));
|
||||
expect(repairedEndpoint.setup.webhookVerifiedAt).toBeNull();
|
||||
await server.db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, created.body.id));
|
||||
await server.db.update(toolConnections).set({ status: "active", enabled: true, healthStatus: "healthy" }).where(eq(toolConnections.id, created.body.connectionId));
|
||||
expect(await findSatisfiedToolConnection(server.db, entryTask, entryIntent)).toBeNull();
|
||||
await server.db.update(chatEndpoints).set({ setup: { ...repairedEndpoint.setup, webhookVerifiedAt: new Date().toISOString() } }).where(eq(chatEndpoints.id, created.body.id));
|
||||
expect((await findSatisfiedToolConnection(server.db, entryTask, entryIntent))?.id).toBe(created.body.connectionId);
|
||||
const [beforeRotation] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
let rotationIntentId = "";
|
||||
for (const token of [f.key.token, f.jwt, f.jwt]) {
|
||||
const rotation = await f.request("POST", `/chat-endpoints/${created.body.id}/setup-secret`, {}, token);
|
||||
expect(rotation, JSON.stringify(rotation)).toMatchObject({ status: 200, body: { status: "needs_user_action", endpointId: created.body.id,
|
||||
requiredUserAction: { kind: "enter_credentials", userId: f.userId } } });
|
||||
expect(rotation.body).not.toHaveProperty("webhookSecret");
|
||||
expect(rotation.body.requiredUserAction.setupPath).toContain("stage=credentials&reconnect=1&rotateSecret=1");
|
||||
if (token === f.jwt) {
|
||||
if (rotationIntentId) expect(rotation.body.interactionId).toBe(rotationIntentId);
|
||||
rotationIntentId = rotation.body.interactionId;
|
||||
}
|
||||
}
|
||||
expect(rotationIntentId).not.toBe(importHandoff.body.interactionId);
|
||||
const [afterRotation] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
expect(afterRotation.credentialSecretRefs).toEqual(beforeRotation.credentialSecretRefs);
|
||||
const [rotationIntent] = await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, rotationIntentId));
|
||||
const [task] = await server.db.select().from(issues).where(eq(issues.id, f.issueId));
|
||||
const setupOptions = await humanRequest(`/api/connection-intents/${rotationIntentId}/setup-options`);
|
||||
expect(setupOptions.status).toBe(200);
|
||||
expect((await setupOptions.json()).chatSetup.path).toContain("stage=credentials&reconnect=1&rotateSecret=1");
|
||||
expect(await findSatisfiedToolConnection(server.db, task, rotationIntent)).toBeNull();
|
||||
await satisfiedConnectionIntentService(server.db).sweepPending();
|
||||
expect((await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, rotationIntentId)))[0].status).toBe("pending");
|
||||
const humanRotation = await humanRequest(`/api/chat-endpoints/${created.body.id}/setup-secret`, "POST", {});
|
||||
expect(humanRotation.status).toBe(201);
|
||||
const generatedRotation = await humanRotation.json();
|
||||
expect(generatedRotation).toMatchObject({ webhookSecret: expect.stringMatching(/^[a-f0-9]{64}$/), credentialRotationId: expect.any(String) });
|
||||
const [humanRotated] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.connectionId));
|
||||
expect(humanRotated.credentialSecretRefs).not.toEqual(beforeRotation.credentialSecretRefs);
|
||||
const rotationState = await f.request("GET", `/chat-endpoints/${endpoint.id}`);
|
||||
expect(rotationState.body.setup).toMatchObject({ credentialRotationId: expect.any(String), webhookVerifiedAt: null });
|
||||
expect(rotationState.body.setup.credentialRotationId).toBe(generatedRotation.credentialRotationId);
|
||||
const nextRotation = await f.request("POST", `/chat-endpoints/${endpoint.id}/setup-secret`, {});
|
||||
expect(nextRotation.body.requiredUserAction.setupPath).toContain(`afterRotationId=${rotationState.body.setup.credentialRotationId}`);
|
||||
expect(await findSatisfiedToolConnection(server.db, task, rotationIntent)).toBeNull();
|
||||
// Provider-fixture states separate restored health from new webhook verification.
|
||||
const [rotatedEndpoint] = await server.db.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id));
|
||||
await server.db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, endpoint.id));
|
||||
await server.db.update(toolConnections).set({ status: "active", enabled: true, healthStatus: "healthy" }).where(eq(toolConnections.id, created.body.connectionId));
|
||||
expect(await findSatisfiedToolConnection(server.db, task, rotationIntent)).toBeNull();
|
||||
await server.db.update(chatEndpoints).set({ setup: { ...rotatedEndpoint.setup, webhookVerifiedAt: new Date().toISOString() } }).where(eq(chatEndpoints.id, endpoint.id));
|
||||
expect((await findSatisfiedToolConnection(server.db, task, rotationIntent))?.id).toBe(created.body.connectionId);
|
||||
} finally { provider = null; }
|
||||
});
|
||||
|
||||
it("creates an email account through the API without exposing its write-only credential and reuses retries", async () => {
|
||||
const f = await fixture();
|
||||
provider = async url => {
|
||||
if (new URL(url).pathname === "/v0/auth/me") return Response.json({ scope_type: "organization", organization_id: "fixture-org" });
|
||||
throw new Error(`Unexpected AgentMail fixture operation: ${new URL(url).pathname}`);
|
||||
};
|
||||
try {
|
||||
const body = { apiKey: "fixture-agentmail-secret", grantKind: "user", agentIds: [f.agentId], allAgents: false, idempotencyKey: randomUUID() };
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/email/connections`, body);
|
||||
expect(created, JSON.stringify(created)).toMatchObject({ status: 201 });
|
||||
expect(JSON.stringify(created.body)).not.toContain(body.apiKey);
|
||||
expect(await f.request("POST", `/companies/${f.companyId}/email/connections`, body)).toMatchObject({ status: 201, body: { id: created.body.id } });
|
||||
expect((await f.request("GET", `/companies/${f.companyId}/email/connections`)).body).toEqual(expect.arrayContaining([expect.objectContaining({ id: created.body.id })]));
|
||||
const [saved] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.id));
|
||||
expect(saved.createdByUserId).toBe(f.userId);
|
||||
const other = await f.request("POST", `/companies/${f.companyId}/email/connections`, { ...body, apiKey: "other-agentmail-secret", grantKind: "organization", idempotencyKey: randomUUID() });
|
||||
expect(other).toMatchObject({ status: 201 });
|
||||
await server.db.update(principalPermissionGrants).set({ scope: { connectionIds: [created.body.id] } }).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
|
||||
for (const token of [f.key.token, f.jwt]) {
|
||||
const listed = await f.request("GET", `/companies/${f.companyId}/email/connections?connectionId=${created.body.id}`, undefined, token);
|
||||
expect(listed, JSON.stringify(listed)).toMatchObject({ status: 200 });
|
||||
expect(listed.body.map((account: { id: string }) => account.id)).toEqual([created.body.id]);
|
||||
}
|
||||
} finally { provider = null; }
|
||||
});
|
||||
|
||||
it("shares tool-activity authorization by task and reuses run identity within one page", async () => {
|
||||
const f = await fixture();
|
||||
const connection = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Activity page", transport: "mcp_remote", authKind: "none", transportConfig: { url: "https://1.1.1.1/mcp" } });
|
||||
expect(connection).toMatchObject({ status: 201 });
|
||||
const [hidden] = await server.db.insert(issues).values({ companyId: f.companyId, title: "Private activity task", visibility: "private", status: "in_progress", responsibleUserId: randomUUID() }).returning();
|
||||
await server.db.insert(toolCallEvents).values(Array.from({ length: 100 }, (_, index) => ({ companyId: f.companyId, connectionId: connection.body.id,
|
||||
eventType: "policy_decision" as const, actorType: "agent", actorId: f.agentId, issueId: index % 2 ? f.issueId : hidden.id, toolName: index % 2 ? "visible" : "private_activity" })));
|
||||
const original = connectionManagementModule.connectionManagementService;
|
||||
const checked: string[] = [];
|
||||
const authorization = vi.spyOn(connectionManagementModule, "connectionManagementService").mockImplementation((db) => {
|
||||
const service = original(db);
|
||||
return { ...service, capability: async (...args: Parameters<typeof service.capability>) => {
|
||||
if (args[1] === "connections:audit") checked.push(args[2].issueId ?? "unbound");
|
||||
return service.capability(...args);
|
||||
} };
|
||||
});
|
||||
const capture = vi.spyOn(runIdentity, "captureRunIdentity");
|
||||
try {
|
||||
const path = `/tool-connections/${connection.body.id}/activity?limit=100`;
|
||||
const result = await f.request("GET", path, undefined, f.jwt);
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ status: 200 });
|
||||
expect(result.body.events).toHaveLength(50);
|
||||
expect(JSON.stringify(result.body)).not.toContain("private_activity");
|
||||
expect(checked, JSON.stringify({ checks: checked.length, captures: capture.mock.calls.length })).toHaveLength(2);
|
||||
expect(capture.mock.calls.length).toBeGreaterThan(0);
|
||||
expect(capture.mock.calls.length).toBeLessThanOrEqual(2);
|
||||
await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:view_audit")));
|
||||
expect(await f.request("GET", path, undefined, f.jwt)).toMatchObject({ status: 403 });
|
||||
} finally { authorization.mockRestore(); capture.mockRestore(); }
|
||||
});
|
||||
|
||||
it("bounds activity authorization to the requested page rather than endpoint history", async () => {
|
||||
const f = await fixture();
|
||||
const endpoint = await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider: "github", assignedAgentId: f.agentId });
|
||||
expect(endpoint).toMatchObject({ status: 201 });
|
||||
const conversations = await server.db.insert(chatConversations).values(Array.from({ length: 200 }, (_, index) => ({
|
||||
companyId: f.companyId, endpointId: endpoint.body.id, issueId: f.issueId,
|
||||
externalConversationId: `history-${index}`, externalLabel: `History ${index}`,
|
||||
}))).returning();
|
||||
const [delivery] = await server.db.insert(chatDeliveries).values({ companyId: f.companyId, endpointId: endpoint.body.id,
|
||||
conversationId: conversations[0].id, providerEventId: randomUUID(), deduplicationKey: randomUUID(), eventKind: "mention", state: "processed", normalizedEvent: {} }).returning();
|
||||
const original = connectionManagementModule.connectionManagementService;
|
||||
const checked: string[] = [];
|
||||
const authorization = vi.spyOn(connectionManagementModule, "connectionManagementService").mockImplementation((db) => {
|
||||
const service = original(db);
|
||||
return { ...service, capability: async (...args: Parameters<typeof service.capability>) => {
|
||||
if (args[1] === "connections:audit") checked.push(args[2].issueId ?? "unbound");
|
||||
return service.capability(...args);
|
||||
} };
|
||||
});
|
||||
try {
|
||||
const result = await f.request("GET", `/chat-endpoints/${endpoint.body.id}/activity?limit=1`, undefined, f.jwt);
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ status: 200, body: { items: [expect.objectContaining({ id: delivery.id })] } });
|
||||
expect(checked).toEqual([f.issueId]);
|
||||
} finally { authorization.mockRestore(); }
|
||||
});
|
||||
|
||||
it("continues activity pagination through private-only windows", async () => {
|
||||
const f = await fixture();
|
||||
const endpoint = await f.request("POST", `/companies/${f.companyId}/chat-endpoints`, { provider: "github", assignedAgentId: f.agentId });
|
||||
const [hidden] = await server.db.insert(issues).values({ companyId: f.companyId, title: "Private history", visibility: "private", status: "in_progress", responsibleUserId: randomUUID() }).returning();
|
||||
const conversations = await server.db.insert(chatConversations).values([f.issueId, hidden.id].map(issueId => ({ companyId: f.companyId, endpointId: endpoint.body.id, issueId,
|
||||
externalConversationId: randomUUID(), externalLabel: "History" }))).returning();
|
||||
const rows = Array.from({ length: 30 }, (_, index) => ({ id: `${f.agentId.slice(0, 24)}${index.toString(16).padStart(12, "0")}`,
|
||||
companyId: f.companyId, endpointId: endpoint.body.id, conversationId: conversations[index < 3 ? 0 : 1].id,
|
||||
providerEventId: randomUUID(), deduplicationKey: randomUUID(), eventKind: "message" as const, state: "processed" as const, redactedError: index < 3 ? null : "private_history", normalizedEvent: {}, createdAt: new Date("2026-10-25T12:00:00.000Z") }));
|
||||
await server.db.insert(chatDeliveries).values(rows);
|
||||
const path = `/chat-endpoints/${endpoint.body.id}/activity?limit=25`;
|
||||
const first = await f.request("GET", path, undefined, f.jwt);
|
||||
expect(first).toMatchObject({ status: 200, body: { items: [], nextCursor: expect.any(String) } });
|
||||
expect(JSON.stringify(first.body)).not.toContain("private_history");
|
||||
const second = await f.request("GET", `${path}&cursor=${encodeURIComponent(first.body.nextCursor)}`, undefined, f.jwt);
|
||||
expect(second).toMatchObject({ status: 200, body: { items: rows.slice(0, 3).reverse().map(row => expect.objectContaining({ id: row.id })), nextCursor: null } });
|
||||
expect(JSON.stringify(second.body)).not.toContain("private_history");
|
||||
});
|
||||
|
||||
it("saves delegated Arcade discovery for the responsible user and shares its inventory with that user", async () => {
|
||||
const f = await fixture();
|
||||
const transport = vi.spyOn(remoteHttpFetch, "guardedRemoteHttpFetch").mockImplementation(async (url, init) => provider!(String(url), init));
|
||||
provider = async (url, init) => {
|
||||
const path = new URL(url).pathname;
|
||||
const rpc = init?.body ? JSON.parse(String(init.body)) : null;
|
||||
if (rpc?.method === "initialize") return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "fixture", version: "1" } } });
|
||||
if (rpc?.method === "notifications/initialized") return new Response(null, { status: 202 });
|
||||
if (rpc?.method === "tools/list") return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { tools: [{ name: "Notion.ListPages", inputSchema: { type: "object" } }] } });
|
||||
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer fixture-arcade-discovery");
|
||||
if (path === "/v1/tools") return Response.json({ items: [{ qualified_name: "Notion.ListPages", toolkit: { name: "Notion" }, requirements: { met: true, authorization: { provider_id: "notion", token_status: "completed" } } }] });
|
||||
if (path === "/v1/admin/user_connections") return Response.json({ items: [{ id: "arcade-work", provider_id: "notion", user_id: "arcade-user", connection_status: "active" }] });
|
||||
throw new Error(`Unexpected Arcade fixture operation: ${path}`);
|
||||
};
|
||||
try {
|
||||
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Arcade fixture", transport: "mcp_remote", authKind: "none", credentialPolicy: "shared", status: "active", enabled: true, config: { sourceTemplateKey: "arcade", url: "https://api.arcade.dev/mcp/test" } });
|
||||
expect(created, JSON.stringify(created)).toMatchObject({ status: 201 });
|
||||
const configured = await f.request("PUT", `/tool-connections/${created.body.id}/aggregator/discovery`, { apiKey: "fixture-arcade-discovery", userId: "arcade-user" }, f.jwt);
|
||||
expect(configured, JSON.stringify(configured)).toMatchObject({ status: 200 });
|
||||
const [saved] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.id));
|
||||
const discovery = saved.config.aggregatorDiscovery as Record<string, { secretId: string }>;
|
||||
expect(discovery[f.agentId]).toBeUndefined();
|
||||
expect(discovery[f.userId]).toMatchObject({ userId: "arcade-user", secretId: expect.any(String) });
|
||||
const [secret] = await server.db.select().from(companySecrets).where(eq(companySecrets.id, discovery[f.userId].secretId));
|
||||
expect(secret.ownerUserId).toBe(f.userId);
|
||||
const events = await server.db.select().from(activityLog).where(eq(activityLog.entityId, saved.id));
|
||||
expect(events).toEqual(expect.arrayContaining([expect.objectContaining({ action: "tool_connection.account_sync_configured", actorType: "agent", actorId: f.agentId, responsibleUserId: f.userId })]));
|
||||
const cookie = await server.humanSession(f.userId);
|
||||
await vi.waitFor(async () => {
|
||||
const response = await fetch(`${server.apiUrl}/api/tool-connections/${saved.id}/aggregator/apps`, { headers: { cookie } });
|
||||
const result = await response.json();
|
||||
expect(result.discovery).toMatchObject({ availability: "available" });
|
||||
expect(result.apps).toEqual(expect.arrayContaining([expect.objectContaining({ provider: "arcade", appSlug: "notion" })]));
|
||||
}, { timeout: 10_000 });
|
||||
} finally { transport.mockRestore(); provider = null; }
|
||||
});
|
||||
|
||||
it("encrypts native local-login checks and replays without exposing device codes in receipts or assets", async () => {
|
||||
const f = await fixture();
|
||||
const priorHome = process.env.PAPERCLIP_HOME;
|
||||
vi.stubEnv("PAPERCLIP_HOME", join(server.root, "local-login-receipt"));
|
||||
const authorizationUrl = "https://fixture.invalid/device?private_handoff=disposable-login";
|
||||
const code = "DISPOSABLE-DEVICE-CODE";
|
||||
const browser = vi.spyOn(localBrowserLogin, "startLocalBrowserLogin").mockReturnValue({ authorizationUrl, code, abort: vi.fn() });
|
||||
const intent = { provider: "openai", method: "subscription", ownership: "personal", name: "Local receipt fixture", agentIds: [], allAgents: false };
|
||||
let sessionId: string | undefined;
|
||||
try {
|
||||
const started = await f.request("POST", `/companies/${f.companyId}/ai-connections/local/attempts`, intent, f.jwt);
|
||||
expect(started, JSON.stringify(started)).toMatchObject({ status: 201, body: { sessionId: expect.any(String) } });
|
||||
sessionId = started.body.sessionId;
|
||||
const call = { tool: "call_api", callId: "local-login-private-check", arguments: {
|
||||
operationId: "POST /api/companies/{companyId}/ai-connections/local/check", body: { ...intent, localSessionId: sessionId },
|
||||
} };
|
||||
const result = await f.authority.execute(call);
|
||||
expect(result).toMatchObject({ ok: true, status: 200, data: { status: "sign_in_required", authorizationUrl, code } });
|
||||
expect(result).not.toHaveProperty("artifact");
|
||||
expect(await f.authority.execute(call)).toEqual(result);
|
||||
const [run] = await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
||||
const receipts = (run.resultJson as { apiToolReceipts: Record<string, { operationId: string }> }).apiToolReceipts;
|
||||
expect(Object.values(receipts).find(receipt => receipt.operationId === call.arguments.operationId)).toHaveProperty("encryptedResult");
|
||||
for (const secret of [authorizationUrl, code]) {
|
||||
expect(JSON.stringify(run.resultJson)).not.toContain(secret);
|
||||
expect(JSON.stringify(redactRunnerApiPayloads(result))).not.toContain(secret);
|
||||
}
|
||||
expect((await f.snapshot()).assets.filter(asset => asset.objectKey.includes("/runner-api/"))).toEqual([]);
|
||||
} finally {
|
||||
if (sessionId) await f.request("DELETE", `/companies/${f.companyId}/ai-connections/local/attempts/${sessionId}`, undefined, f.jwt);
|
||||
browser.mockRestore();
|
||||
if (priorHome === undefined) delete process.env.PAPERCLIP_HOME;
|
||||
else process.env.PAPERCLIP_HOME = priorHome;
|
||||
}
|
||||
});
|
||||
|
||||
// Tokens issued by agents before client-token minting became person-only
|
||||
// remain valid until revoked, so runtime enforcement still covers them.
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,156 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, expect, vi } from "vitest";
|
||||
import { companies, heartbeatRuns, issues } from "@paperclipai/db";
|
||||
import { createLocalAgentJwt } from "../../agent-auth-jwt.js";
|
||||
import { startRunnerApiTestServer } from "./runner-api-server.js";
|
||||
import { configureAgentLifecycle } from "../../services/agent-lifecycle.js";
|
||||
import { agentService } from "../../services/agents.js";
|
||||
import { accessService } from "../../services/access.js";
|
||||
import { instanceSettingsService } from "../../services/instance-settings.js";
|
||||
import { PaperclipRunnerToolAuthority } from "../../services/native-runtime/paperclip-runner-tool-authority.js";
|
||||
|
||||
export type ConnectionManagementProviderHandler = (
|
||||
url: string,
|
||||
init?: RequestInit,
|
||||
) => Promise<Response>;
|
||||
|
||||
export type ConnectionManagementServer = Awaited<
|
||||
ReturnType<typeof startRunnerApiTestServer>
|
||||
>;
|
||||
|
||||
export type ConnectionManagementLifecycle = ReturnType<
|
||||
typeof configureAgentLifecycle
|
||||
>;
|
||||
|
||||
export function createConnectionManagementHarness(
|
||||
getProvider: () => ConnectionManagementProviderHandler | null,
|
||||
) {
|
||||
let server!: ConnectionManagementServer;
|
||||
let lifecycle!: ConnectionManagementLifecycle;
|
||||
let providerFetch: ReturnType<typeof vi.spyOn> | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", randomUUID());
|
||||
vi.stubEnv("PAPERCLIP_RESPONSIBLE_USER_AUTHZ_MODE", "shadow");
|
||||
vi.stubEnv("PAPERCLIP_AUTH_RATE_LIMIT_ENABLED", "false");
|
||||
const realFetch = globalThis.fetch;
|
||||
providerFetch = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
|
||||
const url = String(input);
|
||||
if (new URL(url).hostname === "127.0.0.1") return realFetch(input, init);
|
||||
const provider = getProvider();
|
||||
if (provider) return provider(url, init);
|
||||
throw new Error("Unexpected external request in provider fixture");
|
||||
});
|
||||
server = await startRunnerApiTestServer({
|
||||
authPublicBaseUrl: "https://paperclip.fixture.invalid",
|
||||
humanSessions: true,
|
||||
databaseUrl: process.env.PAPERCLIP_CONNECTION_MANAGEMENT_TEST_DATABASE_URL,
|
||||
});
|
||||
lifecycle = configureAgentLifecycle(server.db, {
|
||||
requiredPluginIds: async () => [],
|
||||
runPlugin: async () => "complete",
|
||||
runHost: async () => "complete",
|
||||
});
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(server.root, "master.key"));
|
||||
await instanceSettingsService(server.db).updateExperimental({
|
||||
enableChatConnectors: true,
|
||||
enableGitHubReviewBots: true,
|
||||
enableGoogleWorkspaceConnector: true,
|
||||
});
|
||||
}, 90_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await lifecycle?.stop();
|
||||
await server?.close();
|
||||
providerFetch?.mockRestore();
|
||||
vi.unstubAllEnvs();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
const base = await server.fixture({ connectionScenario: "fresh" });
|
||||
const userId = base.responsibleUserId!;
|
||||
const access = accessService(server.db);
|
||||
await access.ensureMembership(base.companyId, "user", userId, "operator", "active");
|
||||
await access.ensureRoleDefaultGrants(base.companyId, userId, "operator", userId);
|
||||
await server.db
|
||||
.update(companies)
|
||||
.set({ requireBoardApprovalForNewAgents: false })
|
||||
.where(eq(companies.id, base.companyId));
|
||||
const cookie = await server.humanSession(userId);
|
||||
const created = await fetch(`${server.apiUrl}/api/companies/${base.companyId}/agents`, {
|
||||
method: "POST",
|
||||
headers: { cookie, "Content-Type": "application/json", origin: server.apiUrl },
|
||||
body: JSON.stringify({
|
||||
name: "Fresh standard agent",
|
||||
role: "engineer",
|
||||
adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "codex" },
|
||||
runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: false } },
|
||||
permissions: {},
|
||||
}),
|
||||
});
|
||||
const agent = await created.json();
|
||||
expect(agent, JSON.stringify(agent)).toHaveProperty("id");
|
||||
expect(created.status).toBe(201);
|
||||
await lifecycle.process(agent.id);
|
||||
await vi.waitFor(
|
||||
async () => expect((await agentService(server.db).getById(agent.id))?.status).toBe("idle"),
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
await server.db
|
||||
.update(heartbeatRuns)
|
||||
.set({ agentId: agent.id })
|
||||
.where(eq(heartbeatRuns.id, base.runId));
|
||||
await server.db
|
||||
.update(issues)
|
||||
.set({ assigneeAgentId: agent.id, responsibleUserId: userId })
|
||||
.where(eq(issues.id, base.issueId));
|
||||
const key = await agentService(server.db).createApiKey(
|
||||
agent.id,
|
||||
"integration",
|
||||
{ kind: "standard" },
|
||||
{ responsibleUserId: userId },
|
||||
);
|
||||
const jwt = createLocalAgentJwt(agent.id, base.companyId, "paperclip_runner", base.runId, userId)!;
|
||||
const request = async (method: string, path: string, body?: unknown, token = key.token) => {
|
||||
const response = await fetch(
|
||||
server.apiUrl + (path.startsWith("/mcp/") ? "" : "/api") + path,
|
||||
{
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
},
|
||||
);
|
||||
return { status: response.status, body: await response.json().catch(() => null) };
|
||||
};
|
||||
return {
|
||||
...base,
|
||||
agentId: agent.id,
|
||||
userId,
|
||||
key,
|
||||
jwt,
|
||||
request,
|
||||
authority: new PaperclipRunnerToolAuthority(server.db, {
|
||||
companyId: base.companyId,
|
||||
agentId: agent.id,
|
||||
issueId: base.issueId,
|
||||
runId: base.runId,
|
||||
apiUrl: server.apiUrl,
|
||||
storage: server.storage,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
get server() {
|
||||
return server;
|
||||
},
|
||||
get lifecycle() {
|
||||
return lifecycle;
|
||||
},
|
||||
fixture,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll } from "vitest";
|
||||
import {
|
||||
agentWakeupRequests,
|
||||
agents,
|
||||
companies,
|
||||
companyMemberships,
|
||||
completionContracts,
|
||||
createDb,
|
||||
heartbeatRuns,
|
||||
issueComments,
|
||||
issues,
|
||||
nativeRunFinalizations,
|
||||
nativeRunResults,
|
||||
runIdentityContexts,
|
||||
} from "@paperclipai/db";
|
||||
import { runningProcesses } from "../../adapters/index.js";
|
||||
import { errorHandler } from "../../middleware/index.js";
|
||||
import { issueRoutes } from "../../routes/issues.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./embedded-postgres.js";
|
||||
|
||||
export type QueuedCommentsDb = ReturnType<typeof createDb>;
|
||||
|
||||
export function createIssueQueuedCommentsHarness(prefix = "paperclip-queued-comments-") {
|
||||
let db!: QueuedCommentsDb;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
const testProcesses = new Map<string, ChildProcess>();
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase(prefix);
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 30_000);
|
||||
|
||||
afterEach(async () => {
|
||||
for (const [id, child] of testProcesses) {
|
||||
runningProcesses.delete(id);
|
||||
child.kill();
|
||||
}
|
||||
testProcesses.clear();
|
||||
// Each case owns the entire disposable database. Clear the full company
|
||||
// graph, including attribution rows and constraints added by migrations.
|
||||
await db.execute(sql`TRUNCATE TABLE companies CASCADE`);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end();
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
function app(
|
||||
companyId: string,
|
||||
userId = "queue-owner",
|
||||
agentActor?: { agentId: string; runId: string },
|
||||
database = db,
|
||||
) {
|
||||
const testApp = express();
|
||||
testApp.use(express.json());
|
||||
testApp.use((req, _res, next) => {
|
||||
(req as any).actor = {
|
||||
type: agentActor ? "agent" : "board",
|
||||
...(agentActor ? { ...agentActor, companyId } : {}),
|
||||
source: "session",
|
||||
userId,
|
||||
companyIds: [companyId],
|
||||
memberships: [{ companyId, status: "active", membershipRole: "operator" }],
|
||||
isInstanceAdmin: false,
|
||||
};
|
||||
next();
|
||||
});
|
||||
testApp.use("/api", issueRoutes(database, {} as any, {}));
|
||||
testApp.use(errorHandler);
|
||||
return testApp;
|
||||
}
|
||||
|
||||
async function seedQueue() {
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
const wakeId = randomUUID();
|
||||
const commentIds = [randomUUID(), randomUUID()];
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Queue Test Company",
|
||||
issuePrefix: "QUE",
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await db.insert(agents).values({
|
||||
id: agentId,
|
||||
companyId,
|
||||
name: "Paperclip Runner",
|
||||
role: "engineer",
|
||||
status: "idle",
|
||||
adapterType: "paperclip_runner",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
});
|
||||
await db.insert(companyMemberships).values([
|
||||
{
|
||||
companyId,
|
||||
principalType: "user",
|
||||
principalId: "queue-owner",
|
||||
status: "active",
|
||||
membershipRole: "operator",
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
principalType: "user",
|
||||
principalId: "other-operator",
|
||||
status: "active",
|
||||
membershipRole: "operator",
|
||||
},
|
||||
]);
|
||||
await db.insert(agentWakeupRequests).values({
|
||||
id: wakeId,
|
||||
companyId,
|
||||
agentId,
|
||||
source: "issue_comment",
|
||||
reason: "Follow-up comments arrived during the active run",
|
||||
status: "deferred_issue_execution",
|
||||
requestedByActorType: "user",
|
||||
requestedByActorId: "queue-owner",
|
||||
payload: {
|
||||
issueId,
|
||||
commentId: commentIds[1],
|
||||
_paperclipWakeContext: {
|
||||
commentId: commentIds[1],
|
||||
wakeCommentId: commentIds[1],
|
||||
wakeCommentIds: commentIds,
|
||||
},
|
||||
},
|
||||
});
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId,
|
||||
invocationSource: "assignment",
|
||||
triggerDetail: "queue route test",
|
||||
status: "running",
|
||||
runtimeMode: "native",
|
||||
startedAt: new Date("2026-08-22T15:00:00.000Z"),
|
||||
contextSnapshot: { issueId },
|
||||
});
|
||||
await db.insert(issues).values({
|
||||
id: issueId,
|
||||
companyId,
|
||||
identifier: "QUE-1",
|
||||
title: "Queued steering",
|
||||
status: "in_progress",
|
||||
priority: "medium",
|
||||
assigneeAgentId: agentId,
|
||||
executionRunId: runId,
|
||||
});
|
||||
await db.insert(issueComments).values(commentIds.map((id, index) => ({
|
||||
id,
|
||||
companyId,
|
||||
issueId,
|
||||
authorType: "user" as const,
|
||||
authorUserId: "queue-owner",
|
||||
body: index === 0 ? "First queued message" : "Second queued message",
|
||||
createdAt: new Date(`2026-08-22T15:0${index + 1}:00.000Z`),
|
||||
updatedAt: new Date(`2026-08-22T15:0${index + 1}:00.000Z`),
|
||||
})));
|
||||
return { companyId, agentId, issueId, runId, wakeId, commentIds };
|
||||
}
|
||||
|
||||
async function commitNativeSuccess(f: Awaited<ReturnType<typeof seedQueue>>) {
|
||||
const contractId = randomUUID();
|
||||
const resultId = randomUUID();
|
||||
await db.insert(completionContracts).values({
|
||||
id: contractId,
|
||||
companyId: f.companyId,
|
||||
issueId: f.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({ nativeIssueId: f.issueId, completionContractId: contractId })
|
||||
.where(eq(heartbeatRuns.id, f.runId));
|
||||
await db.insert(nativeRunResults).values({
|
||||
id: resultId,
|
||||
companyId: f.companyId,
|
||||
issueId: f.issueId,
|
||||
runId: f.runId,
|
||||
completionContractId: contractId,
|
||||
serverFingerprint: resultId,
|
||||
schemaStatus: "accepted",
|
||||
canonicalSha256: resultId,
|
||||
resultJson: { terminal: { runTerminalState: "succeeded", reportedWorkDisposition: "completed" } },
|
||||
});
|
||||
await db.insert(nativeRunFinalizations).values({
|
||||
companyId: f.companyId,
|
||||
issueId: f.issueId,
|
||||
runId: f.runId,
|
||||
phase: "committed",
|
||||
resultId,
|
||||
});
|
||||
}
|
||||
|
||||
async function promoteQueue(seeded: Awaited<ReturnType<typeof seedQueue>>) {
|
||||
const queueRunId = randomUUID();
|
||||
const wake = await db
|
||||
.select({ payload: agentWakeupRequests.payload })
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId))
|
||||
.then((rows) => rows[0]);
|
||||
const wakeContext = (wake?.payload as any)?._paperclipWakeContext ?? {};
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({ status: "succeeded", finishedAt: new Date("2026-08-22T15:05:00.000Z") })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: queueRunId,
|
||||
companyId: seeded.companyId,
|
||||
agentId: seeded.agentId,
|
||||
invocationSource: "issue_comment",
|
||||
triggerDetail: "queue route promotion test",
|
||||
status: "queued",
|
||||
runtimeMode: "native",
|
||||
wakeupRequestId: seeded.wakeId,
|
||||
contextSnapshot: {
|
||||
issueId: seeded.issueId,
|
||||
wakeReason: "issue_reopened_via_comment",
|
||||
...wakeContext,
|
||||
},
|
||||
});
|
||||
await db
|
||||
.update(agentWakeupRequests)
|
||||
.set({ status: "queued", runId: queueRunId })
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db
|
||||
.update(issues)
|
||||
.set({ executionRunId: queueRunId })
|
||||
.where(eq(issues.id, seeded.issueId));
|
||||
return queueRunId;
|
||||
}
|
||||
|
||||
async function seedDispatchIdentity(seeded: Awaited<ReturnType<typeof seedQueue>>) {
|
||||
const [identity] = await db.insert(runIdentityContexts).values({
|
||||
companyId: seeded.companyId,
|
||||
runId: seeded.runId,
|
||||
revision: 1,
|
||||
cause: "dispatch",
|
||||
correlationId: "dispatch",
|
||||
status: "accepted",
|
||||
acceptedAt: new Date("2026-08-22T15:00:00.000Z"),
|
||||
}).returning();
|
||||
await db.update(heartbeatRuns)
|
||||
.set({ activeIdentityContextId: identity!.id })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
return identity!;
|
||||
}
|
||||
|
||||
return {
|
||||
get db() {
|
||||
return db;
|
||||
},
|
||||
get tempDb() {
|
||||
return tempDb;
|
||||
},
|
||||
testProcesses,
|
||||
app,
|
||||
seedQueue,
|
||||
commitNativeSuccess,
|
||||
promoteQueue,
|
||||
seedDispatchIdentity,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,890 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { runningProcesses } from "../adapters/index.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { createFullDatabaseResponseCapture, installDatabaseResponseCapture } from "./helpers/full-database-response-capture.js";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agentRuntimeState,
|
||||
agentWakeupRequests,
|
||||
agents,
|
||||
activityLog,
|
||||
companies,
|
||||
companyMemberships,
|
||||
companySkills,
|
||||
completionContracts,
|
||||
createDb,
|
||||
environmentLeases,
|
||||
heartbeatRuns,
|
||||
heartbeatRunEvents,
|
||||
issueComments,
|
||||
issueThreadInteractions,
|
||||
issueRecoveryActions,
|
||||
nativeRunFinalizations,
|
||||
nativeRunResults,
|
||||
issues,
|
||||
runIdentityContexts,
|
||||
} from "@paperclipai/db";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { issueRoutes } from "../routes/issues.js";
|
||||
import { heartbeatService } from "../services/heartbeat.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
import { hasQueuedInteractionResponse } from "../services/queued-interaction-response.js";
|
||||
import { remoteTerminationReceipt } from "../services/remote-execution-termination.js";
|
||||
import { initializeRunIdentity, reconcileSteeredIdentity } from "../services/run-identity.js";
|
||||
import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js";
|
||||
import { claimFirstTurnQueuedInput } from "../services/native-runtime/first-turn-queued-input.js";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
|
||||
const steerNativeSessionMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../services/native-runtime/native-session-executor.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/native-runtime/native-session-executor.js")>();
|
||||
steerNativeSessionMock.mockImplementation(actual.steerNativeSession);
|
||||
return { ...actual, steerNativeSession: steerNativeSessionMock };
|
||||
});
|
||||
const { NativeSessionSteeringError } = await import("../services/native-runtime/native-session-executor.js");
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
if (!embeddedPostgresSupport.supported) {
|
||||
console.warn(
|
||||
`Skipping queued-comment route tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
||||
);
|
||||
}
|
||||
|
||||
import { createIssueQueuedCommentsHarness, type QueuedCommentsDb } from "./helpers/issue-queued-comments-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("issue queued-comment dispatch routes", () => {
|
||||
const h = createIssueQueuedCommentsHarness("paperclip-queued-comments-dispatch-");
|
||||
let db!: QueuedCommentsDb;
|
||||
beforeAll(() => { db = h.db; });
|
||||
const { testProcesses, app, seedQueue, commitNativeSuccess, promoteQueue, seedDispatchIdentity } = h;
|
||||
|
||||
it.each(["discard", "cancel"] as const)("cancels the deferred wake when the final message is discarded before promotion (%s)", async (mode) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.delete(issueComments).where(eq(issueComments.id, seeded.commentIds[1]));
|
||||
await db
|
||||
.update(agentWakeupRequests)
|
||||
.set({
|
||||
payload: {
|
||||
issueId: seeded.issueId,
|
||||
commentId: seeded.commentIds[0],
|
||||
_paperclipWakeContext: {
|
||||
commentId: seeded.commentIds[0],
|
||||
wakeCommentId: seeded.commentIds[0],
|
||||
wakeCommentIds: [seeded.commentIds[0]],
|
||||
},
|
||||
},
|
||||
})
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const discarded = await request(app(seeded.companyId))
|
||||
.delete(mode === "cancel"
|
||||
? `/api/issues/${seeded.issueId}/comments/${seeded.commentIds[0]}?mode=cancel`
|
||||
: `/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision });
|
||||
expect(discarded.status, JSON.stringify(discarded.body)).toBe(200);
|
||||
const [wake, runs] = await Promise.all([
|
||||
db.select({ status: agentWakeupRequests.status })
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId))
|
||||
.then((rows) => rows[0]),
|
||||
db.select({ id: heartbeatRuns.id }).from(heartbeatRuns),
|
||||
]);
|
||||
expect(wake?.status).toBe("cancelled");
|
||||
expect(runs.map((run) => run.id)).toEqual([seeded.runId]);
|
||||
});
|
||||
|
||||
it.each([false, true])("routes comment cancellation through the queue (promoted=%s)", async (promoted) => {
|
||||
const seeded = await seedQueue();
|
||||
const queueRunId = promoted ? await promoteQueue(seeded) : null;
|
||||
const cancelled = await request(app(seeded.companyId))
|
||||
.delete(`/api/issues/${seeded.issueId}/comments/${seeded.commentIds[0]}?mode=cancel`);
|
||||
expect(cancelled.status, JSON.stringify(cancelled.body)).toBe(200);
|
||||
expect(cancelled.body.id).toBe(seeded.commentIds[0]);
|
||||
const [wake, queueRun] = await Promise.all([
|
||||
db.select({ payload: agentWakeupRequests.payload })
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId))
|
||||
.then((rows) => rows[0]),
|
||||
queueRunId ? db.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, queueRunId))
|
||||
.then((rows) => rows[0]) : null,
|
||||
]);
|
||||
expect((wake?.payload as any)?._paperclipWakeContext?.wakeCommentIds).toEqual([
|
||||
seeded.commentIds[1],
|
||||
]);
|
||||
if (promoted) expect((queueRun?.contextSnapshot as any)?.wakeCommentIds).toEqual([
|
||||
seeded.commentIds[1],
|
||||
]);
|
||||
expect(await db.select().from(issueComments).where(eq(issueComments.id, seeded.commentIds[0]))).toEqual([]);
|
||||
const remaining = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(remaining.body.entries.map((entry: any) => entry.comment.id)).toEqual([seeded.commentIds[1]]);
|
||||
});
|
||||
|
||||
it.each(["discard", "cancel"] as const)("reports an explicit conflict after queued-run dispatch has begun (%s)", async (mode) => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const queueRunId = await promoteQueue(seeded);
|
||||
await db
|
||||
.update(agentWakeupRequests)
|
||||
.set({ status: "claimed", claimedAt: new Date() })
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({ status: "running", startedAt: new Date() })
|
||||
.where(eq(heartbeatRuns.id, queueRunId));
|
||||
|
||||
const discard = await request(app(seeded.companyId))
|
||||
.delete(mode === "cancel"
|
||||
? `/api/issues/${seeded.issueId}/comments/${seeded.commentIds[0]}?mode=cancel`
|
||||
: `/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision });
|
||||
expect(discard.status).toBe(409);
|
||||
expect(discard.body.details?.code).toBe("queued_comment_already_dispatching");
|
||||
const comment = await db
|
||||
.select({ id: issueComments.id })
|
||||
.from(issueComments)
|
||||
.where(eq(issueComments.id, seeded.commentIds[0]))
|
||||
.then((rows) => rows[0]);
|
||||
expect(comment?.id).toBe(seeded.commentIds[0]);
|
||||
});
|
||||
|
||||
it.each(["discard", "cancel"] as const)("limits edit and trash to the comment owner (%s)", async (mode) => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId, "other-operator"))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(initial.status).toBe(200);
|
||||
expect(initial.body.entries[0]).toMatchObject({ canEdit: false, canDiscard: false });
|
||||
|
||||
const edit = await request(app(seeded.companyId, "other-operator"))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "not mine" });
|
||||
expect(edit.status).toBe(403);
|
||||
const discard = await request(app(seeded.companyId, "other-operator"))
|
||||
.delete(mode === "cancel"
|
||||
? `/api/issues/${seeded.issueId}/comments/${seeded.commentIds[0]}?mode=cancel`
|
||||
: `/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision });
|
||||
expect(discard.status).toBe(403);
|
||||
});
|
||||
|
||||
it.each(["running", "failed"] as const)("lets the board discard an agent message while the previous run is %s", async (status) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(issueComments).set({ authorType: "agent", authorUserId: null, authorAgentId: seeded.agentId })
|
||||
.where(eq(issueComments.id, seeded.commentIds[0]));
|
||||
if (status === "failed") {
|
||||
await db.update(heartbeatRuns).set({ status, finishedAt: new Date("2026-08-22T15:04:00Z") })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(issues).set({ executionRunId: null, status: "todo" }).where(eq(issues.id, seeded.issueId));
|
||||
}
|
||||
const initial = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(initial.status).toBe(200);
|
||||
expect(initial.body.entries[0]).toMatchObject({ canEdit: false, canDiscard: true });
|
||||
|
||||
const edit = await request(app(seeded.companyId))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "changed author text" });
|
||||
expect(edit.status).toBe(403);
|
||||
|
||||
const discarded = await request(app(seeded.companyId))
|
||||
.delete(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision });
|
||||
expect(discarded.status, JSON.stringify(discarded.body)).toBe(200);
|
||||
expect(discarded.body.entries.map((entry: { comment: { id: string } }) => entry.comment.id)).toEqual([seeded.commentIds[1]]);
|
||||
|
||||
const reloaded = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(reloaded.body.entries.map((entry: { comment: { id: string } }) => entry.comment.id)).toEqual([seeded.commentIds[1]]);
|
||||
const deleted = await db.select().from(issueComments).where(eq(issueComments.id, seeded.commentIds[0]));
|
||||
expect(deleted).toHaveLength(0);
|
||||
const wake = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId)).then(rows => rows[0]);
|
||||
expect((wake?.payload as any)._paperclipWakeContext.wakeCommentIds).toEqual([seeded.commentIds[1]]);
|
||||
const activity = await db.select().from(activityLog).where(eq(activityLog.entityId, seeded.issueId));
|
||||
expect(activity).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
actorType: "user", actorId: "queue-owner", action: "issue.queued_comment_discarded",
|
||||
})]));
|
||||
});
|
||||
|
||||
it.each(["private task", "other company"] as const)("hides an agent queue from a board user outside its %s access", async (boundary) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(issueComments).set({ authorType: "agent", authorUserId: null, authorAgentId: seeded.agentId })
|
||||
.where(eq(issueComments.id, seeded.commentIds[0]));
|
||||
const initial = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
let actorCompanyId = seeded.companyId;
|
||||
if (boundary === "private task") {
|
||||
await db.update(issues).set({ visibility: "private", privacyRootIssueId: seeded.issueId,
|
||||
createdByUserId: "queue-owner", responsibleUserId: "queue-owner" }).where(eq(issues.id, seeded.issueId));
|
||||
} else {
|
||||
actorCompanyId = randomUUID();
|
||||
await db.insert(companies).values({ id: actorCompanyId, name: "Other company", issuePrefix: "OTHER" });
|
||||
await db.insert(companyMemberships).values({ companyId: actorCompanyId, principalType: "user",
|
||||
principalId: "foreign-operator", status: "active", membershipRole: "operator" });
|
||||
}
|
||||
|
||||
const response = await request(app(actorCompanyId, boundary === "private task" ? "other-operator" : "foreign-operator"))
|
||||
.delete(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision });
|
||||
expect(response.status).toBe(404);
|
||||
expect(await db.select().from(issueComments).where(eq(issueComments.id, seeded.commentIds[0]))).toHaveLength(1);
|
||||
const wake = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId)).then(rows => rows[0]);
|
||||
expect((wake?.payload as any)._paperclipWakeContext.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, seeded.issueId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("leaves the selected row queued when no native steering session is attached", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(initial.body.steeringDisposition).toBe("temporarily_unavailable");
|
||||
|
||||
const steered = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({ queueId: seeded.wakeId, targetRunId: seeded.runId, revision: initial.body.revision });
|
||||
|
||||
expect(steered.status).toBe(409);
|
||||
expect(steered.body.details).toMatchObject({
|
||||
code: "steering_temporarily_unavailable",
|
||||
retryable: true,
|
||||
});
|
||||
const queueAfterFailure = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(queueAfterFailure.body.entries.map((entry: any) => entry.comment.id)).toEqual(seeded.commentIds);
|
||||
});
|
||||
|
||||
it("returns the persisted acknowledgement when the final steering response is retried", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await db.delete(issueComments).where(eq(issueComments.id, seeded.commentIds[1]));
|
||||
await db
|
||||
.update(agentWakeupRequests)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
finishedAt: new Date("2026-08-22T15:04:00.000Z"),
|
||||
payload: {
|
||||
issueId: seeded.issueId,
|
||||
commentId: seeded.commentIds[0],
|
||||
_paperclipWakeContext: {
|
||||
commentId: seeded.commentIds[0],
|
||||
wakeCommentId: seeded.commentIds[0],
|
||||
wakeCommentIds: [seeded.commentIds[0]],
|
||||
},
|
||||
},
|
||||
})
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({
|
||||
resultJson: {
|
||||
queuedSteeringAcknowledgements: {
|
||||
[seeded.commentIds[0]]: {
|
||||
status: "acknowledged",
|
||||
queueId: seeded.wakeId,
|
||||
turnId: "turn-acknowledged",
|
||||
acknowledgedAt: "2026-08-22T15:04:00.000Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
|
||||
const retried = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({
|
||||
queueId: seeded.wakeId,
|
||||
targetRunId: seeded.runId,
|
||||
revision: "response-was-lost-before-the-client-stored-the-revision",
|
||||
});
|
||||
|
||||
expect(retried.status, JSON.stringify(retried.body)).toBe(200);
|
||||
expect(retried.body).toMatchObject({
|
||||
issueId: seeded.issueId,
|
||||
queueId: null,
|
||||
state: null,
|
||||
entries: [],
|
||||
});
|
||||
const activity = await db
|
||||
.select({ details: activityLog.details })
|
||||
.from(activityLog)
|
||||
.where(eq(activityLog.action, "issue.queued_comment_steered"))
|
||||
.then((rows) => rows[0]);
|
||||
expect(activity?.details).toMatchObject({
|
||||
commentId: seeded.commentIds[0],
|
||||
targetRunId: seeded.runId,
|
||||
turnId: "turn-acknowledged",
|
||||
duplicate: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not reuse an acknowledgement from a different queue", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({
|
||||
resultJson: {
|
||||
queuedSteeringAcknowledgements: {
|
||||
[seeded.commentIds[0]]: {
|
||||
status: "acknowledged",
|
||||
queueId: randomUUID(),
|
||||
turnId: "turn-from-another-queue",
|
||||
acknowledgedAt: "2026-08-22T15:04:00.000Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
|
||||
const steered = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({
|
||||
queueId: seeded.wakeId,
|
||||
targetRunId: seeded.runId,
|
||||
revision: initial.body.revision,
|
||||
});
|
||||
|
||||
expect(steered.status).toBe(409);
|
||||
expect(steered.body.details).toMatchObject({
|
||||
code: "steering_temporarily_unavailable",
|
||||
retryable: true,
|
||||
});
|
||||
const queueAfterFailure = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(queueAfterFailure.body.entries.map((entry: any) => entry.comment.id))
|
||||
.toEqual(seeded.commentIds);
|
||||
});
|
||||
|
||||
it("keeps queue edits available during handoff but rejects stale same-turn steering", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({ status: "succeeded", finishedAt: new Date("2026-08-22T15:05:00.000Z") })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
|
||||
const edit = await request(app(seeded.companyId))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({
|
||||
queueId: seeded.wakeId,
|
||||
revision: initial.body.revision,
|
||||
body: "edited during handoff",
|
||||
});
|
||||
|
||||
expect(edit.status, JSON.stringify(edit.body)).toBe(200);
|
||||
const stored = await db
|
||||
.select({ body: issueComments.body })
|
||||
.from(issueComments)
|
||||
.where(eq(issueComments.id, seeded.commentIds[0]))
|
||||
.then((rows) => rows[0]);
|
||||
expect(stored?.body).toBe("edited during handoff");
|
||||
const steer = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({
|
||||
queueId: seeded.wakeId,
|
||||
targetRunId: seeded.runId,
|
||||
revision: edit.body.revision,
|
||||
});
|
||||
expect(steer.status).toBe(409);
|
||||
expect(steer.body.details?.code).toBe("queued_comment_stale_target");
|
||||
const wake = await db
|
||||
.select({ status: agentWakeupRequests.status, payload: agentWakeupRequests.payload })
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId))
|
||||
.then((rows) => rows[0]);
|
||||
expect(wake?.status).toBe("deferred_issue_execution");
|
||||
expect((wake?.payload as any)?._paperclipWakeContext?.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
});
|
||||
|
||||
it("cancels a queued continuation whose comments disappeared before claim", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const queueRunId = await promoteQueue(seeded);
|
||||
await db.delete(issueComments).where(eq(issueComments.issueId, seeded.issueId));
|
||||
const heartbeat = heartbeatService(db, { runtimeEnv: {} });
|
||||
|
||||
await heartbeat.resumeQueuedRuns();
|
||||
|
||||
const [queueRun, wake] = await Promise.all([
|
||||
db.select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, queueRunId))
|
||||
.then((rows) => rows[0]),
|
||||
db.select({ status: agentWakeupRequests.status })
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId))
|
||||
.then((rows) => rows[0]),
|
||||
]);
|
||||
expect(queueRun).toMatchObject({
|
||||
status: "cancelled",
|
||||
errorCode: "queued_comment_discarded",
|
||||
});
|
||||
expect(wake?.status).toBe("cancelled");
|
||||
});
|
||||
|
||||
it("keeps a persisted legacy queue on the legacy protocol after the agent changes adapters", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const queueRunId = await promoteQueue(seeded);
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({ runtimeMode: "legacy" })
|
||||
.where(eq(heartbeatRuns.id, queueRunId));
|
||||
|
||||
const queued = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
|
||||
expect(queued.status, JSON.stringify(queued.body)).toBe(200);
|
||||
expect(queued.body).toMatchObject({
|
||||
queueId: seeded.wakeId,
|
||||
state: "queued",
|
||||
targetRunId: null,
|
||||
protocol: "legacy",
|
||||
steeringDisposition: "unsupported",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["paperclip_runner", "codex_local"])("keeps Steer during native preparation even after agent settings change to %s", async adapterType => {
|
||||
const seeded = await seedQueue();
|
||||
const steeringCalls = steerNativeSessionMock.mock.calls.length;
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy", runtimeModeResolvedAt: null,
|
||||
runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } },
|
||||
}).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(agents).set({ adapterType }).where(eq(agents.id, seeded.agentId));
|
||||
const client = app(seeded.companyId);
|
||||
const initial = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(initial.body).toMatchObject({ protocol: "paperclip_runner_v1", steeringDisposition: "temporarily_unavailable" });
|
||||
const edited = await request(client).patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "Updated direction" }).expect(200);
|
||||
expect(edited.body).toMatchObject({ protocol: "paperclip_runner_v1", steeringDisposition: "temporarily_unavailable" });
|
||||
expect(steerNativeSessionMock.mock.calls).toHaveLength(steeringCalls);
|
||||
});
|
||||
|
||||
it.each(["discard", "cancel"] as const)("serializes discard against queued-run claim (%s)", async (mode) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.delete(issueComments).where(eq(issueComments.id, seeded.commentIds[1]));
|
||||
await db
|
||||
.update(agentWakeupRequests)
|
||||
.set({
|
||||
payload: {
|
||||
issueId: seeded.issueId,
|
||||
commentId: seeded.commentIds[0],
|
||||
_paperclipWakeContext: {
|
||||
commentId: seeded.commentIds[0],
|
||||
wakeCommentId: seeded.commentIds[0],
|
||||
wakeCommentIds: [seeded.commentIds[0]],
|
||||
},
|
||||
},
|
||||
})
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const queueRunId = await promoteQueue(seeded);
|
||||
await db
|
||||
.update(agents)
|
||||
.set({
|
||||
adapterType: "process",
|
||||
adapterConfig: {
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
},
|
||||
})
|
||||
.where(eq(agents.id, seeded.agentId));
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({ runtimeMode: "legacy" })
|
||||
.where(eq(heartbeatRuns.id, queueRunId));
|
||||
const heartbeat = heartbeatService(db, { runtimeEnv: {} });
|
||||
|
||||
const [discard] = await Promise.all([
|
||||
request(app(seeded.companyId))
|
||||
.delete(mode === "cancel"
|
||||
? `/api/issues/${seeded.issueId}/comments/${seeded.commentIds[0]}?mode=cancel`
|
||||
: `/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision }),
|
||||
heartbeat.resumeQueuedRuns(),
|
||||
]);
|
||||
|
||||
const queueRun = await db
|
||||
.select({ status: heartbeatRuns.status })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, queueRunId))
|
||||
.then((rows) => rows[0]);
|
||||
if (discard.status === 200) {
|
||||
expect(queueRun?.status).toBe("cancelled");
|
||||
} else {
|
||||
expect(discard.status, JSON.stringify(discard.body)).toBe(409);
|
||||
expect(discard.body.details?.code).toBe("queued_comment_already_dispatching");
|
||||
expect(queueRun?.status).not.toBe("queued");
|
||||
}
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
}, 30_000);
|
||||
|
||||
|
||||
it("writes the identity acceptance, the wake payload, the run acknowledgement, and the activity row on a successful steering transaction", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await seedDispatchIdentity(seeded);
|
||||
steerNativeSessionMock.mockResolvedValueOnce({ turnId: "turn-1" });
|
||||
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const steered = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({ queueId: seeded.wakeId, targetRunId: seeded.runId, revision: initial.body.revision });
|
||||
|
||||
expect(steered.status, JSON.stringify(steered.body)).toBe(200);
|
||||
|
||||
const steeringIdentity = await db
|
||||
.select()
|
||||
.from(runIdentityContexts)
|
||||
.where(eq(runIdentityContexts.messageId, seeded.commentIds[0]))
|
||||
.then((rows) => rows[0]);
|
||||
expect(steeringIdentity).toMatchObject({
|
||||
status: "accepted",
|
||||
responsibleUserId: "queue-owner",
|
||||
cause: "steering",
|
||||
});
|
||||
|
||||
const wake = await db
|
||||
.select({ payload: agentWakeupRequests.payload })
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId))
|
||||
.then((rows) => rows[0]);
|
||||
expect((wake?.payload as any)?._paperclipWakeContext?.wakeCommentIds).toEqual([seeded.commentIds[1]]);
|
||||
|
||||
const run = await db
|
||||
.select({ resultJson: heartbeatRuns.resultJson, activeIdentityContextId: heartbeatRuns.activeIdentityContextId })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, seeded.runId))
|
||||
.then((rows) => rows[0]);
|
||||
expect((run?.resultJson as any)?.queuedSteeringAcknowledgements?.[seeded.commentIds[0]]).toMatchObject({
|
||||
status: "acknowledged",
|
||||
queueId: seeded.wakeId,
|
||||
turnId: "turn-1",
|
||||
});
|
||||
expect(run?.activeIdentityContextId).toBe(steeringIdentity!.id);
|
||||
|
||||
const activity = await db
|
||||
.select({ details: activityLog.details })
|
||||
.from(activityLog)
|
||||
.where(eq(activityLog.action, "issue.queued_comment_steered"))
|
||||
.then((rows) => rows[0]);
|
||||
expect(activity?.details).toMatchObject({
|
||||
commentId: seeded.commentIds[0],
|
||||
targetRunId: seeded.runId,
|
||||
turnId: "turn-1",
|
||||
duplicate: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("allows the runner to persist its acknowledgement while steering, preserving concurrent run updates", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await seedDispatchIdentity(seeded);
|
||||
const originalProfile = { adapterDispatch: { adapterType: "paperclip_runner" },
|
||||
nativeExecutionInput: { provider: { kind: "codex", model: "gpt-5.6-sol", reasoningEffort: "medium" } } };
|
||||
await db.update(heartbeatRuns).set({ runnerProfileJson: originalProfile }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(issues).set({ assigneeAdapterOverrides: { model: "gpt-6-sol", reasoningEffort: "xhigh" } })
|
||||
.where(eq(issues.id, seeded.issueId));
|
||||
steerNativeSessionMock.mockImplementationOnce(async () => {
|
||||
await db.transaction(async tx => {
|
||||
await tx.execute(sql`set local lock_timeout = '1000ms'`);
|
||||
await appendHeartbeatRunEvent(tx as unknown as typeof db, {
|
||||
companyId: seeded.companyId, agentId: seeded.agentId, runId: seeded.runId,
|
||||
eventType: "item.completed", payload: { kind: "steering_acknowledgement" },
|
||||
});
|
||||
await tx.update(heartbeatRuns).set({ resultJson: { concurrentProviderReceipt: "preserve" } })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
});
|
||||
return { turnId: "turn-before-model-change" };
|
||||
});
|
||||
const initial = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const steered = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({ queueId: seeded.wakeId, targetRunId: seeded.runId, revision: initial.body.revision });
|
||||
expect(steered.status, JSON.stringify(steered.body)).toBe(200);
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
expect(run.status).toBe("running");
|
||||
expect(run.runnerProfileJson).toEqual(originalProfile);
|
||||
expect(steerNativeSessionMock).toHaveBeenCalledWith(expect.objectContaining({ runId: seeded.runId,
|
||||
message: "First queued message", correlationId: seeded.commentIds[0] }));
|
||||
expect(run.resultJson).toMatchObject({ concurrentProviderReceipt: "preserve", queuedSteeringAcknowledgements: {
|
||||
[seeded.commentIds[0]]: { status: "acknowledged", turnId: "turn-before-model-change" },
|
||||
} });
|
||||
expect(steered.body.entries.map((entry: any) => entry.comment.id)).toEqual([seeded.commentIds[1]]);
|
||||
});
|
||||
|
||||
it.each(["cancelled", "failed", "succeeded", "different task"] as const)("preserves queued input when the run stops or changes scope during acknowledgement (%s)", async outcome => {
|
||||
const seeded = await seedQueue();
|
||||
await seedDispatchIdentity(seeded);
|
||||
steerNativeSessionMock.mockImplementationOnce(async () => {
|
||||
await db.update(heartbeatRuns).set({
|
||||
...(outcome === "different task" ? { contextSnapshot: { issueId: randomUUID() } } : { status: outcome, finishedAt: new Date() }),
|
||||
resultJson: { providerReceipt: "preserve" },
|
||||
})
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
return { turnId: "turn-that-stopped" };
|
||||
});
|
||||
const initial = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const response = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({ queueId: seeded.wakeId, targetRunId: seeded.runId, revision: initial.body.revision });
|
||||
expect(response.status).toBe(409);
|
||||
expect(response.body.details).toMatchObject({ code: "queued_comment_stale_target" });
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(wake.status).toBe("deferred_issue_execution");
|
||||
expect((wake.payload as any)._paperclipWakeContext.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
expect(run.resultJson).toEqual({ providerReceipt: "preserve" });
|
||||
const [identity] = await db.select().from(runIdentityContexts).where(eq(runIdentityContexts.messageId, seeded.commentIds[0]));
|
||||
expect(identity?.status).toBe("pending");
|
||||
const activity = await db.select().from(activityLog).where(eq(activityLog.action, "issue.queued_comment_steered"));
|
||||
expect(activity).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("keeps the identity pending after a steering timeout, then reconciles it on a later acknowledgement", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await seedDispatchIdentity(seeded);
|
||||
steerNativeSessionMock.mockRejectedValueOnce(
|
||||
new NativeSessionSteeringError("steering_timeout", "The provider did not acknowledge steering in time."),
|
||||
);
|
||||
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const steered = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({ queueId: seeded.wakeId, targetRunId: seeded.runId, revision: initial.body.revision });
|
||||
|
||||
expect(steered.status).toBe(409);
|
||||
expect(steered.body.details).toMatchObject({ code: "steering_timeout", retryable: true });
|
||||
|
||||
const pending = await db
|
||||
.select()
|
||||
.from(runIdentityContexts)
|
||||
.where(eq(runIdentityContexts.messageId, seeded.commentIds[0]))
|
||||
.then((rows) => rows[0]);
|
||||
expect(pending?.status).toBe("pending");
|
||||
|
||||
await reconcileSteeredIdentity(db, pending!);
|
||||
|
||||
const reconciled = await db
|
||||
.select({ status: runIdentityContexts.status })
|
||||
.from(runIdentityContexts)
|
||||
.where(eq(runIdentityContexts.id, pending!.id))
|
||||
.then((rows) => rows[0]);
|
||||
expect(reconciled?.status).toBe("accepted");
|
||||
const run = await db
|
||||
.select({ activeIdentityContextId: heartbeatRuns.activeIdentityContextId })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, seeded.runId))
|
||||
.then((rows) => rows[0]);
|
||||
expect(run?.activeIdentityContextId).toBe(pending!.id);
|
||||
});
|
||||
|
||||
it("sets the identity to rejected on a definite steering rejection", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await seedDispatchIdentity(seeded);
|
||||
steerNativeSessionMock.mockRejectedValueOnce(
|
||||
new NativeSessionSteeringError("steering_rejected", "The provider rejected the steering message."),
|
||||
);
|
||||
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const steered = await request(app(seeded.companyId))
|
||||
.post(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}/steer`)
|
||||
.send({ queueId: seeded.wakeId, targetRunId: seeded.runId, revision: initial.body.revision });
|
||||
|
||||
expect(steered.status).toBe(409);
|
||||
expect(steered.body.details).toMatchObject({ code: "steering_rejected", retryable: true });
|
||||
|
||||
const rejected = await db
|
||||
.select({ status: runIdentityContexts.status })
|
||||
.from(runIdentityContexts)
|
||||
.where(eq(runIdentityContexts.messageId, seeded.commentIds[0]))
|
||||
.then((rows) => rows[0]);
|
||||
expect(rejected?.status).toBe("rejected");
|
||||
});
|
||||
|
||||
it("throws queued_comment_order_mismatch and changes no row for an invalid reorder set", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
|
||||
const invalid = await request(app(seeded.companyId))
|
||||
.put(`/api/issues/${seeded.issueId}/queued-comments/order`)
|
||||
.send({
|
||||
queueId: seeded.wakeId,
|
||||
revision: initial.body.revision,
|
||||
orderedCommentIds: [seeded.commentIds[0], randomUUID()],
|
||||
});
|
||||
|
||||
expect(invalid.status, JSON.stringify(invalid.body)).toBe(409);
|
||||
expect(invalid.body.details?.code).toBe("queued_comment_order_mismatch");
|
||||
|
||||
const wake = await db
|
||||
.select({ payload: agentWakeupRequests.payload })
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId))
|
||||
.then((rows) => rows[0]);
|
||||
expect((wake?.payload as any)?._paperclipWakeContext?.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
const after = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(after.body.entries.map((entry: any) => entry.comment.id)).toEqual(seeded.commentIds);
|
||||
});
|
||||
// BUG-08: a declined connection request (Slack) queued its read-only receipt
|
||||
// ahead of the user's next message. The receipt showed raw JSON, could not be
|
||||
// edited or discarded, and the next message never appeared in the queue.
|
||||
async function seedDeclinedConnectionReceipt(runState: "running" | "legacy" | "stopped") {
|
||||
const seeded = await seedQueue();
|
||||
const interactionId = randomUUID();
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
id: interactionId, companyId: seeded.companyId, issueId: seeded.issueId,
|
||||
kind: "connection_intent", status: "rejected", createdByAgentId: seeded.agentId,
|
||||
sourceRunId: seeded.runId, resolvedByUserId: "queue-owner", resolvedAt: new Date(),
|
||||
continuationPolicy: "wake_assignee", requestedResolverPolicy: "human_only",
|
||||
effectiveResolverPolicy: "human_only", resolverPolicyProvenance: "explicit",
|
||||
title: "Connect Slack", summary: "The agent needs this connection to continue.",
|
||||
payload: { version: 1, serviceSlug: "slack", serviceName: "Slack", phase: "requested",
|
||||
requestingAgentId: seeded.agentId, requestingAgentName: "Paperclip Runner" },
|
||||
result: { version: 1, outcome: "declined", reason: null },
|
||||
});
|
||||
// Same receipt shape as wakeConnectionIntentAfterResolution.
|
||||
await db.update(agentWakeupRequests).set({ payload: { issueId: seeded.issueId,
|
||||
mutation: "interaction", interactionId, interactionKind: "connection_intent", interactionStatus: "rejected",
|
||||
_paperclipWakeContext: { issueId: seeded.issueId, interactionId, interactionKind: "connection_intent",
|
||||
interactionStatus: "rejected", mutation: "interaction", refreshTools: true } },
|
||||
}).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
if (runState === "legacy") {
|
||||
// A busy legacy run defers each new message behind the issue execution.
|
||||
await db.update(agents).set({ adapterType: "claude_local",
|
||||
runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } }).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
testProcesses.set(seeded.runId, child);
|
||||
runningProcesses.set(seeded.runId, { child, graceSec: 1, processGroupId: null });
|
||||
}
|
||||
if (runState === "stopped") {
|
||||
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "workspace_busy" })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, seeded.issueId));
|
||||
// Occupy the agent on another task so admission holds new work without
|
||||
// invoking a provider (the staging agent was busy on ONB-2/ONB-3).
|
||||
await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } })
|
||||
.where(eq(agents.id, seeded.agentId));
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() } });
|
||||
}
|
||||
return { ...seeded, interactionId };
|
||||
}
|
||||
|
||||
it("shows a declined connection receipt as a readable status, not its JSON", async () => {
|
||||
const seeded = await seedDeclinedConnectionReceipt("running");
|
||||
const queue = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(queue.body.entries).toHaveLength(1);
|
||||
const [entry] = queue.body.entries;
|
||||
expect(entry.source).toMatchObject({ kind: "interaction", interactionKind: "connection_intent",
|
||||
summary: "Declined: Slack connection" });
|
||||
// The agent still receives the typed receipt in the steering body.
|
||||
expect(entry.comment.body).toContain('"outcome": "declined"');
|
||||
});
|
||||
|
||||
it.each(["running", "stopped"] as const)(
|
||||
"keeps the next message visible and actionable after a declined connection (%s run)",
|
||||
async (runState) => {
|
||||
const seeded = await seedDeclinedConnectionReceipt(runState);
|
||||
const client = app(seeded.companyId);
|
||||
const sent = await request(client).post(`/api/issues/${seeded.issueId}/comments`)
|
||||
.send({ body: "Skip Slack for now and continue" }).expect(201);
|
||||
await vi.waitFor(async () => expect(await db.select().from(agentWakeupRequests)).toHaveLength(2));
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
const next = queue.body.entries.find((entry: any) => entry.comment.id === sent.body.id);
|
||||
expect(next, JSON.stringify(queue.body.entries.map((entry: any) => entry.comment.body.split("\n")[0])))
|
||||
.toMatchObject({ canEdit: true, canDiscard: true });
|
||||
expect(next.source).toBeUndefined();
|
||||
expect(queue.body.queueId).not.toBe(seeded.wakeId);
|
||||
// The message is the user's own queue entry, so its controls work.
|
||||
await request(client).delete(`/api/issues/${seeded.issueId}/queued-comments/${sent.body.id}`)
|
||||
.send({ queueId: queue.body.queueId, revision: queue.body.revision }).expect(200);
|
||||
// Declining the connection still reaches the agent on its own receipt.
|
||||
const [receipt] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(receipt.status).toBe("deferred_issue_execution");
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["legacy", "stopped"] as const)(
|
||||
"queues every later message together after a declined connection (%s run)",
|
||||
async (runState) => {
|
||||
const seeded = await seedDeclinedConnectionReceipt(runState);
|
||||
const client = app(seeded.companyId);
|
||||
const first = await request(client).post(`/api/issues/${seeded.issueId}/comments`)
|
||||
.send({ body: "Skip Slack for now" }).expect(201);
|
||||
await vi.waitFor(async () => expect(await db.select().from(agentWakeupRequests)).toHaveLength(2));
|
||||
const second = await request(client).post(`/api/issues/${seeded.issueId}/comments`)
|
||||
.send({ body: "Use email updates instead" }).expect(201);
|
||||
await vi.waitFor(async () => {
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(queue.body.entries.map((entry: any) => entry.comment.id)).toEqual([first.body.id, second.body.id]);
|
||||
});
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(queue.body.entries.every((entry: any) => entry.canEdit && entry.canDiscard)).toBe(true);
|
||||
// The receipt is never merged with user input; it keeps its own wake.
|
||||
const [receipt] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(receipt.status).toBe("deferred_issue_execution");
|
||||
expect(receipt.payload?._paperclipWakeContext).not.toHaveProperty("wakeCommentIds");
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
},
|
||||
);
|
||||
|
||||
// N-06: the composer offers "Send" for a deferred queue with no running
|
||||
// turn. The issue's own run can still be waiting to start (queued) or to
|
||||
// retry (scheduled_retry); that Send must be accepted and delivered next.
|
||||
it.each([
|
||||
{ runtime: "native", status: "queued" }, { runtime: "native", status: "scheduled_retry" },
|
||||
{ runtime: "legacy", status: "queued" }, { runtime: "legacy", status: "scheduled_retry" },
|
||||
] as const)("accepts Send while the previous $runtime run is $status and delivers it once that run stops", async ({ runtime, status }) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(agents).set({ adapterType: runtime === "native" ? "paperclip_runner" : "codex_local",
|
||||
runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } },
|
||||
}).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: runtime, status, startedAt: null })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
const client = app(seeded.companyId);
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
// This is the state in which the UI renders the "Send" button.
|
||||
expect(queue.body).toMatchObject({ state: "deferred", targetRunId: null, queueId: seeded.wakeId });
|
||||
const sent = await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, revision: queue.body.revision, targetRunId: null,
|
||||
});
|
||||
expect(sent.status, JSON.stringify(sent.body)).toBe(200);
|
||||
expect(sent.body).toMatchObject({ state: "deferred", queueId: seeded.wakeId });
|
||||
expect(sent.body.entries.map((entry: { comment: { id: string } }) => entry.comment.id)).toEqual(seeded.commentIds);
|
||||
// The previous run is not cancelled: it has not started any work to stop.
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId)))[0]!.status).toBe(status);
|
||||
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(saved.status).toBe("deferred_issue_execution");
|
||||
expect(saved.payload?.queuedCommentInterrupt).toMatchObject({ actorId: "queue-owner" });
|
||||
|
||||
// The previous run then finishes. Occupy the agent on another task so the
|
||||
// successor stays queued and the test never launches a provider.
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
if (runtime === "native") await commitNativeSuccess(seeded);
|
||||
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, seeded.issueId));
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() },
|
||||
});
|
||||
await heartbeatService(db).resumeQueuedCommentInterrupt(seeded.companyId, seeded.wakeId);
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(wake.status).toBe("coalesced");
|
||||
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, wake.runId!));
|
||||
expect(successor.status).toBe("queued");
|
||||
expect(successor.contextSnapshot?.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,828 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { runningProcesses } from "../adapters/index.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { createFullDatabaseResponseCapture, installDatabaseResponseCapture } from "./helpers/full-database-response-capture.js";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agentRuntimeState,
|
||||
agentWakeupRequests,
|
||||
agents,
|
||||
activityLog,
|
||||
companies,
|
||||
companyMemberships,
|
||||
companySkills,
|
||||
completionContracts,
|
||||
createDb,
|
||||
environmentLeases,
|
||||
heartbeatRuns,
|
||||
heartbeatRunEvents,
|
||||
issueComments,
|
||||
issueThreadInteractions,
|
||||
issueRecoveryActions,
|
||||
nativeRunFinalizations,
|
||||
nativeRunResults,
|
||||
issues,
|
||||
runIdentityContexts,
|
||||
} from "@paperclipai/db";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { issueRoutes } from "../routes/issues.js";
|
||||
import { heartbeatService } from "../services/heartbeat.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
import { hasQueuedInteractionResponse } from "../services/queued-interaction-response.js";
|
||||
import { remoteTerminationReceipt } from "../services/remote-execution-termination.js";
|
||||
import { initializeRunIdentity, reconcileSteeredIdentity } from "../services/run-identity.js";
|
||||
import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js";
|
||||
import { claimFirstTurnQueuedInput } from "../services/native-runtime/first-turn-queued-input.js";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
|
||||
const steerNativeSessionMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../services/native-runtime/native-session-executor.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/native-runtime/native-session-executor.js")>();
|
||||
steerNativeSessionMock.mockImplementation(actual.steerNativeSession);
|
||||
return { ...actual, steerNativeSession: steerNativeSessionMock };
|
||||
});
|
||||
const { NativeSessionSteeringError } = await import("../services/native-runtime/native-session-executor.js");
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
if (!embeddedPostgresSupport.supported) {
|
||||
console.warn(
|
||||
`Skipping queued-comment route tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
||||
);
|
||||
}
|
||||
|
||||
import { createIssueQueuedCommentsHarness, type QueuedCommentsDb } from "./helpers/issue-queued-comments-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("issue queued-comment steering routes", () => {
|
||||
const h = createIssueQueuedCommentsHarness("paperclip-queued-comments-steering-");
|
||||
let db!: QueuedCommentsDb;
|
||||
beforeAll(() => { db = h.db; });
|
||||
const { testProcesses, app, seedQueue, commitNativeSuccess, promoteQueue, seedDispatchIdentity } = h;
|
||||
|
||||
it.each(["stale revision", "different issue"] as const)(
|
||||
"rejects queued interruption for a %s without stopping the run",
|
||||
async (scenario) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
const client = app(seeded.companyId);
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
if (scenario === "different issue") {
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: randomUUID() } }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
}
|
||||
await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, targetRunId: seeded.runId,
|
||||
revision: scenario === "stale revision" ? "stale" : queue.body.revision,
|
||||
}).expect(409);
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId)))[0]!.status).toBe("running");
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["preparing", "native"] as const)(
|
||||
"accepts an explicit interrupt fallback for a %s runner and preserves queued messages",
|
||||
async (runtime) => {
|
||||
const seeded = await seedQueue();
|
||||
if (runtime === "preparing") {
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy", runtimeModeResolvedAt: null,
|
||||
executionStage: "preparing",
|
||||
runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } },
|
||||
}).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
} else {
|
||||
await db.update(heartbeatRuns).set({ nativeIssueId: seeded.issueId })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.insert(nativeRunFinalizations).values({ companyId: seeded.companyId,
|
||||
issueId: seeded.issueId, runId: seeded.runId, phase: "observed" });
|
||||
}
|
||||
// Hold the successor in the ordinary queue without launching a provider.
|
||||
await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } })
|
||||
.where(eq(agents.id, seeded.agentId));
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() } });
|
||||
const client = app(seeded.companyId);
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(queue.body).toMatchObject({ protocol: "paperclip_runner_v1", steeringDisposition: "temporarily_unavailable" });
|
||||
const response = await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, targetRunId: seeded.runId, revision: queue.body.revision,
|
||||
});
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
const [waiting] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(waiting.payload?.queuedCommentInterrupt).toMatchObject({ actorId: "queue-owner", targetRunId: seeded.runId });
|
||||
expect(await db.select().from(issueComments).where(eq(issueComments.issueId, seeded.issueId))).toHaveLength(2);
|
||||
expect(waiting.status).toBe("deferred_issue_execution");
|
||||
// The synthetic preparation owner now confirms that its unwind finished.
|
||||
// No provider ran; until this receipt exists, cancellation must hold input.
|
||||
const [stopped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
expect(stopped.status).toBe("cancelled");
|
||||
await db.update(heartbeatRuns).set({ resultJson: { ...stopped.resultJson,
|
||||
startupPreparationSettledAt: new Date().toISOString() } }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await heartbeatService(db).resumeQueuedCommentInterrupt(seeded.companyId, seeded.wakeId);
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(wake.status, JSON.stringify(wake)).toBe("coalesced");
|
||||
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, wake.runId!));
|
||||
expect(successor.status).toBe("queued");
|
||||
expect(successor.contextSnapshot?.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
await heartbeatService(db).resumeQueuedCommentInterrupt(seeded.companyId, seeded.wakeId);
|
||||
expect(await db.select().from(heartbeatRuns)).toHaveLength(3);
|
||||
},
|
||||
);
|
||||
|
||||
async function seedFirstTurnQueue(runtime: "preparing" | "native", queueStartedBy: "user" | "system" = "user") {
|
||||
const seeded = await seedQueue();
|
||||
// A user's follow-ups, as the comment route saves them behind that user's run.
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db.update(agentWakeupRequests).set({ payload: { ...wake!.payload,
|
||||
_paperclipWakeContext: { ...(wake!.payload?._paperclipWakeContext as Record<string, unknown>),
|
||||
issueId: seeded.issueId, wakeReason: "issue_commented" } },
|
||||
// An earlier automatic wake that waited behind the task's execution: the
|
||||
// comment route merges the user's message into it and keeps its requester.
|
||||
...(queueStartedBy === "system" ? { source: "automation", reason: "issue_execution_deferred",
|
||||
requestedByActorType: "system", requestedByActorId: null } : {}),
|
||||
}).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db.update(heartbeatRuns).set(runtime === "preparing"
|
||||
? { responsibleUserId: "queue-owner", runtimeMode: "legacy", runtimeModeResolvedAt: null, executionStage: "preparing",
|
||||
runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } }
|
||||
: { responsibleUserId: "queue-owner", nativeIssueId: seeded.issueId }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
if (runtime === "native") {
|
||||
await db.insert(nativeRunFinalizations).values({ companyId: seeded.companyId,
|
||||
issueId: seeded.issueId, runId: seeded.runId, phase: "observed" });
|
||||
}
|
||||
// Hold any successor in the ordinary queue without launching a provider.
|
||||
await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } })
|
||||
.where(eq(agents.id, seeded.agentId));
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() } });
|
||||
return seeded;
|
||||
}
|
||||
|
||||
it.each(["preparing", "native"] as const)(
|
||||
"keeps a %s run that has not started its first turn and gives it the queued messages",
|
||||
async (runtime) => {
|
||||
const seeded = await seedFirstTurnQueue(runtime);
|
||||
const client = app(seeded.companyId);
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
const response = await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, targetRunId: seeded.runId, revision: queue.body.revision,
|
||||
});
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
expect(response.body.executionWait).toMatchObject({ reason: "first_turn_pending" });
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
expect(run!.status).toBe("running");
|
||||
expect(run!.errorCode).toBeNull();
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(wake!.status).toBe("deferred_issue_execution");
|
||||
expect(wake!.payload?.queuedCommentInterrupt).toBeUndefined();
|
||||
|
||||
// Preparation finishes and the runner seals its first turn's input.
|
||||
if (runtime === "preparing") {
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "native", runtimeModeResolvedAt: new Date(),
|
||||
nativeIssueId: seeded.issueId }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
}
|
||||
const firstTurn = await claimFirstTurnQueuedInput(db, { companyId: seeded.companyId, runId: seeded.runId,
|
||||
issueId: seeded.issueId, agentId: seeded.agentId });
|
||||
expect(firstTurn).toContain("First queued message");
|
||||
expect(firstTurn!.indexOf("First queued message")).toBeLessThan(firstTurn!.indexOf("Second queued message"));
|
||||
// The taken messages leave the visible queue; nothing else can claim them.
|
||||
const after = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(after.body.entries).toEqual([]);
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, seeded.companyId)))
|
||||
.filter(row => row.status === "queued")).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([["preparing", false], ["native", false], ["native", true]] as const)(
|
||||
"stops a %s swarm run (turn started: %s) on Interrupt and delivers the queued message as the next request",
|
||||
async (runtime, turnStarted) => {
|
||||
const seeded = await seedFirstTurnQueue(runtime);
|
||||
// A trusted /swarm run: its only instruction is the recorded request, so no queued message joins it.
|
||||
const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { ...current!.contextSnapshot, antigravitySwarmCommentId: randomUUID() } })
|
||||
.where(eq(heartbeatRuns.id, seeded.runId));
|
||||
if (turnStarted) {
|
||||
await appendHeartbeatRunEvent(db, { companyId: seeded.companyId, runId: seeded.runId, agentId: seeded.agentId,
|
||||
eventType: "turn.accepted", stream: "system", level: "info", message: "turn accepted" });
|
||||
}
|
||||
const client = app(seeded.companyId);
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
// Not shown as taken by the first turn: the swarm will never read it.
|
||||
expect(queue.body.firstTurnCommentIds ?? []).toEqual([]);
|
||||
const response = await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, targetRunId: seeded.runId, revision: queue.body.revision,
|
||||
});
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
expect(response.body.executionWait?.reason).not.toBe("first_turn_pending");
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(wake!.payload?.queuedCommentInterrupt).toMatchObject({ actorId: "queue-owner" });
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
expect(run!.status).toBe("cancelled");
|
||||
},
|
||||
);
|
||||
|
||||
it("gives a booting run's first turn the user's message merged into an earlier automatic wake", async () => {
|
||||
const seeded = await seedFirstTurnQueue("preparing", "system");
|
||||
const client = app(seeded.companyId);
|
||||
// Shown as sent: Steer cannot reach a provider that has not started yet.
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(queue.body.firstTurnCommentIds).toEqual(seeded.commentIds);
|
||||
// Interrupt must not cancel the boot and leave the message behind a recovery wait.
|
||||
const response = await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, targetRunId: seeded.runId, revision: queue.body.revision,
|
||||
});
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
expect(response.body.executionWait).toMatchObject({ reason: "first_turn_pending" });
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
expect(run!.status).toBe("running");
|
||||
expect(run!.errorCode).toBeNull();
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "native", runtimeModeResolvedAt: new Date(),
|
||||
nativeIssueId: seeded.issueId }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
const firstTurn = await claimFirstTurnQueuedInput(db, { companyId: seeded.companyId, runId: seeded.runId,
|
||||
issueId: seeded.issueId, agentId: seeded.agentId });
|
||||
expect(firstTurn).toContain("First queued message");
|
||||
expect(firstTurn).toContain("Second queued message");
|
||||
});
|
||||
|
||||
it.each(["preparing", "native"] as const)(
|
||||
"reports the messages a %s run's first turn takes, before and after it seals them",
|
||||
async (runtime) => {
|
||||
const seeded = await seedFirstTurnQueue(runtime);
|
||||
const client = app(seeded.companyId);
|
||||
// The sandbox is still booting: the messages are sent, not waiting for Steer.
|
||||
const before = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(before.body.firstTurnCommentIds).toEqual(seeded.commentIds);
|
||||
|
||||
if (runtime === "preparing") {
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "native", runtimeModeResolvedAt: new Date(),
|
||||
nativeIssueId: seeded.issueId }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
}
|
||||
await claimFirstTurnQueuedInput(db, { companyId: seeded.companyId, runId: seeded.runId,
|
||||
issueId: seeded.issueId, agentId: seeded.agentId });
|
||||
// After the seal the queue hides them; the view still needs to know where they went.
|
||||
const after = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(after.body.entries).toEqual([]);
|
||||
expect(after.body.firstTurnCommentIds).toEqual(seeded.commentIds);
|
||||
},
|
||||
);
|
||||
|
||||
it("reports no first-turn messages once the run's turn already started", async () => {
|
||||
const seeded = await seedFirstTurnQueue("native");
|
||||
await appendHeartbeatRunEvent(db, { companyId: seeded.companyId, runId: seeded.runId, agentId: seeded.agentId,
|
||||
eventType: "turn.accepted", stream: "system", level: "info", message: "turn accepted" });
|
||||
const queue = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(queue.body.entries).toHaveLength(2);
|
||||
expect(queue.body.firstTurnCommentIds ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
it("still interrupts a preparing run when its queue holds another user's message", async () => {
|
||||
const seeded = await seedFirstTurnQueue("native");
|
||||
// Ordinary comments from two users merge into one wake that keeps the
|
||||
// first author as its requester; the first turn would take only that user's.
|
||||
await db.update(issueComments).set({ authorUserId: "other-operator" }).where(eq(issueComments.id, seeded.commentIds[1]!));
|
||||
const client = app(seeded.companyId);
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
const response = await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, targetRunId: seeded.runId, revision: queue.body.revision,
|
||||
});
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
// The stop is the user's own click: the messages are on their way, not
|
||||
// waiting on a recovery the user should read about.
|
||||
expect(response.body.executionWait?.reason).toBe("interrupt_handoff");
|
||||
const polled = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(polled.body.executionWait?.reason).toBe("interrupt_handoff");
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
expect(run!.status).toBe("cancelled");
|
||||
expect(run!.errorCode).toBe("operator_interrupted");
|
||||
});
|
||||
|
||||
it.each(["accepted turn", "sealed first turn"] as const)(
|
||||
"still interrupts a run whose %s already started",
|
||||
async (state) => {
|
||||
const seeded = await seedFirstTurnQueue("native");
|
||||
if (state === "accepted turn") {
|
||||
// A run saved by the previous release carries no seal; its accepted turn decides.
|
||||
await appendHeartbeatRunEvent(db, { companyId: seeded.companyId, runId: seeded.runId, agentId: seeded.agentId,
|
||||
eventType: "turn.accepted", stream: "system", level: "info", message: "turn accepted" });
|
||||
} else {
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: seeded.issueId, firstTurnQueuedInput: {
|
||||
schema: "paperclip.first-turn-queued-input.v1", runId: seeded.runId, wakeupRequestIds: [], commentIds: [],
|
||||
claimedAt: new Date().toISOString() } } }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
}
|
||||
const client = app(seeded.companyId);
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(queue.body.entries).toHaveLength(2);
|
||||
const response = await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, targetRunId: seeded.runId, revision: queue.body.revision,
|
||||
});
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
expect(run!.status).toBe("cancelled");
|
||||
expect(run!.errorCode).toBe("operator_interrupted");
|
||||
},
|
||||
);
|
||||
|
||||
it("does not accept interruption authority from an agent wake payload", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(agents).set({ adapterType: "claude_local",
|
||||
runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } },
|
||||
}).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await heartbeatService(db).wakeup(seeded.agentId, {
|
||||
source: "on_demand", reason: "issue_commented",
|
||||
requestedByActorType: "agent", requestedByActorId: seeded.agentId,
|
||||
payload: { issueId: seeded.issueId, commentId: seeded.commentIds[1],
|
||||
queuedCommentInterrupt: { actorId: "other-operator", requestedAt: new Date().toISOString() } },
|
||||
contextSnapshot: { issueId: seeded.issueId, wakeCommentId: seeded.commentIds[1] },
|
||||
});
|
||||
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, seeded.companyId));
|
||||
expect(wakes.length).toBeGreaterThan(0);
|
||||
expect(wakes.every(wake => !wake.payload?.queuedCommentInterrupt)).toBe(true);
|
||||
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, seeded.companyId));
|
||||
expect(runs.find(run => run.id === seeded.runId)?.status).toBe("running");
|
||||
expect(runs.every(run => !run.contextSnapshot?.explicitUserContinuation)).toBe(true);
|
||||
});
|
||||
|
||||
it("denies a viewer's interrupt before persisting intent or cancelling a run", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(companyMemberships).set({ membershipRole: "viewer" })
|
||||
.where(eq(companyMemberships.principalId, "other-operator"));
|
||||
const client = app(seeded.companyId, "other-operator");
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, revision: queue.body.revision, targetRunId: seeded.runId,
|
||||
}).expect(403);
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(wake.payload?.queuedCommentInterrupt).toBeUndefined();
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId)))[0].status).toBe("running");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ target: null, runtime: "legacy" }, { target: "stopped-target", runtime: "legacy" },
|
||||
{ target: "system-receipt", runtime: "legacy" }, { target: null, runtime: "native" },
|
||||
] as const)("sends a stopped $runtime queue once with target $target", async ({ target, runtime }) => {
|
||||
const seeded = await seedQueue();
|
||||
if (target === "system-receipt") await db.update(agentWakeupRequests).set({
|
||||
requestedByActorType: "system", requestedByActorId: "heartbeat",
|
||||
}).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db.update(agents).set({ adapterType: runtime === "native" ? "paperclip_runner" : "claude_local",
|
||||
runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } },
|
||||
}).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: runtime, status: "succeeded",
|
||||
finishedAt: new Date("2026-08-22T15:03:00.000Z"),
|
||||
}).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
if (runtime === "native") await commitNativeSuccess(seeded);
|
||||
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, seeded.issueId));
|
||||
// Occupy this agent on a different task so the actual successor remains
|
||||
// queued and the test never launches a provider.
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() },
|
||||
});
|
||||
const client = app(seeded.companyId, "other-operator");
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
expect(queue.body.targetRunId).toBeNull();
|
||||
const body = { queueId: seeded.wakeId, revision: queue.body.revision,
|
||||
targetRunId: target === "stopped-target" ? seeded.runId : null };
|
||||
await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send(body).expect(200);
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(wake.status).toBe("coalesced");
|
||||
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, wake.runId!));
|
||||
expect(successor.status).toBe("queued");
|
||||
expect(successor.responsibleUserId).toBe("other-operator");
|
||||
const identity = await initializeRunIdentity(db, {
|
||||
companyId: seeded.companyId, issueId: seeded.issueId,
|
||||
runId: successor.id, messageIds: seeded.commentIds, responsibleUserId: "queue-owner", cause: "dispatch",
|
||||
});
|
||||
expect(identity.responsibleUserId).toBe("other-operator");
|
||||
expect(identity.cause).toBe("queued_comment_interrupt");
|
||||
expect(successor.contextSnapshot?.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
await heartbeatService(db).resumeQueuedCommentInterrupt(seeded.companyId, seeded.wakeId);
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, seeded.companyId))).toHaveLength(3);
|
||||
await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send(body).expect(409);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["other", "running"], ["other", "queued"], ["other", "scheduled_retry"],
|
||||
["same", "running"], ["same", "queued"], ["same", "scheduled_retry"],
|
||||
] as const)("scopes interrupted queue successors to its agent: %s agent %s", async (owner, status) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(agents).set({ adapterType: "claude_local",
|
||||
runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } },
|
||||
}).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy", status: "succeeded",
|
||||
finishedAt: new Date("2026-08-22T15:03:00.000Z"),
|
||||
}).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, seeded.issueId));
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db.update(agentWakeupRequests).set({ payload: { ...wake.payload,
|
||||
queuedCommentInterrupt: { actorId: "other-operator", requestedAt: new Date().toISOString() },
|
||||
} }).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
// Keep this agent at capacity so successful delivery queues a successor
|
||||
// without launching a provider. The independent run shares only the task.
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() },
|
||||
});
|
||||
const successorAgentId = owner === "same" ? seeded.agentId : randomUUID();
|
||||
if (owner === "other") await db.insert(agents).values({ id: successorAgentId,
|
||||
companyId: seeded.companyId, name: "Independent agent", role: "engineer",
|
||||
status: "idle", adapterType: "claude_local",
|
||||
});
|
||||
const [existingRun] = await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: successorAgentId,
|
||||
status, contextSnapshot: { issueId: seeded.issueId },
|
||||
}).returning();
|
||||
|
||||
await heartbeatService(db).resumeQueuedCommentInterrupt(seeded.companyId, seeded.wakeId, { retryCleanup: true });
|
||||
if (owner === "other" && status !== "scheduled_retry") {
|
||||
// Another agent is not this queue's successor, but ordinary admission
|
||||
// must still preserve the task execution lock until its work stops.
|
||||
const [waiting] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
const [task] = await db.select().from(issues).where(eq(issues.id, seeded.issueId));
|
||||
expect(waiting.status).toBe("deferred_issue_execution");
|
||||
expect(task.executionRunId).toBe(existingRun.id);
|
||||
expect(waiting.payload?.queuedCommentInterrupt).toMatchObject({ actorId: "other-operator" });
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() })
|
||||
.where(eq(heartbeatRuns.id, existingRun.id));
|
||||
await heartbeatService(db).resumeQueuedCommentInterrupt(seeded.companyId, seeded.wakeId, { retryCleanup: true });
|
||||
}
|
||||
const [receipt] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(receipt.status).toBe(owner === "same" ? "deferred_issue_execution" : "coalesced");
|
||||
if (owner === "other") {
|
||||
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, receipt.runId!));
|
||||
expect(successor).toMatchObject({ agentId: seeded.agentId, status: "queued", responsibleUserId: "other-operator" });
|
||||
expect(successor.contextSnapshot?.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
}
|
||||
await heartbeatService(db).resumeQueuedCommentInterrupt(seeded.companyId, seeded.wakeId, { retryCleanup: true });
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, seeded.companyId)))
|
||||
.toHaveLength(owner === "same" ? 3 : 4);
|
||||
});
|
||||
|
||||
it.each(["user", "system"])("keeps stopped-run interruption intent on a %s receipt across restart until the process stops, then delivers once", async (actorType) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(agentWakeupRequests).set({ requestedByActorType: actorType })
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db.update(agents).set({ adapterType: "claude_local",
|
||||
runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } },
|
||||
}).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy", status: "failed",
|
||||
processPid: process.pid, errorCode: "process_lost",
|
||||
finishedAt: new Date("2026-08-22T15:03:00.000Z"),
|
||||
}).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, seeded.issueId));
|
||||
await db.insert(issueRecoveryActions).values({ companyId: seeded.companyId, sourceIssueId: seeded.issueId,
|
||||
kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation", fingerprint: seeded.runId,
|
||||
status: "resolved", outcome: "blocked", nextAction: "Automatic recovery stopped.",
|
||||
evidence: { runId: seeded.runId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } },
|
||||
});
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() },
|
||||
});
|
||||
const client = app(seeded.companyId, "other-operator");
|
||||
const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200);
|
||||
await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({
|
||||
queueId: seeded.wakeId, revision: queue.body.revision, targetRunId: null,
|
||||
}).expect(200);
|
||||
const [waiting] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(waiting.status).toBe("deferred_issue_execution");
|
||||
expect(waiting.payload?.queuedCommentInterrupt).toMatchObject({ actorId: "other-operator" });
|
||||
expect(waiting.payload?.executionWait).toMatchObject({ reason: "process_running" });
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, seeded.companyId))).toHaveLength(2);
|
||||
await db.update(heartbeatRuns).set({ processPid: 999999999 }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(agentWakeupRequests).set({ updatedAt: new Date(0) }).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
// New service instances have no memory of the HTTP request. Concurrent
|
||||
// periodic workers must consume its durable receipt exactly once.
|
||||
await Promise.all([heartbeatService(db).resumeQueuedRuns(), heartbeatService(db).resumeQueuedRuns()]);
|
||||
const [delivered] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(delivered.status).toBe("coalesced");
|
||||
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, delivered.runId!));
|
||||
expect(successor.contextSnapshot).toMatchObject({ wakeCommentIds: seeded.commentIds,
|
||||
previousRunId: seeded.runId, forceFreshSession: true });
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, seeded.companyId))).toHaveLength(3);
|
||||
});
|
||||
|
||||
it.each(["user", "system", "manual_receipt_other_actor", "rejected_admission", "consumed_first", "consumed_last", "deleted_first", "agent_first", "cancelled_queued"])("delivers saved user messages on a %s queue after automatic recovery stopped, without another click", async (actorType) => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(agentWakeupRequests).set({ requestedByActorType: actorType === "user" ? "user" : "system" })
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
if (actorType === "manual_receipt_other_actor") {
|
||||
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
await db.update(agentWakeupRequests).set({ requestedByActorType: "user", requestedByActorId: "other-operator",
|
||||
payload: { ...saved.payload, manualUserWake: true },
|
||||
}).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
}
|
||||
await db.update(agents).set({ adapterType: "claude_local",
|
||||
runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } },
|
||||
}).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy", status: "failed",
|
||||
processPid: process.pid, errorCode: "process_lost", finishedAt: new Date("2026-08-22T15:03:00.000Z"),
|
||||
}).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, seeded.issueId));
|
||||
await db.insert(issueRecoveryActions).values({ companyId: seeded.companyId, sourceIssueId: seeded.issueId,
|
||||
kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation", fingerprint: seeded.runId,
|
||||
status: "resolved", outcome: "blocked", nextAction: "Automatic recovery stopped.",
|
||||
evidence: { runId: seeded.runId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } },
|
||||
});
|
||||
// Leave the agent's only slot occupied on another task so dispatch stays queued.
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() },
|
||||
});
|
||||
await heartbeatService(db).resumeQueuedRuns();
|
||||
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId)))[0].status)
|
||||
.toBe("deferred_issue_execution");
|
||||
await db.update(heartbeatRuns).set({ processPid: 999999999 }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
const excludedIndex = actorType === "consumed_last" ? 1 : 0;
|
||||
const filtersInput = ["consumed_first", "consumed_last", "deleted_first", "agent_first"].includes(actorType);
|
||||
if (actorType.startsWith("consumed_")) await db.update(heartbeatRuns).set({
|
||||
contextSnapshot: { issueId: seeded.issueId, wakeCommentIds: [seeded.commentIds[excludedIndex]] },
|
||||
}).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
if (actorType === "deleted_first") await db.update(issueComments).set({ deletedAt: new Date() })
|
||||
.where(eq(issueComments.id, seeded.commentIds[0]));
|
||||
if (actorType === "agent_first") await db.update(issueComments).set({
|
||||
authorType: "agent", authorUserId: null, authorAgentId: seeded.agentId,
|
||||
}).where(eq(issueComments.id, seeded.commentIds[0]));
|
||||
const expectedIds = seeded.commentIds.filter((_, index) => !filtersInput || index !== excludedIndex);
|
||||
if (actorType === "cancelled_queued") await db.insert(heartbeatRuns).values({
|
||||
companyId: seeded.companyId, agentId: seeded.agentId, status: "cancelled", runtimeMode: "legacy",
|
||||
errorCode: "agent_paused", createdAt: new Date(0), finishedAt: new Date(1),
|
||||
contextSnapshot: { issueId: seeded.issueId, wakeCommentIds: [seeded.commentIds[0]] },
|
||||
});
|
||||
if (actorType === "rejected_admission") {
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "cancelled", runtimeMode: "legacy", errorCode: "execution_reconciliation_required",
|
||||
contextSnapshot: { issueId: seeded.issueId }, finishedAt: new Date(),
|
||||
});
|
||||
}
|
||||
await Promise.all([heartbeatService(db).resumeQueuedRuns(), heartbeatService(db).resumeQueuedRuns()]);
|
||||
const [delivered] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(delivered.status).toBe("coalesced");
|
||||
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, delivered.runId!));
|
||||
expect(successor.contextSnapshot).toMatchObject({ wakeCommentIds: expectedIds,
|
||||
previousRunId: seeded.runId, forceFreshSession: true });
|
||||
if (actorType === "manual_receipt_other_actor") {
|
||||
const [dispatch] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, successor.wakeupRequestId!));
|
||||
expect(dispatch.requestedByActorId).toBe("queue-owner");
|
||||
expect(dispatch.payload?.manualUserWake).toBeUndefined();
|
||||
expect(successor.responsibleUserId).toBe("queue-owner");
|
||||
}
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, seeded.companyId))).toHaveLength(["rejected_admission", "cancelled_queued"].includes(actorType) ? 4 : 3);
|
||||
const [recovery] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, seeded.issueId));
|
||||
expect(recovery.evidence.automaticRecovery).toMatchObject({ actionOutcome: "unknown" });
|
||||
});
|
||||
|
||||
it("recovers a message deferred after legacy finalization released the task lock", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await db.update(agents).set({ adapterType: "claude_local",
|
||||
runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } },
|
||||
}).where(eq(agents.id, seeded.agentId));
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "legacy", status: "succeeded",
|
||||
finishedAt: new Date("2026-08-22T15:03:00.000Z"),
|
||||
}).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, seeded.issueId));
|
||||
await db.insert(heartbeatRuns).values({ companyId: seeded.companyId, agentId: seeded.agentId,
|
||||
status: "running", contextSnapshot: { issueId: randomUUID() },
|
||||
});
|
||||
await heartbeatService(db).resumeQueuedRuns();
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
expect(wake.status).toBe("queued");
|
||||
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, wake.runId!));
|
||||
expect(successor.contextSnapshot?.wakeCommentIds).toEqual(seeded.commentIds);
|
||||
await heartbeatService(db).resumeQueuedRuns();
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, seeded.companyId))).toHaveLength(3);
|
||||
});
|
||||
|
||||
|
||||
it("projects the recovery wait reason only while the message is deferred", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const executionWait = { reason: "remote_cleanup", message: "Waiting for the previous environment to stop." };
|
||||
await db.update(agentWakeupRequests).set({
|
||||
payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb) || ${JSON.stringify({ executionWait })}::jsonb`,
|
||||
}).where(eq(agentWakeupRequests.id, seeded.wakeId));
|
||||
const waiting = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(waiting.status).toBe(200);
|
||||
expect(waiting.body.executionWait).toEqual(executionWait);
|
||||
await promoteQueue(seeded);
|
||||
const admitted = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(admitted.status).toBe(200);
|
||||
expect(admitted.body.executionWait).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns the authoritative order, preserves full Markdown edits, and rejects stale revisions", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
|
||||
expect(initial.status, JSON.stringify(initial.body)).toBe(200);
|
||||
expect(initial.body).toMatchObject({
|
||||
issueId: seeded.issueId,
|
||||
queueId: seeded.wakeId,
|
||||
state: "deferred",
|
||||
targetRunId: seeded.runId,
|
||||
protocol: "paperclip_runner_v1",
|
||||
entries: [
|
||||
{ position: 0, canEdit: true, canDiscard: true, comment: { id: seeded.commentIds[0] } },
|
||||
{ position: 1, canEdit: true, canDiscard: true, comment: { id: seeded.commentIds[1] } },
|
||||
],
|
||||
});
|
||||
|
||||
const markdown = " Keep **all** Markdown. \n";
|
||||
const edited = await request(app(seeded.companyId))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: markdown });
|
||||
expect(edited.status, JSON.stringify(edited.body)).toBe(200);
|
||||
expect(edited.body.entries[0].comment.body).toBe(markdown);
|
||||
expect(edited.body.revision).not.toBe(initial.body.revision);
|
||||
const stored = await db.select({ body: issueComments.body })
|
||||
.from(issueComments)
|
||||
.where(eq(issueComments.id, seeded.commentIds[0]))
|
||||
.then((rows) => rows[0]);
|
||||
expect(stored?.body).toBe(markdown);
|
||||
|
||||
const stale = await request(app(seeded.companyId))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "stale" });
|
||||
expect(stale.status).toBe(409);
|
||||
expect(stale.body.details?.code).toBe("queued_comment_revision_conflict");
|
||||
});
|
||||
|
||||
it("writes one activity log row for each successful queue mutation, and none for a rejected one", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
|
||||
const edited = await request(app(seeded.companyId))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "edited body" });
|
||||
expect(edited.status, JSON.stringify(edited.body)).toBe(200);
|
||||
|
||||
const staleEdit = await request(app(seeded.companyId))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "stale" });
|
||||
expect(staleEdit.status).toBe(409);
|
||||
|
||||
const editRows = await db
|
||||
.select({ details: activityLog.details })
|
||||
.from(activityLog)
|
||||
.where(eq(activityLog.action, "issue.queued_comment_edited"));
|
||||
expect(editRows).toHaveLength(1);
|
||||
expect(editRows[0]?.details).toMatchObject({
|
||||
commentId: seeded.commentIds[0],
|
||||
queueId: seeded.wakeId,
|
||||
revision: edited.body.revision,
|
||||
});
|
||||
|
||||
const reordered = await request(app(seeded.companyId))
|
||||
.put(`/api/issues/${seeded.issueId}/queued-comments/order`)
|
||||
.send({
|
||||
queueId: seeded.wakeId,
|
||||
revision: edited.body.revision,
|
||||
orderedCommentIds: [...seeded.commentIds].reverse(),
|
||||
});
|
||||
expect(reordered.status, JSON.stringify(reordered.body)).toBe(200);
|
||||
const reorderRow = await db
|
||||
.select({ details: activityLog.details })
|
||||
.from(activityLog)
|
||||
.where(eq(activityLog.action, "issue.queued_comments_reordered"))
|
||||
.then((rows) => rows[0]);
|
||||
expect(reorderRow?.details).toMatchObject({
|
||||
queueId: seeded.wakeId,
|
||||
revision: reordered.body.revision,
|
||||
orderedCommentIds: [...seeded.commentIds].reverse(),
|
||||
});
|
||||
|
||||
const discarded = await request(app(seeded.companyId))
|
||||
.delete(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[1]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: reordered.body.revision });
|
||||
expect(discarded.status, JSON.stringify(discarded.body)).toBe(200);
|
||||
const discardRow = await db
|
||||
.select({ details: activityLog.details })
|
||||
.from(activityLog)
|
||||
.where(eq(activityLog.action, "issue.queued_comment_discarded"))
|
||||
.then((rows) => rows[0]);
|
||||
expect(discardRow?.details).toMatchObject({
|
||||
commentId: seeded.commentIds[1],
|
||||
queueId: seeded.wakeId,
|
||||
revision: discarded.body.revision,
|
||||
cancelledRunId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves reordered messages across promotion and cancels the queued run after final trash", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const reordered = await request(app(seeded.companyId))
|
||||
.put(`/api/issues/${seeded.issueId}/queued-comments/order`)
|
||||
.send({
|
||||
queueId: seeded.wakeId,
|
||||
revision: initial.body.revision,
|
||||
orderedCommentIds: [...seeded.commentIds].reverse(),
|
||||
});
|
||||
expect(reordered.status, JSON.stringify(reordered.body)).toBe(200);
|
||||
expect(reordered.body.entries.map((entry: any) => entry.comment.id)).toEqual([...seeded.commentIds].reverse());
|
||||
|
||||
const queueRunId = await promoteQueue(seeded);
|
||||
const promoted = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(promoted.body).toMatchObject({
|
||||
queueId: seeded.wakeId,
|
||||
state: "queued",
|
||||
targetRunId: null,
|
||||
revision: reordered.body.revision,
|
||||
});
|
||||
|
||||
const afterFirstTrash = await request(app(seeded.companyId))
|
||||
.delete(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[1]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: promoted.body.revision });
|
||||
expect(afterFirstTrash.status, JSON.stringify(afterFirstTrash.body)).toBe(200);
|
||||
expect(afterFirstTrash.body.entries.map((entry: any) => entry.comment.id)).toEqual([seeded.commentIds[0]]);
|
||||
const queuedRunAfterFirstTrash = await db
|
||||
.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, queueRunId))
|
||||
.then((rows) => rows[0]);
|
||||
expect((queuedRunAfterFirstTrash?.contextSnapshot as any)?.wakeCommentIds).toEqual([
|
||||
seeded.commentIds[0],
|
||||
]);
|
||||
|
||||
const emptied = await request(app(seeded.companyId))
|
||||
.delete(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: afterFirstTrash.body.revision });
|
||||
expect(emptied.status, JSON.stringify(emptied.body)).toBe(200);
|
||||
expect(emptied.body.entries).toEqual([]);
|
||||
const wake = await db.select({ status: agentWakeupRequests.status })
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, seeded.wakeId))
|
||||
.then((rows) => rows[0]);
|
||||
expect(wake?.status).toBe("cancelled");
|
||||
const [queueRun, storedIssue] = await Promise.all([
|
||||
db.select({ status: heartbeatRuns.status })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, queueRunId))
|
||||
.then((rows) => rows[0]),
|
||||
db.select({ executionRunId: issues.executionRunId })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, seeded.issueId))
|
||||
.then((rows) => rows[0]),
|
||||
]);
|
||||
expect(queueRun?.status).toBe("cancelled");
|
||||
expect(storedIssue?.executionRunId).toBeNull();
|
||||
|
||||
// Two discards happen in this scenario (the first trash, then the final
|
||||
// one that empties the queue), so match the row by its own commentId
|
||||
// instead of assuming insertion order.
|
||||
const discardRows = await db
|
||||
.select({ details: activityLog.details })
|
||||
.from(activityLog)
|
||||
.where(eq(activityLog.action, "issue.queued_comment_discarded"));
|
||||
const finalDiscardRow = discardRows.find(
|
||||
(row) => (row.details as { commentId?: string } | null)?.commentId === seeded.commentIds[0],
|
||||
);
|
||||
expect(finalDiscardRow?.details).toMatchObject({
|
||||
commentId: seeded.commentIds[0],
|
||||
cancelledRunId: queueRunId,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a mutation response's steering disposition in step with a fresh GET after promotion", async () => {
|
||||
const seeded = await seedQueue();
|
||||
await promoteQueue(seeded);
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(initial.body.steeringDisposition).toBe("temporarily_unavailable");
|
||||
|
||||
const edited = await request(app(seeded.companyId))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "edited during promotion" });
|
||||
expect(edited.status, JSON.stringify(edited.body)).toBe(200);
|
||||
const afterEdit = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(edited.body.steeringDisposition).toBe(afterEdit.body.steeringDisposition);
|
||||
|
||||
const reordered = await request(app(seeded.companyId))
|
||||
.put(`/api/issues/${seeded.issueId}/queued-comments/order`)
|
||||
.send({
|
||||
queueId: seeded.wakeId,
|
||||
revision: edited.body.revision,
|
||||
orderedCommentIds: [...seeded.commentIds].reverse(),
|
||||
});
|
||||
expect(reordered.status, JSON.stringify(reordered.body)).toBe(200);
|
||||
const afterReorder = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
expect(reordered.body.steeringDisposition).toBe(afterReorder.body.steeringDisposition);
|
||||
});
|
||||
|
||||
it("returns entry objects with the same keys as the GET endpoint", async () => {
|
||||
const seeded = await seedQueue();
|
||||
const initial = await request(app(seeded.companyId))
|
||||
.get(`/api/issues/${seeded.issueId}/queued-comments`);
|
||||
const edited = await request(app(seeded.companyId))
|
||||
.patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`)
|
||||
.send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "edited body" });
|
||||
expect(edited.status, JSON.stringify(edited.body)).toBe(200);
|
||||
expect(Object.keys(edited.body.entries[0]).sort()).toEqual(Object.keys(initial.body.entries[0]).sort());
|
||||
});
|
||||
|
||||
});
|
||||
Reference in new issue
Block a user