mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
Merge origin/master into feat/antigravity-swarm-command
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * origin/master: refactor(plugin-sdk): remove archivedState from the resume result (#22443) refactor(runner): let the provider decide whether a released Runner relaunches (#22442) fix(connections): drop MCP wording and the MCP guide link from Google Workspace setup (#22793) fix(ui): defer the Connectors announcement until a return visit (#22790) fix(connections): show only the privacy policy link in the Google Workspace picker (#22795) Add count, newest-first and lean run reads to customer-success inspection (#22781) fix(connections): keep a finished setup checklist on screen when the app refreshes queries (#22715) perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729) fix(plan-mode): open the plan review card when a Plan-mode run settles without one (#22732)
This commit is contained in:
commit
3cbfa500f4
142 files changed
+5552
-11636
No files matched your search
@@ -154,6 +154,18 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
|
||||
transactionReads++;
|
||||
return registry.getCustomerSuccessAccount(id);
|
||||
},
|
||||
getStacks: async (ids: readonly string[]) => {
|
||||
await client.query("SELECT 1");
|
||||
transactionReads++;
|
||||
return (await Promise.all(ids.map((id) => registry.getStack(id)))).filter(Boolean);
|
||||
},
|
||||
getAccounts: async (ids: readonly string[]) => {
|
||||
await client.query("SELECT 1");
|
||||
transactionReads++;
|
||||
return (
|
||||
await Promise.all(ids.map((id) => registry.getCustomerSuccessAccount(id)))
|
||||
).filter(Boolean);
|
||||
},
|
||||
listStackIds: async () => registry.listCustomerSuccessStackIds(),
|
||||
});
|
||||
const store = new PostgresInspectionStore(pool, registryForClient);
|
||||
@@ -272,7 +284,9 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
|
||||
const grant=await call('grant',{stackId:'qualification-stack'});
|
||||
const tasks=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'tasks',companyId:${JSON.stringify(customer.id)}}});
|
||||
const file=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'files.download',companyId:${JSON.stringify(customer.id)},resourceId:${JSON.stringify(task.id)},context:{projectId:${JSON.stringify(project.id)},workspaceId:${JSON.stringify(workspace.id)}},path:'result.bin',range:{start:2,end:5}}});
|
||||
console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')]}));
|
||||
const taskCount=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'count',resource:'tasks',companyId:${JSON.stringify(customer.id)}}});
|
||||
const latestRuns=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'runs',companyId:${JSON.stringify(customer.id)},order:'newest',view:'summary',limit:1}});
|
||||
console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')],taskCount,latestRuns}));
|
||||
`;
|
||||
const programFile = join(directory, "qualify.mjs");
|
||||
await writeFile(programFile, program);
|
||||
@@ -298,6 +312,9 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
|
||||
expect(result.exitCode, [...output, ...serverErrors].join("\n")).toBe(0);
|
||||
expect(output.join("")).toContain("First successful task");
|
||||
expect(output.join("")).toContain('"fileBytes":[2,3,4,5]');
|
||||
// Count and newest-first summary reads travel the extended tenant path.
|
||||
expect(output.join("")).toContain('"taskCount":{"total":1,"byStatus":{');
|
||||
expect(output.join("")).toContain('"latestRuns":{"items":[],"nextOffset":null}');
|
||||
expect((await stat(filePath)).mtimeMs).toBe(fileBefore.mtimeMs);
|
||||
expect(await readFile(filePath)).toEqual(Buffer.from([0, 1, 2, 3, 4, 5]));
|
||||
const audit = await pool.query(
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
INSPECTION_HEADER,
|
||||
INSPECTION_PERMIT_TYPE,
|
||||
INSPECTION_RESOURCES,
|
||||
inspectionReadPath,
|
||||
parseInspectionQuery,
|
||||
type InspectionQuery,
|
||||
type InspectionPermit,
|
||||
@@ -21,6 +22,8 @@ import { customerSuccessRunAuthority } from "../services/customer-success-author
|
||||
import {
|
||||
readCustomerSuccessResource,
|
||||
inspectionReaders,
|
||||
RUN_SUMMARY_COLUMNS,
|
||||
primaryKeyColumns,
|
||||
} from "../services/customer-success-inspection.js";
|
||||
import {
|
||||
customerSuccessRoutes,
|
||||
@@ -438,6 +441,29 @@ describe("customer-success read authority", () => {
|
||||
expect((await request(app).post("/api/customer-success/v1/unknown").send({})).status).toEqual(
|
||||
404,
|
||||
);
|
||||
// Count, order and view live only on the extended path, so a tenant that
|
||||
// predates them answers 404 there and Cloud fails closed.
|
||||
const countQuery: InspectionQuery = { operation: "count", resource: "tasks", companyId };
|
||||
const countToken = () => token({ ...claims, jti: randomUUID(), query: countQuery });
|
||||
expect(
|
||||
(
|
||||
await request(app)
|
||||
.post("/api/customer-success/v1/read")
|
||||
.set(INSPECTION_HEADER, countToken())
|
||||
.send(countQuery)
|
||||
).status,
|
||||
).toEqual(403);
|
||||
const counted = await request(app)
|
||||
.post("/api/customer-success/v1/read-v2")
|
||||
.set(INSPECTION_HEADER, countToken())
|
||||
.send(countQuery);
|
||||
expect(counted.status).toEqual(200);
|
||||
expect(counted.body).toEqual({ total: expect.any(Number), byStatus: expect.any(Object) });
|
||||
const original = await request(app)
|
||||
.post("/api/customer-success/v1/read-v2")
|
||||
.set(INSPECTION_HEADER, token())
|
||||
.send(query);
|
||||
expect(original.status).toEqual(200);
|
||||
fetcher.mockResolvedValue(new Response("", { status: 503 }));
|
||||
expect(
|
||||
(
|
||||
@@ -692,6 +718,153 @@ describe("customer-success read authority", () => {
|
||||
})) as { items: unknown[] };
|
||||
expect(versions.items).toHaveLength(1);
|
||||
});
|
||||
it("counts by status, orders newest first, and returns lean run summaries, company scoped", async () => {
|
||||
const [company, other] = await db
|
||||
.insert(schema.companies)
|
||||
.values([
|
||||
{ name: "Counted", issuePrefix: "CNT" },
|
||||
{ name: "Elsewhere", issuePrefix: "ELS" },
|
||||
])
|
||||
.returning();
|
||||
const [countedAgent] = await db
|
||||
.insert(schema.agents)
|
||||
.values({ companyId: company.id, name: "Counted agent", adapterType: "process" })
|
||||
.returning();
|
||||
const [otherAgent] = await db
|
||||
.insert(schema.agents)
|
||||
.values({ companyId: other.id, name: "Other agent", adapterType: "process" })
|
||||
.returning();
|
||||
const heavy = { transcript: "x".repeat(200_000) };
|
||||
const at = (minutes: number) => new Date(Date.UTC(2026, 0, 1, 0, minutes));
|
||||
const runs = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values([
|
||||
{ companyId: company.id, agentId: countedAgent.id, status: "succeeded", createdAt: at(1), startedAt: at(1), finishedAt: at(3), resultJson: heavy, contextSnapshot: heavy },
|
||||
{ companyId: company.id, agentId: countedAgent.id, status: "failed", createdAt: at(5), startedAt: at(5), finishedAt: at(6), errorCode: "adapter_failed", resultJson: heavy },
|
||||
{ companyId: company.id, agentId: countedAgent.id, status: "failed", createdAt: at(9), startedAt: at(9), resultJson: heavy },
|
||||
{ companyId: other.id, agentId: otherAgent.id, status: "failed", createdAt: at(20) },
|
||||
])
|
||||
.returning();
|
||||
await db.insert(schema.issues).values([
|
||||
{ companyId: company.id, title: "Open", status: "todo" },
|
||||
{ companyId: company.id, title: "Shipped", status: "done" },
|
||||
{ companyId: other.id, title: "Not ours", status: "done" },
|
||||
]);
|
||||
|
||||
expect(
|
||||
await readCustomerSuccessResource(db, storage, { operation: "count", resource: "runs", companyId: company.id }),
|
||||
).toEqual({ total: 3, byStatus: { succeeded: 1, failed: 2 } });
|
||||
expect(
|
||||
await readCustomerSuccessResource(db, storage, { operation: "count", resource: "tasks", companyId: company.id }),
|
||||
).toEqual({ total: 2, byStatus: { todo: 1, done: 1 } });
|
||||
expect(
|
||||
await readCustomerSuccessResource(db, storage, {
|
||||
operation: "count",
|
||||
resource: "comments",
|
||||
companyId: company.id,
|
||||
}),
|
||||
).toEqual({ total: 0, byStatus: null });
|
||||
|
||||
const latest = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "list",
|
||||
resource: "runs",
|
||||
companyId: company.id,
|
||||
order: "newest",
|
||||
view: "summary",
|
||||
limit: 1,
|
||||
})) as { items: Array<Record<string, unknown>>; nextOffset: number | null };
|
||||
expect(latest.items.map((r) => r.id)).toEqual([runs[2].id]);
|
||||
expect(latest.nextOffset).toEqual(1);
|
||||
expect(Object.keys(latest.items[0]).sort()).toEqual([...RUN_SUMMARY_COLUMNS, "durationMs"].sort());
|
||||
expect(latest.items[0].durationMs).toBeNull();
|
||||
expect(JSON.stringify(latest).length).toBeLessThan(2_000);
|
||||
|
||||
const page = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "list",
|
||||
resource: "runs",
|
||||
companyId: company.id,
|
||||
order: "newest",
|
||||
view: "summary",
|
||||
limit: 2,
|
||||
offset: 1,
|
||||
})) as { items: Array<Record<string, unknown>> };
|
||||
expect(page.items.map((r) => [r.id, r.durationMs])).toEqual([
|
||||
[runs[1].id, 60_000],
|
||||
[runs[0].id, 120_000],
|
||||
]);
|
||||
const oldest = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "list",
|
||||
resource: "runs",
|
||||
companyId: company.id,
|
||||
order: "oldest",
|
||||
limit: 1,
|
||||
})) as { items: Array<Record<string, unknown>> };
|
||||
expect(oldest.items[0].id).toEqual(runs[0].id);
|
||||
expect(oldest.items[0]).toHaveProperty("resultJson");
|
||||
|
||||
const one = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "get",
|
||||
resource: "runs",
|
||||
companyId: company.id,
|
||||
resourceId: runs[1].id,
|
||||
view: "summary",
|
||||
})) as Record<string, unknown>;
|
||||
expect(one).toMatchObject({ id: runs[1].id, status: "failed", errorCode: "adapter_failed", durationMs: 60_000 });
|
||||
expect(one).not.toHaveProperty("resultJson");
|
||||
expect(one).not.toHaveProperty("contextSnapshot");
|
||||
});
|
||||
it("ordered pages cover rows that share a creation time exactly once", async () => {
|
||||
for (const resource of INSPECTION_RESOURCES)
|
||||
expect(primaryKeyColumns(inspectionReaders[resource].table).length, resource).toBeGreaterThan(0);
|
||||
const [company] = await db
|
||||
.insert(schema.companies)
|
||||
.values({ name: "Labelled", issuePrefix: "LBL" })
|
||||
.returning();
|
||||
const [issue] = await db.insert(schema.issues).values({ companyId: company.id, title: "Tagged" }).returning();
|
||||
const labels = await db
|
||||
.insert(schema.labels)
|
||||
.values(Array.from({ length: 5 }, (_, i) => ({ companyId: company.id, name: `label-${i}`, color: "#000000" })))
|
||||
.returning();
|
||||
const createdAt = new Date(Date.UTC(2026, 0, 2));
|
||||
await db
|
||||
.insert(schema.issueLabels)
|
||||
.values(labels.map((label) => ({ companyId: company.id, issueId: issue.id, labelId: label.id, createdAt })));
|
||||
for (const order of ["newest", "oldest"] as const) {
|
||||
const seen: string[] = [];
|
||||
for (let offset = 0; offset < labels.length; offset += 2) {
|
||||
const page = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "list",
|
||||
resource: "taskLabels",
|
||||
companyId: company.id,
|
||||
order,
|
||||
limit: 2,
|
||||
offset,
|
||||
})) as { items: Array<{ labelId: string }> };
|
||||
seen.push(...page.items.map((row) => row.labelId));
|
||||
}
|
||||
expect(seen.sort()).toEqual(labels.map((label) => label.id).sort());
|
||||
}
|
||||
});
|
||||
it("count, order and view are bounded and take the extended read path", () => {
|
||||
expect(inspectionReadPath(parseInspectionQuery({ operation: "list", resource: "runs", companyId }))).toEqual("/read");
|
||||
for (const value of [
|
||||
{ operation: "count", resource: "runs", companyId },
|
||||
{ operation: "list", resource: "runs", companyId, order: "newest" },
|
||||
{ operation: "get", resource: "runs", companyId, resourceId: agentId, view: "summary" },
|
||||
])
|
||||
expect(inspectionReadPath(parseInspectionQuery(value))).toEqual("/read-v2");
|
||||
for (const value of [
|
||||
{ operation: "count", companyId },
|
||||
{ operation: "count", resource: "runs" },
|
||||
{ operation: "count", resource: "runs", companyId, resourceId: agentId },
|
||||
{ operation: "get", resource: "runs", companyId, resourceId: agentId, order: "newest" },
|
||||
{ operation: "list", resource: "runs", companyId, order: "random" },
|
||||
{ operation: "list", resource: "tasks", companyId, view: "summary" },
|
||||
{ operation: "list", resource: "runs", companyId, view: "full" },
|
||||
{ operation: "runs.log", companyId, resourceId: agentId, view: "summary" },
|
||||
])
|
||||
expect(() => parseInspectionQuery(value)).toThrow();
|
||||
});
|
||||
it("the operation contract has no writes, credentials or unknown parameters", () => {
|
||||
for (const value of [
|
||||
{ operation: "write", companyId },
|
||||
|
||||
@@ -280,6 +280,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
const audit = await db.select().from(toolAccessAuditEvents).where(and(eq(toolAccessAuditEvents.companyId, f.company.id), eq(toolAccessAuditEvents.action, "call_completed")));
|
||||
expect(audit).toHaveLength(1);
|
||||
expect(JSON.stringify(audit[0])).toContain("Google Workspace REST");
|
||||
expect(JSON.stringify(audit[0])).not.toContain("mcpMethod");
|
||||
expect(JSON.stringify([invocation, audit])).not.toContain("workspace-access-1");
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import {
|
||||
agents,
|
||||
agentWakeupRequests,
|
||||
companies,
|
||||
completionContracts,
|
||||
createDb,
|
||||
heartbeatRuns,
|
||||
issueThreadInteractions,
|
||||
issues,
|
||||
statusDecisions,
|
||||
workspaceOperations,
|
||||
} from "@paperclipai/db";
|
||||
import { CONTROL_PLANE_CONFORMANCE_OPEN } from "../vendor/paperclip-runner/testing.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js";
|
||||
import { PaperclipControlPlanePort } from "../services/native-runtime/paperclip-control-plane-port.js";
|
||||
import { documentService } from "../services/documents.js";
|
||||
import { recoveryService } from "../services/recovery/service.js";
|
||||
|
||||
const cardFailure = vi.hoisted(() => ({ next: false }));
|
||||
vi.mock("../services/native-runtime/native-plan-review-card.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-review-card.js")>();
|
||||
return {
|
||||
...actual,
|
||||
ensureNativePlanReviewCard: async (...args: Parameters<typeof actual.ensureNativePlanReviewCard>) => {
|
||||
if (cardFailure.next) {
|
||||
cardFailure.next = false;
|
||||
throw new Error("connection reset while opening the card");
|
||||
}
|
||||
return actual.ensureNativePlanReviewCard(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const committedPlanWait = vi.hoisted(() => ({ runIds: new Set<string>() }));
|
||||
vi.mock("../services/native-runtime/native-plan-wait.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-wait.js")>();
|
||||
return {
|
||||
...actual,
|
||||
hasCommittedNativePlanWait: async (...args: Parameters<typeof actual.hasCommittedNativePlanWait>) =>
|
||||
committedPlanWait.runIds.has(args[1].runId) || actual.hasCommittedNativePlanWait(...args),
|
||||
};
|
||||
});
|
||||
|
||||
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_FINALIZER_TEST_DATABASE_URL");
|
||||
|
||||
// The live failure: the Antigravity process was killed mid Plan-mode run; the
|
||||
// automatic continuation wrote a new plan revision and yielded "waiting for
|
||||
// plan review" without opening the Approve / Request changes card. The task
|
||||
// sat in progress with nothing for the user to act on.
|
||||
describe("Plan-mode run settle opens the plan review", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const companyId = "72300000-0000-4000-8000-000000000001";
|
||||
const agentId = "72300000-0000-4000-8000-000000000002";
|
||||
let seq = 0;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!external) temporary = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-finalizer-");
|
||||
db = createDb(external ?? temporary.connectionString);
|
||||
await db.insert(companies).values({ id: companyId, name: "Plan review", issuePrefix: "PRF" });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Gemma Antigravity", adapterType: "antigravity_local", status: "running" });
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end({ timeout: 1 });
|
||||
await temporary?.cleanup();
|
||||
});
|
||||
|
||||
const yielded = {
|
||||
schema: "paperclip.run_result.v1" as const,
|
||||
reportedWorkDisposition: "yielded" as const,
|
||||
summary: "Saved the plan. Waiting for plan review before executing.",
|
||||
completionClaim: {
|
||||
contractRevision: "plan-v1", objectiveSatisfied: false,
|
||||
criteria: [{ criterionId: "objective", status: "unknown" as const, evidenceRefs: [] }],
|
||||
remainingWork: [],
|
||||
},
|
||||
evidence: [], verification: [], attentionRequests: [], artifacts: [],
|
||||
continuation: { kind: "response_wake" as const, summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
|
||||
};
|
||||
|
||||
async function settleRun(options: { workMode: "planning" | "standard"; writePlan: boolean }) {
|
||||
seq += 1;
|
||||
const id = (n: number) => `72300000-0000-4000-8${String(seq).padStart(3, "0")}-${String(n).padStart(12, "0")}`;
|
||||
const issueId = id(1), contractId = id(2), runId = id(3);
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: `Plan ${seq}`, status: "in_progress",
|
||||
assigneeAgentId: agentId, workMode: options.workMode });
|
||||
await db.insert(completionContracts).values({
|
||||
id: contractId, companyId, issueId, revision: 1,
|
||||
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "phase6-v1", risk: "standard",
|
||||
completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal",
|
||||
contractJson: { revision: "plan-v1", objective: "Plan the file",
|
||||
criteria: [{ id: "objective", requirement: "The plan is approved" }] },
|
||||
canonicalSha256: `plan-contract-${seq}`, createdByActorType: "system", createdByActorId: "test",
|
||||
});
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: runId, companyId, agentId, status: "running", runtimeMode: "native",
|
||||
runtimeModeReason: "persisted_before_kill_switch", nativeIssueId: issueId, nativeSessionId: runId,
|
||||
runnerInstanceId: contractId, completionContractId: contractId,
|
||||
completionContractSha256: `plan-contract-${seq}`, contextSnapshot: { issueId },
|
||||
});
|
||||
if (options.writePlan) {
|
||||
await documentService(db).upsertIssueDocument({ issueId, key: "plan", title: "Plan", format: "markdown",
|
||||
body: "# Create crash-proof.txt\n\n1. Write CRASH.", createdByAgentId: agentId, createdByRunId: runId });
|
||||
}
|
||||
const port = new PaperclipControlPlanePort(db, {
|
||||
companyId, issueId, runId, agentId, sessionId: runId, completionContractId: contractId,
|
||||
completionContractSha256: `plan-contract-${seq}`, sourceInstanceId: contractId,
|
||||
controlPlaneSourceInstanceId: `plan-control-${seq}`,
|
||||
});
|
||||
await port.openRun({ ...CONTROL_PLANE_CONFORMANCE_OPEN,
|
||||
identity: { companyId, issueId, runId, agentId, sessionId: runId }, sourceInstanceId: contractId });
|
||||
await port.completeRun({ result: yielded, terminal: { schema: "paperclip.prp.terminal.v1",
|
||||
turnTerminalState: "completed", runTerminalState: "succeeded", reportedWorkDisposition: "yielded" },
|
||||
callerResultId: `plan-result-${seq}` });
|
||||
await db.insert(workspaceOperations).values({ companyId, heartbeatRunId: runId, issueId,
|
||||
phase: "workspace_finalize", status: "succeeded" });
|
||||
await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.id, issue!.lastStatusDecisionId!));
|
||||
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issueId));
|
||||
const wakes = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
|
||||
eq(agentWakeupRequests.agentId, agentId)));
|
||||
return { issueId, runId, issue: issue!, decision: decision!, cards,
|
||||
wakes: wakes.filter(wake => JSON.stringify(wake.payload ?? {}).includes(issueId)) };
|
||||
}
|
||||
|
||||
it("opens one review card for the new plan revision and waits on it", async () => {
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: true });
|
||||
|
||||
expect(settled.cards).toHaveLength(1);
|
||||
expect(settled.cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending", sourceRunId: settled.runId });
|
||||
expect(settled.cards[0]!.payload).toMatchObject({ target: { type: "issue_document", key: "plan", revisionNumber: 1 } });
|
||||
expect(settled.issue.status).toBe("in_review");
|
||||
expect(settled.decision.reasonCode).toBe("governed_response_waiting");
|
||||
});
|
||||
|
||||
it("asks the agent for its plan when a Plan-mode run yields with none", async () => {
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: false });
|
||||
|
||||
expect(settled.cards).toHaveLength(0);
|
||||
expect(settled.decision.reasonCode).toBe("plan_mode_plan_not_produced");
|
||||
expect(settled.wakes.some(wake => JSON.stringify(wake.payload).includes("Plan mode"))).toBe(true);
|
||||
});
|
||||
|
||||
it("gives a task left without its card by an older release one on the next recovery pass", async () => {
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: true });
|
||||
// The state an older release left: settled, waiting, no card.
|
||||
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
|
||||
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
|
||||
const enqueueWakeup = vi.fn(async () => null);
|
||||
const recovery = recoveryService(db, { enqueueWakeup });
|
||||
|
||||
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
|
||||
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
|
||||
|
||||
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending" });
|
||||
expect(enqueueWakeup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("settles the run when opening the card fails, and the next recovery pass opens it", async () => {
|
||||
cardFailure.next = true;
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: true });
|
||||
|
||||
expect(settled.cards).toHaveLength(0);
|
||||
expect(settled.issue.status).toBe("in_progress");
|
||||
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
|
||||
expect(run).toMatchObject({ status: "succeeded" });
|
||||
|
||||
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
|
||||
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
|
||||
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
|
||||
expect(cards).toEqual([expect.objectContaining({ kind: "request_confirmation", status: "pending" })]);
|
||||
});
|
||||
|
||||
it.each(["finalization reason", "committed plan wait"])("never opens a second card for a plan the user already accepted (%s)", async (proof) => {
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: true });
|
||||
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
|
||||
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
|
||||
if (proof === "finalization reason") {
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
|
||||
await db.update(heartbeatRuns).set({ resultJson: { ...(run!.resultJson as Record<string, unknown>),
|
||||
finalizationReasonCode: "native_plan_accepted_waiting_for_continuation" } }).where(eq(heartbeatRuns.id, settled.runId));
|
||||
} else committedPlanWait.runIds.add(settled.runId);
|
||||
|
||||
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
|
||||
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
|
||||
|
||||
expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("leaves a Standard-mode response wait unchanged", async () => {
|
||||
const settled = await settleRun({ workMode: "standard", writePlan: true });
|
||||
|
||||
expect(settled.cards).toHaveLength(0);
|
||||
expect(settled.issue.status).toBe("in_progress");
|
||||
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,543 @@
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
companies,
|
||||
createDb,
|
||||
documentRevisions,
|
||||
documents,
|
||||
goals,
|
||||
heartbeatRuns,
|
||||
issueComments,
|
||||
issueDocuments,
|
||||
issueThreadInteractions,
|
||||
issues,
|
||||
} from "@paperclipai/db";
|
||||
import { ensureNativePlanReviewCard, planReviewCardIdempotencyKey } from "../services/native-runtime/native-plan-review-card.js";
|
||||
import { synchronizeCompletedProviderPlan } from "../services/native-runtime/native-session-executor.js";
|
||||
import { documentService } from "../services/documents.js";
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
|
||||
// Lets a test hand the card function the document as it was read before a
|
||||
// newer revision landed: the window a delayed settle runs in.
|
||||
const staleRead = vi.hoisted(() => ({ next: null as unknown }));
|
||||
vi.mock("../services/documents.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/documents.js")>();
|
||||
return {
|
||||
...actual,
|
||||
documentService: (db: Parameters<typeof actual.documentService>[0]) => {
|
||||
const service = actual.documentService(db);
|
||||
return {
|
||||
...service,
|
||||
getIssueDocumentByKey: async (...args: Parameters<typeof service.getIssueDocumentByKey>) => {
|
||||
if (staleRead.next) {
|
||||
const snapshot = staleRead.next;
|
||||
staleRead.next = null;
|
||||
return snapshot as Awaited<ReturnType<typeof service.getIssueDocumentByKey>>;
|
||||
}
|
||||
return service.getIssueDocumentByKey(...args);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_CARD_TEST_DATABASE_URL");
|
||||
const embeddedPostgresSupport = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
const PLAN = "# Create crash-proof.txt\n\n1. Write the file.\n2. Verify it.";
|
||||
|
||||
// Harnesses without a provider plan event (Antigravity and other ACPX agents)
|
||||
// write the Plan document with a tool. A Plan-mode run that settles without
|
||||
// opening the review card — for example a run recovered after its process was
|
||||
// killed — must not leave the task waiting on a review nobody can give.
|
||||
describeEmbeddedPostgres("Plan-mode review card on settle", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!external) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-card-");
|
||||
db = createDb(external ?? tempDb!.connectionString, { maxConnections: 6 });
|
||||
}, 20_000);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(activityLog);
|
||||
await db.delete(issueComments);
|
||||
await db.delete(issueThreadInteractions);
|
||||
await db.delete(issueDocuments);
|
||||
await db.delete(documentRevisions);
|
||||
await db.delete(documents);
|
||||
await db.delete(heartbeatRuns);
|
||||
await db.delete(issues);
|
||||
await db.delete(goals);
|
||||
await db.delete(agents);
|
||||
await db.delete(companies);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end({ timeout: 1 });
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
let prefix = 0;
|
||||
async function seed(workMode: "standard" | "planning" = "planning", options: { conversation?: boolean } = {}) {
|
||||
const companyId = randomUUID();
|
||||
const goalId = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: `PRC${++prefix}`, requireBoardApprovalForNewAgents: false });
|
||||
await db.insert(goals).values({ id: goalId, companyId, title: "Ship", level: "task", status: "active" });
|
||||
await db.insert(agents).values({
|
||||
id: agentId, companyId, name: "Gemma", role: "engineer", status: "active",
|
||||
adapterType: "antigravity_local", adapterConfig: {}, runtimeConfig: {}, permissions: {},
|
||||
});
|
||||
await db.insert(issues).values({
|
||||
id: issueId, companyId, goalId, title: "Create crash-proof.txt", status: "in_progress",
|
||||
priority: "medium", assigneeAgentId: agentId, workMode,
|
||||
...(options.conversation ? { conversationAgentId: agentId, conversationUserId: "local-board", conversationState: "active" } : {}),
|
||||
});
|
||||
const newRun = async () => {
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "succeeded", contextSnapshot: { issueId } });
|
||||
return runId;
|
||||
};
|
||||
const binding = (runId: string) => ({ companyId, issueId, agentId, runId });
|
||||
const writePlan = async (runId: string, body = PLAN) => documentService(db).upsertIssueDocument({
|
||||
issueId, key: "plan", title: "Plan", format: "markdown", body,
|
||||
baseRevisionId: (await documentService(db).getIssueDocumentByKey(issueId, "plan"))?.latestRevisionId ?? undefined,
|
||||
createdByAgentId: agentId, createdByRunId: runId,
|
||||
} as never);
|
||||
const cards = () => db.select().from(issueThreadInteractions)
|
||||
.where(and(eq(issueThreadInteractions.issueId, issueId), eq(issueThreadInteractions.kind, "request_confirmation")));
|
||||
return { companyId, issueId, agentId, newRun, binding, writePlan, cards };
|
||||
}
|
||||
|
||||
it("opens exactly one review card for a recovered run's new plan revision", async () => {
|
||||
const t = await seed();
|
||||
await t.newRun(); // the killed run
|
||||
const recovered = await t.newRun();
|
||||
await t.writePlan(recovered);
|
||||
|
||||
const outcome = await ensureNativePlanReviewCard(db, t.binding(recovered));
|
||||
|
||||
expect(outcome.kind).toBe("created");
|
||||
const cards = await t.cards();
|
||||
expect(cards).toHaveLength(1);
|
||||
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
expect(cards[0]).toMatchObject({ status: "pending", sourceRunId: recovered, createdByAgentId: t.agentId });
|
||||
expect(cards[0]!.payload).toMatchObject({
|
||||
acceptLabel: "Approve plan", rejectLabel: "Request changes",
|
||||
target: { type: "issue_document", key: "plan", revisionId: plan!.latestRevisionId, revisionNumber: 1 },
|
||||
});
|
||||
const activity = await db.select().from(activityLog).where(eq(activityLog.entityId, t.issueId));
|
||||
expect(activity).toEqual([expect.objectContaining({ action: "issue.thread_interaction_created", actorType: "system" })]);
|
||||
});
|
||||
|
||||
// The agent's plan card opened as instructed: bound to the saved plan revision.
|
||||
async function agentPlanCard(t: Awaited<ReturnType<typeof seed>>, runId: string, key: string) {
|
||||
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
return issueThreadInteractionService(db).create({ id: t.issueId, companyId: t.companyId }, {
|
||||
kind: "request_confirmation", idempotencyKey: key, sourceRunId: runId, continuationPolicy: "wake_assignee",
|
||||
payload: { version: 1, prompt: "Approve the plan?", acceptLabel: "Approve plan", rejectLabel: "Request changes",
|
||||
target: { type: "issue_document", issueId: t.issueId, documentId: plan!.id, key: "plan",
|
||||
revisionId: plan!.latestRevisionId, revisionNumber: plan!.latestRevisionNumber } },
|
||||
} as never, { agentId: t.agentId, runId });
|
||||
}
|
||||
const plainCard = (t: Awaited<ReturnType<typeof seed>>, runId: string, key: string, prompt: string) =>
|
||||
issueThreadInteractionService(db).create({ id: t.issueId, companyId: t.companyId }, {
|
||||
kind: "request_confirmation", idempotencyKey: key, sourceRunId: runId, continuationPolicy: "wake_assignee_on_accept",
|
||||
payload: { version: 1, prompt, acceptLabel: "Confirm", rejectLabel: "Request changes" },
|
||||
} as never, { agentId: t.agentId, runId });
|
||||
|
||||
it("does nothing when the agent already opened its plan card for the revision", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await t.writePlan(runId);
|
||||
await agentPlanCard(t, runId, "confirm-plan-v1");
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "pending" });
|
||||
expect(await t.cards()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps one card across repeated and concurrent settles of the same and later runs", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await t.writePlan(runId);
|
||||
const reconcileRun = await t.newRun();
|
||||
|
||||
const outcomes = await Promise.all([
|
||||
ensureNativePlanReviewCard(db, t.binding(runId)),
|
||||
ensureNativePlanReviewCard(db, t.binding(runId)),
|
||||
ensureNativePlanReviewCard(db, t.binding(reconcileRun)),
|
||||
]);
|
||||
await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
await ensureNativePlanReviewCard(db, t.binding(reconcileRun));
|
||||
|
||||
expect(outcomes.filter(outcome => outcome.kind === "created")).toHaveLength(1);
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, t.issueId))).toHaveLength(1);
|
||||
const cards = await t.cards();
|
||||
expect(cards.filter(card => card.status === "pending")).toHaveLength(1);
|
||||
expect(cards).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("opens a new card for the revision written after Request changes and leaves the old one unanswerable", async () => {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
const created = await ensureNativePlanReviewCard(db, t.binding(first));
|
||||
if (created.kind !== "created") throw new Error("expected a card");
|
||||
const interactions = issueThreadInteractionService(db);
|
||||
const [oldCard] = await t.cards();
|
||||
await interactions.rejectInteraction(
|
||||
{ id: t.issueId, companyId: t.companyId }, oldCard!.id,
|
||||
{ reason: "Name the file crash-proof-2.txt" } as never, { userId: "local-board" } as never,
|
||||
);
|
||||
|
||||
// Request changes answered this revision: nothing new until the agent revises.
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "reviewed" });
|
||||
|
||||
const second = await t.newRun();
|
||||
await t.writePlan(second, `${PLAN}\n3. Use crash-proof-2.txt.`);
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
const cards = await t.cards();
|
||||
expect(cards).toHaveLength(2);
|
||||
const pending = cards.filter(card => card.status === "pending");
|
||||
expect(pending).toHaveLength(1);
|
||||
expect(pending[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
|
||||
expect(cards.find(card => card.id === oldCard!.id)?.status).toBe("rejected");
|
||||
});
|
||||
|
||||
it("replaces a still-pending card for an older revision", async () => {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
await ensureNativePlanReviewCard(db, t.binding(first));
|
||||
const [oldCard] = await t.cards();
|
||||
const second = await t.newRun();
|
||||
await t.writePlan(second, `${PLAN}\n3. Revised.`);
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
const cards = await t.cards();
|
||||
expect(cards.find(card => card.id === oldCard!.id)?.status).toBe("expired");
|
||||
expect(cards.filter(card => card.status === "pending")).toHaveLength(1);
|
||||
await expect(interactionsAccept(t, oldCard!.id)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("never withdraws a newer revision's card from a delayed settle of an older one", async () => {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
const revisionOne = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
const second = await t.newRun();
|
||||
await t.writePlan(second, `${PLAN}\n3. Revised.`);
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
// The first run's settle read revision 1 before revision 2 landed.
|
||||
staleRead.next = revisionOne;
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "not_applicable" });
|
||||
|
||||
const cards = await t.cards();
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]).toMatchObject({ status: "pending" });
|
||||
expect(cards[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
|
||||
});
|
||||
|
||||
it("withdraws the agent's plan card for v1 when a recovered run writes v2, leaving one answerable card", async () => {
|
||||
const t = await seed();
|
||||
const crashed = await t.newRun();
|
||||
await t.writePlan(crashed);
|
||||
const v1 = await agentPlanCard(t, crashed, "own-v1");
|
||||
const recovered = await t.newRun();
|
||||
await t.writePlan(recovered, `${PLAN}\n3. Revised after recovery.`);
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(recovered))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
const pending = (await t.cards()).filter(card => card.status === "pending");
|
||||
expect(pending).toHaveLength(1);
|
||||
expect(pending[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
|
||||
await expect(interactionsAccept(t, v1.id)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("keeps an unrelated confirmation opened after the plan ordinary: answering it never approves the plan", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await t.writePlan(runId);
|
||||
const unrelated = await plainCard(t, runId, "rename-repo", "May I rename the repository?");
|
||||
expect((unrelated.payload as { target?: unknown }).target).toBeUndefined();
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "created" });
|
||||
await interactionsAccept(t, unrelated.id);
|
||||
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, t.issueId));
|
||||
expect(issue!.workMode).toBe("planning");
|
||||
const planCards = (await t.cards()).filter(card => (card.payload as { target?: { key?: string } }).target?.key === "plan");
|
||||
expect(planCards).toEqual([expect.objectContaining({ status: "pending" })]);
|
||||
});
|
||||
|
||||
it("leaves a card opened before plan binding existed answerable, and still opens the current plan's card", async () => {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
// A row an older release saved: the agent's plan card with no target.
|
||||
const [legacy] = await db.insert(issueThreadInteractions).values({
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: "pending",
|
||||
continuationPolicy: "wake_assignee_on_accept", sourceRunId: first, createdByAgentId: t.agentId,
|
||||
payload: { version: 1, prompt: "Proceed with plan v1?", acceptLabel: "Confirm", rejectLabel: "Request changes" },
|
||||
}).returning();
|
||||
const second = await t.newRun();
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
await t.writePlan(second, `${PLAN}\n3. Revised.`);
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
const cards = await t.cards();
|
||||
// Not withdrawn by guess; its answer reaches the agent as an ordinary confirmation.
|
||||
expect(cards.find(card => card.id === legacy!.id)?.status).toBe("pending");
|
||||
expect(cards.filter(card => card.status === "pending" &&
|
||||
(card.payload as { target?: { revisionNumber?: number } }).target?.revisionNumber === 2)).toHaveLength(1);
|
||||
// Accepting the old card does not approve the newer revision.
|
||||
await interactionsAccept(t, legacy!.id);
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, t.issueId));
|
||||
expect(issue!.workMode).toBe("planning");
|
||||
expect((await t.cards()).filter(card => card.status === "pending")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(["server", "agent"])("keeps run A's pending %s plan card as the gate when run B settles a Plan-mode conversation", async (opener) => {
|
||||
const t = await seed("planning", { conversation: true });
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
if (opener === "server") await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "created" });
|
||||
else await agentPlanCard(t, first, "conversation-plan");
|
||||
const second = await t.newRun();
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "pending" });
|
||||
expect((await t.cards()).filter(card => card.status === "pending")).toHaveLength(1);
|
||||
});
|
||||
|
||||
async function interactionsAccept(t: Awaited<ReturnType<typeof seed>>, id: string) {
|
||||
return issueThreadInteractionService(db).acceptInteraction(
|
||||
{ id: t.issueId, companyId: t.companyId, projectId: null, goalId: null }, id, {} as never, { userId: "local-board" } as never,
|
||||
);
|
||||
}
|
||||
|
||||
it("returns the original card for an identical retry after a plan revision landed", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
const first = await plainCard(t, runId, "retry-key", "May I proceed?");
|
||||
// The response was lost; meanwhile the agent saved its plan.
|
||||
await t.writePlan(runId);
|
||||
|
||||
const retried = await plainCard(t, runId, "retry-key", "May I proceed?");
|
||||
expect(retried.id).toBe(first.id);
|
||||
});
|
||||
|
||||
it("reports a Plan-mode run with no plan, and leaves Standard tasks untouched", async () => {
|
||||
const planning = await seed();
|
||||
const runId = await planning.newRun();
|
||||
await expect(ensureNativePlanReviewCard(db, planning.binding(runId))).resolves.toEqual({ kind: "no_plan" });
|
||||
expect(await planning.cards()).toHaveLength(0);
|
||||
|
||||
const standard = await seed("standard");
|
||||
const standardRun = await standard.newRun();
|
||||
await standard.writePlan(standardRun);
|
||||
await expect(ensureNativePlanReviewCard(db, standard.binding(standardRun))).resolves.toEqual({ kind: "not_applicable" });
|
||||
expect(await standard.cards()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("leaves the card Codex and Claude open from their plan event as the only card", async () => {
|
||||
const t = await seed();
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: t.companyId, agentId: t.agentId, status: "running", contextSnapshot: { issueId: t.issueId } });
|
||||
const synced = await synchronizeCompletedProviderPlan({
|
||||
db,
|
||||
execution: {
|
||||
binding: t.binding(runId), provider: { kind: "codex" }, task: { workMode: "planning" }, executionMode: "plan",
|
||||
planningContext: { documentId: null, baseRevisionId: null, baseRevisionNumber: 0, markdown: "", sha256: "none", reviewContext: {} },
|
||||
} as never,
|
||||
event: { sourceEventId: "event-1", turnId: "turn-1", eventType: "plan.proposed",
|
||||
payload: { schema: "paperclip.plan.proposed.v1", proposalId: "plan-1", status: "completed", markdown: PLAN, source: "codex" } },
|
||||
});
|
||||
expect(synced).toMatchObject({ status: "synchronized" });
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "pending", interactionId: synced!.confirmationId });
|
||||
expect(await t.cards()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not put a person's own plan edit up for review", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await documentService(db).upsertIssueDocument({
|
||||
issueId: t.issueId, key: "plan", title: "Plan", format: "markdown", body: "# My plan", createdByUserId: "local-board",
|
||||
});
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toEqual({ kind: "not_applicable" });
|
||||
expect(await t.cards()).toHaveLength(0);
|
||||
});
|
||||
// Each way a Plan-mode run can leave the task, and the one current action
|
||||
// the user gets: a review card for the revision, or (no plan / already
|
||||
// answered) the arbiter's "save your plan" continuation.
|
||||
type Scenario = { name: string; setup: (t: Awaited<ReturnType<typeof seed>>, runId: string) => Promise<void>;
|
||||
kind: "created" | "pending" | "reviewed" | "no_plan" };
|
||||
const question = async (t: Awaited<ReturnType<typeof seed>>, runId: string) => {
|
||||
const [row] = await db.insert(issueThreadInteractions).values({
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "ask_user_questions", status: "pending",
|
||||
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
|
||||
payload: { version: 1, questions: [{ id: "q1", prompt: "Which name?", selectionMode: "single",
|
||||
options: [{ id: "a", label: "A" }] }] },
|
||||
}).returning();
|
||||
return row!;
|
||||
};
|
||||
const scenarios: Scenario[] = [
|
||||
{ name: "no plan saved", setup: async () => {}, kind: "no_plan" },
|
||||
{ name: "plan saved, agent opened no card (first run or recovered run)", setup: async (t, runId) => { await t.writePlan(runId); }, kind: "created" },
|
||||
{ name: "plan saved, agent opened its plan card bound to the revision", setup: async (t, runId) => {
|
||||
await t.writePlan(runId); await agentPlanCard(t, runId, `own-${runId}`);
|
||||
}, kind: "pending" },
|
||||
{ name: "plan saved, agent opened an unbound confirmation (ordinary, not a plan review)", setup: async (t, runId) => {
|
||||
await t.writePlan(runId); await plainCard(t, runId, `plain-${runId}`, "Proceed?");
|
||||
}, kind: "created" },
|
||||
{ name: "plan saved, agent asked a current question", setup: async (t, runId) => {
|
||||
await t.writePlan(runId); await question(t, runId);
|
||||
}, kind: "pending" },
|
||||
{ name: "plan saved, an older question a later comment made historical", setup: async (t, runId) => {
|
||||
await question(t, runId);
|
||||
await db.insert(issueComments).values({ companyId: t.companyId, issueId: t.issueId, authorType: "user",
|
||||
authorUserId: "local-board", body: "Use A.", createdAt: new Date(Date.now() + 1_000) });
|
||||
await t.writePlan(runId);
|
||||
}, kind: "created" },
|
||||
{ name: "plan saved, an older question the user dismissed", setup: async (t, runId) => {
|
||||
const row = await question(t, runId);
|
||||
await db.update(issueThreadInteractions).set({ dismissedAt: new Date(), dismissedByUserId: "local-board" })
|
||||
.where(eq(issueThreadInteractions.id, row.id));
|
||||
await t.writePlan(runId);
|
||||
}, kind: "created" },
|
||||
...(["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"] as const).flatMap(key =>
|
||||
(["pending", "accepted", "rejected"] as const).map((status): Scenario => ({
|
||||
name: `plan saved, an unrelated ${key} card (${status}) opened after it`,
|
||||
setup: async (t, runId) => {
|
||||
await t.writePlan(runId);
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status,
|
||||
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
|
||||
payload: { version: 1, prompt: "Allow this?", [key]: { id: "governed" } },
|
||||
});
|
||||
},
|
||||
kind: "created",
|
||||
}))),
|
||||
{ name: "plan saved, a confirmation someone else opened after it", setup: async (t, runId) => {
|
||||
await t.writePlan(runId);
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: "rejected",
|
||||
continuationPolicy: "none", createdByUserId: "local-board",
|
||||
payload: { version: 1, prompt: "Unrelated?" },
|
||||
});
|
||||
}, kind: "created" },
|
||||
{ name: "revision already answered with Request changes, no new revision", setup: async (t, runId) => {
|
||||
await t.writePlan(runId);
|
||||
await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
const [card] = await t.cards();
|
||||
await issueThreadInteractionService(db).rejectInteraction({ id: t.issueId, companyId: t.companyId }, card!.id,
|
||||
{ reason: "Rename it" } as never, { userId: "local-board" } as never);
|
||||
}, kind: "reviewed" },
|
||||
{ name: "new revision after Request changes", setup: async (t, runId) => {
|
||||
await t.writePlan(runId);
|
||||
await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
const [card] = await t.cards();
|
||||
await issueThreadInteractionService(db).rejectInteraction({ id: t.issueId, companyId: t.companyId }, card!.id,
|
||||
{ reason: "Rename it" } as never, { userId: "local-board" } as never);
|
||||
await t.writePlan(runId, `${PLAN}\n3. Renamed.`);
|
||||
}, kind: "created" },
|
||||
];
|
||||
|
||||
it.each(scenarios)("$name", async ({ setup, kind }) => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await setup(t, runId);
|
||||
|
||||
const outcome = await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
expect(outcome.kind).toBe(kind);
|
||||
// A repeat settle changes nothing, and at most one review card is pending.
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({
|
||||
kind: kind === "created" ? "pending" : kind });
|
||||
const planReviews = (await t.cards()).filter(card => card.status === "pending" &&
|
||||
(card.payload as { target?: { key?: string } }).target?.key === "plan");
|
||||
expect(planReviews.length).toBeLessThanOrEqual(1);
|
||||
if (kind === "created") expect(planReviews).toHaveLength(1);
|
||||
});
|
||||
// Every state the current revision's own plan card can reach, and what the
|
||||
// user is left with: a current card, or (they decided) the agent's bounded
|
||||
// "revise your plan" continuation. Never a silent wait, never a second card
|
||||
// for a plan the user already accepted.
|
||||
type CardState = { status: string; by?: "user" | "agent" | "system"; dismissed?: boolean; laterComment?: boolean;
|
||||
outcome: "pending" | "reviewed" | "created" };
|
||||
const cardStates: CardState[] = [
|
||||
{ status: "pending", outcome: "pending" },
|
||||
{ status: "pending", dismissed: true, outcome: "pending" },
|
||||
{ status: "pending", laterComment: true, outcome: "pending" },
|
||||
{ status: "accepted", by: "user", outcome: "reviewed" },
|
||||
{ status: "rejected", by: "user", outcome: "reviewed" },
|
||||
{ status: "cancelled", by: "user", outcome: "reviewed" },
|
||||
{ status: "cancelled", by: "agent", outcome: "created" },
|
||||
{ status: "expired", by: "system", outcome: "created" },
|
||||
{ status: "expired", by: "agent", outcome: "created" },
|
||||
{ status: "failed", by: "system", outcome: "created" },
|
||||
];
|
||||
it.each(cardStates)("current revision's card $status (by $by, dismissed $dismissed, later comment $laterComment) -> $outcome",
|
||||
async ({ status, by, dismissed, laterComment, outcome }) => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await t.writePlan(runId);
|
||||
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
const resolved = status !== "pending";
|
||||
const [card] = await db.insert(issueThreadInteractions).values(<typeof issueThreadInteractions.$inferInsert>{
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: status as never,
|
||||
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
|
||||
idempotencyKey: planReviewCardIdempotencyKey(plan!.latestRevisionId!),
|
||||
payload: { version: 1, prompt: "Approve plan revision 1?", acceptLabel: "Approve plan", rejectLabel: "Request changes",
|
||||
target: { type: "issue_document", issueId: t.issueId, documentId: plan!.id, key: "plan",
|
||||
revisionId: plan!.latestRevisionId, revisionNumber: 1 } },
|
||||
...(resolved ? { resolvedAt: new Date(),
|
||||
resolvedByUserId: by === "user" ? "local-board" : null,
|
||||
resolvedByAgentId: by === "agent" ? t.agentId : null } : {}),
|
||||
...(dismissed ? { dismissedAt: new Date(), dismissedByUserId: "local-board" } : {}),
|
||||
}).returning();
|
||||
if (laterComment) await db.insert(issueComments).values({ companyId: t.companyId, issueId: t.issueId, authorType: "user",
|
||||
authorUserId: "local-board", body: "Looking now.", createdAt: new Date(Date.now() + 1_000) });
|
||||
|
||||
const first = await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
expect(first.kind).toBe(outcome);
|
||||
const again = await ensureNativePlanReviewCard(db, t.binding(await t.newRun()));
|
||||
expect(again.kind).toBe(outcome === "created" ? "pending" : outcome);
|
||||
const pending = (await t.cards()).filter(row => row.status === "pending");
|
||||
if (outcome === "reviewed") expect(pending).toHaveLength(0);
|
||||
else expect(pending).toHaveLength(1);
|
||||
if (outcome === "created") expect(pending[0]!.id).not.toBe(card!.id);
|
||||
});
|
||||
it("opens exactly one card for the current revision when settles race across a revision change", async () => {
|
||||
for (let round = 0; round < 15; round += 1) {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
await ensureNativePlanReviewCard(db, t.binding(first));
|
||||
const second = await t.newRun();
|
||||
await t.writePlan(second, `${PLAN}\n3. Round ${round}.`);
|
||||
const runs = await Promise.all([t.newRun(), t.newRun(), t.newRun()]);
|
||||
|
||||
await Promise.all([second, ...runs].map(runId => ensureNativePlanReviewCard(db, t.binding(runId))));
|
||||
|
||||
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
const pending = (await t.cards()).filter(card => card.status === "pending");
|
||||
expect(pending).toHaveLength(1);
|
||||
expect(pending[0]!.payload).toMatchObject({ target: { revisionId: plan!.latestRevisionId } });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -153,6 +153,7 @@ const explicitOpenApiOperationCoverageExclusions = new Set([
|
||||
// Ordinary board sessions and agent API keys cannot invoke these endpoints.
|
||||
"GET /api/customer-success/v1/run-authority",
|
||||
"POST /api/customer-success/v1/read",
|
||||
"POST /api/customer-success/v1/read-v2",
|
||||
"POST /api/customer-success/v1/run-liveness",
|
||||
// OAuth discovery and protocol endpoints have their own metadata contract;
|
||||
// browser connection-management operations remain documented in the board API.
|
||||
|
||||
Reference in new issue
Block a user