From 28aa32e7d7ba72d8f83c03ffd45625c096813e6b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:32:12 -0600 Subject: [PATCH 1/9] fix(plan-mode): open the plan review card when a Plan-mode run settles without one (#22732) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plan mode makes an agent write a plan document. The user then approves the plan or requests changes on a review card. After approval, the agent does the work on the same task. > - For Codex and Claude, the agent session reports the plan as a provider event. Paperclip opens the review card from that event. > - Google Antigravity and other ACPX agents have no such event. They write the plan with a tool, and they must open the review card with another tool. > - When the agent does not open the card, the run settles as "waiting for a response" and the task shows no action. This happened in a live run: the Antigravity process was stopped during a Plan-mode run, and the automatic continuation wrote a new plan revision but did not open the card. > - This pull request makes the server open the review card when a Plan-mode run settles with a plan revision that has no review card. It does this for every harness. > - The benefit is that a Plan-mode task always shows the user the next action, also after a crash or restart. ## Linked Issues or Issue Description Refs #22727 **What happened?** A Google Antigravity agent ran a task in Plan mode. The agent process was stopped during the run. Paperclip continued the run automatically. The new run wrote a new plan revision and finished with "waiting for plan review". It did not open the Approve / Request changes card. The task stayed in progress with no action for the user. **Expected behavior** When a Plan-mode run settles with a new plan revision, the user sees exactly one review card for that revision. Retries, restarts and duplicate settles do not add more cards. A Plan-mode run that produces no plan does not leave the task waiting with no action. **Steps to reproduce** 1. Assign a task to an Antigravity agent in Plan mode. 2. Stop the agent process while the run is in progress. 3. Let Paperclip continue the run automatically. 4. See that the continuation writes the plan but no review card opens. **Paperclip version or commit** master at 18aa2b353d. ## What Changed - New `server/src/services/native-runtime/native-plan-review-card.ts`. It opens the Plan-mode review card for the current plan revision, unless an explicit plan review already covers it. Only a card bound to the plan revision is a plan review: the server card, the Codex/Claude card, or an agent card opened with the plan target. A confirmation without a plan target is an ordinary request: it never covers a revision, never starts execution and is never withdrawn by this logic. Per state of the revision's card: pending is the gate; accepted, rejected, or withdrawn by the user count as the user's decision (the agent is asked once to revise); withdrawn by an agent or the system, expired or failed get a fresh card. The idempotency key is bound to the revision (and to the card it replaces), so concurrent settles open one card. Cards bound to an older revision are withdrawn after re-reading the plan under a lock. One card builder serves this and the Codex/Claude plan cards. A revision that a person wrote is not put up for review. The call that inserts the card logs it in the activity log. - `heartbeat/task-markdown.ts`: the native Plan-mode directive says Paperclip asks the user to approve the saved plan, so the agent does not open its own card. This keeps the common case at one card. - `native-run-finalizer.ts`: when a Plan-mode run settles successfully and does not report done, the finalizer calls the new function before it reads the governance gate. If the card cannot be opened, the run still settles (the error is logged) and the recovery pass opens the card later. The new card then becomes the gate, and the task waits in review on it (`governed_response_waiting`), as for Codex and Claude. - `plan-mode-status.ts` + `status-arbiter.ts`: a Plan-mode run (assigned or started by a comment) that yields a response wait with no plan to review (no plan, or the current revision already answered) no longer settles as a silent wait. The agent gets one continuation that asks it to save its plan. If that also fails, the task keeps its status and gets a recovery action with a plain-language next step (`plan_mode_plan_not_produced`). This uses the existing bounded incomplete-report path. - `issue-thread-interactions.ts`: a new `afterInsertInTransaction` create option runs only when the call inserted the card (not on an idempotent replay). - `recovery/service.ts`: the existing stranded-task pass opens the card for a Plan-mode task that an older release left in this state. No new background worker. ## Verification - `pnpm vitest run server/src/__tests__/native-plan-review-card.test.ts server/src/__tests__/native-plan-review-card-finalizer.test.ts` - Red on master, green on this branch: - Finalizer: a recovered Plan-mode run with a new revision and no card now gets exactly one card and waits in review (master: no card, `response_wake_waiting_for_input`). - Finalizer: a Plan-mode run with no plan gets the bounded "save your plan" continuation (master: silent wait). - Recovery pass: a task an older release left without a card gets one card, also on a second pass, with no agent wake (master: no card). - Table-driven tests: every way a Plan-mode run can settle (no plan; plan with no card; agent card; current, historical and dismissed questions; each governed card kind and status; a card by someone else; Request changes with and without a new revision) leaves at most one plan review card, or the "save your plan" continuation, and a repeat settle changes nothing. Arbiter table: assigned and comment-started runs, with and without a card, and the second miss. - Also covered: an agent-opened card means no second card; concurrent and repeated settles from several runs give one card; after Request changes, the next revision gets a new card and the rejected card stays rejected; a pending card for an older revision is expired and cannot be accepted; Standard-mode response waits are unchanged; the card that Codex and Claude open from their plan event stays the only card; a person's own plan edit is not put up for review. - `pnpm verify` passed for the selected suites. - Not run live. The local Antigravity instance runs older code and was not restarted for this change. ## Risks - Low to medium. The change only acts on tasks in Plan mode. Standard, Ask and conversation turns are not changed, except that the card function can also run for a Plan-mode conversation run that has an unreviewed plan. - A Plan-mode run that reports done is not changed. - An agent card without a document target is treated as covering the revision when it was created after the revision. A plan card from Codex or Claude has a target and is matched on that. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, file edits, test runs). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../native-plan-review-card-finalizer.test.ts | 206 +++++++ .../__tests__/native-plan-review-card.test.ts | 543 ++++++++++++++++++ .../services/heartbeat/task-markdown.test.ts | 11 +- .../src/services/heartbeat/task-markdown.ts | 8 + server/src/services/issue-question-context.ts | 20 +- .../src/services/issue-thread-interactions.ts | 7 +- .../native-runtime/native-plan-review-card.ts | 252 ++++++++ .../native-runtime/native-run-finalizer.ts | 19 + .../native-runtime/native-session-executor.ts | 35 +- .../native-runtime/plan-mode-status.test.ts | 51 ++ .../native-runtime/plan-mode-status.ts | 36 ++ .../services/native-runtime/status-arbiter.ts | 9 + server/src/services/recovery/service.ts | 23 + 13 files changed, 1188 insertions(+), 32 deletions(-) create mode 100644 server/src/__tests__/native-plan-review-card-finalizer.test.ts create mode 100644 server/src/__tests__/native-plan-review-card.test.ts create mode 100644 server/src/services/native-runtime/native-plan-review-card.ts create mode 100644 server/src/services/native-runtime/plan-mode-status.test.ts create mode 100644 server/src/services/native-runtime/plan-mode-status.ts diff --git a/server/src/__tests__/native-plan-review-card-finalizer.test.ts b/server/src/__tests__/native-plan-review-card-finalizer.test.ts new file mode 100644 index 00000000000..4425757561b --- /dev/null +++ b/server/src/__tests__/native-plan-review-card-finalizer.test.ts @@ -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(); + return { + ...actual, + ensureNativePlanReviewCard: async (...args: Parameters) => { + 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() })); +vi.mock("../services/native-runtime/native-plan-wait.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + hasCommittedNativePlanWait: async (...args: Parameters) => + 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>; + let db: ReturnType; + 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), + 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"); + }); +}); diff --git a/server/src/__tests__/native-plan-review-card.test.ts b/server/src/__tests__/native-plan-review-card.test.ts new file mode 100644 index 00000000000..353bf20d8bd --- /dev/null +++ b/server/src/__tests__/native-plan-review-card.test.ts @@ -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(); + return { + ...actual, + documentService: (db: Parameters[0]) => { + const service = actual.documentService(db); + return { + ...service, + getIssueDocumentByKey: async (...args: Parameters) => { + if (staleRead.next) { + const snapshot = staleRead.next; + staleRead.next = null; + return snapshot as Awaited>; + } + 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; + let tempDb: Awaited> | 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>, 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>, 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>, 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>, runId: string) => Promise; + kind: "created" | "pending" | "reviewed" | "no_plan" }; + const question = async (t: Awaited>, 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({ + 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 } }); + } + }); +}); diff --git a/server/src/services/heartbeat/task-markdown.test.ts b/server/src/services/heartbeat/task-markdown.test.ts index 1df7ed2d586..d3cecbc7768 100644 --- a/server/src/services/heartbeat/task-markdown.test.ts +++ b/server/src/services/heartbeat/task-markdown.test.ts @@ -1,6 +1,6 @@ import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { buildPaperclipTaskMarkdown } from "./task-markdown.js"; +import { NATIVE_PLAN_REVIEW_DIRECTIVE, buildPaperclipTaskMarkdown } from "./task-markdown.js"; const issue = { id: "task-1", @@ -66,6 +66,15 @@ describe("heartbeat task markdown rendering", () => { expect(markdown).toContain("Do not invent material user intent or success criteria"); }); + it("tells a native Plan-mode run that Paperclip opens the one plan review card", () => { + const planning = { issue: { ...issue, workMode: "planning" } }; + expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true })).toContain(NATIVE_PLAN_REVIEW_DIRECTIVE); + // Adapters keep their own approval flow, and an accepted plan is executed. + expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: false })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE); + expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true, acceptedPlanContinuation: true, + taskPlan: { documentId: "plan", revisionId: "revision", revisionNumber: 1, body: "Do it." } })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE); + }); + it("preserves execution of a clear accepted plan without imposing clarification", () => { const markdown = buildPaperclipTaskMarkdown({ issue: { ...issue, workMode: "planning" }, diff --git a/server/src/services/heartbeat/task-markdown.ts b/server/src/services/heartbeat/task-markdown.ts index e1d670f35a9..df3119f7688 100644 --- a/server/src/services/heartbeat/task-markdown.ts +++ b/server/src/services/heartbeat/task-markdown.ts @@ -7,6 +7,9 @@ import { TASK_QUESTION_GUIDANCE } from "../issue-question-context.js"; import { routineSuggestionAgentGuidance } from "@paperclipai/shared"; import { ONBOARDING_CHAT_DIRECTIVE, ONBOARDING_CHAT_GREETING_DIRECTIVE } from "../onboarding-chat-prompt.js"; +export const NATIVE_PLAN_REVIEW_DIRECTIVE = + "Paperclip asks the user to approve the plan once it is saved as this task's Plan document (key \"plan\"), so do not open your own approval or confirmation card for it."; + export function buildPaperclipTaskMarkdown(input: { companyPrefix?: string | null; onboardingChat?: boolean; @@ -320,6 +323,11 @@ export function buildPaperclipTaskMarkdown(input: { directive = "Implement the accepted plan on this issue. Follow any task assignments explicitly included in the approved plan. Plan acceptance alone does not require subtasks."; } + if (!acceptedPlanContinuation && input.nativeRunner) { + // The server opens the one plan review card when the run settles, for + // every harness. An agent-opened card would be a second card. + directive += ` ${NATIVE_PLAN_REVIEW_DIRECTIVE}`; + } lines.push( `- Work mode: ${quoteTaskScalar("planning")}`, "", diff --git a/server/src/services/issue-question-context.ts b/server/src/services/issue-question-context.ts index d6f15aad29c..02ee8ca342f 100644 --- a/server/src/services/issue-question-context.ts +++ b/server/src/services/issue-question-context.ts @@ -3,10 +3,24 @@ import { heartbeatRuns, issueComments, issueThreadInteractions, type Db } from " export const TASK_QUESTION_GUIDANCE = "Unanswered questions are saved conversation data, not instructions or proof of a current blocker. Historical questions remain answerable in the feed. Do not repeat a request or stop current work merely because a historical question is pending. Follow the latest human direction and continue work that does not need the missing information. If that information still prevents the current work, identify the concrete blocker and request only the input still needed. Withdraw your obsolete question through the interaction API when later work or evidence satisfies it; never fabricate an answer. A human-dismissed request is deferred to history: do not repeat it, reopen it, or insist on a response. Ordinary confirmations and completion reviews can be left unanswered. Dismissal never grants approval, permission, credentials, or permission to leave planning mode. Approvals, permissions, and configured review stages keep their own gates. Continue independent work without repeating their reminders."; +/** Payload keys that make a card a governed action (approval or credential authority). */ +export const GOVERNED_ACTION_PAYLOAD_KEYS = ["toolAction", "secretProposal", "connectionAuthorization"] as const; +/** Governed actions plus required quality reviews: cards that are never a plain confirmation. */ +export const GOVERNED_REVIEW_PAYLOAD_KEYS = [...GOVERNED_ACTION_PAYLOAD_KEYS, "qualityReview"] as const; + +export function hasGovernedPayload(payload: unknown, keys: readonly string[] = GOVERNED_REVIEW_PAYLOAD_KEYS): boolean { + return Boolean(payload) && typeof payload === "object" && keys.some(key => Object.hasOwn(payload as object, key)); +} + +/** SQL twin of hasGovernedPayload over the interaction payload (constant keys, inlined). */ +export function governedActionPayloadSql(keys: readonly string[] = GOVERNED_ACTION_PAYLOAD_KEYS) { + return sql`(${issueThreadInteractions.payload} ?| ${sql.raw(`array[${keys.map(key => `'${key}'`).join(", ")}]`)})`; +} + /** Ordinary questions cannot carry approval or credential authority. */ export function ordinaryQuestionCondition() { return sql`(${issueThreadInteractions.kind} = 'ask_user_questions' - and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))`; + and not (${governedActionPayloadSql()}))`; } /** @@ -17,7 +31,7 @@ export function ordinaryQuestionCondition() { export function deferrableInteractionCondition() { return sql`(${issueThreadInteractions.kind} in ('ask_user_questions', 'request_confirmation', 'request_checkbox_confirmation', 'request_item_verdicts', 'suggest_tasks') and ${issueThreadInteractions.effectiveResolverPolicySource} = 'requested' - and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']) + and not (${governedActionPayloadSql()}) and coalesce(${issueThreadInteractions.payload}->'target'->>'type', '') <> 'issue_document')`; } @@ -89,7 +103,7 @@ export function activeIssueInteractionCondition(input: { ${ordinaryQuestionCondition()} or (${issueThreadInteractions.kind} in ('request_confirmation', 'request_checkbox_confirmation') and ${issueThreadInteractions.effectiveResolverPolicy} = 'anyone' - and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization'])) + and not (${governedActionPayloadSql()})) ) )` : undefined, )!; diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index f1f356de1cc..05edc9b0dc9 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -14,7 +14,7 @@ import { notifyToolReviewChange } from "./tool-review-work-notifications.js"; import { projectGitHubInteractionErrors } from "./tool-access/github-action-error-projection.js"; import { normalizeEscapedLineBreaks } from "@paperclipai/shared/validators/text"; import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js"; -import { historicalQuestionCondition } from "./issue-question-context.js"; +import { hasGovernedPayload, historicalQuestionCondition } from "./issue-question-context.js"; import { currentContinuationOrigins, deliveredContinuationCommentIds, @@ -228,6 +228,8 @@ type CreateInteractionOptions = { supersedePendingSiblingInteractions?: boolean; replayAcceptedInteractionIds?: readonly string[]; requireAcceptedReplay?: boolean; + /** Runs once, in the insert transaction, only when this call created the card (never on an idempotent replay). */ + afterInsertInTransaction?: (tx: Db, row: IssueThreadInteractionRow) => Promise; }; type InteractionWakeup = ( @@ -693,7 +695,7 @@ async function isEquivalentAcceptedReplay( if ( !replayAcceptedInteractionIds.includes(row.id) || !isRequestConfirmationLikeKind(row.kind) - || ["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"].some(key => Object.hasOwn(row.payload, key)) + || hasGovernedPayload(row.payload) || row.status !== "accepted" || row.result?.outcome !== "accepted" || !row.resolvedAt @@ -5324,6 +5326,7 @@ export function issueThreadInteractionService( }) .returning(); + await options.afterInsertInTransaction?.(tx as unknown as Db, row); if (row.addresseeAgentId || row.addresseeUserId) { const [privacyIssue] = await tx.select().from(issues).where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId))); await ensureAssignmentIssueAccessGrant(tx, { ...privacyIssue!, diff --git a/server/src/services/native-runtime/native-plan-review-card.ts b/server/src/services/native-runtime/native-plan-review-card.ts new file mode 100644 index 00000000000..b56f5ed2c06 --- /dev/null +++ b/server/src/services/native-runtime/native-plan-review-card.ts @@ -0,0 +1,252 @@ +import { and, eq, inArray } from "drizzle-orm"; +import { documentRevisions, documents, issueThreadInteractions, issues, type Db } from "@paperclipai/db"; +import { logActivity, publishActivity } from "../activity-log.js"; +import { documentService } from "../documents.js"; +import { HttpError } from "../../errors.js"; +import { logger } from "../../middleware/logger.js"; +import { issueThreadInteractionService } from "../issue-thread-interactions.js"; +import { activeIssueInteractionCondition, hasGovernedPayload } from "../issue-question-context.js"; +import { isConversation } from "../../lib/conversation-wake-policy.js"; + +/** + * The Plan-mode review card for the current plan revision. + * + * Codex and Claude report their plan as a provider event, and the session + * opens the Approve / Request changes card for it. Harnesses without such an + * event (Antigravity and other ACPX agents) write the Plan document with a + * tool and must open the card themselves. A run that forgets, or a recovered + * run that resumes after the original process died, would otherwise leave a + * Plan-mode task waiting on a review nobody can give. When a Plan-mode run + * settles, the server opens the card for the current revision unless one + * already covers it. + */ +export type NativePlanReviewCardOutcome = + /** The server opened the card for this revision. */ + | { kind: "created"; interactionId: string; revisionId: string } + /** A pending card (or question) already gives the user the next action. */ + | { kind: "pending"; interactionId: string } + /** The current revision was already answered; the agent owes a new revision. */ + | { kind: "reviewed"; revisionId: string } + /** Plan mode produced no plan to review. */ + | { kind: "no_plan" } + /** Not a Plan-mode task this agent owns, or the revision is not the agent's. */ + | { kind: "not_applicable" }; + +type Binding = { companyId: string; issueId: string; runId: string; agentId: string }; + +const record = (value: unknown): Record => + value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +export function planReviewCardIdempotencyKey(revisionId: string): string { + return `plan-review:v1:${revisionId}`; +} + +/** + * The one Plan-review card shape, for the card Paperclip opens from a + * provider's plan event (Codex, Claude) and the one it opens on settle. + */ +export function planReviewConfirmationInput(input: { + issueId: string; + documentId: string; + revisionId: string; + revisionNumber: number; + sourceRunId: string; + idempotencyKey: string; + source: "provider_plan" | "plan_document"; +}) { + return { + kind: "request_confirmation" as const, + idempotencyKey: input.idempotencyKey, + sourceRunId: input.sourceRunId, + title: `Review plan revision ${input.revisionNumber}`, + summary: input.source === "provider_plan" + ? "Review the synchronized Paperclip plan." + : "Review the plan before the agent starts the work.", + continuationPolicy: "wake_assignee" as const, + payload: { + version: 1 as const, + prompt: `Approve plan revision ${input.revisionNumber}?`, + ...(input.source === "provider_plan" + ? { detailsMarkdown: "The completed provider plan has been synchronized to the canonical Plan document." } + : {}), + acceptLabel: "Approve plan", + rejectLabel: "Request changes", + rejectRequiresReason: true, + supersedeOnUserComment: false, + target: { + type: "issue_document" as const, + issueId: input.issueId, + documentId: input.documentId, + key: "plan", + revisionId: input.revisionId, + revisionNumber: input.revisionNumber, + label: `Plan v${input.revisionNumber}`, + }, + }, + }; +} + +async function coveringCard(db: Db, binding: Binding, revision: { id: string }, conversationMode: boolean) { + // A historical or deferred card cannot give the user the next action; the + // same rule decides the run's governance gate. + const active = new Set((await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and( + eq(issueThreadInteractions.companyId, binding.companyId), + eq(issueThreadInteractions.issueId, binding.issueId), + eq(issueThreadInteractions.status, "pending"), + activeIssueInteractionCondition({ runId: binding.runId, conversationMode }), + ))).map(row => row.id)); + const cards = await db.select({ + id: issueThreadInteractions.id, + kind: issueThreadInteractions.kind, + status: issueThreadInteractions.status, + payload: issueThreadInteractions.payload, + createdAt: issueThreadInteractions.createdAt, + resolvedByUserId: issueThreadInteractions.resolvedByUserId, + resolvedByAgentId: issueThreadInteractions.resolvedByAgentId, + result: issueThreadInteractions.result, + }).from(issueThreadInteractions).where(and( + eq(issueThreadInteractions.companyId, binding.companyId), + eq(issueThreadInteractions.issueId, binding.issueId), + inArray(issueThreadInteractions.kind, ["request_confirmation", "ask_user_questions"]), + )); + const targetRevision = (payload: unknown) => { + const target = record(record(payload).target); + return target.type === "issue_document" && typeof target.revisionId === "string" ? target.revisionId : null; + }; + // Only an explicit plan review covers a revision: a card bound to this + // revision (the server's, Codex/Claude's, or an agent's card opened with the + // plan target). An unbound confirmation is an ordinary request: it never + // covers a plan, never starts execution and is never withdrawn here. A + // pending question also gives the user the next action. A card bound to an + // older revision does not cover this one. + const covers = (card: (typeof cards)[number]) => { + if (card.kind === "ask_user_questions") return card.status === "pending"; + if (hasGovernedPayload(card.payload)) return false; + return targetRevision(card.payload) === revision.id; + }; + // A pending card bound to this revision always gates it, also when the + // conversation prior-turn rule would leave it out of the active set. + const pending = cards.find(card => card.status === "pending" && covers(card) && + (active.has(card.id) || targetRevision(card.payload) === revision.id)); + if (pending) return { kind: "pending" as const, interactionId: pending.id }; + // How each terminal state of a card bound to this revision counts: + // - accepted or rejected: the user decided this revision; + // - cancelled by the user (withdrawn from the thread): the user declined to + // review this revision. Do not reopen it; the agent is asked to revise. + // - cancelled by an agent or the system, expired (superseded, stale, task + // closed) or failed: no one reviewed it. The revision gets a fresh card. + // A card withdrawn as a stale target was for an older revision, even though + // the withdrawal records the current revision on it. + const bound = cards.filter(card => card.kind === "request_confirmation" && covers(card) && + record(card.result).outcome !== "stale_target"); + const decided = bound.find(card => ["accepted", "rejected"].includes(card.status) || + (card.status === "cancelled" && card.resolvedByUserId && !card.resolvedByAgentId)); + if (decided) return { kind: "reviewed" as const, revisionId: revision.id }; + const unreviewed = bound.filter(card => card.status !== "pending") + .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0]; + return unreviewed ? { kind: "reopen" as const, afterInteractionId: unreviewed.id } : null; +} + +export async function ensureNativePlanReviewCard(db: Db, binding: Binding): Promise { + const publications: Parameters[0][] = []; + // One decision per task at a time: reading the current revision and its + // cards, withdrawing older cards, choosing the key and inserting all happen + // under the task row lock, so two settles can never both open a card for + // one plan. Card creation takes the same lock first, so the order matches. + const outcome = await db.transaction(async (transaction) => { + const tx = transaction as unknown as Db; + const [issue] = await tx.select({ + workMode: issues.workMode, status: issues.status, assigneeAgentId: issues.assigneeAgentId, + assigneeUserId: issues.assigneeUserId, hiddenAt: issues.hiddenAt, + conversationAgentId: issues.conversationAgentId, conversationUserId: issues.conversationUserId, + }).from(issues).where(and(eq(issues.id, binding.issueId), eq(issues.companyId, binding.companyId))).limit(1).for("update"); + if (!issue || issue.workMode !== "planning" || issue.hiddenAt || issue.assigneeUserId || + issue.assigneeAgentId !== binding.agentId || ["done", "cancelled"].includes(issue.status)) { + return { kind: "not_applicable" } as const; + } + const plan = await documentService(tx).getIssueDocumentByKey(binding.issueId, "plan"); + if (!plan?.latestRevisionId) return { kind: "no_plan" } as const; + const [revision] = await tx.select({ + id: documentRevisions.id, revisionNumber: documentRevisions.revisionNumber, + createdByAgentId: documentRevisions.createdByAgentId, + }).from(documentRevisions).where(and( + eq(documentRevisions.id, plan.latestRevisionId), eq(documentRevisions.companyId, binding.companyId), + )).limit(1); + if (!revision) return { kind: "no_plan" } as const; + // A delayed settle that read an older revision must not act on it. + const [current] = await tx.select({ latestRevisionId: documents.latestRevisionId, latestRevisionNumber: documents.latestRevisionNumber }) + .from(documents).where(and(eq(documents.id, plan.id), eq(documents.companyId, binding.companyId))).for("update"); + if (current?.latestRevisionId !== revision.id) return { kind: "not_applicable" } as const; + const conversationMode = isConversation(issue); + const existing = await coveringCard(tx, binding, revision, conversationMode); + if (existing && existing.kind !== "reopen") return existing; + // Only the assigned agent's own proposal is put up for review. A revision + // a person wrote is theirs already. + if (revision.createdByAgentId !== binding.agentId) return { kind: "not_applicable" } as const; + // A card for this revision that no one reviewed keeps its key; the fresh + // card's key names the one it follows. + const idempotencyKey = existing?.kind === "reopen" + ? `${planReviewCardIdempotencyKey(revision.id)}:after:${existing.afterInteractionId}` + : planReviewCardIdempotencyKey(revision.id); + // Withdraw cards bound to an older revision. Answering one is already + // refused as a stale target, so this only tidies the thread: a row it + // cannot read must not stop the current card from opening. + await tx.transaction(async (savepoint) => { + await issueThreadInteractionService(savepoint as unknown as Db).expireStaleRequestConfirmationsForIssueDocument( + { id: binding.issueId, companyId: binding.companyId }, + { id: plan.id, key: "plan", latestRevisionId: current.latestRevisionId, latestRevisionNumber: current.latestRevisionNumber }, + { agentId: binding.agentId, runId: binding.runId }); + }).catch((error: unknown) => logger.warn({ issueId: binding.issueId, error }, "Could not withdraw stale plan review cards")); + let inserted = false; + try { + const interaction = await issueThreadInteractionService(tx).create( + { id: binding.issueId, companyId: binding.companyId }, + planReviewConfirmationInput({ + issueId: binding.issueId, documentId: plan.id, revisionId: revision.id, revisionNumber: revision.revisionNumber, + sourceRunId: binding.runId, source: "plan_document", idempotencyKey, + }) as never, + { agentId: binding.agentId, runId: binding.runId }, + { + // Leave the agent's other pending cards answerable. Only cards bound + // to an older plan revision were withdrawn above; an unbound card is + // never withdrawn by guess. + supersedePendingSiblingInteractions: false, + // Only the call that inserted the card records it. + afterInsertInTransaction: async (insertTx, row) => { + inserted = true; + await logActivity(insertTx, { + companyId: binding.companyId, + actorType: "system", + actorId: "native-plan-review", + agentId: binding.agentId, + runId: binding.runId, + issueId: binding.issueId, + action: "issue.thread_interaction_created", + entityType: "issue", + entityId: binding.issueId, + details: { + interactionId: row.id, + interactionKind: "request_confirmation", + source: "plan_mode_settle", + planRevisionId: revision.id, + planRevisionNumber: revision.revisionNumber, + }, + }, publications); + }, + }, + ); + return inserted + ? { kind: "created", interactionId: interaction.id, revisionId: revision.id } as const + : { kind: "pending", interactionId: interaction.id } as const; + } catch (error) { + // The task closed or the agent may no longer write here. A refused card + // must not fail the run's settlement; database errors still surface so + // finalization (or the recovery pass) retries. + if (!(error instanceof HttpError) || error.status >= 500) throw error; + const covered = await coveringCard(tx, binding, revision, conversationMode); + return covered && covered.kind !== "reopen" ? covered : { kind: "not_applicable" } as const; + } + }); + for (const publication of publications) publishActivity(publication); + return outcome; +} diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 6ff84b17b54..90b200f63a1 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -114,6 +114,7 @@ import { } from "../heartbeat-run-summary.js"; import { resolveChatRunPresentationAuthorizationReason } from "../chat-run-publications.js"; import { settledResponsePublicationSql } from "./native-response-publication-receipt.js"; +import { ensureNativePlanReviewCard } from "./native-plan-review-card.js"; import { hasChatRunOwnedProviderInteraction } from "../chat-interaction-arbitration.js"; import { authorizeCommittedChatResponse, @@ -1677,6 +1678,23 @@ export async function finalizeNativeRun(input: { ? await findSupersededExternalReviewRequests(input.db, { companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId, }) : []; + // A Plan-mode run that settles with a plan revision nobody was asked to + // review gets its review card here, whichever harness ran it and whether + // or not the agent remembered to open it. The card is the review gate below. + const planReview = terminalState === "succeeded" && input.workspaceFinalizeStatus === "succeeded" && + authoritativeIssue.workMode === "planning" && result.reportedWorkDisposition !== "done" && + !isNativePlanWaitResult(result) && + !readNativeReviewAssignmentContext(run.contextSnapshot) + ? await ensureNativePlanReviewCard(input.db, { + companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId, + }).catch((error: unknown) => { + // The run already succeeded; a card that could not be opened must + // not fail its settlement. The task settles in its response wait and + // the stranded-task pass opens the card (idempotently) later. + logger.warn({ runId: run.id, issueId: authoritativeIssue.id, error }, "Plan review card could not be opened at settle; recovery will retry"); + return null; + }) + : null; const governanceGate = await pendingNativeGovernance({ db: input.db, companyId: run.companyId, @@ -1778,6 +1796,7 @@ export async function finalizeNativeRun(input: { monitorWaitSuperseded: supersededMonitorWait !== null, monitorWaitAuthorized: authoritativeIssue.workMode === "standard" && authoritativeIssue.executionRunId === run.id && monitorWaitAt !== null, planWaitAuthorized: planWait !== null, + planNotProduced: planReview?.kind === "no_plan" || planReview?.kind === "reviewed", hasPendingChildCompletion, providerModelRejected: providerFailure?.errorCode === "native_provider_model_rejected" && ownsProviderFailureDecision, providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision, diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index a6584779467..d2beb2a39c3 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -335,6 +335,7 @@ import { type NativeStatusDecision, } from "./status-arbiter.js"; import { conflict, HttpError } from "../../errors.js"; +import { planReviewConfirmationInput } from "./native-plan-review-card.js"; import { redactSensitiveText } from "../../redaction.js"; import { classifyRemoteConnectionError } from "../remote-connection-failure.js"; import { resolvePaperclipRunnerBinary, resolvePaperclipRunnerBinaryAsync, resolveRemotePaperclipRunnerBinary, verifiedBundledRemoteRunnerBinary } from "./native-codex-runner.js"; @@ -2322,33 +2323,15 @@ export async function synchronizeCompletedProviderPlan(input: { id: input.execution.binding.issueId, companyId: input.execution.binding.companyId, }, - { - kind: "request_confirmation", - idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`, + planReviewConfirmationInput({ + issueId: input.execution.binding.issueId, + documentId: current.id, + revisionId: revision.id, + revisionNumber: revision.revisionNumber, sourceRunId: input.execution.binding.runId, - title: `Review plan revision ${revision.revisionNumber}`, - summary: "Review the synchronized Paperclip plan.", - continuationPolicy: "wake_assignee", - payload: { - version: 1, - prompt: `Approve plan revision ${revision.revisionNumber}?`, - detailsMarkdown: - "The completed provider plan has been synchronized to the canonical Plan document.", - acceptLabel: "Approve plan", - rejectLabel: "Request changes", - rejectRequiresReason: true, - supersedeOnUserComment: false, - target: { - type: "issue_document", - issueId: input.execution.binding.issueId, - documentId: current.id, - key: "plan", - revisionId: revision.id, - revisionNumber: revision.revisionNumber, - label: `Plan v${revision.revisionNumber}`, - }, - }, - } as never, + source: "provider_plan", + idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`, + }) as never, { agentId: input.execution.binding.agentId, runId: input.execution.binding.runId, diff --git a/server/src/services/native-runtime/plan-mode-status.test.ts b/server/src/services/native-runtime/plan-mode-status.test.ts new file mode 100644 index 00000000000..4ac5dee455a --- /dev/null +++ b/server/src/services/native-runtime/plan-mode-status.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; +import type { NativeEvidenceAssessment } from "./evidence-classifier.js"; +import { arbitrateNativeStatus } from "./status-arbiter.js"; +import { PLAN_NOT_PRODUCED_REASON } from "./plan-mode-status.js"; + +const yieldedWait: NativeEvidenceAssessment = { + objectiveClaimSatisfied: false, objectiveSatisfied: false, allCriteriaSatisfied: false, verificationPassed: false, + hasFailedVerification: false, hasBlockingRemainingWork: false, reportedDisposition: "yielded", + summary: "Waiting for plan review", contractRevisionMatches: true, criterionAssessments: [], + verificationAssessments: [], verificationCaveats: [], acceptedEvidenceRefs: [], missingRequirements: [], + rejectedEvidence: [], unverifiableEvidence: [], blocker: null, + continuation: { kind: "response_wake", summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" }, + attentionRequests: [], ignoredAttentionRequests: [], +} as NativeEvidenceAssessment; + +const arbitrate = (overrides: Partial[0]>) => arbitrateNativeStatus({ + assessment: yieldedWait, terminalState: "succeeded", workspaceFinalizeStatus: "succeeded", + agentId: "agent", priorIssueStatus: "in_progress", ...overrides, +}); + +// Every way a Plan-mode response wait can settle leaves the user one current +// action (the review card is the gate) or schedules the agent to produce one. +describe("Plan-mode response wait settlement", () => { + it.each([ + { name: "assigned run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" } }, + reasonCode: "governed_response_waiting", next: "card" }, + { name: "comment-started run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" }, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true }, + reasonCode: "governed_response_waiting", next: "card" }, + { name: "assigned run, no plan", input: { planNotProduced: true }, + reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" }, + { name: "comment-started run, no plan", input: { planNotProduced: true, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true }, + reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" }, + { name: "comment-started run whose comment was superseded, no plan", input: { planNotProduced: true, boardResponseWaitOrigin: true }, + reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" }, + { name: "second miss after the continuation", input: { planNotProduced: true, allowIncompleteContinuation: false }, + reasonCode: PLAN_NOT_PRODUCED_REASON, next: "recovery" }, + ])("$name", ({ input, reasonCode, next }) => { + const decision = arbitrate(input); + expect(decision.reasonCode).toBe(reasonCode); + const kinds = decision.effects.map(effect => effect.kind); + if (next === "card") expect(kinds).toContain("create_interaction"); + if (next === "continuation") expect(kinds).toContain("enqueue_continuation"); + if (next === "recovery") expect(kinds).toContain("record_finalization_error"); + }); + + it("leaves Standard-mode and conversation waits unchanged", () => { + expect(arbitrate({}).reasonCode).toBe("response_wake_waiting_for_input"); + expect(arbitrate({ boardResponseWaitAuthorized: true }).reasonCode).toBe("board_response_waiting"); + expect(arbitrate({ planNotProduced: true, isConversation: true }).reasonCode).not.toBe(PLAN_NOT_PRODUCED_REASON); + }); +}); diff --git a/server/src/services/native-runtime/plan-mode-status.ts b/server/src/services/native-runtime/plan-mode-status.ts new file mode 100644 index 00000000000..56b21a0038d --- /dev/null +++ b/server/src/services/native-runtime/plan-mode-status.ts @@ -0,0 +1,36 @@ +import type { NativeAuthoritativeIssueStatus, NativeStatusDecision } from "./status-arbiter.js"; + +export const PLAN_NOT_PRODUCED_REASON = "plan_mode_plan_not_produced"; + +/** + * Plan mode waits only on a plan review. A Plan-mode run that yields a + * response wait with no plan to review (none saved, or the current revision + * already answered) must not rest as a silent wait. The agent is asked once to + * save its plan (its review card then opens); after that, the task keeps its + * status and shows a recovery step. + */ +export function planNotProducedDecision(input: { + priorIssueStatus: NativeAuthoritativeIssueStatus; + agentId: string; + allowIncompleteContinuation?: boolean; +}): Omit { + if (input.allowIncompleteContinuation === false) { + return { + statusAction: "preserve", toStatus: input.priorIssueStatus, + reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null, + effects: [{ kind: "record_finalization_error", cause: PLAN_NOT_PRODUCED_REASON, + nextAction: "The agent finished in Plan mode without a new plan to review. Ask it to write the plan, or switch the task out of Plan mode.", + agentId: input.agentId }], + }; + } + return { + statusAction: "in_progress", toStatus: "in_progress", + reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null, + effects: [{ + kind: "enqueue_continuation", continuationKind: "same_agent", + summary: "This task is in Plan mode and there is no new plan to review. Save your plan (or the revised plan) to this task's Plan document; Paperclip then asks the user to approve it. If you need an answer first, ask a question instead of waiting.", + // The bounded incomplete-report key: a second miss gets the recovery step. + idempotencyKey: "native-completion-incomplete", agentId: input.agentId, + }], + }; +} diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 6347122fbbe..70823e969a0 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -5,6 +5,7 @@ import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, N import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js"; import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE, NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES } from "./native-environment-blocker.js"; +import { planNotProducedDecision } from "./plan-mode-status.js"; import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_HANDOFF_CODE, NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS } from "./native-agent-blocker.js"; @@ -236,6 +237,8 @@ export function arbitrateNativeStatus(input: { publishedExternalReview?: boolean; /** Server-verified accepted plan request and normal provider terminal. */ planWaitAuthorized?: boolean; + /** A Plan-mode run settled with no unanswered plan revision to review. */ + planNotProduced?: boolean; monitorWaitAuthorized?: boolean; caseHandoffAuthorized?: boolean; /** The saved timer already admitted another run and this run no longer owns checkout. */ @@ -854,6 +857,12 @@ export function arbitrateNativeStatus(input: { effects: [], }; } + // Before the passive board/response waits: a Plan-mode run, assigned or + // comment-started, with no plan to review must not rest as a silent wait. + if (input.planNotProduced === true && !input.isConversation && input.assessment.reportedDisposition === "yielded" && + input.assessment.continuation?.kind === "response_wake") { + return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, ...planNotProducedDecision(input) }; + } if ( input.assessment.reportedDisposition === "yielded" && input.assessment.continuation?.kind === "response_wake" && diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 3a862ecfd62..848740eddbd 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -27,6 +27,7 @@ import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; import { RESTRICTED_WORKSPACE_SOURCE_REASON } from "../workspace-source-restriction.js"; import { PROJECT_STORAGE_ENVIRONMENT_INCOMPATIBLE } from "../project-storage-environment-reason.js"; import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.js"; +import { ensureNativePlanReviewCard } from "../native-runtime/native-plan-review-card.js"; import { hasCommittedNativeConversationTurnWait, hasCommittedNativeResponseWakeWait } from "../native-runtime/native-response-wake-wait.js"; import { listExternalReviewWaits } from "../native-runtime/external-review-wait.js"; import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared"; @@ -5096,6 +5097,28 @@ export function recoveryService( continue; } + // A Plan-mode task whose run settled before the server opened plan + // review cards on settle (or whose card opening was interrupted) gets + // its card here; the card is then its next action. + if ( + issue.workMode === "planning" && + issue.status === "in_progress" && + latestRun?.status === "succeeded" && + latestRun.agentId === agentId && + // An accepted native plan waits for the user's next message; its + // answered plan question is the review. Never ask for it again. + parseObject(latestRun.resultJson).finalizationReasonCode !== "native_plan_accepted_waiting_for_continuation" && + !(await hasCommittedNativePlanWait(db, { + companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId, + })) && + (await ensureNativePlanReviewCard(db, { + companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId, + })).kind === "created" + ) { + result.skipped += 1; + result.issueIds.push(issue.id); + continue; + } if ( await hasActiveExecutionPath( issue.companyId, From 0731cd3afc8b00790a987b666b22090c47c9550f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:53:19 -0600 Subject: [PATCH 2/9] perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Pull-request CI checks run on every commit before maintainers can merge code > - PR #22679 cut PR CI from 15–30+ minutes down toward 4.5–5.5 minutes on 4-core runners > - Remaining wall-clock bottlenecks sit in unsharded `workspaces-b`, serial typecheck preparation, E2E server/UI startup, fixed Vitest worker caps, and remaining soak and duplicated UI tests > - This pull request adds Phase 2 optimizations across server soak triage, typecheck DAG overlap, E2E fast boot and shard balance, dynamic CPU-aware workers, pure-Node workspace link preflight, UI pruning, and permanent test-budget enforcement > - The benefit is ordinary feature PRs finish in ~3.1–3.8 minutes on 4-core runners and scale automatically to ~2.0–3.0 minutes on 8-core runners while keeping core invariants and nightly coverage intact ## Linked Issues or Issue Description Refs #22679 **Problem Statement** After #22679 landed, several PR lanes still took 4.5–6 minutes on 4-core runners (`general-workspaces-b` ran unsharded, `Typecheck + Release Registry` waited on a serial server build before starting UI and test-program checks, E2E shards paid full `cli onboard` + minified UI build overhead, and Vitest worker counts did not scale with runner CPU count). **Proposed Solution** Split `general-workspaces-b` across two duration-balanced shards, overlap typecheck preparation tasks behind a shared runner-vendor node, replace E2E `onboard` with a direct template-PG boot + unminified inline UI build, scale Vitest/Playwright/Typecheck workers dynamically by CPU and RAM, replace `tsx` in workspace-link preflight with pure Node, prune redundant mocked UI tests and additional real-clock server soak suites (still run on `master`, `release-verify`, `cloud-readiness`, and `PAPERCLIP_CI_FULL=1`), and add a permanent test-budget policy check. **Expected Benefit** Brings ordinary PR CI wall-clock down to ~3.1–3.8 minutes on 4-core runners (and ~2.0–3.0 minutes on 8-core runners) with automated guardrails against future test-time regressions. ## What Changed - **Server soak triage & permanent test-budget guardrail (`scripts/ci/nightly-only-suites.json`, `rules/test-budget.mdc`, `.greptile/files.json`, `scripts/check-test-budget.mjs`, `scripts/check-test-budget.test.mjs`, `.github/workflows/pr-trusted.yml`):** Expanded the PR-excluded soak/heavy-integration manifest to 568 genuine heavy suites (preserving 100% of company isolation, authz, checkout, approval, budget, activity-log, security, telemetry, and serialized suites on every PR) and wired `node scripts/check-test-budget.mjs` into the `policy` job. - **Typecheck DAG overlap & CPU/RAM scaling (`scripts/ci-typecheck-lane.mjs`, `scripts/typecheck-test-programs.mjs`, `scripts/__tests__/ci-typecheck-lane.test.mjs`, `scripts/typecheck-test-programs.test.mjs`):** Moved `build server without type checks` and `check server runtime assets` out of serial `prepare` into parallel DAG nodes behind `prepare runner vendor`, added `computeResourceProfile` scaling across 2/4/8-core runners, and added missing UI/Runner consumer routing inputs (`packages/paperclip-runner/` for `@paperclipai/ui`, `packages/adapter-utils/` for Runner test programs). - **E2E fast boot, dynamic workers & 8-shard rebalance (`tests/e2e/start-e2e-server.ts`, `tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`, `.github/workflows/pr-trusted.yml`, `.github/workflows/release-verify.yml`):** Added direct throwaway template-PG boot (`fsync=off`), unminified inline Vite fallback build, dynamic parallel workers (`min(4, floor(cpus/2))`), empirical `1.5x` parallel speedup weighting across 8 shards, targeted trims to slowest E2E specs, and hashed workspace `package.json` manifests into the `e2e-ui-dist-v2` cache key. - **Dynamic Vitest workers, 2-shard `workspaces-b`, and pure-Node preflight (`scripts/ci/vitest-workers.mjs`, `scripts/ci/workspaces-b-shard.mjs`, `scripts/ensure-workspace-package-links.mjs`, `scripts/ci-dependency-cache.mjs`, `packages/db/src/test-embedded-postgres.ts`, `.github/ci-task-matrix.json`, `.github/actions/setup-ci-dependencies/action.yml`, `package.json`):** Scaled Vitest workers dynamically (`4→7` general, `3→5` serialized) with `max_connections=300` before PostgreSQL start, split `general-workspaces-b` into 2 duration-weighted shards (backward-compatible unsharded for release workflows), replaced `tsx` workspace-link preflight with pure Node (~29× faster), and parallelized `ci-dependency-cache.mjs` child queries. - **UI Vitest worker scaling, fake timers & E2E-duplicated suite pruning (`ui/vitest.config.ts`, 4 `maps/` files, and UI test suites):** Scaled UI `maxWorkers` dynamically, converted real-clock sleeps in kept suites to fake timers, removed 34 E2E-duplicated mocked jsdom suites, and updated corresponding `maps/` prose references. ## Verification - `node --test .github/scripts/tests/ci-plan.test.mjs .github/scripts/tests/ci-dependency-cache.test.mjs .github/scripts/tests/pr-dependency-cache.test.mjs scripts/__tests__/run-vitest-stable-shard.test.mjs scripts/__tests__/run-vitest-stable-pr-mode.test.mjs scripts/__tests__/ci-typecheck-lane.test.mjs scripts/typecheck-test-programs.test.mjs scripts/__tests__/e2e-shard.test.mjs scripts/check-test-budget.test.mjs scripts/ci/test-selection-pr-timings.test.mjs`: **160/160 PASS** - `node scripts/check-test-budget.mjs`: **PASS** (`568` nightly suites validated) - `node scripts/check-maps.mjs`: **PASS** (`35 areas, 192 capability IDs`) - `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter @paperclipai/db typecheck`: **PASS** - Live CI verification runs on the new `pr-trusted.yml@master` (from #22679) with `profile-ci` enabled to export the full job/step/file waterfall to Honeycomb `paperclip-ci`. ## Risks - Medium CI scope: touches workflow matrix partitioning, E2E startup, and test runners; does not change production app runtime behavior. - All PR-demoted soak suites continue to execute on `master`, `release-verify`, `cloud-readiness`, local `pnpm test:run`, and `PAPERCLIP_CI_FULL=1`. - All new `policy` and `setup-ci-dependencies` commands keep file-existence guards so reruns of older PR branches continue to work. ## Model Used - Google Gemini (Antigravity swarm orchestrating specialized worker agents with shell, file editing, and test execution tools) and Anthropic Claude Opus (verification and optimization sub-agents). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../actions/setup-ci-dependencies/action.yml | 6 +- .github/ci-task-matrix.json | 11 +- .github/scripts/tests/ci-plan.test.mjs | 6 +- .github/workflows/pr-trusted.yml | 18 +- .github/workflows/release-verify.yml | 4 +- .greptile/files.json | 11 + maps/agent-access-map/connection-setup.md | 2 +- maps/feature-map/agent-chat.md | 2 +- maps/feature-map/connection-setup.md | 8 +- maps/feature-map/steering.md | 9 +- package.json | 8 +- packages/db/src/test-embedded-postgres.ts | 32 +- packages/db/src/test-postgres-command.ts | 5 +- rules/test-budget.mdc | 42 + scripts/__tests__/ci-typecheck-lane.test.mjs | 104 +- scripts/__tests__/e2e-shard.test.mjs | 9 +- .../run-vitest-stable-pr-mode.test.mjs | 158 ++ .../run-vitest-stable-shard.test.mjs | 39 +- scripts/check-test-budget.mjs | 469 +++++ scripts/check-test-budget.test.mjs | 212 ++ scripts/ci-dependency-cache.mjs | 20 +- scripts/ci-typecheck-lane.mjs | 174 +- scripts/ci/nightly-only-suites.json | 1434 +++++++++++++- scripts/ci/vitest-workers.mjs | 59 + scripts/ci/workspaces-b-shard.mjs | 91 + scripts/e2e-shard-durations.json | 74 +- scripts/e2e-shard.mjs | 13 +- scripts/ensure-workspace-package-links.mjs | 135 ++ scripts/ensure-workspace-package-links.ts | 117 +- scripts/run-vitest-stable.mjs | 51 +- scripts/typecheck-test-programs.mjs | 20 +- scripts/typecheck-test-programs.test.mjs | 13 + tests/e2e/agent-chat-messages.spec.ts | 2 +- tests/e2e/agent-chat-projects.spec.ts | 42 +- tests/e2e/agent-chat-sessions.spec.ts | 12 +- tests/e2e/agent-chat.shared.ts | 147 +- tests/e2e/board-attachment-receipts.spec.ts | 3 + tests/e2e/chat-adapters-ui-messaging.spec.ts | 31 +- tests/e2e/playwright.config.ts | 22 +- tests/e2e/start-e2e-server.ts | 133 ++ .../runner-e2e/source-sdk-public-inputs.json | 2 +- ui/src/components/AgentChatPicker.test.tsx | 167 -- ui/src/components/AgentMultiSelect.test.tsx | 187 -- ui/src/components/ChatComposer.test.tsx | 254 --- .../DocumentAnnotationLayer.test.tsx | 302 --- .../components/DocumentMarkdownBody.test.tsx | 142 -- ui/src/components/EnvVarEditor.test.tsx | 127 -- ui/src/components/FileTree.test.tsx | 231 --- .../components/InlineEntitySelector.test.tsx | 500 ----- .../InteractionGovernancePanel.test.tsx | 241 --- ui/src/components/IssueRow.test.tsx | 968 ---------- .../MarkdownEditor.autocomplete.test.tsx | 135 -- ui/src/components/QueryView.test.tsx | 306 --- ui/src/components/ScheduleEditor.test.tsx | 133 -- ui/src/components/SearchableSelect.test.tsx | 539 ------ .../StandaloneBrowserControls.test.tsx | 170 -- .../folders/FolderControls.test.tsx | 480 ----- .../folders/SkillFolderTree.test.tsx | 131 -- .../mcp-app/McpAppIssueContext.test.tsx | 100 - .../mcp-app/McpAppTurnViews.test.tsx | 111 -- ui/src/components/mcp-app/McpAppView.test.tsx | 131 -- .../task-chat/ComposerFileDropTarget.test.tsx | 226 --- .../ComposerRunSettingsPicker.test.tsx | 453 ----- .../task-chat/TaskChatQueuedMessages.test.tsx | 705 ------- .../task-chat/TaskChatRunnerTurn.test.tsx | 1712 ----------------- .../task-chat/TaskMessageScroller.test.tsx | 686 ------- ui/src/context/CompanyContext.test.tsx | 17 +- .../connections/AwsRoleSetup.test.tsx | 233 --- .../ConnectionIntentInteractionBody.test.tsx | 929 --------- .../GoogleWorkspaceServices.test.tsx | 245 --- .../connections/MachineSignInSetup.test.tsx | 161 -- .../RemoteMcpProductionSetup.test.tsx | 100 - ui/src/hooks/useRecentTaskOpenWarmup.test.tsx | 4 +- ui/src/lib/recent-selections.test.ts | 2 - ui/src/lib/responsibility-outline-v2.test.ts | 5 +- ui/src/lib/task-browsers-refresh.test.ts | 1 - ui/src/pages/apps/TailscaleConnector.test.tsx | 21 +- .../apps/app-detail/ActionTestDialog.test.tsx | 9 +- 78 files changed, 3376 insertions(+), 11238 deletions(-) create mode 100644 rules/test-budget.mdc create mode 100644 scripts/check-test-budget.mjs create mode 100644 scripts/check-test-budget.test.mjs create mode 100644 scripts/ci/vitest-workers.mjs create mode 100644 scripts/ci/workspaces-b-shard.mjs create mode 100644 scripts/ensure-workspace-package-links.mjs create mode 100644 tests/e2e/start-e2e-server.ts delete mode 100644 ui/src/components/AgentChatPicker.test.tsx delete mode 100644 ui/src/components/AgentMultiSelect.test.tsx delete mode 100644 ui/src/components/ChatComposer.test.tsx delete mode 100644 ui/src/components/DocumentAnnotationLayer.test.tsx delete mode 100644 ui/src/components/DocumentMarkdownBody.test.tsx delete mode 100644 ui/src/components/EnvVarEditor.test.tsx delete mode 100644 ui/src/components/FileTree.test.tsx delete mode 100644 ui/src/components/InlineEntitySelector.test.tsx delete mode 100644 ui/src/components/InteractionGovernancePanel.test.tsx delete mode 100644 ui/src/components/IssueRow.test.tsx delete mode 100644 ui/src/components/MarkdownEditor.autocomplete.test.tsx delete mode 100644 ui/src/components/QueryView.test.tsx delete mode 100644 ui/src/components/ScheduleEditor.test.tsx delete mode 100644 ui/src/components/SearchableSelect.test.tsx delete mode 100644 ui/src/components/StandaloneBrowserControls.test.tsx delete mode 100644 ui/src/components/folders/FolderControls.test.tsx delete mode 100644 ui/src/components/folders/SkillFolderTree.test.tsx delete mode 100644 ui/src/components/mcp-app/McpAppIssueContext.test.tsx delete mode 100644 ui/src/components/mcp-app/McpAppTurnViews.test.tsx delete mode 100644 ui/src/components/mcp-app/McpAppView.test.tsx delete mode 100644 ui/src/components/task-chat/ComposerFileDropTarget.test.tsx delete mode 100644 ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx delete mode 100644 ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx delete mode 100644 ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx delete mode 100644 ui/src/components/task-chat/TaskMessageScroller.test.tsx delete mode 100644 ui/src/features/connections/AwsRoleSetup.test.tsx delete mode 100644 ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx delete mode 100644 ui/src/features/connections/GoogleWorkspaceServices.test.tsx delete mode 100644 ui/src/features/connections/MachineSignInSetup.test.tsx delete mode 100644 ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.test.tsx diff --git a/.github/actions/setup-ci-dependencies/action.yml b/.github/actions/setup-ci-dependencies/action.yml index 0a78e542c91..e219d04a70a 100644 --- a/.github/actions/setup-ci-dependencies/action.yml +++ b/.github/actions/setup-ci-dependencies/action.yml @@ -85,7 +85,11 @@ runs: shell: bash working-directory: ${{ inputs.working-directory }} run: | - pnpm run preflight:workspace-links + if [ -f scripts/ensure-workspace-package-links.mjs ]; then + node scripts/ensure-workspace-package-links.mjs + else + pnpm run preflight:workspace-links + fi node scripts/ensure-plugin-build-deps.mjs - name: Save installed dependencies diff --git a/.github/ci-task-matrix.json b/.github/ci-task-matrix.json index 067ab518009..c63e7423cee 100644 --- a/.github/ci-task-matrix.json +++ b/.github/ci-task-matrix.json @@ -196,7 +196,16 @@ }, { "group": "general-workspaces-b", - "group_label": "workspaces-b", + "group_label": "workspaces-b (1/2)", + "shard_index": 0, + "shard_count": 2, + "task": "ci:workspaces-b" + }, + { + "group": "general-workspaces-b", + "group_label": "workspaces-b (2/2)", + "shard_index": 1, + "shard_count": 2, "task": "ci:workspaces-b" }, { diff --git a/.github/scripts/tests/ci-plan.test.mjs b/.github/scripts/tests/ci-plan.test.mjs index 6eae69eeb9c..b8563b0d3ba 100644 --- a/.github/scripts/tests/ci-plan.test.mjs +++ b/.github/scripts/tests/ci-plan.test.mjs @@ -114,8 +114,8 @@ test("PR workflow keeps Build fast and passes PR-mode context to typecheck and V const e2e = workflow.split("\n e2e_shards:\n")[1].split("\n e2e:\n")[0]; const releaseVerify = readFileSync(new URL(".github/workflows/release-verify.yml", root), "utf8"); const releaseBuild = releaseVerify.split("\n build:\n")[1].split("\n runner_binary_targets:\n")[0]; - const prKey = e2e.match(/key: (e2e-ui-dist-v1-.+)/)?.[1]; - const releaseKey = releaseBuild.match(/key: (e2e-ui-dist-v1-.+)/)?.[1]; + const prKey = e2e.match(/key: (e2e-ui-dist-v2-.+)/)?.[1]; + const releaseKey = releaseBuild.match(/key: (e2e-ui-dist-v2-.+)/)?.[1]; assert.ok(prKey && releaseKey, "both pr-trusted.yml and release-verify.yml must define the E2E UI dist cache key"); assert.equal(prKey, releaseKey, "E2E UI dist reader and writer keys must match exactly"); assert.doesNotMatch(e2e.split("Restore prebuilt UI assets")[1].split("Run e2e tests")[0], /restore-keys:/); @@ -374,7 +374,7 @@ else process.exit(3); else { assert.notEqual(value, "plan=", `${JSON.stringify(overrides)}: ${result.stderr}`); const resultPlan = JSON.parse(value.slice("plan=".length)); - assert.equal(resultPlan.jobs.general_tests.selected, overrides.PROFILE_CI || overrides.STACK_JSON ? 29 : 2); + assert.equal(resultPlan.jobs.general_tests.selected, overrides.PROFILE_CI || overrides.STACK_JSON ? 30 : 2); assert.equal(resultPlan.diff.base, base); assert.deepEqual(resultPlan.changed, ["ui/src/components/Sidebar.tsx"]); } diff --git a/.github/workflows/pr-trusted.yml b/.github/workflows/pr-trusted.yml index 9963714fc9e..685848b978b 100644 --- a/.github/workflows/pr-trusted.yml +++ b/.github/workflows/pr-trusted.yml @@ -251,6 +251,20 @@ jobs: - name: Test e2e shard partition run: node "$CI_NODE_TEST" ./scripts/__tests__/e2e-shard.test.mjs + - name: Check CI test budget policy + run: | + if [[ -f ./scripts/check-test-budget.mjs ]]; then + base_sha="${{ github.event.pull_request.base.sha }}" + if [[ -n "$base_sha" ]]; then + node ./scripts/check-test-budget.mjs --base "$base_sha" + else + node ./scripts/check-test-budget.mjs + fi + fi + if [[ -f ./scripts/check-test-budget.test.mjs ]]; then + node "$CI_NODE_TEST" ./scripts/check-test-budget.test.mjs + fi + - name: Test release verify workflow wiring run: | tests=(./scripts/__tests__/release-verify-workflow.test.mjs ./scripts/__tests__/eval-schedule-monitor.test.mjs ./scripts/__tests__/prepare-runner-release-image.test.mjs ./scripts/cloud-source-verification.test.mjs ./scripts/cloud-readiness-runner-loss.test.mjs ./scripts/standard-image-contract.test.mjs ./scripts/reuse-canary-image.test.mjs) @@ -521,7 +535,7 @@ jobs: strategy: fail-fast: false max-parallel: ${{ needs.gate.outputs.runner == 'ubuntu-latest' && 4 || 256 }} - matrix: ${{ fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan) != '' && toJSON(fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan)).jobs.general_tests.matrix) || '{"include":[{"group":"general-server-without-chat","group_label":"server (1/20)","shard_index":0,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (2/20)","shard_index":1,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (3/20)","shard_index":2,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (4/20)","shard_index":3,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (5/20)","shard_index":4,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (6/20)","shard_index":5,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (7/20)","shard_index":6,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (8/20)","shard_index":7,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (9/20)","shard_index":8,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (10/20)","shard_index":9,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (11/20)","shard_index":10,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (12/20)","shard_index":11,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (13/20)","shard_index":12,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (14/20)","shard_index":13,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (15/20)","shard_index":14,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (16/20)","shard_index":15,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (17/20)","shard_index":16,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (18/20)","shard_index":17,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (19/20)","shard_index":18,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (20/20)","shard_index":19,"shard_count":20,"task":"ci:server"},{"group":"general-chat","group_label":"chat (1/5)","shard_index":0,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (2/5)","shard_index":1,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (3/5)","shard_index":2,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (4/5)","shard_index":3,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (5/5)","shard_index":4,"shard_count":5,"task":"ci:chat"},{"group":"general-workspaces-a","group_label":"workspaces-a (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-a","group_label":"workspaces-a (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-b","group_label":"workspaces-b","task":"ci:workspaces-b"},{"group":"general-workspaces-c","group_label":"workspaces-c","task":"ci:db"}]}') }} + matrix: ${{ fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan) != '' && toJSON(fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan)).jobs.general_tests.matrix) || '{"include":[{"group":"general-server-without-chat","group_label":"server (1/20)","shard_index":0,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (2/20)","shard_index":1,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (3/20)","shard_index":2,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (4/20)","shard_index":3,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (5/20)","shard_index":4,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (6/20)","shard_index":5,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (7/20)","shard_index":6,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (8/20)","shard_index":7,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (9/20)","shard_index":8,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (10/20)","shard_index":9,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (11/20)","shard_index":10,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (12/20)","shard_index":11,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (13/20)","shard_index":12,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (14/20)","shard_index":13,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (15/20)","shard_index":14,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (16/20)","shard_index":15,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (17/20)","shard_index":16,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (18/20)","shard_index":17,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (19/20)","shard_index":18,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (20/20)","shard_index":19,"shard_count":20,"task":"ci:server"},{"group":"general-chat","group_label":"chat (1/5)","shard_index":0,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (2/5)","shard_index":1,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (3/5)","shard_index":2,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (4/5)","shard_index":3,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (5/5)","shard_index":4,"shard_count":5,"task":"ci:chat"},{"group":"general-workspaces-a","group_label":"workspaces-a (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-a","group_label":"workspaces-a (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-b","group_label":"workspaces-b (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-b"},{"group":"general-workspaces-b","group_label":"workspaces-b (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-b"},{"group":"general-workspaces-c","group_label":"workspaces-c","task":"ci:db"}]}') }} env: PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }} @@ -1740,7 +1754,7 @@ jobs: uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: server/ui-dist - key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + key: e2e-ui-dist-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/package.json', 'packages/shared/src/**', 'packages/adapter-utils/package.json', 'packages/adapter-utils/src/**', 'packages/adapters/*/package.json', 'packages/adapters/*/src/**', 'packages/plugins/sdk/package.json', 'packages/plugins/sdk/src/**', 'announcements/examples/animated/**') }} - name: Run e2e tests env: diff --git a/.github/workflows/release-verify.yml b/.github/workflows/release-verify.yml index 55044cb9a1c..e7513ffa0c7 100644 --- a/.github/workflows/release-verify.yml +++ b/.github/workflows/release-verify.yml @@ -573,7 +573,7 @@ jobs: with: lookup-only: true path: server/ui-dist - key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + key: e2e-ui-dist-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/package.json', 'packages/shared/src/**', 'packages/adapter-utils/package.json', 'packages/adapter-utils/src/**', 'packages/adapters/*/package.json', 'packages/adapters/*/src/**', 'packages/plugins/sdk/package.json', 'packages/plugins/sdk/src/**', 'announcements/examples/animated/**') }} - name: Stage prebuilt UI assets for E2E cache if: ${{ github.repository == 'paperclipai/paperclip' && github.event_name == 'push' && github.ref == 'refs/heads/master' && inputs.ref == github.sha && steps.e2e_ui_dist.outputs.cache-hit != 'true' }} @@ -584,7 +584,7 @@ jobs: uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: server/ui-dist - key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + key: e2e-ui-dist-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/package.json', 'packages/shared/src/**', 'packages/adapter-utils/package.json', 'packages/adapter-utils/src/**', 'packages/adapters/*/package.json', 'packages/adapters/*/src/**', 'packages/plugins/sdk/package.json', 'packages/plugins/sdk/src/**', 'announcements/examples/animated/**') }} runner_binary_targets: if: inputs.runner_binaries_only diff --git a/.greptile/files.json b/.greptile/files.json index 080b8aa1fe8..061c6a67430 100644 --- a/.greptile/files.json +++ b/.greptile/files.json @@ -161,6 +161,17 @@ "server/src/routes/sidebar-preferences.ts", "server/src/services/sidebar-preferences.ts" ] + }, + { + "path": "rules/test-budget.mdc", + "description": "CI test budget: prevent unbudgeted real-clock sleeps >1s, historical SQL migration test sprawl, brittle static prose-grep tests, and tiny standalone embedded-Postgres files while keeping core invariants on PRs.", + "scope": [ + "packages/db/src/**/*.test.ts", + "server/src/**/*.test.ts", + "ui/src/**/*.test.ts", + "ui/src/**/*.test.tsx", + "tests/e2e/**/*.spec.ts" + ] } ] } diff --git a/maps/agent-access-map/connection-setup.md b/maps/agent-access-map/connection-setup.md index 8f47af39dd3..e67fda9544d 100644 --- a/maps/agent-access-map/connection-setup.md +++ b/maps/agent-access-map/connection-setup.md @@ -189,7 +189,7 @@ Gaps: This individual operation has source review but no recorded HTTP verificat API: `present` — `POST /api/tools/oauth/{connectionId}/start`; JSON REST. Agent access: `available` — agent REST and default native `search_api` / `call_api`. Policy: `tools:manage_connections`; [shared management policy](../../doc/plans/2026-10-13-connection-api-parity.md#authorization-contract). Resolved resources and every affected target are checked; personal ownership remains the responsible user. Returns the saved setup without issuing agent-bound OAuth state; the human browser initiates provider consent. -Evidence: `verified` — [authenticated integration fixtures](../../server/src/__tests__/connection-management.integration.test.ts) passed through production authentication and database persistence, including saved Google service choices addressed to the responsible user. [Service-picker tests](../../ui/src/features/connections/GoogleWorkspaceServices.test.tsx) cover restoring only that user's request and retaining newer consent. +Evidence: `verified` — [authenticated integration fixtures](../../server/src/__tests__/connection-management.integration.test.ts) passed through production authentication and database persistence, including saved Google service choices addressed to the responsible user. (Mocked `GoogleWorkspaceServices` UI service-picker tests were removed; verify UI consent-picker restoration manually.) Verification: `passed` — deterministic local fixture; no live provider qualification. Gaps: Provider fixtures do not qualify live provider setup or availability. diff --git a/maps/feature-map/agent-chat.md b/maps/feature-map/agent-chat.md index bb1af2be115..6e58f009883 100644 --- a/maps/feature-map/agent-chat.md +++ b/maps/feature-map/agent-chat.md @@ -61,7 +61,7 @@ uses real app APIs and a deterministic process agent to verify first-chat discov unread state across reloads, source navigation and follow-up context. It does not qualify live PR retrieval or a model's editorial choices. -Automated: [composer picker](../../ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx) covers fixed-agent model/effort selection on desktop and mobile; [composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) covers Coordinator gating and settings submission without reassignment. (Mocked `IssueDetail` UI tests for canonical first/existing-chat IDs and settings-before-comment ordering were removed; verify those page-level flows manually.) These tests mock the API and do not prove provider execution with the chosen model. +Automated: [composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) covers Coordinator gating and settings submission without reassignment. (Mocked `ComposerRunSettingsPicker` and `IssueDetail` UI tests for model/effort selection, canonical first/existing-chat IDs, and settings-before-comment ordering were removed; verify those UI flows manually.) These tests mock the API and do not prove provider execution with the chosen model. Automated: [thread and composer](../../ui/src/components/TaskChatThread.test.tsx) keeps an in-flight attachment through first-chat creation on desktop and mobile, diff --git a/maps/feature-map/connection-setup.md b/maps/feature-map/connection-setup.md index 797b2725338..446fd0223b5 100644 --- a/maps/feature-map/connection-setup.md +++ b/maps/feature-map/connection-setup.md @@ -242,10 +242,10 @@ Slack setup does not qualify Discord, Telegram, GitHub, email, or iMessage. Automated: [agent-authenticated integration](../../server/src/__tests__/connection-management.integration.test.ts) uses production agent creation, persistent keys, run JWTs, native tool bindings, human sessions, PostgreSQL and deterministic provider fixtures. It covers saved -setup, ownership, attribution, scope, trust, work modes and revocation. The -[Google service picker tests](../../ui/src/features/connections/GoogleWorkspaceServices.test.tsx) -cover pending choices, consent precedence and failed grant loading with API mocks. -These are separate from live provider setup and model success. +setup, ownership, attribution, scope, trust, work modes and revocation. (Mocked +`GoogleWorkspaceServices` UI service-picker tests were removed; verify pending +choices and consent-picker UI manually.) These are separate from live provider +setup and model success. Manual: Have the agent perform authorized setup, then open its saved handoff as the addressed person. Reload before completing the required human step; verify diff --git a/maps/feature-map/steering.md b/maps/feature-map/steering.md index 2605e60ea48..fe1cd5d771f 100644 --- a/maps/feature-map/steering.md +++ b/maps/feature-map/steering.md @@ -65,12 +65,11 @@ unsupported steering without treating an absent capability as a product failure. ### `task-composer` -Automated: [queued-message UI](../../ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx) -covers order, failure restoration, unavailable steering, stale revisions, and -discard acknowledgements. [Queue routes](../../server/src/__tests__/issue-queued-comments-routes.test.ts) +Automated: [Queue routes](../../server/src/__tests__/issue-queued-comments-routes.test.ts) cover durable ordering, authorization, steering acknowledgements, interrupt recovery, and concurrent dispatch. [Composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) -covers drafts and uncertain saves. +covers drafts and uncertain saves. (Mocked `TaskChatQueuedMessages` UI tests were +removed; verify queued-message UI rendering manually.) Mocked `IssueDetail` delivery-race UI tests were removed (verify late send-response and queue-snapshot races manually). Expected behavior: a started @@ -186,4 +185,4 @@ Capability ID: `steering/approval-queue`. Scope: ui Storybook: Answered question/accepted approval delivery waiting, eligible steer/interrupt, failed delivery and fresh-session-only approval. Production: Keep response delivery durable and distinct from editable comments; coalesce once, enforce fresh-session restrictions and deduplicate concurrent/retried continuation. -Sources: Source: [TaskChatQueuedMessages.tsx](../../ui/src/components/task-chat/TaskChatQueuedMessages.tsx), [question-response-delivery.ts](../../server/src/services/question-response-delivery.ts). Tests: [TaskChatQueuedMessages.test.tsx](../../ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx), [question-response-delivery.test.ts](../../server/src/__tests__/question-response-delivery.test.ts), [issue-queued-comments-routes.test.ts](../../server/src/__tests__/issue-queued-comments-routes.test.ts) +Sources: Source: [TaskChatQueuedMessages.tsx](../../ui/src/components/task-chat/TaskChatQueuedMessages.tsx), [question-response-delivery.ts](../../server/src/services/question-response-delivery.ts). Tests: [question-response-delivery.test.ts](../../server/src/__tests__/question-response-delivery.test.ts), [issue-queued-comments-routes.test.ts](../../server/src/__tests__/issue-queued-comments-routes.test.ts) diff --git a/package.json b/package.json index 416070f08a9..d9d6052ec03 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "scripts": { "perf:workspace-admission": "node --import ./server/node_modules/tsx/dist/loader.mjs server/scripts/benchmark-workspace-admission.ts", "postinstall": "node scripts/link-plugin-dev-sdk.mjs", - "preflight:workspace-links": "node cli/node_modules/tsx/dist/cli.mjs scripts/ensure-workspace-package-links.ts", + "preflight:workspace-links": "node scripts/ensure-workspace-package-links.mjs", "dev": "pnpm --filter @paperclipai/server exec tsx ../scripts/dev-runner.ts watch", "dev:watch": "pnpm --filter @paperclipai/server exec tsx ../scripts/dev-runner.ts watch", "dev:once": "pnpm --filter @paperclipai/server exec tsx ../scripts/dev-runner.ts dev", @@ -28,8 +28,8 @@ "test:run": "pnpm run preflight:workspace-links && node scripts/run-vitest-stable.mjs", "test:runner-acceptance": "vitest run --config tests/runner-acceptance/vitest.config.ts", "test:runner-acceptance:typecheck": "tsc -p tests/runner-acceptance/tsconfig.json", - "test:run:general": "pnpm run preflight:workspace-links && pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && node scripts/run-vitest-stable.mjs --mode general", - "test:run:serialized": "pnpm run preflight:workspace-links && pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && node scripts/run-vitest-stable.mjs --mode serialized", + "test:run:general": "node scripts/ensure-workspace-package-links.mjs && node scripts/ensure-plugin-build-deps.mjs && node scripts/run-vitest-stable.mjs --mode general", + "test:run:serialized": "node scripts/ensure-workspace-package-links.mjs && node scripts/ensure-plugin-build-deps.mjs && node scripts/run-vitest-stable.mjs --mode serialized", "db:generate": "pnpm --filter @paperclipai/db generate", "db:migrate": "pnpm --filter @paperclipai/db migrate", "issue-references:backfill": "pnpm run preflight:workspace-links && tsx scripts/backfill-issue-reference-mentions.ts", @@ -95,7 +95,7 @@ "test:lifecycle-baseline": "node tests/lifecycle-baseline/run.mjs", "test:lifecycle-baseline:support": "node --test tests/lifecycle-baseline/report.test.mjs", "test:lifecycle-baseline:typecheck": "node scripts/typecheck-test-projects.mjs tests/lifecycle-baseline", - "verify": "node --import ./cli/node_modules/tsx/dist/loader.mjs scripts/ensure-workspace-package-links.ts && node scripts/local-verify.mjs" + "verify": "node scripts/ensure-workspace-package-links.mjs && node scripts/local-verify.mjs" }, "devDependencies": { "@playwright/test": "^1.62.1", diff --git a/packages/db/src/test-embedded-postgres.ts b/packages/db/src/test-embedded-postgres.ts index 0e2488523c6..13895a6285b 100644 --- a/packages/db/src/test-embedded-postgres.ts +++ b/packages/db/src/test-embedded-postgres.ts @@ -203,11 +203,30 @@ async function stopEmbeddedPostgresBounded( // a fresh port and a fresh data directory, so a transient collision clears. const EMBEDDED_POSTGRES_START_MAX_ATTEMPTS = 5; +export type EmbeddedPostgresTestDatabaseOptions = { + maxConnections?: number; +}; + +function applyPostgresConfigOverrides(dataDir: string, options?: EmbeddedPostgresTestDatabaseOptions): void { + const maxConnections = options?.maxConnections; + if (!maxConnections || !Number.isInteger(maxConnections) || maxConnections < 1) { + return; + } + const configPath = path.join(dataDir, "postgresql.conf"); + if (!fs.existsSync(configPath)) { + return; + } + fs.appendFileSync(configPath, `\nmax_connections = ${maxConnections}\n`, "utf8"); +} + // Start one embedded Postgres cluster with a bounded retry. Each attempt gets a // fresh port and a fresh data directory. On a failed attempt we stop the cluster // and remove its data directory before the next attempt. After the last attempt // we throw with the real Postgres output so the failure is loud and diagnosable. -async function startEmbeddedPostgresWithRetry(tempDirPrefix: string): Promise<{ +async function startEmbeddedPostgresWithRetry( + tempDirPrefix: string, + options?: EmbeddedPostgresTestDatabaseOptions, +): Promise<{ port: number; dataDir: string; instance: EmbeddedPostgresInstance; @@ -218,6 +237,7 @@ async function startEmbeddedPostgresWithRetry(tempDirPrefix: string): Promise<{ const created = await createEmbeddedPostgresTestInstance(tempDirPrefix); try { await created.instance.initialise(); + applyPostgresConfigOverrides(created.dataDir, options); await created.instance.start(); return { port: created.port, dataDir: created.dataDir, instance: created.instance }; } catch (error) { @@ -542,6 +562,7 @@ function resetTemplateDirCache(): void { async function startEmbeddedPostgresFromTemplateWithRetry( templateDir: string, tempDirPrefix: string, + options?: EmbeddedPostgresTestDatabaseOptions, ): Promise<{ port: number; dataDir: string; instance: EmbeddedPostgresInstance }> { let lastError = new Error("embedded Postgres startup from template failed"); @@ -556,6 +577,7 @@ async function startEmbeddedPostgresFromTemplateWithRetry( fs.cpSync(templateDir, dataDir, { recursive: true }); // Postgres refuses a data directory that is group or world accessible. fs.chmodSync(dataDir, 0o700); + applyPostgresConfigOverrides(dataDir, options); created = await createEmbeddedPostgresTestInstanceAt(dataDir); await created.instance.start(); return { port: created.port, dataDir: rootDir, instance: created.instance }; @@ -640,12 +662,13 @@ export async function getEmbeddedPostgresTestSupport(): Promise { const templateDir = await getEmbeddedPostgresTemplateDir(); if (templateDir !== null) { try { - const started = await startEmbeddedPostgresFromTemplateWithRetry(templateDir, tempDirPrefix); + const started = await startEmbeddedPostgresFromTemplateWithRetry(templateDir, tempDirPrefix, options); return { ...started, mode: "template" }; } catch (error) { if (error instanceof TestPostgresShutdownError) throw error; @@ -663,16 +686,17 @@ async function startEmbeddedPostgresClusterForSuite( // The bounded retry hardens the cluster start against the port race. It throws // with the real Postgres output if every attempt fails. - const started = await startEmbeddedPostgresWithRetry(tempDirPrefix); + const started = await startEmbeddedPostgresWithRetry(tempDirPrefix, options); return { ...started, mode: "fresh" }; } export async function startEmbeddedPostgresTestDatabase( tempDirPrefix: string, + options?: EmbeddedPostgresTestDatabaseOptions, ): Promise { const adminUrl = testPostgresAdminUrl(); if (adminUrl) return startTestPostgresDatabase(adminUrl); - const { port, dataDir, instance, mode } = await startEmbeddedPostgresClusterForSuite(tempDirPrefix); + const { port, dataDir, instance, mode } = await startEmbeddedPostgresClusterForSuite(tempDirPrefix, options); lastStartMode = mode; try { diff --git a/packages/db/src/test-postgres-command.ts b/packages/db/src/test-postgres-command.ts index dcedaac7254..2ae85e503a7 100644 --- a/packages/db/src/test-postgres-command.ts +++ b/packages/db/src/test-postgres-command.ts @@ -16,7 +16,10 @@ try { let adminUrl = testPostgresAdminUrl(); if (adminUrl) await checkTestPostgresAdmin(adminUrl); else { - server = await startEmbeddedPostgresTestDatabase("paperclip-test-command-"); + // Shared multi-worker test server: raise max_connections above Postgres's + // default 100 so 7-8 parallel Vitest fork workers (each with main + private + // pools) never exhaust backend slots on 8-core runners or dev workstations. + server = await startEmbeddedPostgresTestDatabase("paperclip-test-command-", { maxConnections: 300 }); const url = new URL(server.connectionString); url.pathname = "/postgres"; adminUrl = url.toString(); diff --git a/rules/test-budget.mdc b/rules/test-budget.mdc new file mode 100644 index 00000000000..10c3a5e7cc4 --- /dev/null +++ b/rules/test-budget.mdc @@ -0,0 +1,42 @@ +--- +description: Keep PR tests fast and high-signal: avoid unbudgeted real-clock sleeps >1s, historical SQL migration replay sprawl, brittle static prose-grep tests, and tiny standalone embedded-Postgres files. +alwaysApply: false +globs: packages/db/src/**/*.test.ts, server/src/**/*.test.ts, ui/src/**/*.test.ts, ui/src/**/*.test.tsx, tests/e2e/**/*.spec.ts +--- + +# CI test budget + +This rule applies to Vitest and Playwright test files across `packages/db`, `server`, `ui`, and `tests/e2e`. + +## Required behavior + +1. **No unbudgeted real-clock sleeps over 1 second in PR tests.** + - Use fake timers (`vi.useFakeTimers()`), deterministic event/condition waits, or direct service calls instead of `setTimeout(..., >1000)`, `delay(>1000)`, or `page.waitForTimeout(>1000)`. + - True real-clock soak, lease-expiry, restart, crash-recovery, retention-sweep, and load/benchmark suites must be registered in `scripts/ci/nightly-only-suites.json` so they run on `master`, `release-verify`, `cloud-readiness`, local `pnpm test:run`, and `PAPERCLIP_CI_FULL=1` without blocking ordinary PRs. + - If a PR test genuinely requires a real-clock wait over 1s (for example testing a real idle-timeout or socket deadline), annotate the line with `// test-budget:allow-sleep: `. + +2. **No historical one-time SQL migration replay sprawl.** + - Do not add standalone `*-migration.test.ts` files that tear down schema and replay already-shipped SQL migrations against embedded Postgres. + - Test ongoing migration-runner invariants, safety rules, and schema/snapshot integrity in the core owner suites: `packages/db/src/client.test.ts`, `packages/db/src/check-migration-safety.test.ts`, `packages/db/src/migration-compatibility.test.ts`, and `packages/db/src/migration-snapshot-drift.test.ts`. + - Active runtime migration services (not historical SQL replay) are exempt, and long-running migration soaks belong in `scripts/ci/nightly-only-suites.json`. + +3. **No brittle static prose-grep tests.** + - Do not add `*-guidance.test.ts` suites that `readFileSync` / `readFile` markdown docs, skill prose, or `ui/src/*.tsx` solely to assert exact wording or copy strings. + - Security, authz, and safety static guards (such as `cli-invocation-safety.test.ts`, `authz-existence-oracle-guard.test.ts`, and `app-private-hostname-gate.test.ts`) are explicit exceptions. + +4. **Extend existing owner suites instead of adding tiny standalone embedded-Postgres files.** + - Each standalone server/DB test file pays isolated Vitest worker import, transform, and disposable-database setup cost. + - Do not create a new `<= 80` LOC test file that boots embedded Postgres (`startEmbeddedPostgresTestDatabase` / `createTestPostgres`) for one narrow regression case; add the test case to the owning service or route suite instead. + - If a standalone file is required for process or environment isolation, annotate the file with `// test-budget:allow-standalone-db: `. + +5. **Preserve core control-plane invariants on every PR.** + - Never demote suites covering company isolation, board/agent authz, atomic checkout, single-assignee rules, approval gates, budget hard-stops, mutation activity logging, secrets/CSRF/redaction/privacy, or telemetry/Sentry contracts into `scripts/ci/nightly-only-suites.json`. + +## Automated guardrail + +Run `node scripts/check-test-budget.mjs` (or `--base ` / `--files `) to validate `scripts/ci/nightly-only-suites.json` integrity and enforce the budget rules on new or changed test files. + +## Review criteria + +- Flag new PR test files with unannotated sleeps `> 1000ms`, historical SQL migration replay files, static prose-grep guidance tests, or tiny `<= 80` LOC embedded-Postgres files that belong in an existing owner suite. +- Flag any edit to `scripts/ci/nightly-only-suites.json` that adds missing/duplicate paths or demotes a core control-plane or security/privacy invariant suite. diff --git a/scripts/__tests__/ci-typecheck-lane.test.mjs b/scripts/__tests__/ci-typecheck-lane.test.mjs index 04c745a0de6..938de3de91a 100644 --- a/scripts/__tests__/ci-typecheck-lane.test.mjs +++ b/scripts/__tests__/ci-typecheck-lane.test.mjs @@ -4,8 +4,11 @@ import { getPriority } from "node:os"; import test from "node:test"; import { BACKGROUND_PRIORITY, + BUILD_SERVER_EMIT_ONLY, + computeResourceProfile, createReporter, planLane, + PREPARE_RUNNER_VENDOR, resolveScope, runLane, selectBuildGapPackages, @@ -23,12 +26,19 @@ const plan = () => const quietReporter = (lines = []) => createReporter({ write: (text) => lines.push(text), github: false }); const node = (name, source, needs) => ({ name, command: process.execPath, args: ["-e", source], needs }); -test("the shared outputs are written before the parallel checks start", () => { +test("the shared outputs are written before dependent checks start, while emit-only server build overlaps", () => { const { prepare, tasks } = plan(); - const names = prepare.map((task) => task.name); - const build = prepare.find((task) => task.args.includes("@paperclipai/server") && task.args.includes("build")); - assert.deepEqual(build.env, { PAPERCLIP_TSC_EMIT_ONLY: "1" }); - assert.ok(names.indexOf("check server runtime assets") > names.indexOf(build.name)); + const byName = new Map(tasks.map((task) => [task.name, task])); + assert.ok(!prepare.some((task) => task.name === BUILD_SERVER_EMIT_ONLY)); + assert.ok(!prepare.some((task) => task.name === "check server runtime assets")); + const build = byName.get(BUILD_SERVER_EMIT_ONLY); + assert.deepEqual(build.env, { + PAPERCLIP_TSC_EMIT_ONLY: "1", + PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT: "1", + }); + assert.deepEqual(build.needs, [PREPARE_RUNNER_VENDOR]); + assert.equal(build.background, true); + assert.deepEqual(byName.get("check server runtime assets").needs, [BUILD_SERVER_EMIT_ONLY]); assert.ok(prepare.some((task) => task.args.join(" ") === "scripts/typecheck-test-programs.mjs --prepare-only")); for (const name of SERIAL_BUILD_GAPS) { assert.ok(prepare.some((task) => task.name === `typecheck ${name}`), name); @@ -37,22 +47,26 @@ test("the shared outputs are written before the parallel checks start", () => { const guidance = prepare.find((task) => task.name === "CLI guidance safety"); assert.ok(guidance.args.includes("server/src/__tests__/cli-invocation-safety.test.ts")); assert.equal(guidance.background, undefined); - const programs = tasks.find((task) => task.name === "typecheck test programs"); + const programs = byName.get("typecheck test programs"); assert.ok(programs.args.includes("--skip-prepare")); + assert.deepEqual(programs.needs, [PREPARE_RUNNER_VENDOR]); for (const task of tasks) { assert.ok(!(task.args.includes("@paperclipai/server") && task.args.includes("typecheck")), task.name); } }); -test("every check of the sequential job is planned, and only declaration readers wait", () => { +test("every check of the sequential job is planned with exact DAG dependencies", () => { const { tasks } = plan(); const byName = new Map(tasks.map((task) => [task.name, task])); + assert.deepEqual(byName.get(PREPARE_RUNNER_VENDOR).args, ["--filter", "@paperclipai/server", "run", "prepare:runner-vendor"]); + assert.equal(byName.get(PREPARE_RUNNER_VENDOR).needs, undefined); assert.deepEqual(byName.get("server declarations").args, [ "server/scripts/typecheck-layers.mjs", "--declarations-only", "--checkers", "2", ]); + assert.deepEqual(byName.get("server declarations").needs, [PREPARE_RUNNER_VENDOR]); for (const layer of ["tests", "test-tree-0"]) { const task = byName.get(`server layer ${layer}`); assert.deepEqual(task.args, ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"]); @@ -65,15 +79,68 @@ test("every check of the sequential job is planned, and only declaration readers assert.deepEqual(task.needs, ["server declarations"]); } for (const name of ["paperclipai", "@paperclipai/ui"]) assert.ok(byName.has(`typecheck ${name}`), name); + assert.deepEqual(byName.get("typecheck paperclipai").needs, [PREPARE_RUNNER_VENDOR]); + assert.equal(byName.get("typecheck @paperclipai/ui").needs, undefined); assert.deepEqual(byName.get("typecheck @paperclipai/ui").env, { GOMAXPROCS: "2" }); assert.deepEqual(byName.get("release registry tests").args, ["run", "test:release-registry"]); + assert.equal(byName.get("release registry tests").needs, undefined); assert.ok(!byName.has("CLI guidance safety")); - const waiting = tasks.filter((task) => task.needs); - assert.equal(waiting.length, 2 + PROJECTS.length); - assert.deepEqual( - tasks.filter((task) => !task.background).map((task) => task.name), - ["server declarations", "release registry tests", ...waiting.map((task) => task.name)], - ); + const declarationReaders = tasks.filter((task) => task.needs?.includes("server declarations")); + assert.equal(declarationReaders.length, 2 + PROJECTS.length); +}); + +test("computeResourceProfile scales concurrency, checkers, and UI GOMAXPROCS across 2/4/8-core runners", () => { + const GiB = 1024 ** 3; + assert.deepEqual(computeResourceProfile({ cpus: 2, totalMemoryBytes: 8 * GiB }), { + laneConcurrency: 2, + serverDeclCheckers: 1, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 1, + testProgramsConcurrency: 1, + testProgramsCheckers: 1, + }); + assert.deepEqual(computeResourceProfile({ cpus: 4, totalMemoryBytes: 16 * GiB }), { + laneConcurrency: 3, + serverDeclCheckers: 2, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 2, + testProgramsConcurrency: 2, + testProgramsCheckers: 1, + }); + // 8-core / 16 GiB (c8i.2xlarge): 4 concurrent tasks so all 4 server layers finish in 1 wave under 16 GiB. + const c8i = computeResourceProfile({ cpus: 8, totalMemoryBytes: 16 * GiB }); + assert.deepEqual(c8i, { + laneConcurrency: 4, + serverDeclCheckers: 3, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 4, + testProgramsConcurrency: 3, + testProgramsCheckers: 1, + }); + // 8-core / 32 GiB (m8i.2xlarge): higher checkers and concurrency. + const m8i = computeResourceProfile({ cpus: 8, totalMemoryBytes: 32 * GiB }); + assert.deepEqual(m8i, { + laneConcurrency: 6, + serverDeclCheckers: 4, + serverLayerCheckers: 2, + testProjectCheckers: 2, + uiGomaxprocs: 4, + testProgramsConcurrency: 4, + testProgramsCheckers: 2, + }); + + const { tasks } = planLane({ + buildGapPackages: ["@paperclipai/ui"], + testLayers: ["tests"], + resources: c8i, + }); + const byName = new Map(tasks.map((t) => [t.name, t])); + assert.deepEqual(byName.get("server declarations").args.slice(-2), ["--checkers", "3"]); + assert.deepEqual(byName.get("typecheck @paperclipai/ui").env, { GOMAXPROCS: "4" }); + assert.ok(byName.get("typecheck test programs").args.join(" ").includes("--concurrency 3")); }); test("resolveScope uses CI_PLAN in PR mode, honors PAPERCLIP_CI_FULL, and fails closed", () => { @@ -138,11 +205,14 @@ test("PR mode for a server-only change skips release registry, UI, runner, sandb const prepareNames = prepare.map((task) => task.name); const taskNames = tasks.map((task) => task.name); - assert.ok(prepareNames.includes("build server without type checks")); + assert.ok(!prepareNames.includes("build server without type checks")); assert.ok(prepareNames.includes("CLI guidance safety")); assert.ok(!prepareNames.includes("install test program dependencies")); assert.ok(!prepareNames.includes("typecheck @paperclipai/paperclip-runner")); + assert.ok(taskNames.includes(PREPARE_RUNNER_VENDOR)); + assert.ok(taskNames.includes(BUILD_SERVER_EMIT_ONLY)); + assert.ok(taskNames.includes("check server runtime assets")); assert.ok(taskNames.includes("server declarations")); assert.ok(taskNames.includes("server layer tests")); assert.ok(taskNames.includes("typecheck paperclipai")); @@ -167,6 +237,8 @@ test("selectTestProjects follows the import graph so imported UI and server help assert.deepEqual(selectTestProjects(["ui/src/components/Sidebar.tsx"]), []); assert.ok(selectTestProjects(["server/src/services/issues.ts"]).includes("tests/runner-e2e")); assert.ok(selectTestProjects(["server/src/services/issues.ts"]).includes("server/src/__tests__/helpers/maintenance")); + assert.ok(selectTestProjects(["server/src/index.ts"]).includes("tests/e2e")); + assert.ok(selectTestProjects(["packages/db/src/test-embedded-postgres.ts"]).includes("tests/e2e")); assert.ok(selectTestProjects(["tests/unknown-new-project/a.ts"], [...PROJECTS, "tests/unknown-new-project"]).includes("tests/unknown-new-project")); const uiHelperPlan = planLane({ @@ -222,6 +294,10 @@ test("PR mode fails closed for unknown build-gap packages and global typecheck i assert.deepEqual(selectBuildGapPackages(["@paperclipai/ui", "@paperclipai/new-pkg"], ["server/src/a.ts"]), [ "@paperclipai/new-pkg", ]); + assert.deepEqual( + selectBuildGapPackages(["@paperclipai/ui"], ["packages/paperclip-runner/src/drivers/acpx/pi-extension-adapter.ts"]), + ["@paperclipai/ui"], + ); const globalPlan = planLane({ buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"], testLayers: ["tests"], diff --git a/scripts/__tests__/e2e-shard.test.mjs b/scripts/__tests__/e2e-shard.test.mjs index d19d0eba92a..f71afb68578 100644 --- a/scripts/__tests__/e2e-shard.test.mjs +++ b/scripts/__tests__/e2e-shard.test.mjs @@ -9,6 +9,7 @@ import test from "node:test"; import { defaultSuiteWeight, loadShardDurations } from "../general-server-shard.mjs"; import { DEFAULT_PARALLEL_WORKERS, + EFFECTIVE_PARALLEL_SPEEDUP, IGNORED_SPECS, SERIAL_SPECS, isSerialE2eSpec, @@ -152,10 +153,12 @@ test("the serial spec list matches playwright.config.ts SERIAL_SPECS and never m } }); -test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1", () => { +test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1 and uses unminified inline builds", () => { const config = readFileSync(playwrightConfig, "utf8"); assert.match(config, /PAPERCLIP_E2E_SKIP_UI_BUILD/); assert.match(config, /ui-dist.*index\.html/); + assert.match(config, /--minify false/); + assert.match(config, /availableParallelism/); }); test("the duration manifest only names specs that still exist", () => { @@ -172,11 +175,11 @@ test("the weighted partition keeps the shards close to balanced", () => { const specs = listE2eSpecs(); const fallbackWeight = defaultSuiteWeight(durations); const shards = partitionE2eShards(specs, SHARD_COUNT, durations, { - parallelWorkers: DEFAULT_PARALLEL_WORKERS, + parallelWorkers: EFFECTIVE_PARALLEL_SPEEDUP, }); const wallWeights = shards.map((shard) => { const serialSum = shard.files.reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0); - return shard.mode === "parallel" ? serialSum / DEFAULT_PARALLEL_WORKERS : serialSum; + return shard.mode === "parallel" ? serialSum / EFFECTIVE_PARALLEL_SPEEDUP : serialSum; }); const heaviest = Math.max(...wallWeights); diff --git a/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs b/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs index 0e53b26f544..867719a20f3 100644 --- a/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs +++ b/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs @@ -6,6 +6,13 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import test from "node:test"; import { selectionHash } from "../ci/test-selection-manifest.mjs"; +import { + defaultServerParallelWorkers, + resolveServerParallelWorkers, + resolveWorkspaceParallelWorkers, +} from "../ci/vitest-workers.mjs"; +import { partitionWorkspaceProjects, selectWorkspaceProjectsShard } from "../ci/workspaces-b-shard.mjs"; +import { discoverWorkspacePackagePaths, ensureAllWorkspaceLinksCurrent } from "../ensure-workspace-package-links.mjs"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const script = path.join(repoRoot, "scripts", "run-vitest-stable.mjs"); @@ -19,6 +26,7 @@ function workflowEnv(envOverrides = {}) { "PAPERCLIP_CI_EXCLUDE_NIGHTLY", "PAPERCLIP_CI_NIGHTLY_SUITES_FILE", "PAPERCLIP_VITEST_MAX_WORKERS", + "PAPERCLIP_VITEST_CPU_COUNT", "PAPERCLIP_TEST_POSTGRES_ADMIN_URL", "PAPERCLIP_CI_TEST_SELECTION", "PAPERCLIP_CI_SELECTION_HASH", @@ -74,6 +82,7 @@ test("general-workspaces-b and general-workspaces-a batch all projects into one const aProjectsArg = aCalls[0].flatMap((arg, index) => (arg === "--project" ? [aCalls[0][index + 1]] : [])); assert.deepEqual(aProjectsArg, workspacesAProjects); assert.ok(aCalls[0].includes("--shard=2/2")); + assert.ok(aCalls[0].some((arg) => /^--maxWorkers=\d+$/.test(arg)), `expected top-level --maxWorkers in ${aCalls[0].join(" ")}`); } finally { rmSync(directory, { recursive: true, force: true }); } @@ -233,3 +242,152 @@ test("shared Postgres wrapper skips non-Postgres workspace groups even when opte rmSync(directory, { recursive: true, force: true }); } }); + +test("dynamic server workers scale cleanly across 4-core and 8-core runners while honoring explicit overrides", { skip: process.platform === "win32" }, () => { + assert.equal(defaultServerParallelWorkers("general", 1), 1); + assert.equal(defaultServerParallelWorkers("general", 4), 4); + assert.equal(defaultServerParallelWorkers("general", 8), 7); + assert.equal(defaultServerParallelWorkers("general", 16), 8); + + assert.equal(defaultServerParallelWorkers("serialized", 1), 1); + assert.equal(defaultServerParallelWorkers("serialized", 4), 3); + assert.equal(defaultServerParallelWorkers("serialized", 8), 5); + assert.equal(defaultServerParallelWorkers("serialized", 16), 6); + + assert.equal(resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_CPU_COUNT: "8" }), 7); + assert.equal(resolveServerParallelWorkers("serialized", { PAPERCLIP_VITEST_CPU_COUNT: "8" }), 5); + assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "4" }), 4); + assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "8" }), 7); + assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "8", PAPERCLIP_VITEST_MAX_WORKERS: "3" }), 3); + assert.equal( + resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_CPU_COUNT: "8", PAPERCLIP_VITEST_MAX_WORKERS: "2" }), + 2, + ); + assert.throws(() => resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_MAX_WORKERS: "0" })); + + const directory = mkdtempSync(path.join(os.tmpdir(), "dynamic-workers-")); + const receipt = path.join(directory, "args.json"); + const fakePnpm = path.join(directory, "pnpm"); + writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').writeFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)));\n`); + chmodSync(fakePnpm, 0o755); + try { + for (const [cpuCount, expectedGeneral, expectedSerialized] of [ + ["4", 4, 3], + ["8", 7, 5], + ]) { + for (const [modeArgs, expectedWorkers] of [ + [["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], expectedGeneral], + [["--mode", "general", "--group", "general-server-native-runner"], expectedGeneral], + [["--mode", "serialized", "--shard-index", "0", "--shard-count", "9"], expectedSerialized], + ]) { + const result = spawnSync(process.execPath, [script, ...modeArgs], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv({ + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0", + PAPERCLIP_VITEST_CPU_COUNT: cpuCount, + }), + }); + assert.equal(result.status, 0, result.stdout + result.stderr); + const args = JSON.parse(readFileSync(receipt, "utf8")); + assert.ok(args.includes(`--maxWorkers=${expectedWorkers}`), `cpu=${cpuCount} expected --maxWorkers=${expectedWorkers} in ${args.join(" ")}`); + } + } + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("general-workspaces-b 2-shard split partitions projects cleanly without Vitest --shard and balances adapter-utils", { skip: process.platform === "win32" }, () => { + const unsharded = dryRunJson(["--mode", "general", "--group", "general-workspaces-b"]); + const shard0 = dryRunJson(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "0", "--shard-count", "2"]); + const shard1 = dryRunJson(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "1", "--shard-count", "2"]); + + assert.equal(shard0.workspacesVitestShard, null); + assert.equal(shard1.workspacesVitestShard, null); + assert.deepEqual(shard0.workspaceProjects, ["@paperclipai/adapter-utils"]); + assert.ok(shard1.workspaceProjects.length === unsharded.workspaceProjects.length - 1); + + const combined = [...shard0.workspaceProjects, ...shard1.workspaceProjects].sort(); + assert.deepEqual(combined, [...unsharded.workspaceProjects].sort(), "2-shard partition must cover every project exactly once"); + + // Unknown future projects get default weight and are still partitioned cleanly. + const withFuture = partitionWorkspaceProjects([...unsharded.workspaceProjects, "@paperclipai/future-pkg"], 2); + assert.ok(withFuture.flatMap((s) => s.projects).includes("@paperclipai/future-pkg")); + assert.deepEqual(selectWorkspaceProjectsShard(unsharded.workspaceProjects, 0, 1), unsharded.workspaceProjects); + + const directory = mkdtempSync(path.join(os.tmpdir(), "workspaces-b-shards-")); + const receipt = path.join(directory, "calls.ndjson"); + const fakePnpm = path.join(directory, "pnpm"); + writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').appendFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n`); + chmodSync(fakePnpm, 0o755); + try { + const run = (args) => { + rmSync(receipt, { force: true }); + const result = spawnSync(process.execPath, [script, ...args], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv({ + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0", + }), + }); + assert.equal(result.status, 0, result.stdout + result.stderr); + return existsSync(receipt) + ? readFileSync(receipt, "utf8").trim().split("\n").map((line) => JSON.parse(line)) + : []; + }; + + for (const [index, expectedProjects] of [ + ["0", shard0.workspaceProjects], + ["1", shard1.workspaceProjects], + ]) { + const calls = run(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", index, "--shard-count", "2"]); + assert.equal(calls.length, 1, `workspaces-b shard ${index}/2 must invoke vitest once`); + const projectsArg = calls[0].flatMap((arg, i) => (arg === "--project" ? [calls[0][i + 1]] : [])); + assert.deepEqual(projectsArg, expectedProjects); + assert.ok(!calls[0].some((arg) => arg.startsWith("--shard=")), "project-partitioned shard must not pass --shard"); + } + + // Over-sharded empty bucket skips vitest rather than running unfiltered. + const emptyCalls = run(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "20", "--shard-count", "25"]); + assert.deepEqual(emptyCalls, []); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("ensure-workspace-package-links discovers workspace packages and repairs stale links without tsx", { skip: process.platform === "win32" }, async () => { + const discovered = discoverWorkspacePackagePaths(repoRoot); + for (const name of ["@paperclipai/server", "@paperclipai/ui", "@paperclipai/shared", "@paperclipai/db", "@paperclipai/plugin-sdk", "paperclipai"]) { + assert.ok(discovered.has(name), `expected workspace package ${name}`); + } + + const fixtureRoot = mkdtempSync(path.join(os.tmpdir(), "ws-links-fixture-")); + const { mkdirSync, symlinkSync, realpathSync } = await import("node:fs"); + try { + const sharedDir = path.join(fixtureRoot, "packages", "shared"); + const staleDir = path.join(fixtureRoot, "stale-target"); + const serverDir = path.join(fixtureRoot, "server"); + mkdirSync(path.join(sharedDir, "src"), { recursive: true }); + mkdirSync(staleDir, { recursive: true }); + mkdirSync(path.join(serverDir, "node_modules", "@paperclipai"), { recursive: true }); + writeFileSync(path.join(sharedDir, "package.json"), JSON.stringify({ name: "@paperclipai/shared" })); + writeFileSync(path.join(serverDir, "package.json"), JSON.stringify({ + name: "@paperclipai/server", + dependencies: { "@paperclipai/shared": "workspace:*" }, + })); + symlinkSync(staleDir, path.join(serverDir, "node_modules", "@paperclipai", "shared")); + + await ensureAllWorkspaceLinksCurrent(fixtureRoot); + assert.equal( + realpathSync(path.join(serverDir, "node_modules", "@paperclipai", "shared")), + realpathSync(sharedDir), + ); + } finally { + rmSync(fixtureRoot, { recursive: true, force: true }); + } +}); diff --git a/scripts/__tests__/run-vitest-stable-shard.test.mjs b/scripts/__tests__/run-vitest-stable-shard.test.mjs index 8868e8301c5..2f3b9cb8cc2 100644 --- a/scripts/__tests__/run-vitest-stable-shard.test.mjs +++ b/scripts/__tests__/run-vitest-stable-shard.test.mjs @@ -15,6 +15,7 @@ import { import { assertManifestSource } from "../ci/pr-run-durations.mjs"; import { assertSelectedTests, partitionTestLines } from "../test-line-shard.mjs"; import { chatManifestData, entryDurations } from "../ci/refresh-chat-shard-durations.mjs"; +import { defaultServerParallelWorkers } from "../ci/vitest-workers.mjs"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const script = path.join(repoRoot, "scripts", "run-vitest-stable.mjs"); @@ -37,6 +38,7 @@ function workflowEnv(envOverrides = {}) { "PAPERCLIP_CI_EXCLUDE_NIGHTLY", "PAPERCLIP_CI_NIGHTLY_SUITES_FILE", "PAPERCLIP_VITEST_MAX_WORKERS", + "PAPERCLIP_VITEST_CPU_COUNT", "PAPERCLIP_TEST_POSTGRES_ADMIN_URL", ]) { if (!(key in envOverrides)) { @@ -101,12 +103,10 @@ test("general shards retain scripts and route-named suites outside the serialize ]) assert.ok(general.selectedGeneralServerSuites.includes(file), `missing configured server suite: ${file}`); }); -for (const group of ["general-workspaces-b", "general-workspaces-c"]) { - test(`shard flags are rejected for the ${group} group`, () => { - const result = dryRun(["--mode", "general", "--group", group, "--shard-index", "0", "--shard-count", "3"]); - assert.notEqual(result.status, 0, `${group} must not accept shard flags`); - }); -} +test("shard flags are rejected for the general-workspaces-c group", () => { + const result = dryRun(["--mode", "general", "--group", "general-workspaces-c", "--shard-index", "0", "--shard-count", "3"]); + assert.notEqual(result.status, 0, "general-workspaces-c must not accept shard flags"); +}); test("workspace lanes cover every non-server project in the root Vitest configuration", () => { const config = readFileSync(path.join(repoRoot, "vitest.config.ts"), "utf8"); @@ -183,11 +183,19 @@ test("workspaces-c runs the db project alone and workspaces-b no longer carries const sharded = entries.filter(entry => entry.group === "general-workspaces-a"); assert.ok(sharded.length > 0 && sharded.every(entry => entry.keys.includes("shard_index") && entry.keys.includes("shard_count")), `${workflow} must carry the sharded workspaces-a entries`); - for (const group of ["general-workspaces-b", "general-workspaces-c"]) { - const matching = entries.filter(entry => entry.group === group); - assert.equal(matching.length, 1, `${workflow} must run ${group} exactly once`); - assert.ok(matching[0].keys.includes("group_label"), `${workflow} must label the ${group} job`); - assert.deepEqual(matching[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} must run ${group} unsharded`); + const workspacesCEntries = entries.filter(entry => entry.group === "general-workspaces-c"); + assert.equal(workspacesCEntries.length, 1, `${workflow} must run general-workspaces-c exactly once`); + assert.ok(workspacesCEntries[0].keys.includes("group_label"), `${workflow} must label the general-workspaces-c job`); + assert.deepEqual(workspacesCEntries[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} must run general-workspaces-c unsharded`); + + const workspacesBEntries = entries.filter(entry => entry.group === "general-workspaces-b"); + assert.ok(workspacesBEntries.length >= 1, `${workflow} must run general-workspaces-b`); + assert.ok(workspacesBEntries.every(entry => entry.keys.includes("group_label")), `${workflow} must label every general-workspaces-b job`); + if (workspacesBEntries.length === 1) { + assert.deepEqual(workspacesBEntries[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} single general-workspaces-b entry must be unsharded`); + } else { + assert.ok(workspacesBEntries.every(entry => entry.keys.includes("shard_index") && entry.keys.includes("shard_count")), + `${workflow} multi-shard general-workspaces-b entries must declare shard_index and shard_count`); } } }); @@ -885,11 +893,12 @@ test("a failed chat child fails the job after its sibling finishes", { skip: pro } }); -for (const [label, modeArgs, parallelWorkers] of [ - ["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], 4], - ["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], 4], - ["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], 3], +for (const [label, modeArgs, lane] of [ + ["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], "general"], + ["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], "general"], + ["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], "serialized"], ]) test(`${label} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => { + const parallelWorkers = defaultServerParallelWorkers(lane); const directory = mkdtempSync(path.join(os.tmpdir(), "native-file-workers-")); const receipt = path.join(directory, "args.json"); const fakePnpm = path.join(directory, "pnpm"); diff --git a/scripts/check-test-budget.mjs b/scripts/check-test-budget.mjs new file mode 100644 index 00000000000..dfd0423b332 --- /dev/null +++ b/scripts/check-test-budget.mjs @@ -0,0 +1,469 @@ +#!/usr/bin/env node +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRootDefault = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +export const NIGHTLY_MANIFEST_REL = "scripts/ci/nightly-only-suites.json"; + +const TEST_FILE_PATTERN = /^(?:packages\/db\/src|server\/src|ui\/src)\/.+\.test\.tsx?$|^tests\/e2e\/.+\.spec\.ts$/; +const SLEEP_CALL_START_PATTERN = /\b(setTimeout|delay|waitForTimeout)\s*\(/g; +const READ_FILE_START_PATTERN = /\breadFile(?:Sync)?\s*\(/g; +const HISTORICAL_MIGRATION_FILE_PATTERN = /^(?:packages\/db\/src|server\/src)\/.*migration\.test\.ts$/; +const HISTORICAL_MIGRATION_CONTENT_PATTERN = /\b0\d{3}_[a-z0-9_]+\.sql\b|--> statement-breakpoint/; +const GUIDANCE_FILE_PATTERN = /-guidance\.test\.ts$/; +const PROSE_TARGET_PATTERN = /\.(?:md|tsx)\b|SKILL\.md|AGENTS\.md|README\.md/; +const EMBEDDED_PG_PATTERN = /\b(?:startEmbeddedPostgresTestDatabase|createTestPostgres)\b/; + +export const PROTECTED_INVARIANT_PATTERN = + /(?:auth|authz|-access(?:\.|\/|$)|company-access|isolation|checkout|assignee|approval|(?:^|\/)budget-|budget-policy|budget-cancellation|budget-evaluation|budget-hold|activity-log|secret|csrf|redaction|guard|security|tenant|privacy|sentry|telemetry|otel|observability|injection|ssrf|oracle|cli-invocation-safety|webhook-ingress|credential|signature|device-login|policy-sweep|connection-management|document-scope)/i; + +const MAX_PR_SLEEP_MS = 1_000; +const TINY_DB_FILE_MAX_LOC = 80; + +function extractBalancedCallArgs(text, openParenIndex) { + let depth = 0; + let quote = null; + let escaped = false; + let argStart = openParenIndex + 1; + const args = []; + for (let i = openParenIndex; i < text.length; i += 1) { + const ch = text[i]; + if (quote) { + if (escaped) { + escaped = false; + } else if (ch === "\\") { + escaped = true; + } else if (ch === quote) { + quote = null; + } + continue; + } + if (ch === "'" || ch === '"' || ch === "`") { + quote = ch; + continue; + } + if (ch === "(" || ch === "[" || ch === "{") { + depth += 1; + continue; + } + if (ch === ")" || ch === "]" || ch === "}") { + depth -= 1; + if (depth === 0) { + args.push(text.slice(argStart, i)); + return { args, endIndex: i }; + } + continue; + } + if (ch === "," && depth === 1) { + args.push(text.slice(argStart, i)); + argStart = i + 1; + } + } + return null; +} + +function evaluateDurationExprMs(expr) { + const cleaned = expr.replace(/\/\*[\s\S]*?\*\//g, "").trim(); + if (!cleaned) return 0; + // Match pure numeric expressions like `2500`, `1_500`, `60 * 1000`, `5 * 60 * 1_000`, `2_000 + 500`. + if (/^[\d_\s+*().]+$/.test(cleaned)) { + const sumTerms = cleaned.replace(/[()]/g, "").split("+"); + let total = 0; + for (const term of sumTerms) { + const factors = term.split("*").map((part) => Number(part.trim().replaceAll("_", ""))); + if (factors.some((n) => !Number.isFinite(n))) return 0; + total += factors.reduce((acc, n) => acc * n, 1); + } + return total; + } + // Fallback: inspect the largest standalone numeric literal inside a compound expression. + let max = 0; + for (const m of cleaned.matchAll(/\b(\d[\d_]*)\b/g)) { + const value = Number(m[1].replaceAll("_", "")); + if (Number.isFinite(value) && value > max) max = value; + } + return max; +} + +function lineNumberAt(source, offset) { + let line = 1; + for (let i = 0; i < offset; i += 1) { + if (source.charCodeAt(i) === 10) line += 1; + } + return line; +} + +function hasProseSourceRead(source) { + READ_FILE_START_PATTERN.lastIndex = 0; + let match; + while ((match = READ_FILE_START_PATTERN.exec(source)) !== null) { + const openParen = match.index + match[0].length - 1; + const call = extractBalancedCallArgs(source, openParen); + const firstArg = call?.args[0] ?? ""; + if (PROSE_TARGET_PATTERN.test(firstArg)) { + return true; + } + } + return false; +} + +function fakeTimersFakesSetTimeout(rawArgs) { + const args = (rawArgs ?? "").trim(); + if (!args) return true; + const toFakeMatch = args.match(/\btoFake\s*:\s*\[([^\]]*)\]/); + if (toFakeMatch) { + return /['"`]setTimeout['"`]/.test(toFakeMatch[1]); + } + const doNotFakeMatch = args.match(/\bdoNotFake\s*:\s*\[([^\]]*)\]/); + if (doNotFakeMatch && /['"`]setTimeout['"`]/.test(doNotFakeMatch[1])) { + return false; + } + return true; +} + +function buildFakeTimeoutRanges(source) { + // Walk timer-mode transitions and test boundaries in source order so partial + // fakes (e.g. `toFake: ["Date"]`) and real-clock tests in mixed-clock files + // are still checked for unbudgeted `setTimeout` sleeps. + const events = []; + const hookRanges = []; + const hookRe = /\b(beforeEach|beforeAll|afterEach|afterAll)\s*\(/g; + let m; + while ((m = hookRe.exec(source)) !== null) { + const call = extractBalancedCallArgs(source, m.index + m[0].length - 1); + if (!call) continue; + hookRanges.push({ kind: m[1], start: m.index, end: call.endIndex }); + } + const hookKindAt = (offset) => { + for (const h of hookRanges) { + if (offset >= h.start && offset <= h.end) return h.kind; + } + return null; + }; + + const fakeRe = /\b(?:vi|jest)\.useFakeTimers\s*\(/g; + while ((m = fakeRe.exec(source)) !== null) { + const call = extractBalancedCallArgs(source, m.index + m[0].length - 1); + const fakesSetTimeout = fakeTimersFakesSetTimeout(call?.args[0] ?? ""); + const hook = hookKindAt(m.index); + events.push({ + offset: m.index, + kind: hook === "beforeEach" || hook === "beforeAll" ? "hook-fake" : "fake", + fakesSetTimeout, + }); + } + + const realRe = /\b(?:vi|jest)\.useRealTimers\s*\(/g; + while ((m = realRe.exec(source)) !== null) { + const hook = hookKindAt(m.index); + if (hook === "afterEach" || hook === "afterAll") continue; + events.push({ offset: m.index, kind: "real", fakesSetTimeout: false }); + } + + const testBoundaryRe = /^\s*(?:it|test|describe)(?:\.(?:only|skip|concurrent|sequential|each))?\s*\(/gm; + while ((m = testBoundaryRe.exec(source)) !== null) { + events.push({ offset: m.index, kind: "boundary", fakesSetTimeout: false }); + } + + events.sort((a, b) => a.offset - b.offset); + + return function isSetTimeoutFakedAt(offset) { + let hookFake = false; + let localFake = false; + for (const ev of events) { + if (ev.offset > offset) break; + if (ev.kind === "hook-fake") { + hookFake = ev.fakesSetTimeout; + localFake = hookFake; + } else if (ev.kind === "boundary") { + localFake = hookFake; + } else if (ev.kind === "fake") { + localFake = ev.fakesSetTimeout; + } else if (ev.kind === "real") { + localFake = false; + } + } + return localFake; + }; +} + +export function findUnbudgetedSleeps(source, { onlyLineNumbers = null } = {}) { + const violations = []; + const lines = source.split(/\r?\n/); + const isSetTimeoutFakedAt = buildFakeTimeoutRanges(source); + const clearedHandles = new Set( + [...source.matchAll(/\bclearTimeout\s*\(\s*([A-Za-z_$][\w$]*)\s*\)/g)].map((m) => m[1]), + ); + SLEEP_CALL_START_PATTERN.lastIndex = 0; + let match; + while ((match = SLEEP_CALL_START_PATTERN.exec(source)) !== null) { + const lineNumber = lineNumberAt(source, match.index); + const line = lines[lineNumber - 1] ?? ""; + if (/^\s*\/\//.test(line)) continue; + const openParen = match.index + match[0].length - 1; + const call = extractBalancedCallArgs(source, openParen); + if (!call) continue; + const endLineNumber = lineNumberAt(source, call.endIndex); + if (onlyLineNumbers) { + let touchesAdded = false; + for (let ln = lineNumber; ln <= endLineNumber; ln += 1) { + if (onlyLineNumbers.has(ln)) { + touchesAdded = true; + break; + } + } + if (!touchesAdded) continue; + } + let allowed = false; + for (let ln = lineNumber; ln <= endLineNumber; ln += 1) { + if ((lines[ln - 1] ?? "").includes("test-budget:allow-sleep")) { + allowed = true; + break; + } + } + if (allowed) continue; + + const callee = match[1]; + if (callee === "setTimeout") { + if (isSetTimeoutFakedAt(match.index)) continue; + // Ignore cancellable deadline timers (e.g. `const timer = setTimeout(...); ... clearTimeout(timer)`). + const beforeOnLine = source.slice(Math.max(0, match.index - 80), match.index); + const assignedVar = beforeOnLine.match(/([A-Za-z_$][\w$]*)\s*=\s*$/); + if (assignedVar && clearedHandles.has(assignedVar[1])) { + continue; + } + } + const delayArg = callee === "setTimeout" ? call.args[1] ?? "" : call.args[0] ?? ""; + const ms = evaluateDurationExprMs(delayArg); + if (ms > MAX_PR_SLEEP_MS) { + violations.push({ + rule: "sleep-over-1s", + line: lineNumber, + message: `Unbudgeted real-clock sleep (${ms}ms > ${MAX_PR_SLEEP_MS}ms). Use fake timers/condition waits, move soak suite to ${NIGHTLY_MANIFEST_REL}, or annotate with // test-budget:allow-sleep: .`, + }); + } + } + return violations; +} + +export function validateNightlyManifest(root = repoRootDefault, manifestRel = NIGHTLY_MANIFEST_REL) { + const fullPath = path.join(root, manifestRel); + const violations = []; + if (!existsSync(fullPath)) { + return { paths: new Set(), violations: [{ file: manifestRel, rule: "nightly-manifest", message: "Missing nightly manifest." }] }; + } + + let parsed; + try { + parsed = JSON.parse(readFileSync(fullPath, "utf8")); + } catch (error) { + return { + paths: new Set(), + violations: [{ file: manifestRel, rule: "nightly-manifest", message: `Invalid JSON: ${error.message}` }], + }; + } + + if (!Array.isArray(parsed?.suites)) { + return { + paths: new Set(), + violations: [{ file: manifestRel, rule: "nightly-manifest", message: "Manifest must contain a suites array." }], + }; + } + + const seen = new Set(); + for (const entry of parsed.suites) { + const suitePath = typeof entry === "string" ? entry : entry?.path; + if (typeof suitePath !== "string" || !suitePath.trim()) { + violations.push({ file: manifestRel, rule: "nightly-manifest", message: "Suite entry is missing a non-empty string path." }); + continue; + } + if (suitePath.startsWith("/") || suitePath.includes("\\") || suitePath.split("/").includes("..")) { + violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Invalid non-repo-relative path: ${suitePath}` }); + continue; + } + if (seen.has(suitePath)) { + violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Duplicate suite path: ${suitePath}` }); + continue; + } + seen.add(suitePath); + if (!existsSync(path.join(root, suitePath))) { + violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Nightly suite does not exist on disk: ${suitePath}` }); + } + if (PROTECTED_INVARIANT_PATTERN.test(suitePath)) { + violations.push({ + file: manifestRel, + rule: "protected-invariant", + message: `Core control-plane / security / privacy invariant suite must remain on PRs, not in ${manifestRel}: ${suitePath}`, + }); + } + } + + return { paths: seen, violations }; +} + +export function checkTestFileBudget(fileRel, source, { isNew = true, nightlyPaths = new Set(), addedLineNumbers = null } = {}) { + if (!TEST_FILE_PATTERN.test(fileRel)) return []; + const violations = []; + const isNightly = nightlyPaths.has(fileRel); + + if (!isNightly) { + for (const v of findUnbudgetedSleeps(source, { onlyLineNumbers: isNew ? null : addedLineNumbers })) { + violations.push({ file: fileRel, ...v }); + } + } + + if (isNew) { + if ( + HISTORICAL_MIGRATION_FILE_PATTERN.test(fileRel) && + HISTORICAL_MIGRATION_CONTENT_PATTERN.test(source) && + !source.includes("test-budget:allow-migration-test") + ) { + violations.push({ + file: fileRel, + rule: "historical-migration-test", + message: "Do not add standalone historical SQL migration replay tests; extend core runner tests in packages/db/src/client.test.ts or migration-compatibility.test.ts.", + }); + } + + if ( + GUIDANCE_FILE_PATTERN.test(fileRel) && + hasProseSourceRead(source) && + !source.includes("test-budget:allow-prose-check") + ) { + violations.push({ + file: fileRel, + rule: "prose-guidance-grep", + message: "Do not add brittle static prose-grep guidance tests over .md/.tsx files.", + }); + } + + const lineCount = source.split(/\r?\n/).length; + if ( + !isNightly && + lineCount <= TINY_DB_FILE_MAX_LOC && + EMBEDDED_PG_PATTERN.test(source) && + !source.includes("test-budget:allow-standalone-db") + ) { + violations.push({ + file: fileRel, + rule: "tiny-standalone-db-test", + message: `New embedded-Postgres test file is only ${lineCount} LOC (<= ${TINY_DB_FILE_MAX_LOC}). Extend the owning service/route suite instead, or annotate with // test-budget:allow-standalone-db: .`, + }); + } + } + + return violations; +} + +function addedLinesFromDiff(root, baseRef, fileRel) { + const diff = execFileSync("git", ["diff", "-U0", `${baseRef}...HEAD`, "--", fileRel], { + cwd: root, + encoding: "utf8", + }); + const added = new Set(); + let currentLine = 0; + for (const line of diff.split(/\r?\n/)) { + const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/); + if (hunk) { + currentLine = Number(hunk[1]); + continue; + } + if (line.startsWith("+") && !line.startsWith("+++")) { + added.add(currentLine); + currentLine += 1; + } else if (!line.startsWith("-")) { + currentLine += 1; + } + } + return added; +} + +function changedTestFilesFromBase(root, baseRef) { + const out = execFileSync("git", ["diff", "--diff-filter=AM", "--name-status", `${baseRef}...HEAD`], { + cwd: root, + encoding: "utf8", + }); + const entries = []; + for (const raw of out.split(/\r?\n/)) { + if (!raw.trim()) continue; + const [status, fileRel] = raw.split("\t"); + if (!fileRel || !TEST_FILE_PATTERN.test(fileRel)) continue; + entries.push({ fileRel, isNew: status === "A" }); + } + return entries; +} + +export function parseBudgetArgs(argv) { + const options = { base: null, files: [], root: repoRootDefault, manifestOnly: false }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "--base") { + options.base = argv[++i] ?? null; + } else if (arg.startsWith("--base=")) { + options.base = arg.slice("--base=".length); + } else if (arg === "--root") { + options.root = path.resolve(argv[++i] ?? repoRootDefault); + } else if (arg === "--manifest-only") { + options.manifestOnly = true; + } else if (arg === "--files") { + while (i + 1 < argv.length && !argv[i + 1].startsWith("--")) { + options.files.push(argv[++i]); + } + } else if (!arg.startsWith("--")) { + options.files.push(arg); + } + } + return options; +} + +export function runTestBudgetCheck(options) { + const root = options.root ?? repoRootDefault; + const { paths: nightlyPaths, violations } = validateNightlyManifest(root); + + if (options.manifestOnly) { + return { nightlyCount: nightlyPaths.size, checkedFiles: 0, violations }; + } + + let targets = []; + if (options.files?.length) { + targets = options.files.map((fileRel) => ({ fileRel, isNew: true, addedLineNumbers: null })); + } else if (options.base) { + targets = changedTestFilesFromBase(root, options.base).map((entry) => ({ + ...entry, + addedLineNumbers: entry.isNew ? null : addedLinesFromDiff(root, options.base, entry.fileRel), + })); + } + + for (const target of targets) { + const absPath = path.join(root, target.fileRel); + if (!existsSync(absPath)) continue; + const source = readFileSync(absPath, "utf8"); + violations.push( + ...checkTestFileBudget(target.fileRel, source, { + isNew: target.isNew, + nightlyPaths, + addedLineNumbers: target.addedLineNumbers, + }), + ); + } + + return { nightlyCount: nightlyPaths.size, checkedFiles: targets.length, violations }; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const options = parseBudgetArgs(process.argv.slice(2)); + const result = runTestBudgetCheck(options); + if (result.violations.length > 0) { + console.error(`[check-test-budget] FAILED with ${result.violations.length} violation(s):`); + for (const v of result.violations) { + const loc = v.line ? `${v.file}:${v.line}` : v.file; + console.error(` - [${v.rule}] ${loc}: ${v.message}`); + } + process.exit(1); + } + console.log( + `[check-test-budget] PASS (${result.nightlyCount} nightly suites validated, ${result.checkedFiles} test file(s) checked).`, + ); +} diff --git a/scripts/check-test-budget.test.mjs b/scripts/check-test-budget.test.mjs new file mode 100644 index 00000000000..6ad05fc8241 --- /dev/null +++ b/scripts/check-test-budget.test.mjs @@ -0,0 +1,212 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + checkTestFileBudget, + findUnbudgetedSleeps, + runTestBudgetCheck, + validateNightlyManifest, +} from "./check-test-budget.mjs"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +test("checked-in scripts/ci/nightly-only-suites.json passes full manifest & invariant validation", () => { + const result = runTestBudgetCheck({ manifestOnly: true }); + assert.deepEqual(result.violations, []); + assert.ok(result.nightlyCount > 0, "expected non-empty nightly-only-suites.json"); +}); + +test("findUnbudgetedSleeps flags real-clock sleeps >1000ms (including inline callbacks and products) and respects allow-sleep annotations", () => { + const source = [ + "await delay(500);", + "await delay(1000);", + "await delay(1_500);", + "await setTimeout(resolve, 2500);", + "await new Promise((resolve) => setTimeout(() => resolve(), 2500));", + "await new Promise((resolve) => setTimeout(() => { resolve(); }, 60 * 1000));", + "await delay(2 * 1000);", + "await page.waitForTimeout(3000);", + "await delay(5000); // test-budget:allow-sleep: socket idle check", + "// await delay(9000);", + ].join("\n"); + + const violations = findUnbudgetedSleeps(source); + assert.deepEqual( + violations.map((v) => ({ rule: v.rule, line: v.line })), + [ + { rule: "sleep-over-1s", line: 3 }, + { rule: "sleep-over-1s", line: 4 }, + { rule: "sleep-over-1s", line: 5 }, + { rule: "sleep-over-1s", line: 6 }, + { rule: "sleep-over-1s", line: 7 }, + { rule: "sleep-over-1s", line: 8 }, + ], + ); + + // Cancellable deadline timers and full fake-timer scopes must not produce false positives. + assert.deepEqual( + findUnbudgetedSleeps( + "const timer = setTimeout(() => reject(new Error('timeout')), 60_000);\nclearTimeout(timer);", + ), + [], + ); + assert.deepEqual( + findUnbudgetedSleeps("vi.useFakeTimers();\nsetTimeout(() => done(), 10_000);"), + [], + ); + assert.deepEqual( + findUnbudgetedSleeps( + 'beforeEach(() => { vi.useFakeTimers(); });\nafterEach(() => { vi.useRealTimers(); });\nit("faked", () => {\n setTimeout(() => done(), 5000);\n});', + ), + [], + ); + assert.deepEqual( + findUnbudgetedSleeps( + 'vi.useFakeTimers({ toFake: ["Date", "setTimeout"] });\nsetTimeout(() => done(), 2500);', + ), + [], + ); + + // Partial fake timers (e.g. Date-only) and real-clock tests in mixed-clock files MUST still be flagged. + assert.deepEqual( + findUnbudgetedSleeps( + 'vi.useFakeTimers({ toFake: ["Date"] });\nawait new Promise((resolve) => setTimeout(resolve, 2500));', + ).map((v) => ({ rule: v.rule, line: v.line })), + [{ rule: "sleep-over-1s", line: 2 }], + ); + assert.deepEqual( + findUnbudgetedSleeps( + 'vi.useFakeTimers({ doNotFake: ["setTimeout"] });\nawait new Promise((resolve) => setTimeout(resolve, 2500));', + ).map((v) => ({ rule: v.rule, line: v.line })), + [{ rule: "sleep-over-1s", line: 2 }], + ); + assert.deepEqual( + findUnbudgetedSleeps( + [ + 'it("faked", () => {', + " vi.useFakeTimers();", + " setTimeout(() => done(), 5000);", + "});", + 'it("real", async () => {', + " await new Promise((resolve) => setTimeout(resolve, 2500));", + "});", + ].join("\n"), + ).map((v) => ({ rule: v.rule, line: v.line })), + [{ rule: "sleep-over-1s", line: 6 }], + ); + assert.deepEqual( + findUnbudgetedSleeps( + [ + 'it("restores", async () => {', + " vi.useFakeTimers();", + " setTimeout(() => done(), 5000);", + " vi.useRealTimers();", + " await new Promise((resolve) => setTimeout(resolve, 2500));", + "});", + ].join("\n"), + ).map((v) => ({ rule: v.rule, line: v.line })), + [{ rule: "sleep-over-1s", line: 5 }], + ); +}); + +test("checkTestFileBudget enforces migration, prose-guidance, and tiny embedded-PG rules on new files", () => { + const mig = checkTestFileBudget( + "packages/db/src/old-backfill-migration.test.ts", + 'const sql = readFileSync("./migrations/0420_backfill.sql", "utf8");', + { isNew: true }, + ); + assert.deepEqual(mig.map((v) => v.rule), ["historical-migration-test"]); + + const guidance = checkTestFileBudget( + "server/src/__tests__/foo-guidance.test.ts", + 'const text = readFileSync("ui/src/App.tsx", "utf8"); expect(text).toContain("Settings");', + { isNew: true }, + ); + assert.deepEqual(guidance.map((v) => v.rule), ["prose-guidance-grep"]); + + const nestedGuidance = checkTestFileBudget( + "server/src/__tests__/bar-guidance.test.ts", + 'const text = readFileSync(path.join(dir, "README.md"), "utf8"); expect(text).toContain("Usage");', + { isNew: true }, + ); + assert.deepEqual(nestedGuidance.map((v) => v.rule), ["prose-guidance-grep"]); + + const tinyPg = checkTestFileBudget( + "server/src/__tests__/tiny-one-off.test.ts", + 'import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";\nit("works", async () => {});', + { isNew: true }, + ); + assert.deepEqual(tinyPg.map((v) => v.rule), ["tiny-standalone-db-test"]); + + const tinyPgAllowed = checkTestFileBudget( + "server/src/__tests__/tiny-one-off.test.ts", + '// test-budget:allow-standalone-db: needs isolated process env\nimport { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";', + { isNew: true }, + ); + assert.deepEqual(tinyPgAllowed, []); + + // Nightly-registered suites are exempt from PR sleep & tiny-DB limits. + const nightly = checkTestFileBudget( + "server/src/__tests__/soak-example.test.ts", + 'import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";\nawait delay(5000);', + { isNew: true, nightlyPaths: new Set(["server/src/__tests__/soak-example.test.ts"]) }, + ); + assert.deepEqual(nightly, []); +}); + +test("validateNightlyManifest rejects missing files, duplicates, and protected core invariant suites", () => { + const tmp = mkdtempSync(path.join(os.tmpdir(), "paperclip-test-budget-")); + try { + mkdirSync(path.join(tmp, "scripts/ci"), { recursive: true }); + mkdirSync(path.join(tmp, "server/src/__tests__"), { recursive: true }); + mkdirSync(path.join(tmp, "server/src/services/connectors"), { recursive: true }); + writeFileSync(path.join(tmp, "server/src/__tests__/authz-company-access.test.ts"), "// authz\n"); + writeFileSync(path.join(tmp, "server/src/services/connectors/slack-access.test.ts"), "// access\n"); + writeFileSync(path.join(tmp, "server/src/services/budget-resume-continuation.test.ts"), "// budget\n"); + writeFileSync(path.join(tmp, "server/src/__tests__/webhook-ingress.test.ts"), "// webhook\n"); + writeFileSync(path.join(tmp, "server/src/__tests__/storage-s3-credential-rotation.test.ts"), "// cred\n"); + writeFileSync(path.join(tmp, "server/src/__tests__/connection-management.integration.test.ts"), "// isolation\n"); + writeFileSync(path.join(tmp, "server/src/__tests__/real-soak.test.ts"), "// soak\n"); + writeFileSync( + path.join(tmp, "scripts/ci/nightly-only-suites.json"), + JSON.stringify({ + suites: [ + { path: "server/src/__tests__/real-soak.test.ts" }, + { path: "server/src/__tests__/real-soak.test.ts" }, + { path: "server/src/__tests__/missing-suite.test.ts" }, + { path: "server/src/__tests__/authz-company-access.test.ts" }, + { path: "server/src/services/connectors/slack-access.test.ts" }, + { path: "server/src/services/budget-resume-continuation.test.ts" }, + { path: "server/src/__tests__/webhook-ingress.test.ts" }, + { path: "server/src/__tests__/storage-s3-credential-rotation.test.ts" }, + { path: "server/src/__tests__/connection-management.integration.test.ts" }, + ], + }), + ); + + const { violations } = validateNightlyManifest(tmp); + assert.deepEqual( + violations.map((v) => v.rule), + [ + "nightly-manifest", + "nightly-manifest", + "protected-invariant", + "protected-invariant", + "protected-invariant", + "protected-invariant", + "protected-invariant", + "protected-invariant", + ], + ); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +}); + +test("pr-trusted.yml invokes check-test-budget.mjs with --base on pull requests", () => { + const workflow = readFileSync(path.join(repoRoot, ".github/workflows/pr-trusted.yml"), "utf8"); + assert.match(workflow, /node \.\/scripts\/check-test-budget\.mjs --base "\$base_sha"/); +}); diff --git a/scripts/ci-dependency-cache.mjs b/scripts/ci-dependency-cache.mjs index cca636cfb45..1b267340fd7 100644 --- a/scripts/ci-dependency-cache.mjs +++ b/scripts/ci-dependency-cache.mjs @@ -1,10 +1,13 @@ -import { execFileSync } from "node:child_process"; +import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { appendFileSync, existsSync, readFileSync, realpathSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; import { readPluginsUnder } from "./link-plugin-dev-sdk.mjs"; +const execFileAsync = promisify(execFile); + const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const postinstallHooks = new Map([ @@ -55,9 +58,16 @@ export function cachePlan({ files, read, scope, packageDirs }) { } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - const files = execFileSync("git", ["ls-files", "-z"], { cwd: root }).toString().split("\0").filter(Boolean); - const command = (args) => execFileSync("pnpm", args, { cwd: root, encoding: "utf8" }).trim(); - const workspaces = JSON.parse(command(['-r', 'list', '--depth=-1', '--json'])); + const command = (bin, args) => + execFileAsync(bin, args, { cwd: root, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).then(({ stdout }) => stdout); + const [gitFilesRaw, workspacesRaw, pnpmVersionRaw, pnpmStoreRaw] = await Promise.all([ + command("git", ["ls-files", "-z"]), + command("pnpm", ["-r", "list", "--depth=-1", "--json"]), + command("pnpm", ["--version"]), + command("pnpm", ["store", "path", "--silent"]), + ]); + const files = gitFilesRaw.split("\0").filter(Boolean); + const workspaces = JSON.parse(workspacesRaw.trim()); const packageDirs = ['.', ...workspaces.map((workspace) => path.relative(root, workspace.path).split(path.sep).join('/') || '.'), ...readPluginsUnder(path.join(root, 'packages/plugins/sandbox-providers')).map((directory) => path.relative(root, directory).split(path.sep).join('/')), @@ -71,7 +81,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me root: realpathSync(root), node: process.version, abi: process.versions.modules, platform: process.platform, arch: process.arch, libc: process.report.getReport().header.glibcVersionRuntime ?? null, - pnpm: command(["--version"]), store: command(["store", "path", "--silent"]), + pnpm: pnpmVersionRaw.trim(), store: pnpmStoreRaw.trim(), }, }); const output = [ diff --git a/scripts/ci-typecheck-lane.mjs b/scripts/ci-typecheck-lane.mjs index 3595963956f..eb8bd50bf69 100644 --- a/scripts/ci-typecheck-lane.mjs +++ b/scripts/ci-typecheck-lane.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node import { execFileSync, spawn, spawnSync } from "node:child_process"; -import { availableParallelism, setPriority } from "node:os"; +import { availableParallelism, setPriority, totalmem } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { listLayers } from "../server/scripts/typecheck-layers.mjs"; @@ -13,10 +13,72 @@ export const SERIAL_BUILD_GAPS = ["@paperclipai/paperclip-runner"]; export const BACKGROUND_PRIORITY = 10; export const DEFAULT_MAX_CONCURRENCY = 3; export const DEFAULT_TEST_PROGRAMS_CONCURRENCY = 2; +export const PREPARE_RUNNER_VENDOR = "prepare runner vendor"; +export const BUILD_SERVER_EMIT_ONLY = "build server without type checks"; const SERVER_DECLARATIONS = "server declarations"; export const CLI_GUIDANCE_SAFETY = "CLI guidance safety"; const lowMemory = { [LOW_MEMORY_VARIABLE]: "1" }; +/** + * Computes CPU- and RAM-aware concurrency and TypeScript 7 checker/GOMAXPROCS settings. + * Keeps peak memory safely under 16 GiB on 4-core (m8i.xlarge) and 8-core (c8i.2xlarge) + * runners while scaling up cleanly on 8+ core / >= 24 GiB machines. + */ +export function computeResourceProfile({ cpus = availableParallelism(), totalMemoryBytes = totalmem() } = {}) { + const safeCpus = Math.max(1, Number.isFinite(cpus) ? Math.floor(cpus) : 4); + const totalMemGiB = totalMemoryBytes / 1024 ** 3; + if (safeCpus <= 2 || totalMemGiB < 12) { + return { + laneConcurrency: Math.min(2, safeCpus), + serverDeclCheckers: 1, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 1, + testProgramsConcurrency: 1, + testProgramsCheckers: 1, + }; + } + if (safeCpus <= 4) { + return { + laneConcurrency: 3, + serverDeclCheckers: 2, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 2, + testProgramsConcurrency: 2, + testProgramsCheckers: 1, + }; + } + if (totalMemGiB < 24) { + // 8-core / 16 GiB (e.g. c8i.2xlarge): run all 4 server test layers in 1 wave at 1 checker each (~10 GiB), + // give server declarations 3 checkers (~6.5 GiB) and UI GOMAXPROCS=4 (~4.4 GiB). + return { + laneConcurrency: Math.min(4, safeCpus), + serverDeclCheckers: 3, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 4, + testProgramsConcurrency: 3, + testProgramsCheckers: 1, + }; + } + // 6-8+ core / >= 24 GiB (e.g. m8i.2xlarge or local dev): maximize parallelism across declarations, layers, and UI. + return { + laneConcurrency: Math.min(6, safeCpus), + serverDeclCheckers: Math.min(4, Math.max(3, Math.floor(safeCpus / 2))), + serverLayerCheckers: 2, + testProjectCheckers: 2, + uiGomaxprocs: 4, + testProgramsConcurrency: 4, + testProgramsCheckers: 2, + }; +} + +export const DEFAULT_RESOURCE_PROFILE = computeResourceProfile({ + cpus: 4, + totalMemoryBytes: 16 * 1024 ** 3, +}); + const GLOBAL_TYPECHECK_INPUTS = new Set([ "package.json", "pnpm-lock.yaml", @@ -89,7 +151,9 @@ export function selectBuildGapPackages(buildGapPackages, changedFiles) { "packages/shared/", "packages/adapter-utils/", "packages/adapters/", + "packages/paperclip-runner/", "packages/plugins/sdk/", + "announcements/examples/animated/", "maps/", ]); } @@ -208,7 +272,8 @@ export function planLane({ testLayers, projects = PROJECTS, changedFiles = null, - testProgramsConcurrency = DEFAULT_TEST_PROGRAMS_CONCURRENCY, + resources = DEFAULT_RESOURCE_PROFILE, + testProgramsConcurrency = resources.testProgramsConcurrency ?? DEFAULT_TEST_PROGRAMS_CONCURRENCY, }) { const isPrMode = Array.isArray(changedFiles); const selectedBuildGaps = selectBuildGapPackages(buildGapPackages, changedFiles); @@ -217,13 +282,14 @@ export function planLane({ const runReleaseRegistry = shouldRunReleaseRegistryTests(changedFiles); const programSelection = selectTestPrograms(changedFiles); - const typecheckPackage = (name, background) => ({ + const typecheckPackage = (name, background, needs) => ({ name: `typecheck ${name}`, command: "pnpm", args: ["--filter", name, "typecheck"], - // UI typecheck runs ~7x faster without --singleThreaded while staying at ~4.4 GiB with GOMAXPROCS=2. - env: name === "@paperclipai/ui" ? { GOMAXPROCS: "2" } : lowMemory, + // UI typecheck runs ~7-10x faster without --singleThreaded while staying at ~4.4 GiB with bounded GOMAXPROCS. + env: name === "@paperclipai/ui" ? { GOMAXPROCS: String(resources.uiGomaxprocs) } : lowMemory, background, + ...(needs ? { needs } : {}), }); const prepare = [{ name: "link workspace packages", command: "pnpm", args: ["run", "preflight:workspace-links"] }]; @@ -231,27 +297,11 @@ export function planLane({ if (runServer || selectedBuildGaps.length > 0 || programSelection.programs.length > 0) { prepare.push({ name: "build plugin SDK", - command: "pnpm", - args: ["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"], + command: "node", + args: ["scripts/ensure-plugin-build-deps.mjs"], }); } - if (runServer) { - prepare.push( - { - name: "build server without type checks", - command: "pnpm", - args: ["--filter", "@paperclipai/server", "build"], - env: { [EMIT_ONLY_VARIABLE]: "1" }, - }, - { - name: "check server runtime assets", - command: "node", - args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"], - }, - ); - } - if (programSelection.includeProviders || programSelection.includeRunnerEval) { const prepareArgs = ["scripts/typecheck-test-programs.mjs", "--prepare-only"]; if (isPrMode) { @@ -271,15 +321,31 @@ export function planLane({ }, ); + const needsRunnerVendor = [PREPARE_RUNNER_VENDOR]; const needsDeclarations = [SERVER_DECLARATIONS]; const tasks = []; if (runServer) { - tasks.push({ - name: SERVER_DECLARATIONS, - command: "node", - args: ["server/scripts/typecheck-layers.mjs", "--declarations-only", "--checkers", "2"], - }); + // Ensure packages/paperclip-runner/dist is current once in parallel with UI / non-runner checks, + // then fan out server declarations and emit-only server build without racing on runner dist. + tasks.push( + { + name: PREPARE_RUNNER_VENDOR, + command: "pnpm", + args: ["--filter", "@paperclipai/server", "run", "prepare:runner-vendor"], + }, + { + name: SERVER_DECLARATIONS, + command: "node", + args: [ + "server/scripts/typecheck-layers.mjs", + "--declarations-only", + "--checkers", + String(resources.serverDeclCheckers), + ], + needs: needsRunnerVendor, + }, + ); } if (runReleaseRegistry) { @@ -291,7 +357,7 @@ export function planLane({ "scripts/typecheck-test-programs.mjs", "--skip-prepare", "--checkers", - "1", + String(resources.testProgramsCheckers), "--concurrency", String(testProgramsConcurrency), ]; @@ -315,6 +381,7 @@ export function planLane({ command: "node", args: programArgs, background: true, + ...(runServer && programSelection.includeRunnerEval ? { needs: needsRunnerVendor } : {}), }); } @@ -323,20 +390,53 @@ export function planLane({ ...testLayers.map((layer) => ({ name: `server layer ${layer}`, command: "node", - args: ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"], + args: [ + "server/scripts/typecheck-layers.mjs", + "--layer", + layer, + "--checkers", + String(resources.serverLayerCheckers), + ], needs: needsDeclarations, })), ...selectedProjects.map((project) => ({ name: `test project ${project}`, command: "node", - args: ["scripts/typecheck-test-projects.mjs", "--checkers", "1", "--reuse-declarations", project], + args: [ + "scripts/typecheck-test-projects.mjs", + "--checkers", + String(resources.testProjectCheckers), + "--reuse-declarations", + project, + ], needs: needsDeclarations, })), + { + name: BUILD_SERVER_EMIT_ONLY, + command: "pnpm", + args: ["--filter", "@paperclipai/server", "build"], + env: { + [EMIT_ONLY_VARIABLE]: "1", + PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT: "1", + }, + needs: needsRunnerVendor, + background: true, + }, + { + name: "check server runtime assets", + command: "node", + args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"], + needs: [BUILD_SERVER_EMIT_ONLY], + }, ); } tasks.push( - ...selectedBuildGaps.filter((name) => !SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, true)), + ...selectedBuildGaps + .filter((name) => !SERIAL_BUILD_GAPS.includes(name)) + .map((name) => + typecheckPackage(name, true, runServer && name === "paperclipai" ? needsRunnerVendor : undefined), + ), ); return { prepare, tasks }; @@ -524,7 +624,8 @@ function listBuildGapPackages(root) { if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); - let concurrency = Math.max(1, Math.min(DEFAULT_MAX_CONCURRENCY, availableParallelism())); + const resources = computeResourceProfile(); + let concurrency = resources.laneConcurrency; let base; let full = false; let valid = true; @@ -559,10 +660,11 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me scope.mode === "pr" ? `PR (${scope.changedFiles.length} changed files via ${scope.reason})` : `full (${scope.reason})`; - const lanePlan = planLane({ buildGapPackages, testLayers, changedFiles: scope.changedFiles }); + const lanePlan = planLane({ buildGapPackages, testLayers, changedFiles: scope.changedFiles, resources }); console.log( - `typecheck lane: ${concurrency} at a time; mode: ${scopeDetail}; ` + - `prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` + + `typecheck lane: ${concurrency} at a time (${availableParallelism()} vCPU, ${(totalmem() / 1024 ** 3).toFixed(1)} GiB; ` + + `decl=${resources.serverDeclCheckers}, layers=${resources.serverLayerCheckers}, ui=${resources.uiGomaxprocs}); ` + + `mode: ${scopeDetail}; prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` + `build gaps: ${buildGapPackages.join(", ")}`, ); process.exitCode = await runLane({ ...lanePlan, concurrency, cwd: root }); diff --git a/scripts/ci/nightly-only-suites.json b/scripts/ci/nightly-only-suites.json index 768f344cd7e..d10b6e5ec3d 100644 --- a/scripts/ci/nightly-only-suites.json +++ b/scripts/ci/nightly-only-suites.json @@ -97,6 +97,12 @@ "reason": "Long-running external chat wait & native restart soak (85 cases, 181s)", "measuredMs": 181027 }, + { + "path": "server/src/services/heartbeat/workspace-preparation.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (178.9s in run 45238253588)", + "measuredMs": 178931 + }, { "path": "server/src/__tests__/issue-recovery-dependencies.test.ts", "category": "recovery-idle-maintenance-soak", @@ -127,6 +133,12 @@ "reason": "Heavy object-storage, archive, or retention integration soak (152.2s in run 45238253588)", "measuredMs": 152199 }, + { + "path": "server/src/services/heartbeat/run-completion.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (151.9s in run 45238253588)", + "measuredMs": 151888 + }, { "path": "server/src/__tests__/idle-sleep-safety.test.ts", "category": "recovery-idle-maintenance-soak", @@ -139,6 +151,12 @@ "reason": "Issue recovery deadline & 1000-issue scan bound soak (20 cases, 148s)", "measuredMs": 148225 }, + { + "path": "server/src/services/native-runtime/native-session-executor.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (145.5s in run 45238253588)", + "measuredMs": 145454 + }, { "path": "server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts", "category": "recovery-idle-maintenance-soak", @@ -241,6 +259,12 @@ "reason": "Executable 53-fixture x 70-row status-authority corpus (68 cases, 98s)", "measuredMs": 98250 }, + { + "path": "server/src/__tests__/queued-run-dispatch-stacking.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (98.1s in run 45238253588)", + "measuredMs": 98136 + }, { "path": "server/src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts", "category": "restart-lease-soak", @@ -271,6 +295,12 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (85.1s in run 45238253588)", "measuredMs": 85133 }, + { + "path": "server/src/__tests__/agent-interaction-acceptance.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (85.1s in run 45238253588)", + "measuredMs": 85112 + }, { "path": "server/src/services/object-byte-journal.test.ts", "category": "storage-integration-soak", @@ -283,6 +313,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (81.4s in run 45238253588)", "measuredMs": 81437 }, + { + "path": "server/src/__tests__/attention-summary-counts.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (80.7s in run 45238253588)", + "measuredMs": 80693 + }, { "path": "server/src/__tests__/heartbeat-repository-catalog-recovery.test.ts", "category": "recovery-idle-maintenance-soak", @@ -307,6 +343,12 @@ "reason": "Attention retention background sweep soak (77s)", "measuredMs": 77085 }, + { + "path": "server/src/services/heartbeat/runtime-selection.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (75.3s in run 45238253588)", + "measuredMs": 75268 + }, { "path": "server/src/__tests__/issue-recovery-agent-row-write-census.test.ts", "category": "recovery-idle-maintenance-soak", @@ -325,6 +367,12 @@ "reason": "Report-only ownership reconciliation matrix soak (48 cases, 73s)", "measuredMs": 73104 }, + { + "path": "server/src/__tests__/heartbeat-stop-queued-task.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (71.2s in run 45238253588)", + "measuredMs": 71194 + }, { "path": "server/src/__tests__/plugin-scheduled-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -373,6 +421,12 @@ "reason": "Workspace recovery preparation proof soak (3 cases, 61s)", "measuredMs": 60597 }, + { + "path": "server/src/services/case-handoffs.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (59.6s in run 45238253588)", + "measuredMs": 59635 + }, { "path": "server/src/services/workspace-recovery-preparation-dispatch.test.ts", "category": "workspace-recovery-soak", @@ -409,12 +463,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (55.2s in run 45238253588)", "measuredMs": 55190 }, + { + "path": "server/src/__tests__/generic-mcp-connection.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (55.1s in run 45238253588)", + "measuredMs": 55072 + }, { "path": "server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Serialized heartbeat issue liveness escalation soak (29 cases, 55s)", "measuredMs": 54768 }, + { + "path": "server/src/__tests__/satisfied-connection-intents.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (54.6s in run 45238253588)", + "measuredMs": 54642 + }, { "path": "server/src/__tests__/heartbeat-retry-scheduling.test.ts", "category": "recovery-idle-maintenance-soak", @@ -469,6 +535,12 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (50.1s in run 45238253588)", "measuredMs": 50141 }, + { + "path": "server/src/__tests__/automatic-run-start-gate.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy automatic run-start gate lifecycle matrix (50.1s in run 45238253588)", + "measuredMs": 50100 + }, { "path": "server/src/services/remote-workspace-transport.test.ts", "category": "workspace-recovery-soak", @@ -523,12 +595,42 @@ "reason": "Idle issue schedule quietness soak (13 cases, 45s)", "measuredMs": 45057 }, + { + "path": "server/src/services/native-runtime/native-question-bridge.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (44.7s in run 45238253588)", + "measuredMs": 44675 + }, + { + "path": "server/src/services/native-runtime/paperclip-control-plane-port.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (43.4s in run 45238253588)", + "measuredMs": 43404 + }, + { + "path": "server/src/__tests__/onboarding-first-task-admission.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (43.1s in run 45238253588)", + "measuredMs": 43108 + }, { "path": "server/src/__tests__/terminal-workspace-deadlines.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (42.8s in run 45238253588)", "measuredMs": 42823 }, + { + "path": "server/src/__tests__/durable-chat-wakeup.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (42.1s in run 45238253588)", + "measuredMs": 42102 + }, + { + "path": "server/src/services/native-runtime/native-case-tools.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (41.7s in run 45238253588)", + "measuredMs": 41747 + }, { "path": "server/src/__tests__/issue-recovery-work-debug-attribution.test.ts", "category": "recovery-idle-maintenance-soak", @@ -571,6 +673,12 @@ "reason": "Heavy external channel/connector integration soak (40.1s in run 45238253588)", "measuredMs": 40117 }, + { + "path": "server/src/__tests__/heartbeat-session-preparation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (39.5s in run 45238253588)", + "measuredMs": 39528 + }, { "path": "server/src/__tests__/idle-connection-history.test.ts", "category": "recovery-idle-maintenance-soak", @@ -673,6 +781,12 @@ "reason": "Harness backup retention/expiration soak (35s)", "measuredMs": 34702 }, + { + "path": "server/src/__tests__/agent-chat-messages.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (34.7s in run 45238253588)", + "measuredMs": 34676 + }, { "path": "server/src/__tests__/issue-monitor-scheduler.test.ts", "category": "recovery-idle-maintenance-soak", @@ -685,6 +799,12 @@ "reason": "Native runner replacement, lease, or continuation recovery soak (34.3s in run 45238253588)", "measuredMs": 34340 }, + { + "path": "server/src/__tests__/heartbeat-run-output.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (34.1s in run 45238253588)", + "measuredMs": 34150 + }, { "path": "server/src/__tests__/failed-continuation-continues-again.test.ts", "category": "restart-lease-soak", @@ -715,6 +835,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (32.3s in run 45238253588)", "measuredMs": 32314 }, + { + "path": "server/src/__tests__/heartbeat-execution-configuration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy heartbeat execution configuration integration matrix (32.3s in run 45238253588)", + "measuredMs": 32284 + }, { "path": "server/src/__tests__/idle-incoming-wake.test.ts", "category": "recovery-idle-maintenance-soak", @@ -727,12 +853,72 @@ "reason": "Heavy object-storage, archive, or retention integration soak (31.8s in run 45238253588)", "measuredMs": 31824 }, + { + "path": "server/src/__tests__/connection-aggregator-fallback.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (31.8s in run 45238253588)", + "measuredMs": 31814 + }, + { + "path": "server/src/__tests__/chat-project-tools.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (31.6s in run 45238253588)", + "measuredMs": 31556 + }, + { + "path": "server/src/__tests__/slack-conversation-lifecycle.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (31.5s in run 45238253588)", + "measuredMs": 31522 + }, + { + "path": "server/src/__tests__/native-session-resumption.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (30.9s in run 45238253588)", + "measuredMs": 30914 + }, + { + "path": "server/src/__tests__/heartbeat-blocked-question-answer.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (30.8s in run 45238253588)", + "measuredMs": 30782 + }, + { + "path": "server/src/__tests__/status-cards.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy status-cards integration suite (30.7s in run 45238253588)", + "measuredMs": 30724 + }, + { + "path": "server/src/__tests__/agent-conversations.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (30.4s in run 45238253588)", + "measuredMs": 30413 + }, { "path": "server/src/__tests__/workspace-worktree-concurrency.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (30.4s in run 45238253588)", "measuredMs": 30390 }, + { + "path": "server/src/services/heartbeat/run-lifecycle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (30.4s in run 45238253588)", + "measuredMs": 30357 + }, + { + "path": "server/src/__tests__/claude-local-execute.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (29.9s in run 45238253588)", + "measuredMs": 29948 + }, + { + "path": "server/src/__tests__/historical-cleanup-verification.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (29.9s in run 45238253588)", + "measuredMs": 29875 + }, { "path": "server/src/services/workspace-recovery-fallback.test.ts", "category": "workspace-recovery-soak", @@ -745,30 +931,150 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (29.3s in run 45238253588)", "measuredMs": 29322 }, + { + "path": "server/src/__tests__/github-skill-source.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (29.0s in run 45238253588)", + "measuredMs": 28979 + }, { "path": "server/src/__tests__/native-result-commit-idle.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (29.0s in run 45238253588)", "measuredMs": 28978 }, + { + "path": "server/src/__tests__/agent-hire-ai-connections.test.ts", + "category": "provider-adapter-soak", + "reason": "Heavy agent-hire AI connections integration suite (28.9s in run 45238253588)", + "measuredMs": 28940 + }, + { + "path": "server/src/__tests__/native-question-process-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (28.9s in run 45238253588)", + "measuredMs": 28851 + }, + { + "path": "server/src/__tests__/attention-close.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (28.3s in run 45238253588)", + "measuredMs": 28295 + }, + { + "path": "server/src/__tests__/server-startup-feedback-export.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (28.0s in run 45238253588)", + "measuredMs": 28040 + }, + { + "path": "server/src/__tests__/run-start-handover.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (28.0s in run 45238253588)", + "measuredMs": 28002 + }, { "path": "server/src/__tests__/slack-cloud-owner-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (27.5s in run 45238253588)", "measuredMs": 27508 }, + { + "path": "server/src/__tests__/mcp-tasks-demo-server.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (27.1s in run 45238253588)", + "measuredMs": 27076 + }, + { + "path": "server/src/services/runner-lost-mid-turn-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (26.9s in run 45238253588)", + "measuredMs": 26927 + }, + { + "path": "server/src/__tests__/terminal-workspace-rotation-limits.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (26.8s in run 45238253588)", + "measuredMs": 26808 + }, + { + "path": "server/src/__tests__/controller-instance-lease.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (26.8s in run 45238253588)", + "measuredMs": 26788 + }, + { + "path": "server/src/__tests__/heartbeat-accepted-plan-workspace-refresh.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (26.4s in run 45238253588)", + "measuredMs": 26442 + }, + { + "path": "server/src/__tests__/heartbeat-person-tree-dispatch.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (26.1s in run 45238253588)", + "measuredMs": 26150 + }, { "path": "server/src/services/workspace-recovery-passive-fairness.test.ts", "category": "workspace-recovery-soak", "reason": "Workspace recovery passive fairness soak (26s)", "measuredMs": 25923 }, + { + "path": "server/src/__tests__/heartbeat-workspace-session.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (25.9s in run 45238253588)", + "measuredMs": 25884 + }, + { + "path": "server/src/__tests__/deferred-chat-wake-sweep.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (25.7s in run 45238253588)", + "measuredMs": 25678 + }, + { + "path": "server/src/__tests__/heartbeat-slack-invitation.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (25.6s in run 45238253588)", + "measuredMs": 25600 + }, { "path": "server/src/__tests__/voice-recovery-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (25.4s in run 45238253588)", "measuredMs": 25368 }, + { + "path": "server/src/services/chat-publication-text-parts.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (25.3s in run 45238253588)", + "measuredMs": 25286 + }, + { + "path": "server/src/__tests__/muse-terminal-settlement.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (25.3s in run 45238253588)", + "measuredMs": 25265 + }, + { + "path": "server/src/services/heartbeat/agent-status.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (25.2s in run 45238253588)", + "measuredMs": 25170 + }, + { + "path": "server/src/services/fresh-continuation-move-forward-offer.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (24.9s in run 45238253588)", + "measuredMs": 24878 + }, + { + "path": "server/src/__tests__/heartbeat-provider-limit-wait.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (24.8s in run 45238253588)", + "measuredMs": 24818 + }, { "path": "server/src/services/native-runtime/native-failed-workspace-recovery.test.ts", "category": "workspace-recovery-soak", @@ -781,6 +1087,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (24.8s in run 45238253588)", "measuredMs": 24764 }, + { + "path": "server/src/services/native-runtime/confirmation-comment-api.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (24.6s in run 45238253588)", + "measuredMs": 24611 + }, + { + "path": "server/src/services/workspace-runtime-exposure.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (24.5s in run 45238253588)", + "measuredMs": 24475 + }, + { + "path": "server/src/__tests__/grok-bot-routine.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (24.4s in run 45238253588)", + "measuredMs": 24423 + }, { "path": "server/src/__tests__/decision-effect-recovery-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -793,60 +1117,252 @@ "reason": "Native runner replacement, lease, or continuation recovery soak (24.3s in run 45238253588)", "measuredMs": 24304 }, + { + "path": "server/src/__tests__/issue-read-filter-batching.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Issue read filter batching performance/query suite (23.8s in run 45238253588)", + "measuredMs": 23819 + }, + { + "path": "server/src/services/native-log-archive.integration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (23.7s in run 45238253588)", + "measuredMs": 23689 + }, { "path": "server/src/services/workspace-recovery-disk-full.test.ts", "category": "workspace-recovery-soak", "reason": "Workspace recovery disk-full soak (23s)", "measuredMs": 23363 }, + { + "path": "server/src/__tests__/heartbeat-active-run-output-watchdog.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (23.2s in run 45238253588)", + "measuredMs": 23228 + }, + { + "path": "server/src/__tests__/heartbeat-task-drain-admission-release.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (23.1s in run 45238253588)", + "measuredMs": 23078 + }, + { + "path": "server/src/__tests__/file-resources.test.ts", + "category": "storage-integration-soak", + "reason": "Heavy file-resources object-storage integration suite (23.0s in run 45238253588)", + "measuredMs": 23012 + }, + { + "path": "server/src/__tests__/heartbeat-git-restore-point-resume.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (22.9s in run 45238253588)", + "measuredMs": 22905 + }, + { + "path": "server/src/__tests__/automatic-run-brake.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (22.9s in run 45238253588)", + "measuredMs": 22864 + }, + { + "path": "server/src/services/native-runtime/native-workspace-finalizer.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (22.6s in run 45238253588)", + "measuredMs": 22571 + }, + { + "path": "server/src/__tests__/issue-blocker-stall-wakeups.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (22.5s in run 45238253588)", + "measuredMs": 22472 + }, + { + "path": "server/src/services/heartbeat/environment-selection.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (22.4s in run 45238253588)", + "measuredMs": 22396 + }, + { + "path": "server/src/services/native-runtime/native-workspace-export-retry.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (22.4s in run 45238253588)", + "measuredMs": 22367 + }, { "path": "server/src/services/native-runtime/agent-chat-response-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (22.3s in run 45238253588)", "measuredMs": 22254 }, + { + "path": "server/src/__tests__/heartbeat-agent-directory-busy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (22.1s in run 45238253588)", + "measuredMs": 22123 + }, + { + "path": "server/src/__tests__/heartbeat-instruction-working-copy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (22.0s in run 45238253588)", + "measuredMs": 21994 + }, + { + "path": "server/src/services/__tests__/run-failure-report.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy run failure report classification matrix (22.0s in run 45238253588)", + "measuredMs": 21951 + }, + { + "path": "server/src/services/native-runtime/native-response-publication-retry.test.ts", + "category": "restart-lease-soak", + "reason": "Native response publication retry soak (21.9s in run 45238253588)", + "measuredMs": 21924 + }, { "path": "server/src/__tests__/routine-schedule-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (21.9s in run 45238253588)", "measuredMs": 21858 }, + { + "path": "server/src/services/remote-workspace-readonly-capture-budget.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (21.5s in run 45238253588)", + "measuredMs": 21512 + }, + { + "path": "server/src/services/native-runtime/native-remote-retry-admission.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (21.5s in run 45238253588)", + "measuredMs": 21484 + }, + { + "path": "server/src/__tests__/task-workspace-api.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy task-workspace API git integration suite (21.4s in run 45238253588)", + "measuredMs": 21431 + }, { "path": "server/src/__tests__/chat-receiver-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (21.3s in run 45238253588)", "measuredMs": 21267 }, + { + "path": "server/src/__tests__/agent-runtime-hooks.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy agent runtime hooks integration suite (21.2s in run 45238253588)", + "measuredMs": 21201 + }, + { + "path": "server/src/__tests__/skill-package-store.test.ts", + "category": "storage-integration-soak", + "reason": "Skill package object-store integration soak (21.0s in run 45238253588)", + "measuredMs": 21032 + }, { "path": "server/src/services/workspace-recovery-stop-proof.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.9s in run 45238253588)", "measuredMs": 20908 }, + { + "path": "server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (20.9s in run 45238253588)", + "measuredMs": 20887 + }, { "path": "server/src/services/remote-workspace-snapshot-retention.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.9s in run 45238253588)", "measuredMs": 20875 }, + { + "path": "server/src/__tests__/file-delivery-bridges.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (20.9s in run 45238253588)", + "measuredMs": 20870 + }, + { + "path": "server/src/__tests__/heartbeat-native-cleanup-admission.test.ts", + "category": "restart-lease-soak", + "reason": "Native cleanup admission soak (20.8s in run 45238253588)", + "measuredMs": 20757 + }, { "path": "server/src/services/remote-workspace-save-concurrency.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.7s in run 45238253588)", "measuredMs": 20703 }, + { + "path": "server/src/services/native-runtime/native-recovered-owner-followup.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (20.7s in run 45238253588)", + "measuredMs": 20680 + }, + { + "path": "server/src/__tests__/task-watchdogs-scheduler.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (20.6s in run 45238253588)", + "measuredMs": 20633 + }, { "path": "server/src/services/workspace-recovery-scheduled-preparation.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.6s in run 45238253588)", "measuredMs": 20606 }, + { + "path": "server/src/__tests__/heartbeat-task-context.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy heartbeat task-context assembly suite (20.6s in run 45238253588)", + "measuredMs": 20582 + }, + { + "path": "server/src/__tests__/heartbeat-runtime-services.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy heartbeat runtime-services process lifecycle suite (20.5s in run 45238253588)", + "measuredMs": 20472 + }, + { + "path": "server/src/__tests__/heartbeat-issue-rewake-throttle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock issue rewake throttle soak (20.3s in run 45238253588)", + "measuredMs": 20323 + }, + { + "path": "server/src/__tests__/execution-workspace-reopen.test.ts", + "category": "workspace-recovery-soak", + "reason": "Execution workspace reopen git/DB soak (20.3s in run 45238253588)", + "measuredMs": 20305 + }, { "path": "server/src/__tests__/heartbeat-remote-workspace-busy.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.2s in run 45238253588)", "measuredMs": 20229 }, + { + "path": "server/src/__tests__/storage-outage-wait.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (20.1s in run 45238253588)", + "measuredMs": 20089 + }, + { + "path": "server/src/__tests__/project-workspace-provider.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (19.9s in run 45238253588)", + "measuredMs": 19935 + }, + { + "path": "server/src/services/chat-monitor-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (19.9s in run 45238253588)", + "measuredMs": 19929 + }, { "path": "server/src/__tests__/native-environment-settlement-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -865,12 +1381,84 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (19.9s in run 45238253588)", "measuredMs": 19860 }, + { + "path": "server/src/__tests__/routine-status-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (19.8s in run 45238253588)", + "measuredMs": 19810 + }, + { + "path": "server/src/__tests__/runner-connection-eval-fixtures.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (19.8s in run 45238253588)", + "measuredMs": 19765 + }, + { + "path": "server/src/__tests__/chat-completion-delivery.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (19.6s in run 45238253588)", + "measuredMs": 19576 + }, + { + "path": "server/src/__tests__/heartbeat-subtask-acquired-repository.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (19.5s in run 45238253588)", + "measuredMs": 19535 + }, + { + "path": "server/src/__tests__/settled-native-process-rechecks.test.ts", + "category": "restart-lease-soak", + "reason": "Settled native process recheck soak (19.5s in run 45238253588)", + "measuredMs": 19494 + }, + { + "path": "server/src/__tests__/deployment-connections.test.ts", + "category": "provider-adapter-soak", + "reason": "Deployment connections integration suite (19.3s in run 45238253588)", + "measuredMs": 19322 + }, + { + "path": "server/src/__tests__/question-response-delivery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Question response delivery retry soak (19.3s in run 45238253588)", + "measuredMs": 19309 + }, + { + "path": "server/src/__tests__/company-skills-catalog-service.test.ts", + "category": "storage-integration-soak", + "reason": "Company skills catalog sync/archive suite (19.3s in run 45238253588)", + "measuredMs": 19294 + }, + { + "path": "server/src/services/native-preclaim-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (19.2s in run 45238253588)", + "measuredMs": 19224 + }, + { + "path": "server/src/__tests__/agent-file-durability.test.ts", + "category": "storage-integration-soak", + "reason": "Agent file durability storage soak (19.1s in run 45238253588)", + "measuredMs": 19117 + }, { "path": "server/src/services/native-runtime/plugin-task-source-recovery.integration.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (18.7s in run 45238253588)", "measuredMs": 18697 }, + { + "path": "server/src/__tests__/plugin-workspaces.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (18.6s in run 45238253588)", + "measuredMs": 18587 + }, + { + "path": "server/src/services/native-runtime/create-skill.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (18.3s in run 45238253588)", + "measuredMs": 18316 + }, { "path": "server/src/__tests__/issue-recovery-pass-reads.test.ts", "category": "recovery-idle-maintenance-soak", @@ -907,18 +1495,48 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (17.4s in run 45238253588)", "measuredMs": 17358 }, + { + "path": "server/src/services/muse-maintenance.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (17.3s in run 45238253588)", + "measuredMs": 17264 + }, + { + "path": "server/src/services/native-runtime/runner-api-artifacts.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (17.0s in run 45238253588)", + "measuredMs": 17044 + }, + { + "path": "server/src/__tests__/daytona-connection.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (16.8s in run 45238253588)", + "measuredMs": 16846 + }, { "path": "server/src/services/online-remote-workspace-recovery-hold.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (16.8s in run 45238253588)", "measuredMs": 16840 }, + { + "path": "server/src/__tests__/agent-commentary.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (16.8s in run 45238253588)", + "measuredMs": 16813 + }, { "path": "server/src/__tests__/recovery-durable-wait-projection.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.8s in run 45238253588)", "measuredMs": 16751 }, + { + "path": "server/src/services/native-runtime/task-document-body.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (16.7s in run 45238253588)", + "measuredMs": 16703 + }, { "path": "server/src/__tests__/retained-native-session-cleanup-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -931,12 +1549,42 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.3s in run 45238253588)", "measuredMs": 16340 }, + { + "path": "server/src/__tests__/case-handoff-legacy.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (16.3s in run 45238253588)", + "measuredMs": 16308 + }, + { + "path": "server/src/services/native-runtime/native-harness-backup-download-deadline.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (16.3s in run 45238253588)", + "measuredMs": 16303 + }, { "path": "server/src/__tests__/task-creation-recovery.integration.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.3s in run 45238253588)", "measuredMs": 16295 }, + { + "path": "server/src/services/fresh-continuation-retry-delivery.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (16.2s in run 45238253588)", + "measuredMs": 16226 + }, + { + "path": "server/src/services/native-runtime/native-provider-capacity.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (16.1s in run 45238253588)", + "measuredMs": 16101 + }, + { + "path": "server/src/__tests__/archived-nested-repository.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (16.0s in run 45238253588)", + "measuredMs": 16037 + }, { "path": "server/src/__tests__/decision-expiry-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -955,18 +1603,36 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (15.3s in run 45238253588)", "measuredMs": 15340 }, + { + "path": "server/src/__tests__/assigned-work-sweep-round-trips.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (15.2s in run 45238253588)", + "measuredMs": 15224 + }, { "path": "server/src/services/remote-workspace-snapshot-storage.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (15.0s in run 45238253588)", "measuredMs": 14951 }, + { + "path": "server/src/services/unrecoverable-saved-work-retry.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (14.9s in run 45238253588)", + "measuredMs": 14901 + }, { "path": "server/src/__tests__/native-result-commit-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (14.8s in run 45238253588)", "measuredMs": 14821 }, + { + "path": "server/src/services/native-runtime/muse-native-visibility.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (14.8s in run 45238253588)", + "measuredMs": 14758 + }, { "path": "server/src/__tests__/native-retention-blocker-batch.test.ts", "category": "recovery-idle-maintenance-soak", @@ -979,6 +1645,42 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (14.6s in run 45238253588)", "measuredMs": 14584 }, + { + "path": "server/src/services/heartbeat/run-completion-reviewed-chat-report.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (14.3s in run 45238253588)", + "measuredMs": 14349 + }, + { + "path": "server/src/services/native-runtime/native-startup-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (14.2s in run 45238253588)", + "measuredMs": 14172 + }, + { + "path": "server/src/services/native-runtime/native-failed-turn-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (14.1s in run 45238253588)", + "measuredMs": 14062 + }, + { + "path": "server/src/services/covered-historical-workspace-source.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (14.0s in run 45238253588)", + "measuredMs": 13981 + }, + { + "path": "server/src/services/native-runtime/update-skill.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (14.0s in run 45238253588)", + "measuredMs": 13979 + }, + { + "path": "server/src/__tests__/heartbeat-run-start-handover.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (13.9s in run 45238253588)", + "measuredMs": 13908 + }, { "path": "server/src/services/saved-work-recovery-overdue.test.ts", "category": "recovery-idle-maintenance-soak", @@ -991,6 +1693,18 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.8s in run 45238253588)", "measuredMs": 13796 }, + { + "path": "server/src/__tests__/muse-client-contract.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (13.7s in run 45238253588)", + "measuredMs": 13742 + }, + { + "path": "server/src/services/fresh-continuation-schedule-queries.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (13.6s in run 45238253588)", + "measuredMs": 13634 + }, { "path": "server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1009,12 +1723,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.6s in run 45238253588)", "measuredMs": 13581 }, + { + "path": "server/src/__tests__/assigned-work-stalled-queued-run.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (13.5s in run 45238253588)", + "measuredMs": 13543 + }, { "path": "server/src/__tests__/eval-feedback-recovery.integration.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.5s in run 45238253588)", "measuredMs": 13456 }, + { + "path": "server/src/services/native-runtime/native-session-resumption-binding.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (13.4s in run 45238253588)", + "measuredMs": 13387 + }, { "path": "server/src/__tests__/login-cleanup-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1039,6 +1765,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.1s in run 45238253588)", "measuredMs": 13089 }, + { + "path": "server/src/__tests__/teams-catalog-install-no-overrides.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (13.0s in run 45238253588)", + "measuredMs": 13040 + }, { "path": "server/src/__tests__/continuation-delivery-unwakeable-agent-idle.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1051,6 +1783,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (12.9s in run 45238253588)", "measuredMs": 12889 }, + { + "path": "server/src/__tests__/native-tool-call-loop-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (12.8s in run 45238253588)", + "measuredMs": 12786 + }, + { + "path": "server/src/services/native-runtime/native-skill-library-tools.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (12.5s in run 45238253588)", + "measuredMs": 12497 + }, + { + "path": "server/src/__tests__/coordinator-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (12.4s in run 45238253588)", + "measuredMs": 12393 + }, { "path": "server/src/services/native-runtime/native-idle-sleep-continuation.integration.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1075,6 +1825,30 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (12.0s in run 45238253588)", "measuredMs": 11990 }, + { + "path": "server/src/__tests__/google-workspace-rest-transport.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (12.0s in run 45238253588)", + "measuredMs": 11985 + }, + { + "path": "server/src/__tests__/codex-local-execute.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (11.9s in run 45238253588)", + "measuredMs": 11921 + }, + { + "path": "server/src/services/native-runtime/task-monitor.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (11.8s in run 45238253588)", + "measuredMs": 11794 + }, + { + "path": "server/src/services/native-runtime/native-provider-pack-admission.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (11.8s in run 45238253588)", + "measuredMs": 11771 + }, { "path": "server/src/__tests__/decision-retention-service.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1087,6 +1861,12 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (11.6s in run 45238253588)", "measuredMs": 11646 }, + { + "path": "server/src/__tests__/workspace-delivery-cleanup.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (11.6s in run 45238253588)", + "measuredMs": 11616 + }, { "path": "server/src/__tests__/issue-recovery-signal-fanout.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1111,108 +1891,426 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (11.4s in run 45238253588)", "measuredMs": 11370 }, + { + "path": "server/src/services/saved-bootstrap-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (11.2s in run 45238253588)", + "measuredMs": 11165 + }, + { + "path": "server/src/services/native-runtime/native-closed-session-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (11.1s in run 45238253588)", + "measuredMs": 11115 + }, + { + "path": "server/src/services/native-runtime/scheduled-resume-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (11.1s in run 45238253588)", + "measuredMs": 11093 + }, + { + "path": "server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (10.9s in run 45238253588)", + "measuredMs": 10912 + }, + { + "path": "server/src/services/native-runtime/native-runner-file-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (10.8s in run 45238253588)", + "measuredMs": 10846 + }, { "path": "server/src/__tests__/chat-run-milestone-governed-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.8s in run 45238253588)", "measuredMs": 10752 }, + { + "path": "server/src/services/native-runtime/native-governed-wait-lost-state-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (10.7s in run 45238253588)", + "measuredMs": 10705 + }, + { + "path": "server/src/services/execution-control-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (10.7s in run 45238253588)", + "measuredMs": 10688 + }, + { + "path": "server/src/__tests__/git-restore-point.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (10.7s in run 45238253588)", + "measuredMs": 10673 + }, + { + "path": "server/src/__tests__/heartbeat-pending-cleanup-sweep.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (10.6s in run 45238253588)", + "measuredMs": 10615 + }, { "path": "server/src/services/isolated-remote-workspace-source-lock.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (10.5s in run 45238253588)", "measuredMs": 10495 }, + { + "path": "server/src/services/native-runtime/agent-instruction-tools.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.4s in run 45238253588)", + "measuredMs": 10416 + }, { "path": "server/src/services/workspace-recovery-source.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (10.4s in run 45238253588)", "measuredMs": 10414 }, + { + "path": "server/src/services/native-runtime/native-environment-blocker.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.4s in run 45238253588)", + "measuredMs": 10409 + }, + { + "path": "server/src/services/native-runtime/native-provider-failure.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.4s in run 45238253588)", + "measuredMs": 10393 + }, { "path": "server/src/__tests__/plugin-environment-driver-ready-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.4s in run 45238253588)", "measuredMs": 10383 }, + { + "path": "server/src/services/legacy-source-unavailable-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (10.2s in run 45238253588)", + "measuredMs": 10232 + }, { "path": "server/src/__tests__/terminal-workspace-idle.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.2s in run 45238253588)", "measuredMs": 10197 }, + { + "path": "server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.1s in run 45238253588)", + "measuredMs": 10117 + }, + { + "path": "server/src/__tests__/smoke-lab.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (10.0s in run 45238253588)", + "measuredMs": 10012 + }, { "path": "server/src/__tests__/heartbeat-run-scratch-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.0s in run 45238253588)", "measuredMs": 10008 }, + { + "path": "server/src/__tests__/heartbeat-orphaned-active-lease-sweep.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (10.0s in run 45238253588)", + "measuredMs": 9957 + }, + { + "path": "server/src/__tests__/antigravity-ai-connections.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.0s in run 45238253588)", + "measuredMs": 9951 + }, { "path": "server/src/services/skill-package-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.9s in run 45238253588)", "measuredMs": 9936 }, + { + "path": "server/src/services/native-runtime/native-execution-lease-batch.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.9s in run 45238253588)", + "measuredMs": 9912 + }, + { + "path": "server/src/services/native-runtime/native-provider-overload.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.9s in run 45238253588)", + "measuredMs": 9905 + }, + { + "path": "server/src/services/native-runtime/native-harness-filesystem-independence-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.8s in run 45238253588)", + "measuredMs": 9813 + }, + { + "path": "server/src/__tests__/heartbeat-case-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.7s in run 45238253588)", + "measuredMs": 9748 + }, { "path": "server/src/__tests__/online-workspace-migration-compatibility.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (9.7s in run 45238253588)", "measuredMs": 9742 }, + { + "path": "server/src/__tests__/workspace-runtime-start-terminality.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (9.7s in run 45238253588)", + "measuredMs": 9698 + }, + { + "path": "server/src/services/native-runtime/native-startup-rejected-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.7s in run 45238253588)", + "measuredMs": 9672 + }, + { + "path": "server/src/__tests__/plugin-warm-tasks.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.7s in run 45238253588)", + "measuredMs": 9651 + }, + { + "path": "server/src/__tests__/link-preview-store.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.6s in run 45238253588)", + "measuredMs": 9626 + }, + { + "path": "server/src/__tests__/voice-inbound-cleanup.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (9.6s in run 45238253588)", + "measuredMs": 9552 + }, { "path": "server/src/__tests__/legacy-workspace-restore-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.6s in run 45238253588)", "measuredMs": 9551 }, + { + "path": "server/src/__tests__/voice-call-reports.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (9.5s in run 45238253588)", + "measuredMs": 9524 + }, + { + "path": "server/src/__tests__/case-mutation-fence.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.5s in run 45238253588)", + "measuredMs": 9507 + }, + { + "path": "server/src/services/native-runtime/artifact-transfer.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.5s in run 45238253588)", + "measuredMs": 9481 + }, + { + "path": "server/src/services/native-runtime/native-client-timeout-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.5s in run 45238253588)", + "measuredMs": 9480 + }, { "path": "server/src/services/native-runtime/tool-receipt-recovery.integration.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.5s in run 45238253588)", "measuredMs": 9465 }, + { + "path": "server/src/__tests__/plugin-worker-manager-daytona-close.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (9.5s in run 45238253588)", + "measuredMs": 9454 + }, + { + "path": "server/src/__tests__/plugin-runner-task.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.4s in run 45238253588)", + "measuredMs": 9392 + }, { "path": "server/src/services/legacy-explicit-continuation-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.4s in run 45238253588)", "measuredMs": 9358 }, + { + "path": "server/src/__tests__/workspace-runtime-exposure-reservation.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (9.3s in run 45238253588)", + "measuredMs": 9335 + }, { "path": "server/src/__tests__/chat-run-milestone-recovery-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.2s in run 45238253588)", "measuredMs": 9193 }, + { + "path": "server/src/__tests__/composio-app-setup.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (9.2s in run 45238253588)", + "measuredMs": 9173 + }, + { + "path": "server/src/services/native-runtime/muse-native-follow-up.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (9.2s in run 45238253588)", + "measuredMs": 9157 + }, + { + "path": "server/src/services/native-runtime/sandbox-runner-port-holders.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.2s in run 45238253588)", + "measuredMs": 9151 + }, + { + "path": "server/src/maintenance/native-harness-prestage-runtime.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.1s in run 45238253588)", + "measuredMs": 9103 + }, + { + "path": "server/src/__tests__/plugin-install-autobuild.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (9.1s in run 45238253588)", + "measuredMs": 9089 + }, + { + "path": "server/src/services/native-runtime/native-bootstrap-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.1s in run 45238253588)", + "measuredMs": 9069 + }, + { + "path": "server/src/services/native-runtime/native-harness-backup-obligations.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.0s in run 45238253588)", + "measuredMs": 8992 + }, + { + "path": "server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.0s in run 45238253588)", + "measuredMs": 8957 + }, + { + "path": "server/src/__tests__/board-native-attachments.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.9s in run 45238253588)", + "measuredMs": 8898 + }, { "path": "server/src/__tests__/heartbeat-agent-status-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.9s in run 45238253588)", "measuredMs": 8890 }, + { + "path": "server/src/__tests__/native-cancellation-request.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.8s in run 45238253588)", + "measuredMs": 8844 + }, { "path": "server/src/services/native-runtime/remote-warm-session-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.8s in run 45238253588)", "measuredMs": 8796 }, + { + "path": "server/src/services/native-runtime/native-coordinator-claim-deadlock.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.8s in run 45238253588)", + "measuredMs": 8794 + }, + { + "path": "server/src/__tests__/plugin-workspace-terminal-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.8s in run 45238253588)", + "measuredMs": 8780 + }, + { + "path": "server/src/services/chat-channels/github/response-run-state.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (8.8s in run 45238253588)", + "measuredMs": 8778 + }, { "path": "server/src/__tests__/chat-run-milestone-identity-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.7s in run 45238253588)", "measuredMs": 8727 }, + { + "path": "server/src/__tests__/tool-connection-installs.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.7s in run 45238253588)", + "measuredMs": 8725 + }, { "path": "server/src/__tests__/issue-recovery-terminal-run-settling.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.7s in run 45238253588)", "measuredMs": 8681 }, + { + "path": "server/src/__tests__/heartbeat-case-terminal-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.6s in run 45238253588)", + "measuredMs": 8571 + }, + { + "path": "server/src/__tests__/workspace-operations-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.5s in run 45238253588)", + "measuredMs": 8506 + }, + { + "path": "server/src/__tests__/environment-pending-cleanup-queue-owner.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (8.5s in run 45238253588)", + "measuredMs": 8493 + }, { "path": "server/src/services/recovery/issue-state-read.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.4s in run 45238253588)", "measuredMs": 8448 }, + { + "path": "server/src/__tests__/git-restore-point-ledger.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (8.4s in run 45238253588)", + "measuredMs": 8440 + }, + { + "path": "server/src/services/native-runtime/native-stop-accounting.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.4s in run 45238253588)", + "measuredMs": 8429 + }, + { + "path": "server/src/services/chat-interaction-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.4s in run 45238253588)", + "measuredMs": 8423 + }, { "path": "server/src/__tests__/human-directed-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1225,6 +2323,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.4s in run 45238253588)", "measuredMs": 8390 }, + { + "path": "server/src/__tests__/heartbeat-native-orphan-sweep-lease-race.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.3s in run 45238253588)", + "measuredMs": 8348 + }, + { + "path": "server/src/__tests__/heartbeat-task-drain.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.3s in run 45238253588)", + "measuredMs": 8334 + }, + { + "path": "server/src/__tests__/merged-pr-confirmation-sweep.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.3s in run 45238253588)", + "measuredMs": 8317 + }, { "path": "server/src/services/native-runtime/native-controller-host-recovery.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1243,6 +2359,42 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (8.3s in run 45238253588)", "measuredMs": 8274 }, + { + "path": "server/src/__tests__/native-observer-replay.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.3s in run 45238253588)", + "measuredMs": 8254 + }, + { + "path": "server/src/services/native-runtime/native-scheduled-resume-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.2s in run 45238253588)", + "measuredMs": 8229 + }, + { + "path": "server/src/services/offline-workspace-operation-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.2s in run 45238253588)", + "measuredMs": 8220 + }, + { + "path": "server/src/services/native-runtime/native-failure-write-lock-contention.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.2s in run 45238253588)", + "measuredMs": 8216 + }, + { + "path": "server/src/__tests__/issue-blocker-stall-waiter-statement.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.1s in run 45238253588)", + "measuredMs": 8086 + }, + { + "path": "server/src/__tests__/plugin-fresh-workspaces.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.1s in run 45238253588)", + "measuredMs": 8075 + }, { "path": "server/src/__tests__/chat-run-milestone-resource-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1262,10 +2414,28 @@ "measuredMs": 8020 }, { - "path": "server/src/__tests__/recovery-observability.test.ts", + "path": "server/src/services/native-runtime/native-human-self-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.0s in run 45238253588)", + "measuredMs": 8019 + }, + { + "path": "server/src/services/connectors/tailscale/connections.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (8.0s in run 45238253588)", + "measuredMs": 7964 + }, + { + "path": "server/src/__tests__/heartbeat-drain-native-resume-dispatch.test.ts", "category": "recovery-idle-maintenance-soak", - "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.8s in run 45238253588)", - "measuredMs": 7801 + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.9s in run 45238253588)", + "measuredMs": 7922 + }, + { + "path": "server/src/__tests__/slack-tool-preparation.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.9s in run 45238253588)", + "measuredMs": 7909 }, { "path": "server/src/services/native-runtime/native-staged-attachment-recovery.test.ts", @@ -1297,12 +2467,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.7s in run 45238253588)", "measuredMs": 7656 }, + { + "path": "server/src/__tests__/agent-connection-catalog.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (7.6s in run 45238253588)", + "measuredMs": 7637 + }, { "path": "server/src/services/recovery/service.pause-durability.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.6s in run 45238253588)", "measuredMs": 7577 }, + { + "path": "server/src/services/environment-runtime-reusable-lease-probe.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.6s in run 45238253588)", + "measuredMs": 7560 + }, { "path": "server/src/__tests__/idle-accounting-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1315,30 +2497,84 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.5s in run 45238253588)", "measuredMs": 7505 }, + { + "path": "server/src/services/native-runtime/native-workspace-finalizer-failure.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.5s in run 45238253588)", + "measuredMs": 7494 + }, + { + "path": "server/src/services/chat-channels/slack/form-owner-rearm.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.5s in run 45238253588)", + "measuredMs": 7463 + }, + { + "path": "server/src/services/native-runtime/native-case-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.5s in run 45238253588)", + "measuredMs": 7463 + }, { "path": "server/src/services/native-runtime/native-controller-recovery.test.ts", "category": "restart-lease-soak", "reason": "Native runner replacement, lease, or continuation recovery soak (7.5s in run 45238253588)", "measuredMs": 7453 }, + { + "path": "server/src/services/chat-discord-command-registration-store.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.4s in run 45238253588)", + "measuredMs": 7446 + }, { "path": "server/src/services/recovery/run-context-read.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.4s in run 45238253588)", "measuredMs": 7429 }, + { + "path": "server/src/services/chat-discord-native-interaction.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.4s in run 45238253588)", + "measuredMs": 7411 + }, + { + "path": "server/src/services/chat-channels/slack/cloud-event.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.4s in run 45238253588)", + "measuredMs": 7407 + }, + { + "path": "server/src/services/native-runtime/continuation-contract.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.4s in run 45238253588)", + "measuredMs": 7392 + }, { "path": "server/src/services/native-runtime/native-blocked-reply-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.4s in run 45238253588)", "measuredMs": 7382 }, + { + "path": "server/src/__tests__/task-watchdogs-classifier.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.4s in run 45238253588)", + "measuredMs": 7353 + }, { "path": "server/src/services/public-mcp/idle-sleep-proof.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.3s in run 45238253588)", "measuredMs": 7346 }, + { + "path": "server/src/services/execution-continuation-provenance.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.3s in run 45238253588)", + "measuredMs": 7312 + }, { "path": "server/src/services/idle-incoming-wake.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1357,12 +2593,48 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.2s in run 45238253588)", "measuredMs": 7215 }, + { + "path": "server/src/__tests__/work-product-runtime-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.2s in run 45238253588)", + "measuredMs": 7198 + }, { "path": "server/src/services/recovery/native-runner-routing.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.2s in run 45238253588)", "measuredMs": 7196 }, + { + "path": "server/src/__tests__/workspace-runtime-lifecycle.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (7.2s in run 45238253588)", + "measuredMs": 7179 + }, + { + "path": "server/src/services/native-runtime/native-retired-backup-source.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (7.2s in run 45238253588)", + "measuredMs": 7163 + }, + { + "path": "server/src/services/skill-version-cache-lock.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.1s in run 45238253588)", + "measuredMs": 7117 + }, + { + "path": "server/src/__tests__/delivery-work-coordinator.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.1s in run 45238253588)", + "measuredMs": 7099 + }, + { + "path": "server/src/__tests__/connection-install-capabilities.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.1s in run 45238253588)", + "measuredMs": 7067 + }, { "path": "server/src/services/remote-workspace-reservation.test.ts", "category": "workspace-recovery-soak", @@ -1375,12 +2647,30 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.0s in run 45238253588)", "measuredMs": 6988 }, + { + "path": "server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.0s in run 45238253588)", + "measuredMs": 6985 + }, + { + "path": "server/src/services/chat-sdk-runtime.adapters.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.0s in run 45238253588)", + "measuredMs": 6978 + }, { "path": "server/src/services/recovery/run-result-read.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.0s in run 45238253588)", "measuredMs": 6976 }, + { + "path": "server/src/services/native-runtime/cursor-cloud-artifact-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.0s in run 45238253588)", + "measuredMs": 6960 + }, { "path": "server/src/services/native-runtime/native-restart-recovery.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1399,6 +2689,18 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.9s in run 45238253588)", "measuredMs": 6940 }, + { + "path": "server/src/services/workspace-restore-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (6.9s in run 45238253588)", + "measuredMs": 6919 + }, + { + "path": "server/src/services/run-intake-stall-watch.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (6.9s in run 45238253588)", + "measuredMs": 6858 + }, { "path": "server/src/services/execution-recovery-dead-controller.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1417,6 +2719,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.8s in run 45238253588)", "measuredMs": 6830 }, + { + "path": "server/src/services/native-runtime/native-session-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (6.8s in run 45238253588)", + "measuredMs": 6818 + }, { "path": "server/src/services/heartbeat/remote-workspace-source.test.ts", "category": "workspace-recovery-soak", @@ -1429,6 +2737,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.7s in run 45238253588)", "measuredMs": 6716 }, + { + "path": "server/src/services/chat-channels/github/response-sweep-scope.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.7s in run 45238253588)", + "measuredMs": 6654 + }, { "path": "server/src/__tests__/idle-sleep-preparation.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1447,6 +2761,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.6s in run 45238253588)", "measuredMs": 6591 }, + { + "path": "server/src/services/chat-channels/slack/cloud-drain.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.6s in run 45238253588)", + "measuredMs": 6585 + }, { "path": "server/src/__tests__/recovery-classifiers.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1459,6 +2779,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.4s in run 45238253588)", "measuredMs": 6415 }, + { + "path": "server/src/services/chat-channels/github/retry.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.4s in run 45238253588)", + "measuredMs": 6396 + }, { "path": "server/src/__tests__/recovery-deadline-bootstrap.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1483,6 +2809,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.2s in run 45238253588)", "measuredMs": 6236 }, + { + "path": "server/src/services/execution-continuation-history-read.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (6.2s in run 45238253588)", + "measuredMs": 6235 + }, { "path": "server/src/__tests__/chat-delivery-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1501,6 +2833,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.2s in run 45238253588)", "measuredMs": 6172 }, + { + "path": "server/src/services/execution-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (6.1s in run 45238253588)", + "measuredMs": 6146 + }, { "path": "server/src/services/native-runtime/native-finalization-recovery-state.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1519,30 +2857,90 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.1s in run 45238253588)", "measuredMs": 6083 }, + { + "path": "server/src/services/native-runtime/native-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (6.1s in run 45238253588)", + "measuredMs": 6062 + }, { "path": "server/src/services/native-runtime/native-recovery-preparation-failure.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.1s in run 45238253588)", "measuredMs": 6054 }, + { + "path": "server/src/__tests__/rerun-survival.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (6.1s in run 45238253588)", + "measuredMs": 6052 + }, + { + "path": "server/src/services/workspace-runtime-exposure-backfill.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (6.0s in run 45238253588)", + "measuredMs": 6047 + }, { "path": "server/src/services/system-recovery-state.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.0s in run 45238253588)", "measuredMs": 6030 }, + { + "path": "server/src/services/chat-channels/run-origin.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.0s in run 45238253588)", + "measuredMs": 6023 + }, { "path": "server/src/services/online-legacy-workspace-recovery.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (6.0s in run 45238253588)", "measuredMs": 6018 }, + { + "path": "server/src/services/heartbeat/instruction-working-copy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (6.0s in run 45238253588)", + "measuredMs": 5974 + }, + { + "path": "server/src/services/chat-channels/slack/cloud-callback.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.0s in run 45238253588)", + "measuredMs": 5968 + }, { "path": "server/src/services/execution-recovery-attempt.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.9s in run 45238253588)", "measuredMs": 5915 }, + { + "path": "server/src/services/native-runtime/native-bootstrap-claim-time-proof.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (5.9s in run 45238253588)", + "measuredMs": 5878 + }, + { + "path": "server/src/__tests__/slack-form-publication-readiness.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (5.8s in run 45238253588)", + "measuredMs": 5820 + }, + { + "path": "server/src/services/native-runtime/native-recoverable-lost-turn.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (5.8s in run 45238253588)", + "measuredMs": 5815 + }, + { + "path": "server/src/__tests__/storage-s3-multipart.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (5.8s in run 45238253588)", + "measuredMs": 5750 + }, { "path": "server/src/services/recovery/review-path-recovery.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1555,6 +2953,18 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.5s in run 45238253588)", "measuredMs": 5474 }, + { + "path": "server/src/__tests__/automatic-run-brake-import.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (5.3s in run 45238253588)", + "measuredMs": 5272 + }, + { + "path": "server/src/__tests__/email-address-check.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (5.3s in run 45238253588)", + "measuredMs": 5253 + }, { "path": "server/src/modules/wake-queue/adapters/retryable-before-provider-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1567,12 +2977,24 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (5.2s in run 45238253588)", "measuredMs": 5150 }, + { + "path": "server/src/services/native-runtime/remote-opencode-artifacts.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (5.1s in run 45238253588)", + "measuredMs": 5149 + }, { "path": "server/src/services/isolated-remote-workspace-source.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (5.1s in run 45238253588)", "measuredMs": 5129 }, + { + "path": "server/src/services/chat-slack-receipts.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (5.1s in run 45238253588)", + "measuredMs": 5112 + }, { "path": "server/src/__tests__/recovery-deadline-ordinary-bootstrap.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1639,12 +3061,6 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.7s in run 45238253588)", "measuredMs": 2696 }, - { - "path": "server/src/services/native-runtime/antigravity-credential-recovery.test.ts", - "category": "recovery-idle-maintenance-soak", - "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.7s in run 45238253588)", - "measuredMs": 2691 - }, { "path": "server/src/__tests__/scheduled-work.test.ts", "category": "recovery-idle-maintenance-soak", diff --git a/scripts/ci/vitest-workers.mjs b/scripts/ci/vitest-workers.mjs new file mode 100644 index 00000000000..b3ca9008c3f --- /dev/null +++ b/scripts/ci/vitest-workers.mjs @@ -0,0 +1,59 @@ +import os from "node:os"; + +function parsePositiveIntegerEnv(raw, name) { + const parsed = Number(raw); + if (raw.trim() === "" || !Number.isInteger(parsed) || parsed < 1) { + throw new Error(`${name} must be a positive integer. Received "${raw}".`); + } + return parsed; +} + +export function resolveAvailableCpuCount(env = process.env) { + const override = env.PAPERCLIP_VITEST_CPU_COUNT?.trim(); + if (override) { + return parsePositiveIntegerEnv(override, "PAPERCLIP_VITEST_CPU_COUNT"); + } + return Math.max(1, os.availableParallelism()); +} + +export function defaultServerParallelWorkers(lane, cpuCount = resolveAvailableCpuCount()) { + if (!Number.isInteger(cpuCount) || cpuCount < 1) { + throw new Error(`CPU count must be a positive integer. Received "${cpuCount}".`); + } + if (lane === "general") { + // 4-core runners keep 4 workers; 8-core runners scale to 7 (leaving 1 core + // for shared PostgreSQL + Vitest coordinator) and cap at 8 on large hosts. + if (cpuCount <= 4) { + return cpuCount; + } + return Math.min(8, cpuCount - 1); + } + if (lane === "serialized") { + // Route/authz suites are heavier per fork; keep 3 workers on 4-core runners + // and scale smoothly to 5 workers on 8-core runners (capped at 6). + if (cpuCount <= 2) return 1; + if (cpuCount === 3) return 2; + if (cpuCount === 4) return 3; + return Math.min(6, Math.max(3, Math.round((cpuCount * 5) / 8))); + } + throw new Error(`Unknown server worker lane "${lane}". Expected "general" or "serialized".`); +} + +export function resolveServerParallelWorkers(lane, env = process.env) { + const raw = env.PAPERCLIP_VITEST_MAX_WORKERS?.trim(); + if (raw) { + return parsePositiveIntegerEnv(raw, "PAPERCLIP_VITEST_MAX_WORKERS"); + } + return defaultServerParallelWorkers(lane, resolveAvailableCpuCount(env)); +} + +export function resolveWorkspaceParallelWorkers(env = process.env) { + const raw = env.PAPERCLIP_VITEST_MAX_WORKERS?.trim(); + if (raw) { + return parsePositiveIntegerEnv(raw, "PAPERCLIP_VITEST_MAX_WORKERS"); + } + // Vitest defaults to cpus - 1 for forks (3 workers on 4-core CI, leaving a core idle). + // Use 4 workers on 4-core runners and cap at 7 on 8+-core runners so 1 core stays + // free for the Vite transform server. + return Math.min(7, resolveAvailableCpuCount(env)); +} diff --git a/scripts/ci/workspaces-b-shard.mjs b/scripts/ci/workspaces-b-shard.mjs new file mode 100644 index 00000000000..23c07748351 --- /dev/null +++ b/scripts/ci/workspaces-b-shard.mjs @@ -0,0 +1,91 @@ +// Duration-weighted project sharding for `general-workspaces-b`. +// Measured weights (ms, batched multi-project Vitest run on 4-core runners): +// `@paperclipai/adapter-utils` (~2,146 tests, ~135s) dominates the 17-project +// lane and equals the combined batched runtime of the remaining 16 packages +// (~133s), so a 2-shard LPT split naturally balances ~2.2m per shard. +export const DEFAULT_WORKSPACE_PROJECT_WEIGHT_MS = 10_000; + +export const WORKSPACES_B_PROJECT_DURATIONS_MS = Object.freeze({ + "@paperclipai/adapter-utils": 135_000, + "@paperclipai/plugin-daytona": 34_000, + "@paperclipai/adapter-claude-local": 20_000, + "@paperclipai/adapter-codex-local": 17_500, + "@paperclipai/adapter-gemini-local": 8_800, + "@paperclipai/hermes-paperclip-adapter": 7_900, + "@paperclipai/adapter-grok-local": 7_400, + "@paperclipai/shared": 6_500, + "@paperclipai/plugin-sdk": 6_000, + "@paperclipai/adapter-opencode-local": 5_100, + "@paperclipai/adapter-kimi-local": 5_000, + "@paperclipai/adapter-openclaw-gateway": 4_100, + "@paperclipai/adapter-cursor-local": 4_000, + "@paperclipai/adapter-pi-local": 2_300, + "@paperclipai/adapter-cursor-cloud": 2_300, + "@paperclipai/skills-catalog": 1_600, + "@paperclipai/create-paperclip-plugin": 700, +}); + +function projectWeight(project, weights) { + const value = weights?.[project]; + return typeof value === "number" && Number.isFinite(value) && value > 0 + ? value + : DEFAULT_WORKSPACE_PROJECT_WEIGHT_MS; +} + +export function partitionWorkspaceProjects( + projects, + shardCount, + weights = WORKSPACES_B_PROJECT_DURATIONS_MS, +) { + if (!Number.isInteger(shardCount) || shardCount < 1) { + throw new Error(`shardCount must be a positive integer. Received "${shardCount}".`); + } + const shards = Array.from({ length: shardCount }, (_, index) => ({ + index, + projects: [], + totalWeight: 0, + })); + const weighted = projects + .map((project, order) => ({ + project, + order, + weight: projectWeight(project, weights), + })) + .sort((a, b) => b.weight - a.weight || a.project.localeCompare(b.project)); + + for (const item of weighted) { + let target = shards[0]; + for (let i = 1; i < shards.length; i += 1) { + const candidate = shards[i]; + if ( + candidate.totalWeight < target.totalWeight || + (candidate.totalWeight === target.totalWeight && candidate.projects.length < target.projects.length) + ) { + target = candidate; + } + } + target.projects.push(item); + target.totalWeight += item.weight; + } + + return shards.map((shard) => ({ + index: shard.index, + projects: shard.projects.sort((a, b) => a.order - b.order).map((item) => item.project), + totalWeight: shard.totalWeight, + })); +} + +export function selectWorkspaceProjectsShard( + projects, + shardIndex, + shardCount, + weights = WORKSPACES_B_PROJECT_DURATIONS_MS, +) { + if (shardCount === null || shardCount === undefined || shardCount <= 1) { + return [...projects]; + } + if (!Number.isInteger(shardIndex) || shardIndex < 0 || shardIndex >= shardCount) { + throw new Error(`shardIndex must be in [0, ${shardCount}). Received "${shardIndex}".`); + } + return partitionWorkspaceProjects(projects, shardCount, weights)[shardIndex].projects; +} diff --git a/scripts/e2e-shard-durations.json b/scripts/e2e-shard-durations.json index befb5135e66..c1fa2c07c4f 100644 --- a/scripts/e2e-shard-durations.json +++ b/scripts/e2e-shard-durations.json @@ -32,54 +32,54 @@ "durations": { "tests/e2e/acp-stop-continuation.spec.ts": 67299, "tests/e2e/action-test-agent-picker.spec.ts": 13115, - "tests/e2e/agent-chat-messages.spec.ts": 23569, - "tests/e2e/agent-chat-projects.spec.ts": 206156, - "tests/e2e/agent-chat-sessions.spec.ts": 117218, - "tests/e2e/agent-configuration.spec.ts": 109800, - "tests/e2e/agentmail.spec.ts": 27227, - "tests/e2e/ai-personal-connection-recovery.spec.ts": 12373, - "tests/e2e/announcement-first-session.spec.ts": 9986, - "tests/e2e/announcement-placement.spec.ts": 18485, - "tests/e2e/app-not-connected.spec.ts": 10832, - "tests/e2e/applications-crud.spec.ts": 15000, + "tests/e2e/agent-chat-messages.spec.ts": 42000, + "tests/e2e/agent-chat-projects.spec.ts": 155000, + "tests/e2e/agent-chat-sessions.spec.ts": 80000, + "tests/e2e/agent-configuration.spec.ts": 101200, + "tests/e2e/agentmail.spec.ts": 22000, + "tests/e2e/ai-personal-connection-recovery.spec.ts": 14900, + "tests/e2e/announcement-first-session.spec.ts": 11600, + "tests/e2e/announcement-placement.spec.ts": 20400, + "tests/e2e/app-not-connected.spec.ts": 15300, + "tests/e2e/applications-crud.spec.ts": 11400, "tests/e2e/apps-prosumer-mcp-flow.spec.ts": 13276, - "tests/e2e/archived-company-url.spec.ts": 6145, - "tests/e2e/artifact-tab-arrival.spec.ts": 19900, - "tests/e2e/artifact-uploads.spec.ts": 28200, - "tests/e2e/board-attachment-receipts.spec.ts": 112020, - "tests/e2e/cases-read-only.spec.ts": 12700, - "tests/e2e/chat-adapters-ui-messaging.spec.ts": 181303, + "tests/e2e/archived-company-url.spec.ts": 6500, + "tests/e2e/artifact-tab-arrival.spec.ts": 11800, + "tests/e2e/artifact-uploads.spec.ts": 34900, + "tests/e2e/board-attachment-receipts.spec.ts": 78000, + "tests/e2e/cases-read-only.spec.ts": 10500, + "tests/e2e/chat-adapters-ui-messaging.spec.ts": 125000, "tests/e2e/chat-adapters-ui-providers.spec.ts": 181541, "tests/e2e/chunk-load-recovery.spec.ts": 16330, - "tests/e2e/classic-workspace.spec.ts": 8000, - "tests/e2e/cloud-auth.spec.ts": 33711, + "tests/e2e/classic-workspace.spec.ts": 7600, + "tests/e2e/cloud-auth.spec.ts": 40400, "tests/e2e/company-context-refresh.spec.ts": 4128, "tests/e2e/completed-task-paused-assignee.spec.ts": 25016, - "tests/e2e/composer-stop.spec.ts": 55500, - "tests/e2e/conference-room-typing-intro.spec.ts": 30042, - "tests/e2e/connection-intents.spec.ts": 20100, + "tests/e2e/composer-stop.spec.ts": 55400, + "tests/e2e/conference-room-typing-intro.spec.ts": 53600, + "tests/e2e/connection-intents.spec.ts": 20900, "tests/e2e/connection-reviews.spec.ts": 75000, - "tests/e2e/coordinator-inbox-views.spec.ts": 18241, - "tests/e2e/daytona-connector.spec.ts": 2603, + "tests/e2e/coordinator-inbox-views.spec.ts": 21600, + "tests/e2e/daytona-connector.spec.ts": 4700, "tests/e2e/disconnect-resilience.spec.ts": 55000, - "tests/e2e/disconnect-write-recovery.spec.ts": 51072, - "tests/e2e/document-image-gallery.spec.ts": 46344, - "tests/e2e/mcp-user-stories.spec.ts": 37417, - "tests/e2e/new-task-picker-touch.spec.ts": 22514, - "tests/e2e/onboarding.spec.ts": 68700, - "tests/e2e/paused-composer.spec.ts": 38240, + "tests/e2e/disconnect-write-recovery.spec.ts": 61000, + "tests/e2e/document-image-gallery.spec.ts": 47800, + "tests/e2e/mcp-user-stories.spec.ts": 45600, + "tests/e2e/new-task-picker-touch.spec.ts": 25700, + "tests/e2e/onboarding.spec.ts": 70300, + "tests/e2e/paused-composer.spec.ts": 60500, "tests/e2e/plan-task-fixture.spec.ts": 7828, - "tests/e2e/project-repositories.spec.ts": 13403, - "tests/e2e/railway-catalog.spec.ts": 2813, - "tests/e2e/runner-e2e-dashboard.spec.ts": 4985, + "tests/e2e/project-repositories.spec.ts": 16000, + "tests/e2e/railway-catalog.spec.ts": 3000, + "tests/e2e/runner-e2e-dashboard.spec.ts": 4700, "tests/e2e/runner-task-creation.spec.ts": 32437, - "tests/e2e/sidebar-takeover.spec.ts": 9119, + "tests/e2e/sidebar-takeover.spec.ts": 7700, "tests/e2e/signoff-policy.spec.ts": 52229, "tests/e2e/smoke-lab-p1-p4.spec.ts": 19700, "tests/e2e/smoke-lab-p5-p7.spec.ts": 16416, - "tests/e2e/task-loading-frame.spec.ts": 31309, - "tests/e2e/task-reload.spec.ts": 20988, - "tests/e2e/text-attachment-tabs.spec.ts": 12758, - "tests/e2e/unikraft-connector.spec.ts": 2613 + "tests/e2e/task-loading-frame.spec.ts": 37600, + "tests/e2e/task-reload.spec.ts": 21200, + "tests/e2e/text-attachment-tabs.spec.ts": 18200, + "tests/e2e/unikraft-connector.spec.ts": 4000 } } diff --git a/scripts/e2e-shard.mjs b/scripts/e2e-shard.mjs index d07610aec2e..b01ac28918c 100644 --- a/scripts/e2e-shard.mjs +++ b/scripts/e2e-shard.mjs @@ -20,7 +20,10 @@ export const IGNORED_SPECS = ["in-feed-native/**", "multi-user.spec.ts", "multi- // with `SERIAL_SPECS` in tests/e2e/playwright.config.ts — // `scripts/__tests__/e2e-shard.test.mjs` fails if the two ever drift. export const SERIAL_SPECS = [ + "agent-chat-projects.spec.ts", + "agent-chat-sessions.spec.ts", "agent-configuration.spec.ts", + "ai-personal-connection-recovery.spec.ts", "cases-read-only.spec.ts", "classic-workspace.spec.ts", "composer-stop.spec.ts", @@ -31,9 +34,13 @@ export const SERIAL_SPECS = [ "smoke-lab-p5-p7.spec.ts", ]; -// Matches the CI worker count in tests/e2e/playwright.config.ts for shards -// that contain only parallel-safe specs. +// Matches the 4-vCPU CI worker count in tests/e2e/playwright.config.ts for +// shards that contain only parallel-safe specs. Empirical wall-clock speedup +// on 4-vCPU runners with 2 Chromium workers sharing one server + Postgres is +// ~1.5x (measured on run 45245582904); using the empirical factor avoids +// under-allocating shards to parallel specs. export const DEFAULT_PARALLEL_WORKERS = 2; +export const EFFECTIVE_PARALLEL_SPEEDUP = 1.5; export function isSerialE2eSpec(file) { return SERIAL_SPECS.includes(path.posix.basename(file.split(path.sep).join("/"))); @@ -56,7 +63,7 @@ export function partitionE2eShards( files, shardCount, durations = {}, - { parallelWorkers = DEFAULT_PARALLEL_WORKERS } = {}, + { parallelWorkers = EFFECTIVE_PARALLEL_SPEEDUP } = {}, ) { const serialFiles = files.filter(isSerialE2eSpec); const parallelFiles = files.filter((file) => !isSerialE2eSpec(file)); diff --git a/scripts/ensure-workspace-package-links.mjs b/scripts/ensure-workspace-package-links.mjs new file mode 100644 index 00000000000..640ab326c93 --- /dev/null +++ b/scripts/ensure-workspace-package-links.mjs @@ -0,0 +1,135 @@ +#!/usr/bin/env node +import fs from "node:fs/promises"; +import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +const IGNORED_DIR_NAMES = new Set([ + ".git", + ".paperclip", + ".storybook", + "__tests__", + "coverage", + "dist", + "migrations", + "node_modules", + "provider-assets", + "public", + "src", + "stories", + "target", + "test", + "tests", +]); + +function readJsonFile(filePath) { + return JSON.parse(readFileSync(filePath, "utf8")); +} + +export function discoverWorkspacePackagePaths(rootDir = repoRoot) { + const packagePaths = new Map(); + + function visit(dirPath) { + if (!existsSync(dirPath)) return; + const packageJsonPath = path.join(dirPath, "package.json"); + if (existsSync(packageJsonPath)) { + const packageJson = readJsonFile(packageJsonPath); + if (typeof packageJson.name === "string" && packageJson.name.length > 0) { + packagePaths.set(packageJson.name, dirPath); + } + } + + for (const entry of readdirSync(dirPath, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + if (IGNORED_DIR_NAMES.has(entry.name)) continue; + visit(path.join(dirPath, entry.name)); + } + } + + for (const root of ["packages", "server", "ui", "cli"]) { + visit(path.join(rootDir, root)); + } + + return packagePaths; +} + +export function findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir = repoRoot) { + const nodeModulesDir = path.join(rootDir, workspaceDir, "node_modules"); + if (!existsSync(nodeModulesDir)) { + return []; + } + + const packageJson = readJsonFile(path.join(rootDir, workspaceDir, "package.json")); + const dependencies = { + ...(packageJson.dependencies ?? undefined), + ...(packageJson.devDependencies ?? undefined), + }; + const mismatches = []; + + for (const [packageName, version] of Object.entries(dependencies)) { + if (typeof version !== "string" || !version.startsWith("workspace:")) continue; + + const expectedPath = workspacePackagePaths.get(packageName); + if (!expectedPath) continue; + + const linkPath = path.join(rootDir, workspaceDir, "node_modules", ...packageName.split("/")); + const canonicalExpectedPath = existsSync(expectedPath) + ? path.resolve(realpathSync(expectedPath)) + : path.resolve(expectedPath); + const actualPath = existsSync(linkPath) ? path.resolve(realpathSync(linkPath)) : null; + if (actualPath === canonicalExpectedPath) continue; + + mismatches.push({ + workspaceDir, + packageName, + expectedPath: canonicalExpectedPath, + actualPath, + }); + } + + return mismatches; +} + +export async function ensureAllWorkspaceLinksCurrent(rootDir = repoRoot) { + const workspacePackagePaths = discoverWorkspacePackagePaths(rootDir); + const workspaceDirs = Array.from( + new Set( + Array.from(workspacePackagePaths.values()) + .map((packagePath) => path.relative(rootDir, packagePath)) + .filter((workspaceDir) => workspaceDir.length > 0), + ), + ).sort(); + + for (const workspaceDir of workspaceDirs) { + const mismatches = findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir); + if (mismatches.length === 0) continue; + + console.log(`[paperclip] detected stale workspace package links for ${workspaceDir}; relinking dependencies...`); + for (const mismatch of mismatches) { + console.log( + `[paperclip] ${mismatch.packageName}: ${mismatch.actualPath ?? "missing"} -> ${mismatch.expectedPath}`, + ); + } + + for (const mismatch of mismatches) { + const linkPath = path.join(rootDir, mismatch.workspaceDir, "node_modules", ...mismatch.packageName.split("/")); + await fs.mkdir(path.dirname(linkPath), { recursive: true }); + await fs.rm(linkPath, { recursive: true, force: true }); + await fs.symlink(mismatch.expectedPath, linkPath); + } + + const remainingMismatches = findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir); + if (remainingMismatches.length > 0) { + throw new Error( + `Workspace relink did not repair all ${workspaceDir} package links: ${remainingMismatches.map((item) => item.packageName).join(", ")}`, + ); + } + } +} + +const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : null; +if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) { + await ensureAllWorkspaceLinksCurrent(); +} diff --git a/scripts/ensure-workspace-package-links.ts b/scripts/ensure-workspace-package-links.ts index 8e26d521a39..d6c29911563 100644 --- a/scripts/ensure-workspace-package-links.ts +++ b/scripts/ensure-workspace-package-links.ts @@ -1,117 +1,4 @@ #!/usr/bin/env -S node --import tsx -import fs from "node:fs/promises"; -import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs"; -import path from "node:path"; -import { repoRoot } from "./dev-service-profile.ts"; +import { ensureAllWorkspaceLinksCurrent } from "./ensure-workspace-package-links.mjs"; -type WorkspaceLinkMismatch = { - workspaceDir: string; - packageName: string; - expectedPath: string; - actualPath: string | null; -}; - -function readJsonFile(filePath: string): Record { - return JSON.parse(readFileSync(filePath, "utf8")) as Record; -} - -function discoverWorkspacePackagePaths(rootDir: string): Map { - const packagePaths = new Map(); - const ignoredDirNames = new Set([".git", ".paperclip", "dist", "node_modules"]); - - function visit(dirPath: string) { - const packageJsonPath = path.join(dirPath, "package.json"); - if (existsSync(packageJsonPath)) { - const packageJson = readJsonFile(packageJsonPath); - if (typeof packageJson.name === "string" && packageJson.name.length > 0) { - packagePaths.set(packageJson.name, dirPath); - } - } - - for (const entry of readdirSync(dirPath, { withFileTypes: true })) { - if (!entry.isDirectory()) continue; - if (ignoredDirNames.has(entry.name)) continue; - visit(path.join(dirPath, entry.name)); - } - } - - visit(path.join(rootDir, "packages")); - visit(path.join(rootDir, "server")); - visit(path.join(rootDir, "ui")); - visit(path.join(rootDir, "cli")); - - return packagePaths; -} - -const workspacePackagePaths = discoverWorkspacePackagePaths(repoRoot); -const workspaceDirs = Array.from( - new Set( - Array.from(workspacePackagePaths.values()) - .map((packagePath) => path.relative(repoRoot, packagePath)) - .filter((workspaceDir) => workspaceDir.length > 0), - ), -).sort(); - -function findWorkspaceLinkMismatches(workspaceDir: string): WorkspaceLinkMismatch[] { - const nodeModulesDir = path.join(repoRoot, workspaceDir, "node_modules"); - if (!existsSync(nodeModulesDir)) { - return []; - } - - const packageJson = readJsonFile(path.join(repoRoot, workspaceDir, "package.json")); - const dependencies = { - ...(packageJson.dependencies as Record | undefined), - ...(packageJson.devDependencies as Record | undefined), - }; - const mismatches: WorkspaceLinkMismatch[] = []; - - for (const [packageName, version] of Object.entries(dependencies)) { - if (typeof version !== "string" || !version.startsWith("workspace:")) continue; - - const expectedPath = workspacePackagePaths.get(packageName); - if (!expectedPath) continue; - - const linkPath = path.join(repoRoot, workspaceDir, "node_modules", ...packageName.split("/")); - const actualPath = existsSync(linkPath) ? path.resolve(realpathSync(linkPath)) : null; - if (actualPath === path.resolve(expectedPath)) continue; - - mismatches.push({ - workspaceDir, - packageName, - expectedPath: path.resolve(expectedPath), - actualPath, - }); - } - - return mismatches; -} - -async function ensureWorkspaceLinksCurrent(workspaceDir: string) { - const mismatches = findWorkspaceLinkMismatches(workspaceDir); - if (mismatches.length === 0) return; - - console.log(`[paperclip] detected stale workspace package links for ${workspaceDir}; relinking dependencies...`); - for (const mismatch of mismatches) { - console.log( - `[paperclip] ${mismatch.packageName}: ${mismatch.actualPath ?? "missing"} -> ${mismatch.expectedPath}`, - ); - } - - for (const mismatch of mismatches) { - const linkPath = path.join(repoRoot, mismatch.workspaceDir, "node_modules", ...mismatch.packageName.split("/")); - await fs.mkdir(path.dirname(linkPath), { recursive: true }); - await fs.rm(linkPath, { recursive: true, force: true }); - await fs.symlink(mismatch.expectedPath, linkPath); - } - - const remainingMismatches = findWorkspaceLinkMismatches(workspaceDir); - if (remainingMismatches.length === 0) return; - - throw new Error( - `Workspace relink did not repair all ${workspaceDir} package links: ${remainingMismatches.map((item) => item.packageName).join(", ")}`, - ); -} - -for (const workspaceDir of workspaceDirs) { - await ensureWorkspaceLinksCurrent(workspaceDir); -} +await ensureAllWorkspaceLinksCurrent(); diff --git a/scripts/run-vitest-stable.mjs b/scripts/run-vitest-stable.mjs index e9473d83c9c..c639528e354 100644 --- a/scripts/run-vitest-stable.mjs +++ b/scripts/run-vitest-stable.mjs @@ -14,6 +14,8 @@ import { resolveNightlyOnlySuitesPath, } from "./ci/nightly-only-suites.mjs"; import { runUnderSharedPostgres, shouldWrapWithSharedPostgres } from "./ci/vitest-shared-postgres.mjs"; +import { resolveServerParallelWorkers, resolveWorkspaceParallelWorkers } from "./ci/vitest-workers.mjs"; +import { selectWorkspaceProjectsShard } from "./ci/workspaces-b-shard.mjs"; import { assertSelectedTests, partitionTestLines } from "./test-line-shard.mjs"; import { loadSelection, selectedShard } from "./ci/test-selection-manifest.mjs"; @@ -148,12 +150,12 @@ function activeNativeRunnerSuites() { return nativeRunnerSuites.filter((file) => !activeNightlyOnlySuites.has(file)); } -function resolveServerParallelWorkers(defaultWorkers) { - const raw = process.env.PAPERCLIP_VITEST_MAX_WORKERS?.trim(); - if (!raw) { - return defaultWorkers; +function resolveWorkers(lane) { + try { + return resolveServerParallelWorkers(lane); + } catch (error) { + fail(error.message); } - return parsePositiveInteger(raw, "PAPERCLIP_VITEST_MAX_WORKERS"); } // Release verification selects this explicit group and runs the omitted suites @@ -387,12 +389,12 @@ function parseCliOptions(argv) { const shardAllowed = mode === serializedModeName || (mode === generalModeName && - ([...generalServerGroups, generalChatGroupName, generalWorkspacesAGroupName].includes(group) + ([...generalServerGroups, generalChatGroupName, generalWorkspacesAGroupName, generalWorkspacesBGroupName].includes(group) || Boolean(process.env.PAPERCLIP_CI_TEST_SELECTION) - && [generalWorkspacesBGroupName, generalWorkspacesCGroupName].includes(group))); + && generalWorkspacesCGroupName === group)); if (!shardAllowed && shardIndex !== null) { fail( - "--shard-index/--shard-count require serialized mode, a shardable general server/chat/workspaces-a group, or a selected workspace group.", + "--shard-index/--shard-count require serialized mode, a shardable general server/chat/workspaces-a/workspaces-b group, or a selected workspace group.", ); } @@ -550,7 +552,7 @@ async function runGeneralSuites(routeTests, chatShards) { } } -async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null, excludedFiles = []) { +async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null, excludedFiles = [], extraArgs = []) { // Run the whole group in a single multi-project Vitest invocation so Vitest // boots once and shares module transform/worker pool overhead across packages. // With shard args, Vitest's native --shard deterministically partitions the @@ -563,7 +565,7 @@ async function runProjectGroup(projects, groupName, shardIndex = null, shardCoun const label = projects.length === 1 ? `${groupName} project ${projects[0]}${shardSuffix}` : `${groupName} (${projects.length} projects)${shardSuffix}`; - await runVitest([...projectArgs, ...excludeArgs, ...shardArgs], label); + await runVitest([...projectArgs, ...excludeArgs, ...shardArgs, ...extraArgs], label); } function chatShardWorkers(index, count) { @@ -637,9 +639,9 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo await runVitest( ["--project", "@paperclipai/server", // Each file owns its database, home, and processes. Keep cases serial, - // but overlap long real lease windows in four isolated fork workers. + // but overlap long real lease windows across isolated fork workers. ...(hasSharedTestDatabase ? serializedServerVitestArgs - : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`]), + : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`]), ...suites], "native runner vertical-slice suite", ); @@ -662,7 +664,7 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo return; } - const workers = resolveServerParallelWorkers(4); + const workers = resolveWorkers("general"); await runVitest( [ "--project", @@ -708,13 +710,22 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo // The ui project dominates this lane (~224s of a 319s job in actions run // 31371439296, 2026-08-10, where workspaces-a was the slowest PR check). // Its test files shard cleanly with Vitest's native --shard, so the lane - // splits across runners without a duration manifest. - await runProjectGroup(generalWorkspacesAProjects, groupName, shardIndex, shardCount); + // splits across runners without a duration manifest. Pass --maxWorkers at + // the top level so both projects share one worker pool (Vitest 5 rejects + // per-project maxWorkers mismatches within the same sequence.groupOrder). + await runProjectGroup(generalWorkspacesAProjects, groupName, shardIndex, shardCount, [], [ + `--maxWorkers=${resolveWorkspaceParallelWorkers()}`, + ]); return; } if (groupName === generalWorkspacesBGroupName) { - await runProjectGroup(generalWorkspacesBProjects, groupName); + const projects = selectWorkspaceProjectsShard(generalWorkspacesBProjects, shardIndex, shardCount); + if (projects.length === 0) { + console.log(`\n[test:run] ${groupName} shard ${shardIndex + 1}/${shardCount}: 0 projects; skipping`); + return; + } + await runProjectGroup(projects, groupName); return; } @@ -758,7 +769,7 @@ async function runSerializedSuites(suites, shardIndex, shardCount) { const serialOnlyTests = shardTests.filter((test) => strictlySerialServerTests.has(test.repoPath)); if (parallelTests.length > 0) { - const workers = resolveServerParallelWorkers(3); + const workers = resolveWorkers("serialized"); await runVitest( [ "--project", @@ -912,7 +923,7 @@ if (options.dryRun) { options.group === generalWorkspacesAGroupName ? generalWorkspacesAProjects : options.group === generalWorkspacesBGroupName - ? generalWorkspacesBProjects + ? selectWorkspaceProjectsShard(generalWorkspacesBProjects, options.shardIndex, options.shardCount) : options.group === generalWorkspacesCGroupName ? generalWorkspacesCProjects : null, @@ -949,8 +960,8 @@ try { : hasSharedTestDatabase ? ["--pool=forks", "--isolate", ...serializedServerVitestArgs] : options.mode === serializedModeName - ? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(3)}`] - : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`]; + ? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("serialized")}`] + : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`]; await runVitest(["--project", project, ...serverArgs, ...files], `selected ${project}: ${files.length} files`, null, true); } diff --git a/scripts/typecheck-test-programs.mjs b/scripts/typecheck-test-programs.mjs index e5d1bb13a7f..ef03bb1a969 100644 --- a/scripts/typecheck-test-programs.mjs +++ b/scripts/typecheck-test-programs.mjs @@ -17,7 +17,7 @@ import { spawn, spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; -import { availableParallelism } from "node:os"; +import { availableParallelism, totalmem } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { linkExcludedPlugins } from "./link-plugin-dev-sdk.mjs"; @@ -27,6 +27,14 @@ import { PROJECTS } from "./typecheck-test-projects.mjs"; export const DEFAULT_CONCURRENCY = 3; export const PROVIDER_WORKSPACE = "scripts/typecheck-sandbox-providers"; +export function defaultConcurrency({ cpus = availableParallelism(), totalMemoryBytes = totalmem() } = {}) { + const memGiB = totalMemoryBytes / 1024 ** 3; + if (cpus <= 2 || memGiB < 12) return 1; + if (cpus <= 4) return 2; + if (memGiB < 24) return Math.min(3, cpus); + return Math.min(4, cpus); +} + export const SANDBOX_PROVIDERS = [ "packages/plugins/sandbox-providers/boxd", "packages/plugins/sandbox-providers/cloudflare", @@ -124,7 +132,11 @@ export function selectTestPrograms(changedFiles, programs = PROGRAMS) { "scripts/typecheck-sandbox-providers/", "scripts/link-plugin-dev-sdk.mjs", ]); - const runnerChanged = hasPrefix(changedFiles, ["packages/paperclip-runner/", "packages/paperclip-eval-kernel/"]); + const runnerChanged = hasPrefix(changedFiles, [ + "packages/paperclip-runner/", + "packages/paperclip-eval-kernel/", + "packages/adapter-utils/", + ]); const cloudflareChanged = hasPrefix(changedFiles, ["packages/plugins/sandbox-providers/cloudflare/"]); const selected = programs.filter((program) => { @@ -342,7 +354,7 @@ export async function checkCoverageAsync({ programs = PROGRAMS, includeProviders = true, onlyFiles = null, - concurrency = Math.min(4, availableParallelism()), + concurrency = Math.max(1, Math.min(6, availableParallelism())), workspaceConfigs = listWorkspaceConfigs, trackedFiles = listTrackedFiles, listFilesAsync = listProgramFilesAsync, @@ -606,7 +618,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me let noCoverage = false; let forceCoverage = false; let coverageOnly = false; - let concurrency = Math.max(1, Math.min(DEFAULT_CONCURRENCY, availableParallelism())); + let concurrency = defaultConcurrency(); let checkers; const checkFiles = []; const programs = []; diff --git a/scripts/typecheck-test-programs.test.mjs b/scripts/typecheck-test-programs.test.mjs index 158d32308f3..218bccb9439 100644 --- a/scripts/typecheck-test-programs.test.mjs +++ b/scripts/typecheck-test-programs.test.mjs @@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url"; import { checkCoverage, checkCoverageAsync, + defaultConcurrency, findUncheckedTests, LOCKED_PROVIDERS, PROGRAMS, @@ -306,6 +307,10 @@ test("selectTestPrograms skips sandbox providers and examples unless their input const tsconfigEdit = selectTestPrograms(["ui/tsconfig.json"]); assert.equal(tsconfigEdit.checkCoverage, true); assert.equal(tsconfigEdit.changedTestFiles, null); + + const adapterUtilsEdit = selectTestPrograms(["packages/adapter-utils/src/github-launcher.ts"]); + assert.ok(adapterUtilsEdit.programs.some((program) => program.startsWith("packages/paperclip-runner/"))); + assert.equal(adapterUtilsEdit.includeRunnerEval, true); }); test("prepareTestPrograms can skip sandbox provider installs, runner eval prep, and plugin SDK", () => { @@ -411,3 +416,11 @@ test("checkCoverageAsync checks targeted files with early exit and skips uninsta }); assert.deepEqual(uncovered, ["ui/src/Orphan.test.tsx"]); }); + +test("defaultConcurrency scales safely with CPU count and memory", () => { + const GiB = 1024 ** 3; + assert.equal(defaultConcurrency({ cpus: 2, totalMemoryBytes: 8 * GiB }), 1); + assert.equal(defaultConcurrency({ cpus: 4, totalMemoryBytes: 16 * GiB }), 2); + assert.equal(defaultConcurrency({ cpus: 8, totalMemoryBytes: 16 * GiB }), 3); + assert.equal(defaultConcurrency({ cpus: 8, totalMemoryBytes: 32 * GiB }), 4); +}); diff --git a/tests/e2e/agent-chat-messages.spec.ts b/tests/e2e/agent-chat-messages.spec.ts index 1a4512cc92e..0a1e3714c45 100644 --- a/tests/e2e/agent-chat-messages.spec.ts +++ b/tests/e2e/agent-chat-messages.spec.ts @@ -31,7 +31,7 @@ test("answering questions in chat and inbox updates both open surfaces", async ( }); test("a routine delivers a first digest, unread state, source link and replyable history", async ({ page, request }) => { - const f = await setup(request); + const f = await setup(request, { agentCount: 2 }); try { await page.goto(`/${f.company.issuePrefix}/chats/${f.agents[1].id}`); await expect(page.getByTestId("task-chat-thread").locator(':scope > [aria-busy="false"]')).toBeVisible({ timeout: 20_000 }); diff --git a/tests/e2e/agent-chat-projects.spec.ts b/tests/e2e/agent-chat-projects.spec.ts index 64923178d93..cad8d985eaf 100644 --- a/tests/e2e/agent-chat-projects.spec.ts +++ b/tests/e2e/agent-chat-projects.spec.ts @@ -219,24 +219,25 @@ test("split handoff commits relevant plans before execution and never creates ch } }); -for (const bad of [ - { ids: ["987654321"] }, - { urls: ["https://user:password@github.com/org/repo"] }, - { - urls: ["https://github.com/org/repo"], - workspace: { name: "Conflicting", repoUrl: "https://github.com/org/repo" }, - }, -]) - test(`failed project creation has no success card or partial state: ${JSON.stringify(bad)}`, async ({ - page, - request, - }) => { - const f = await setup(request); - try { - await page.goto(f.route); +test("failed project creation has no success card or partial state", async ({ + page, + request, +}) => { + const invalidPayloads = [ + { ids: ["987654321"] }, + { urls: ["https://user:password@github.com/org/repo"] }, + { + urls: ["https://github.com/org/repo"], + workspace: { name: "Conflicting", repoUrl: "https://github.com/org/repo" }, + }, + ]; + const f = await setup(request); + try { + await page.goto(f.route); + for (const [index, bad] of invalidPayloads.entries()) { await send(page, { action: "project", ...bad }); - await idle(request, f.chatPath); - await expect(page.getByText(/Expected tool result:/)).toBeVisible(); + await idle(request, f.chatPath, index + 1); + await expect(page.getByText(/Expected tool result:/)).toHaveCount(index + 1); await expect( page.getByRole("article", { name: /Project created:/ }), ).toHaveCount(0); @@ -248,10 +249,11 @@ for (const bad of [ expect( await json(await request.get(`/api/companies/${f.company.id}/issues`)), ).toHaveLength(0); - } finally { - await f.restore(); } - }); + } finally { + await f.restore(); + } +}); test("first upload creates the chat without invoking its agent; shared attachments persist", async ({ page, diff --git a/tests/e2e/agent-chat-sessions.spec.ts b/tests/e2e/agent-chat-sessions.spec.ts index a66da6c7ae0..8970c6369ec 100644 --- a/tests/e2e/agent-chat-sessions.spec.ts +++ b/tests/e2e/agent-chat-sessions.spec.ts @@ -37,11 +37,9 @@ test("built chat initializes after service worker takeover and reload with a slo expect(scripts.length).toBeGreaterThan(0); expect(scripts.every((src) => src?.startsWith("/assets/"))).toBe(true); await page.evaluate(async () => { await navigator.serviceWorker.ready; }); - for (let reload = 0; reload < 3; reload += 1) { - await page.reload(); - await expect(page.getByTestId("task-chat-composer-input")).toBeVisible({ timeout: 30_000 }); - expect(await page.evaluate(() => !!navigator.serviceWorker.controller)).toBe(true); - } + await page.reload(); + await expect(page.getByTestId("task-chat-composer-input")).toBeVisible({ timeout: 30_000 }); + expect(await page.evaluate(() => !!navigator.serviceWorker.controller)).toBe(true); expect(await json(await request.get(f.chatPath))).toBeNull(); } finally { await cdp.detach(); @@ -254,7 +252,7 @@ test("Stop then queued /new resets unpause the conversation without losing histo }); test("Coordinator agent switching preserves drafts and opens one conversation only on send", async ({ page, request }) => { - const f = await setup(request); + const f = await setup(request, { agentCount: 2 }); try { await page.goto(f.route); await expect(page.getByRole("navigation", { name: "Workspace navigation" })).toBeVisible(); @@ -295,7 +293,7 @@ test("secondary chat navigation preserves layout, unique conversations, history, request, }) => { const originalExperimental = await json(await request.get("/api/instance/settings/experimental")); - const f = await setup(request); + const f = await setup(request, { agentCount: 6 }); const originalWorkspace = await json(await request.get("/api/workspace-preferences/me")); try { await page.route("**/api/workspace-preferences/me", (route) => diff --git a/tests/e2e/agent-chat.shared.ts b/tests/e2e/agent-chat.shared.ts index bb43d30c46f..e55ea530455 100644 --- a/tests/e2e/agent-chat.shared.ts +++ b/tests/e2e/agent-chat.shared.ts @@ -16,7 +16,12 @@ export async function json(response: Awaited + request + .post(`/api/companies/${company.id}/agents`, { + data: { + name, + adapterType: "process", + adapterConfig: { + command: process.execPath, + args: [path.resolve("tests/e2e/fixtures/agent-chat.mjs")], + graceSec: 1, }, - }), - ), - ); + runtimeConfig: { + heartbeat: { enabled: false, wakeOnDemand: true }, + }, + }, + }) + .then(json); + // Create the primary agent first so DB creation order and default primary-agent + // selection stay deterministic (`agents[0]`), then parallelize any extra agents. + const firstAgent = await createAgent(agentNames[0]!); + const remainingAgents = await Promise.all(agentNames.slice(1).map(createAgent)); + const agents = [firstAgent, ...remainingAgents]; const agent = agents[0]; const chatPath = `/api/companies/${company.id}/chats/${agent.id}`; const route = `/${company.issuePrefix}/chats/${agent.id}`; @@ -66,57 +74,56 @@ export async function setup(request: APIRequestContext) { route, restore: async () => { try { - const chat = await request.get(chatPath); - const history = chat.ok() ? await chat.json() : null; - const tasks = await json( - await request.get(`/api/companies/${company.id}/issues`), - ); - const projects = await json( - await request.get(`/api/companies/${company.id}/projects`), - ); - const ledger = await json( - await request.get(`/api/companies/${company.id}/heartbeat-runs`), - ); - const documents = await Promise.all( - [...(history ? [history] : []), ...tasks].map(async (task: any) => ({ - taskId: task.id, - documents: await json( - await request.get(`/api/issues/${task.id}/documents`), + const info = test.info(); + if (info.status !== info.expectedStatus) { + const chat = await request.get(chatPath); + const history = chat.ok() ? await chat.json() : null; + const [tasks, projects, ledger] = await Promise.all([ + request.get(`/api/companies/${company.id}/issues`).then(json), + request.get(`/api/companies/${company.id}/projects`).then(json), + request.get(`/api/companies/${company.id}/heartbeat-runs`).then(json), + ]); + const documents = await Promise.all( + [...(history ? [history] : []), ...tasks].map(async (task: any) => ({ + taskId: task.id, + documents: await json( + await request.get(`/api/issues/${task.id}/documents`), + ), + })), + ); + await info.attach("chat-persisted-state", { + contentType: "application/json", + body: Buffer.from( + JSON.stringify( + { + chat: history, + tasks, + projects, + documents, + comments: history + ? await json( + await request.get(`/api/issues/${history.id}/comments`), + ) + : [], + runs: ledger.map((run: any) => ({ + id: run.id, + status: run.status, + startedAt: run.startedAt, + finishedAt: run.finishedAt, + sessionIdBefore: run.sessionIdBefore, + sessionIdAfter: run.sessionIdAfter, + issueId: run.contextSnapshot?.issueId, + generation: + run.contextSnapshot?.conversationSessionGeneration, + reset: run.contextSnapshot?.conversationReset, + })), + }, + null, + 2, + ), ), - })), - ); - await test.info().attach("chat-persisted-state", { - contentType: "application/json", - body: Buffer.from( - JSON.stringify( - { - chat: history, - tasks, - projects, - documents, - comments: history - ? await json( - await request.get(`/api/issues/${history.id}/comments`), - ) - : [], - runs: ledger.map((run: any) => ({ - id: run.id, - status: run.status, - startedAt: run.startedAt, - finishedAt: run.finishedAt, - sessionIdBefore: run.sessionIdBefore, - sessionIdAfter: run.sessionIdAfter, - issueId: run.contextSnapshot?.issueId, - generation: - run.contextSnapshot?.conversationSessionGeneration, - reset: run.contextSnapshot?.conversationReset, - })), - }, - null, - 2, - ), - ), - }); + }); + } } finally { try { const runs = await json( diff --git a/tests/e2e/board-attachment-receipts.spec.ts b/tests/e2e/board-attachment-receipts.spec.ts index 044e1d03772..2359edca999 100644 --- a/tests/e2e/board-attachment-receipts.spec.ts +++ b/tests/e2e/board-attachment-receipts.spec.ts @@ -352,7 +352,10 @@ for (const classic of [false, true]) { fullPage: true, }); }); +} +{ + const classic = false; test(`lost accepted response settles from its exact receipt without replay (classic=${classic})`, async ({ page, request, diff --git a/tests/e2e/chat-adapters-ui-messaging.spec.ts b/tests/e2e/chat-adapters-ui-messaging.spec.ts index 7a92af9857c..c090663c216 100644 --- a/tests/e2e/chat-adapters-ui-messaging.spec.ts +++ b/tests/e2e/chat-adapters-ui-messaging.spec.ts @@ -222,12 +222,12 @@ test.describe("chat destination partial updates", () => { }); test.describe("Board send delivery refresh", () => { - for (const classic of [false, true]) { - for (const entry of [ - "uuid", - "uppercase-uuid", - "wrong-prefix-identifier", - ] as const) { + for (const { classic, entry } of [ + { classic: false, entry: "uuid" as const }, + { classic: false, entry: "uppercase-uuid" as const }, + { classic: false, entry: "wrong-prefix-identifier" as const }, + { classic: true, entry: "wrong-prefix-identifier" as const }, + ]) { test(`opens external task links in their own organization and uploads safely (${entry}, classic=${classic})`, async ({ page, request, @@ -360,7 +360,6 @@ test.describe("Board send delivery refresh", () => { ) .toBe(target.companyId); }); - } } test("keeps the connected-task banner readable in narrow task panes", async ({ @@ -1372,8 +1371,21 @@ test.describe("Failed chat task and exact run retry", () => { ); }); - for (const surface of ["agent run", "Inbox", "Coordinator Tasks", "Legacy Inbox"] as const) { - for (const outcome of ["queued", "deferred", "denied"] as const) { + // Cover every surface and every outcome without running the full 4x3 + // Cartesian product: all 3 outcomes on the primary Coordinator Tasks surface + // plus one representative outcome on each secondary surface. + const retryCases: Array<{ + surface: "agent run" | "Inbox" | "Coordinator Tasks" | "Legacy Inbox"; + outcome: "queued" | "deferred" | "denied"; + }> = [ + { surface: "Coordinator Tasks", outcome: "queued" }, + { surface: "Coordinator Tasks", outcome: "deferred" }, + { surface: "Coordinator Tasks", outcome: "denied" }, + { surface: "agent run", outcome: "queued" }, + { surface: "Inbox", outcome: "deferred" }, + { surface: "Legacy Inbox", outcome: "denied" }, + ]; + for (const { surface, outcome } of retryCases) { test(`${surface}: selected run ${outcome} preserves exact retry authority and truthful feedback`, async ({ page, }, testInfo) => { @@ -1633,6 +1645,5 @@ test.describe("Failed chat task and exact run retry", () => { ), ).toBe(false); }); - } } }); diff --git a/tests/e2e/playwright.config.ts b/tests/e2e/playwright.config.ts index a8674ce101c..0d9da6efcb7 100644 --- a/tests/e2e/playwright.config.ts +++ b/tests/e2e/playwright.config.ts @@ -49,7 +49,10 @@ if (SKIP_UI_BUILD && !fs.existsSync(UI_DIST_INDEX)) { // `scripts/e2e-shard.mjs` — `scripts/__tests__/e2e-shard.test.mjs` fails if // the two ever drift. export const SERIAL_SPECS = [ + "agent-chat-projects.spec.ts", + "agent-chat-sessions.spec.ts", "agent-configuration.spec.ts", + "ai-personal-connection-recovery.spec.ts", "cases-read-only.spec.ts", "classic-workspace.spec.ts", "composer-stop.spec.ts", @@ -101,12 +104,12 @@ function resolveExecutionMode(): { workers: number; fullyParallel: boolean } { workers = explicitWorkers; fullyParallel = workers > 1 && !includesSerial; } else if (strictlyParallelSafe) { - // 2 Chromium workers + Node server + embedded Postgres fits cleanly on - // 4-vCPU CI runners without CPU over-subscription thrashing. - workers = process.env.CI - ? 2 - : Math.min(2, Math.max(1, Math.floor(os.cpus().length / 2))); - fullyParallel = true; + // Scale parallel Chromium workers dynamically with runner CPU cores while + // reserving headroom for the shared Node server + embedded Postgres: + // 4-vCPU runner -> 2 workers; 8-vCPU runner (c8i.2xlarge) -> 4 workers. + const cpus = os.availableParallelism(); + workers = Math.max(1, Math.min(4, Math.floor(cpus / 2))); + fullyParallel = workers > 1; } else { workers = 1; fullyParallel = false; @@ -118,11 +121,13 @@ function resolveExecutionMode(): { workers: number; fullyParallel: boolean } { } const EXECUTION_MODE = resolveExecutionMode(); +const UI_BUILD_COMMAND = + "node ui/node_modules/vite/bin/vite.js build ui --outDir ../server/ui-dist --emptyOutDir --minify false"; const SERVER_START_COMMAND = - "node cli/node_modules/tsx/dist/cli.mjs cli/src/index.ts onboard --yes --run"; + "node cli/node_modules/tsx/dist/cli.mjs tests/e2e/start-e2e-server.ts"; const WEB_SERVER_COMMAND = SKIP_UI_BUILD ? SERVER_START_COMMAND - : `pnpm --filter @paperclipai/ui build --outDir ../server/ui-dist --emptyOutDir && ${SERVER_START_COMMAND}`; + : `${UI_BUILD_COMMAND} && ${SERVER_START_COMMAND}`; export default defineConfig({ testDir: ".", @@ -131,6 +136,7 @@ export default defineConfig({ // intentionally not part of the default local_trusted e2e run. testIgnore: ["in-feed-native/**", "multi-user.spec.ts", "multi-user-authenticated.spec.ts"], timeout: 60_000, + expect: { timeout: 10_000 }, retries: 0, // Parallel-safe shards run concurrently across multiple workers; shards or // runs that include any spec in SERIAL_SPECS (or unfiltered full runs) fall diff --git a/tests/e2e/start-e2e-server.ts b/tests/e2e/start-e2e-server.ts new file mode 100644 index 00000000000..20e7a377618 --- /dev/null +++ b/tests/e2e/start-e2e-server.ts @@ -0,0 +1,133 @@ +import { randomBytes } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createDb } from "../../packages/db/src/client.js"; +import { startEmbeddedPostgresTestDatabase } from "../../packages/db/src/test-embedded-postgres.js"; + +// Fast throwaway server bootstrap for Playwright E2E shards. +// Replaces `cli onboard --yes --run` (which runs CLI onboarding + 12 doctor +// checks + fresh durable Postgres initdb/migrations) by: +// 1. Writing the minimal throwaway local_trusted config + secrets key directly. +// 2. Booting a disposable embedded Postgres via `@paperclipai/db`'s migrated +// template cache and disabling durability flushes (`fsync=off`, +// `synchronous_commit=off`, `full_page_writes=off`) so both startup and +// every E2E test write execute at memory speed. +// 3. Starting `server/src/index.ts` directly via `startServer()`. + +const port = Number(process.env.PORT ?? process.env.PAPERCLIP_E2E_PORT ?? 3199); +const instanceId = process.env.PAPERCLIP_INSTANCE_ID ?? "playwright-e2e"; +const homeDir = + process.env.PAPERCLIP_HOME ?? + fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-e2e-home-")); +const instanceRoot = path.join(homeDir, "instances", instanceId); +const configPath = + process.env.PAPERCLIP_CONFIG ?? path.join(instanceRoot, "config.json"); +const logsDir = path.join(instanceRoot, "logs"); +const storageDir = path.join(instanceRoot, "data", "storage"); +const masterKeyPath = path.join(instanceRoot, "secrets", "master.key"); + +fs.mkdirSync(logsDir, { recursive: true }); +fs.mkdirSync(storageDir, { recursive: true }); +fs.mkdirSync(path.dirname(masterKeyPath), { recursive: true }); +fs.mkdirSync(path.dirname(configPath), { recursive: true }); + +if (!fs.existsSync(masterKeyPath)) { + fs.writeFileSync(masterKeyPath, randomBytes(32).toString("base64"), { + encoding: "utf8", + mode: 0o600, + }); +} + +let db: Awaited> | undefined; +let shutdownServer: ((signal?: "SIGINT" | "SIGTERM") => Promise) | undefined; +let shuttingDown = false; + +async function shutdown(signal: "SIGINT" | "SIGTERM") { + if (shuttingDown) return; + shuttingDown = true; + try { + await shutdownServer?.(signal); + } finally { + await db?.cleanup(); + } + process.exit(0); +} + +process.once("SIGINT", () => { + void shutdown("SIGINT"); +}); +process.once("SIGTERM", () => { + void shutdown("SIGTERM"); +}); + +try { + const usesExternalPostgres = Boolean(process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL?.trim()); + db = await startEmbeddedPostgresTestDatabase("paperclip-e2e-pg-"); + + // Only tune cluster-wide durability settings on a disposable embedded + // PostgreSQL instance owned by this script. Never mutate a shared external + // PostgreSQL server passed via PAPERCLIP_TEST_POSTGRES_ADMIN_URL. + if (!usesExternalPostgres) { + const adminUrl = new URL(db.connectionString); + adminUrl.pathname = "/postgres"; + const admin = createDb(adminUrl.toString(), { maxConnections: 1 }); + try { + await admin.$client.unsafe("ALTER SYSTEM SET fsync = off"); + await admin.$client.unsafe("ALTER SYSTEM SET synchronous_commit = off"); + await admin.$client.unsafe("ALTER SYSTEM SET full_page_writes = off"); + await admin.$client.unsafe("SELECT pg_reload_conf()"); + } finally { + await admin.$client.end({ timeout: 1 }); + } + } + + const config = { + $meta: { + version: 1, + updatedAt: new Date().toISOString(), + source: "onboard", + }, + database: { + mode: "postgres", + connectionString: db.connectionString, + backup: { enabled: false, intervalMinutes: 60, retentionDays: 7, dir: path.join(instanceRoot, "data", "backups") }, + }, + logging: { mode: "file", logDir: logsDir }, + server: { + deploymentMode: "local_trusted", + exposure: "private", + bind: "loopback", + host: "127.0.0.1", + port, + allowedHostnames: [], + serveUi: true, + }, + auth: { baseUrlMode: "auto", disableSignUp: false }, + storage: { provider: "local_disk", localDisk: { baseDir: storageDir } }, + secrets: { + provider: "local_encrypted", + strictMode: false, + localEncrypted: { keyFilePath: masterKeyPath }, + }, + }; + fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { + encoding: "utf8", + mode: 0o600, + }); + + process.env.PAPERCLIP_HOME = homeDir; + process.env.PAPERCLIP_INSTANCE_ID = instanceId; + process.env.PAPERCLIP_CONFIG = configPath; + process.env.DATABASE_URL = db.connectionString; + process.env.PAPERCLIP_STORAGE_LOCAL_DIR = storageDir; + process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = masterKeyPath; + process.env.PAPERCLIP_DB_BACKUP_ENABLED = "false"; + + const { startServer } = await import("../../server/src/index.js"); + const started = await startServer(); + shutdownServer = started.shutdown; +} catch (error) { + await db?.cleanup(); + throw error; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 908316dc65d..a98da2aef16 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -1,6 +1,6 @@ { "inputs": { - "package.json": "416070f08a97a51ad73bf8839ec52336ecb7ad4e", + "package.json": "d9d6052ec03ec7bf20a875d9bcbe83ea96695097", "packages/plugins/sdk/package.json": "b7a4936e2803fd0d3b32dd7f17fc1ea86609ead0", "packages/plugins/sdk/src/bundlers.ts": "883bf3d9f2bd42877cfc0c3707cd882a6f6248d0", "packages/plugins/sdk/src/define-plugin.ts": "a99e07ce77ef72fcf1df1347346aacb8ba12e284", diff --git a/ui/src/components/AgentChatPicker.test.tsx b/ui/src/components/AgentChatPicker.test.tsx deleted file mode 100644 index 71d70dbcd6f..00000000000 --- a/ui/src/components/AgentChatPicker.test.tsx +++ /dev/null @@ -1,167 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { Agent } from "@paperclipai/shared"; -import { appearanceForPalette } from "@paperclipai/shared"; -import { AgentChatPicker, type AgentChatPickerProps } from "./AgentChatPicker"; - -const agents = [ - { id: "first", name: "Alex", title: "Engineering Lead", role: "engineer", icon: "code", status: "idle" }, - { id: "second", name: "Alex", title: "Product Designer", role: "designer", icon: "palette", status: "paused" }, -] as Agent[]; - -let root: Root; -let container: HTMLDivElement; -let props: AgentChatPickerProps; -async function render(overrides: Partial = {}) { - props = { ...props, ...overrides }; - await act(async () => { root.render(); }); -} -async function search(value: string) { - const input = document.querySelector("[role=combobox]")!; - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); -} -const options = () => [...document.querySelectorAll("[role=option]")]; - -beforeEach(() => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} }); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - props = { agents, open: true, onOpenChange: vi.fn(), onSelect: vi.fn() }; -}); -afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - vi.unstubAllGlobals(); -}); - -describe("AgentChatPicker", () => { - it("shows unread per agent through search and clears it when read state updates", async () => { - await render({ existingChatAgentIds: ["first", "second"], unreadMessageCounts: new Map([["first", 0], ["second", 12]]) }); - expect(options()[0].querySelector('[aria-label*="unread message"]')).toBeNull(); - expect(options()[1].querySelector('[aria-label="12 unread messages from Alex"]')?.textContent).toBe("12"); - await search("designer"); - expect(options()).toHaveLength(1); - expect(options()[0].textContent).toContain("12"); - await render({ unreadMessageCounts: new Map([["second", 0]]) }); - expect(options()[0].textContent).not.toContain("12"); - expect(options()[0].textContent).toContain("Open chat"); - }); - - it("uses indexed counts and memoized chat membership for a large team", async () => { - const roster = Array.from({ length: 500 }, (_, index) => ({ ...agents[index % 2], id: `agent-${index}`, name: `Agent ${index}` })); - let visits = 0; - const ids = roster.map(agent => agent.id); - const boundedIds = new Proxy(ids, { get(target, key, receiver) { - if (typeof key === "string" && /^\d+$/.test(key) && ++visits > ids.length * 2) throw new Error("Repeated chat membership scan"); - return Reflect.get(target, key, receiver); - } }); - const counts = new Map(ids.map(id => [id, 7])); - const getCount = vi.spyOn(counts, "get"); - await render({ agents: roster, existingChatAgentIds: boundedIds, unreadMessageCounts: counts }); - expect(options()).toHaveLength(500); - expect(document.querySelectorAll('[aria-label^="7 unread messages from"]')).toHaveLength(500); - expect(visits).toBe(500); - expect(getCount).toHaveBeenCalledTimes(500); - await search("Agent 499"); - expect(options().length).toBeLessThan(500); - expect(options().some(option => option.textContent?.includes("Agent 499"))).toBe(true); - expect(visits).toBe(500); - expect(getCount).toHaveBeenCalledTimes(1000); - }); - - it("shows saved custom avatars and default avatars in agent choices", async () => { - await render({ agents: [ - { ...agents[0], appearance: { ...appearanceForPalette("deep-tide"), customAvatarAssetId: "22222222-2222-4222-8222-222222222222" } }, - agents[1], - ] }); - const customImage = options()[0].querySelector("img"); - expect(customImage?.getAttribute("src")).toBe("/api/assets/22222222-2222-4222-8222-222222222222/content"); - expect(customImage?.getAttribute("width")).toBe("32"); - expect(options()[1].querySelector("img")?.getAttribute("src")).toMatch(/^\/api\/agent-avatars\/cap-v1\//); - }); - - it("lets a custom renderer replace the default avatar", async () => { - await render({ renderAgentIcon: agent => {agent.title} marker }); - expect(options()[0].textContent).toContain("Engineering Lead marker"); - expect(options()[1].textContent).toContain("Product Designer marker"); - expect(options().flatMap(option => [...option.querySelectorAll("img")])).toHaveLength(0); - }); - - it("does not close a reopened picker when an earlier selection finishes", async () => { - let finish!: () => void; - await render({ onSelect: () => new Promise(resolve => { finish = resolve; }) }); - await act(async () => options()[0].click()); - await render({ open: false }); - await render({ open: true }); - await search("designer"); - await act(async () => finish()); - expect(props.onOpenChange).not.toHaveBeenCalled(); - expect(document.querySelector("[role=combobox]")!.value).toBe("designer"); - expect(options()).toHaveLength(1); - }); - - it("searches by role and selects the correct same-name agent with Enter", async () => { - await render(); - expect(options()).toHaveLength(2); - await search("designer"); - expect(options()).toHaveLength(1); - expect(options()[0].textContent).toContain("Paused"); - await act(async () => { - document.querySelector("[role=combobox]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - }); - expect(props.onSelect).toHaveBeenCalledWith(agents[1], expect.any(AbortSignal)); - expect(props.onOpenChange).toHaveBeenCalledWith(false); - }); - - it("distinguishes existing conversations and selects the same agent when reopened", async () => { - await render({ existingChatAgentIds: ["first"] }); - expect(options()[0].textContent).toContain("Open chat"); - expect(options()[1].textContent).toContain("New chat"); - await search("designer"); - await act(async () => options()[0].click()); - expect(props.onSelect).toHaveBeenLastCalledWith(agents[1], expect.any(AbortSignal)); - await render({ open: false }); - await render({ open: true, existingChatAgentIds: ["first", "second"] }); - await search("designer"); - expect(options()[0].textContent).toContain("Open chat"); - expect(options()[0].textContent).not.toContain("New chat"); - await act(async () => options()[0].click()); - expect(props.onSelect).toHaveBeenLastCalledWith(agents[1], expect.any(AbortSignal)); - }); - - it("recovers from no results and resets search when reopened", async () => { - await render(); - await search("accountant"); - expect(options()).toHaveLength(0); - expect(document.body.textContent).toContain("No agents match"); - const clear = [...document.querySelectorAll("button")].find((b) => b.textContent === "Clear search")!; - await act(async () => clear.click()); - expect(options()).toHaveLength(2); - await search("designer"); - await render({ open: false }); - await render({ open: true }); - expect(document.querySelector("[role=combobox]")!.value).toBe(""); - expect(options()).toHaveLength(2); - }); - - it("shows loading, a retryable error, and an empty roster without stale choices", async () => { - await render({ loading: true }); - expect(document.querySelector("[role=status]")?.textContent).toContain("Loading agents"); - expect(options()).toHaveLength(0); - const retry = vi.fn(); - await render({ loading: false, error: new Error("Unavailable"), onRetry: retry }); - expect(document.querySelector("[role=alert]")?.textContent).toContain("Couldn’t load agents"); - expect(options()).toHaveLength(0); - await act(async () => [...document.querySelectorAll("button")].find((b) => b.textContent === "Retry")!.click()); - expect(retry).toHaveBeenCalledOnce(); - await render({ error: null, agents: [] }); - expect(document.body.textContent).toContain("Create an agent from the Agents page"); - }); -}); diff --git a/ui/src/components/AgentMultiSelect.test.tsx b/ui/src/components/AgentMultiSelect.test.tsx deleted file mode 100644 index 81353d0afab..00000000000 --- a/ui/src/components/AgentMultiSelect.test.tsx +++ /dev/null @@ -1,187 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { AgentMultiSelect, AgentSelect } from "./AgentMultiSelect"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -function act(callback: () => void | Promise) { - let result: void | Promise | undefined; - flushSync(() => { - result = callback(); - }); - return result; -} - -async function flush() { - await act(async () => { - await Promise.resolve(); - }); -} - -function setInputValue(input: HTMLInputElement, value: string) { - act(() => { - const valueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set; - valueSetter?.call(input, value); - input.dispatchEvent(new InputEvent("input", { bubbles: true, data: value, inputType: "insertText" })); - }); -} - -describe("AgentMultiSelect", () => { - let container: HTMLDivElement; - let root: Root | null; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = null; - }); - - afterEach(() => { - if (root) { - act(() => { - root?.unmount(); - }); - } - container.remove(); - document.body.innerHTML = ""; - }); - - it("keeps agent lists compact and searchable", async () => { - const onChange = vi.fn(); - const agents = Array.from({ length: 20 }, (_, index) => ({ - id: `agent-${index}`, - name: index === 17 ? "Search Target" : `Agent ${index}`, - title: `Role ${index}`, - })); - - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(container.textContent).toBe("Select agents"); - expect(document.body.textContent).not.toContain("Agent 0"); - - act(() => { - container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - const filter = document.body.querySelector('input[placeholder="Filter agents"]'); - expect(filter).not.toBeNull(); - setInputValue(filter!, "search target"); - await flush(); - - expect(document.body.textContent).toContain("Search Target"); - expect(document.body.textContent).not.toContain("Agent 0"); - - act(() => { - document.body - .querySelector('[aria-label="Allow Search Target"]') - ?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - expect(onChange).toHaveBeenCalledTimes(1); - expect(onChange.mock.calls[0]?.[0]).toEqual(new Set(["agent-17"])); - }); - - it("filters and selects a single agent", async () => { - const onChange = vi.fn(); - const agents = [ - { id: "agent-1", name: "Alpha", title: "Engineer" }, - { id: "agent-2", name: "Bravo", title: "Researcher" }, - ]; - - root = createRoot(container); - act(() => { - root?.render(); - }); - - act(() => { - container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - const filter = document.body.querySelector('input[placeholder="Filter agents"]'); - expect(filter).not.toBeNull(); - setInputValue(filter!, "research"); - await flush(); - - expect(document.body.textContent).toContain("Bravo"); - expect(document.body.textContent).not.toContain("Alpha"); - - act(() => { - document.body - .querySelector('[aria-label="Select Bravo"]') - ?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - expect(onChange).toHaveBeenCalledWith("agent-2"); - expect(document.body.querySelector('input[placeholder="Filter agents"]')).toBeNull(); - }); - - it("uses the same agent avatar in the selected value and every option", async () => { - const agents = [{ id: "agent-1", name: "Ralph" }, { id: "agent-2", name: "Support" }]; - root = createRoot(container); - act(() => root?.render()); - const selected = container.querySelector('[data-slot="agent-avatar"] img')?.getAttribute("src"); - expect(selected).toBeTruthy(); - act(() => container.querySelector("button")?.click()); - await flush(); - expect(document.querySelector('[aria-label="Select Ralph"] [data-slot="agent-avatar"] img')?.getAttribute("src")).toBe(selected); - expect(document.querySelector('[aria-label="Select Support"] [data-slot="agent-avatar"] img')).not.toBeNull(); - }); - - it("previews selected agents and stages changes until save", async () => { - const onSave = vi.fn(); - const agents = Array.from({ length: 6 }, (_, index) => ({ - id: `agent-${index}`, - name: `Agent ${index}`, - })); - - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(container.textContent).toContain("Agent 0"); - expect(container.textContent).toContain("Agent 2"); - expect(container.textContent).toContain("and 2 more"); - expect(container.textContent).not.toContain("Agent 4"); - - act(() => { - container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - act(() => { - document.body - .querySelector('[aria-label="Allow Agent 5"]') - ?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - expect(onSave).not.toHaveBeenCalled(); - const save = Array.from(document.body.querySelectorAll("button")).find((button) => button.textContent === "Save"); - act(() => { - save?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - expect(onSave).toHaveBeenCalledWith(new Set(agents.map((agent) => agent.id))); - }); -}); diff --git a/ui/src/components/ChatComposer.test.tsx b/ui/src/components/ChatComposer.test.tsx deleted file mode 100644 index aa3f7919105..00000000000 --- a/ui/src/components/ChatComposer.test.tsx +++ /dev/null @@ -1,254 +0,0 @@ -// @vitest-environment jsdom - -import { act, useState } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ChatComposer, type ChatComposerProps } from "./ChatComposer"; - -(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -/** Stateful harness so the controlled textarea reflects typed input. */ -function Harness(props: Partial & { initial?: string }) { - const { initial = "", onChange, ...rest } = props; - const [value, setValue] = useState(initial); - return ( - { - setValue(v); - onChange?.(v); - }} - onSubmit={rest.onSubmit ?? (() => {})} - {...rest} - /> - ); -} - -function typeInput(textarea: HTMLTextAreaElement, text: string) { - const setter = Object.getOwnPropertyDescriptor( - window.HTMLTextAreaElement.prototype, - "value", - )?.set; - setter?.call(textarea, text); - textarea.dispatchEvent(new Event("input", { bubbles: true })); -} - -describe("ChatComposer", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - }); - - function input() { - return container.querySelector('[data-testid="chat-composer-input"]')!; - } - function sendButton() { - return container.querySelector('button[aria-label="Send message"]')!; - } - function attachButton() { - return container.querySelector('button[aria-label="Attach files"]'); - } - - it("renders a bare textarea + send and no attach button without a handler", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - expect(input()).toBeTruthy(); - expect(input().placeholder).toBe("Ask anything…"); - expect(attachButton()).toBeNull(); - // No formatting toolbar — there is exactly one button (send) when bare. - expect(container.querySelectorAll("button").length).toBe(1); - act(() => root.unmount()); - }); - - it("shows the attach affordance when onAttachFiles is provided", () => { - const root = createRoot(container); - act(() => { - root.render( {}} />); - }); - expect(attachButton()).toBeTruthy(); - act(() => root.unmount()); - }); - - it("disables send while empty and enables it once there is text", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - expect(sendButton().disabled).toBe(true); - act(() => { - typeInput(input(), "hello"); - }); - expect(sendButton().disabled).toBe(false); - act(() => root.unmount()); - }); - - it("submits on click", () => { - const onSubmit = vi.fn(); - const root = createRoot(container); - act(() => { - root.render(); - }); - act(() => { - sendButton().dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - expect(onSubmit).toHaveBeenCalledTimes(1); - act(() => root.unmount()); - }); - - it('submitKey="enter": plain Enter submits, Shift+Enter does not', () => { - const onSubmit = vi.fn(); - const root = createRoot(container); - act(() => { - root.render(); - }); - act(() => { - input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, shiftKey: true })); - }); - expect(onSubmit).not.toHaveBeenCalled(); - act(() => { - input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - }); - expect(onSubmit).toHaveBeenCalledTimes(1); - act(() => root.unmount()); - }); - - it('submitKey="mod-enter": plain Enter does not submit, Cmd/Ctrl+Enter does', () => { - const onSubmit = vi.fn(); - const root = createRoot(container); - act(() => { - root.render(); - }); - act(() => { - input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - }); - expect(onSubmit).not.toHaveBeenCalled(); - act(() => { - input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, metaKey: true })); - }); - expect(onSubmit).toHaveBeenCalledTimes(1); - act(() => root.unmount()); - }); - - it("singleLine strips newlines from input", () => { - const onChange = vi.fn(); - const root = createRoot(container); - act(() => { - root.render(); - }); - act(() => { - typeInput(input(), "one\ntwo"); - }); - expect(onChange).toHaveBeenLastCalledWith("one two"); - act(() => root.unmount()); - }); - - it("default (multiline) mode soft-wraps and auto-grows instead of clipping (PAP-116)", () => { - // The conference room composer adopts this default mode. Text must wrap and - // the box grow up to a cap — never clip horizontally or show an idle scrollbar. - const root = createRoot(container); - act(() => { - root.render(); - }); - const el = input(); - expect(el.getAttribute("wrap")).toBe("soft"); - expect(el.className).toContain("overflow-y-auto"); - expect(el.className).toContain("max-h-(--sz-200px)"); - expect(el.className).not.toContain("whitespace-nowrap"); - expect(el.className).not.toContain("overflow-x-auto"); - act(() => root.unmount()); - }); - - it("singleLine mode clips to one row (opt-in only)", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - const el = input(); - expect(el.getAttribute("wrap")).toBe("off"); - expect(el.className).toContain("whitespace-nowrap"); - expect(el.className).toContain("max-h-(--sz-22px)"); - act(() => root.unmount()); - }); - - it('tone="planning" is reflected on the container', () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - const box = container.querySelector('[data-testid="chat-composer"]'); - expect(box?.getAttribute("data-tone")).toBe("planning"); - act(() => root.unmount()); - }); - - it('tone="ask" is reflected on the container', () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - const box = container.querySelector('[data-testid="chat-composer"]'); - expect(box?.getAttribute("data-tone")).toBe("ask"); - expect(box?.className).toContain("sky"); - act(() => root.unmount()); - }); - - it('defaults to the opaque "card" surface', () => { - // PAP-131: surface is opt-in — existing adopters keep the bg-card box. - const root = createRoot(container); - act(() => { - root.render(); - }); - const box = container.querySelector('[data-testid="chat-composer"]')!; - expect(box.getAttribute("data-surface")).toBe("card"); - expect(box.className).toContain("bg-card"); - expect(box.className).not.toContain("backdrop-blur"); - // Rounded corners are shared chrome on both surfaces. - expect(box.className).toContain("rounded-xl"); - act(() => root.unmount()); - }); - - it('surface="translucent" applies the task glass recipe and keeps shared chrome (PAP-131)', () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - const box = container.querySelector('[data-testid="chat-composer"]')!; - expect(box.getAttribute("data-surface")).toBe("translucent"); - // Glass recipe — mirrors the task-comments composer shell. - expect(box.className).toContain("bg-background/95"); - expect(box.className).toContain("supports-[backdrop-filter]:bg-background/85"); - expect(box.className).toContain("backdrop-blur"); - expect(box.className).toContain("shadow-(--shadow-extract-4)"); - expect(box.className).toContain("dark:shadow-(--shadow-extract-5)"); - expect(box.className).not.toContain("bg-card"); - // Shared chrome survives: rounded-xl corners + neutral focus darkening. - expect(box.className).toContain("rounded-xl"); - expect(box.className).toContain("focus-within:border-muted-foreground/40"); - act(() => root.unmount()); - }); - - it("translucent surface keeps the drag-over attach layering", () => { - const root = createRoot(container); - act(() => { - root.render( {}} />); - }); - const box = container.querySelector('[data-testid="chat-composer"]')!; - act(() => { - const dataTransfer = { types: ["Files"], dropEffect: "none" }; - const evt = new Event("dragenter", { bubbles: true }) as DragEvent & { - dataTransfer: typeof dataTransfer; - }; - Object.defineProperty(evt, "dataTransfer", { value: dataTransfer }); - box.dispatchEvent(evt); - }); - expect(container.querySelector('[data-testid="chat-composer-drop-overlay"]')).toBeTruthy(); - act(() => root.unmount()); - }); -}); diff --git a/ui/src/components/DocumentAnnotationLayer.test.tsx b/ui/src/components/DocumentAnnotationLayer.test.tsx deleted file mode 100644 index e03dd75a61a..00000000000 --- a/ui/src/components/DocumentAnnotationLayer.test.tsx +++ /dev/null @@ -1,302 +0,0 @@ -// @vitest-environment jsdom - -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { DocumentAnnotationLayer } from "./DocumentAnnotationLayer"; - -const mockBuildAnchorFromContainerSelection = vi.hoisted(() => vi.fn()); -const mockGetContainerTextOffset = vi.hoisted(() => vi.fn()); -const mockRangesForNormalizedSpan = vi.hoisted(() => vi.fn()); - -vi.mock("@/lib/document-annotation-selection", () => ({ - buildAnchorFromContainerSelection: mockBuildAnchorFromContainerSelection, - getContainerTextOffset: mockGetContainerTextOffset, - rangesForNormalizedSpan: mockRangesForNormalizedSpan, -})); - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - await callback(); - await Promise.resolve(); - await new Promise((resolve) => setTimeout(resolve, 0)); -} - -function makeRect(left: number, top: number, width: number, height: number): DOMRect { - return { - x: left, - y: top, - left, - top, - right: left + width, - bottom: top + height, - width, - height, - toJSON: () => ({}), - } as DOMRect; -} - -function makeRange(rects: DOMRect[], commonAncestorContainer: Node = document.createTextNode("")): Range { - return { - commonAncestorContainer, - getClientRects: () => rects, - } as unknown as Range; -} - -describe("DocumentAnnotationLayer", () => { - let container: HTMLDivElement; - let rectSpy: ReturnType; - let root: Root | null = null; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - mockRangesForNormalizedSpan.mockReturnValue([makeRange([makeRect(8, 12, 80, 18)])]); - rectSpy = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(makeRect(0, 0, 400, 300)); - }); - - afterEach(async () => { - if (root) { - await act(() => root?.unmount()); - root = null; - } - rectSpy.mockRestore(); - container.remove(); - vi.clearAllMocks(); - }); - - it("uses borderless token-driven overlay boxes for annotation highlight states", async () => { - const body = document.createElement("div"); - body.textContent = "Annotated body text."; - root = createRoot(container); - - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - const highlights = Array.from(container.querySelectorAll(".paperclip-doc-annotation-highlight")); - expect(highlights).toHaveLength(4); - - for (const highlight of highlights) { - expect(highlight.className).toBe("paperclip-doc-annotation-highlight absolute"); - expect(highlight.className).not.toContain("outline"); - expect(highlight.className).not.toContain("shadow"); - } - expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "focused") - ?.getAttribute("data-focused")).toBe("true"); - expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "stale") - ?.getAttribute("data-anchor-state")).toBe("stale"); - expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "resolved") - ?.getAttribute("data-status")).toBe("resolved"); - }); - - it("does not render highlights for text clipped by folded document content", async () => { - const body = document.createElement("div"); - const clippedContent = document.createElement("div"); - clippedContent.className = "fold-curtain__content"; - const hiddenText = document.createTextNode("Hidden folded text"); - clippedContent.appendChild(hiddenText); - body.appendChild(clippedContent); - mockRangesForNormalizedSpan.mockReturnValue([makeRange([makeRect(8, 60, 80, 18)], hiddenText)]); - rectSpy.mockImplementation(function (this: HTMLElement) { - if (this === clippedContent) return makeRect(0, 0, 400, 40); - return makeRect(0, 0, 400, 120); - }); - root = createRoot(container); - - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - expect(container.querySelector(".paperclip-doc-annotation-highlight")).toBeNull(); - expect(container.querySelector(".paperclip-doc-annotation-hit-target")).toBeNull(); - }); - - it("does not capture annotation comments from editable selections", async () => { - const body = document.createElement("div"); - const editable = document.createElement("div"); - editable.setAttribute("contenteditable", "true"); - const text = document.createTextNode("Editing routine instructions"); - editable.appendChild(text); - body.appendChild(editable); - - const range = document.createRange(); - range.setStart(text, 0); - range.setEnd(text, "Editing".length); - const getSelectionSpy = vi.spyOn(window, "getSelection").mockReturnValue({ - rangeCount: 1, - isCollapsed: false, - getRangeAt: () => range, - } as unknown as Selection); - const onPendingAnchorChange = vi.fn(); - root = createRoot(container); - - try { - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - await act(async () => { - document.dispatchEvent(new Event("selectionchange")); - }); - - expect(mockGetContainerTextOffset).not.toHaveBeenCalled(); - expect(mockBuildAnchorFromContainerSelection).not.toHaveBeenCalled(); - expect(onPendingAnchorChange).toHaveBeenCalledWith(null); - expect(container.querySelector('[data-testid="document-annotation-selection-toolbar"]')).toBeNull(); - } finally { - getSelectionSpy.mockRestore(); - } - }); - - it("does not capture annotation comments from bare contenteditable selections", async () => { - const body = document.createElement("div"); - const editable = document.createElement("div"); - editable.setAttribute("contenteditable", ""); - const text = document.createTextNode("Editing routine instructions"); - editable.appendChild(text); - body.appendChild(editable); - - const range = document.createRange(); - range.setStart(text, 0); - range.setEnd(text, "Editing".length); - const getSelectionSpy = vi.spyOn(window, "getSelection").mockReturnValue({ - rangeCount: 1, - isCollapsed: false, - getRangeAt: () => range, - } as unknown as Selection); - const onPendingAnchorChange = vi.fn(); - root = createRoot(container); - - try { - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - await act(async () => { - document.dispatchEvent(new Event("selectionchange")); - }); - - expect(mockGetContainerTextOffset).not.toHaveBeenCalled(); - expect(mockBuildAnchorFromContainerSelection).not.toHaveBeenCalled(); - expect(onPendingAnchorChange).toHaveBeenCalledWith(null); - expect(container.querySelector('[data-testid="document-annotation-selection-toolbar"]')).toBeNull(); - } finally { - getSelectionSpy.mockRestore(); - } - }); - - it("keeps native CSS highlight ranges synchronized while using the overlay for visual paint", async () => { - const originalCss = globalThis.CSS; - const originalHighlight = (globalThis as { Highlight?: unknown }).Highlight; - const setHighlight = vi.fn(); - const deleteHighlight = vi.fn(); - class MockHighlight { - ranges: Range[]; - - constructor(...ranges: Range[]) { - this.ranges = ranges; - } - } - (globalThis as { CSS?: unknown }).CSS = { - ...(originalCss ?? {}), - highlights: { - set: setHighlight, - delete: deleteHighlight, - }, - }; - (globalThis as { Highlight?: unknown }).Highlight = MockHighlight; - - const body = document.createElement("div"); - body.textContent = "Annotated body text."; - root = createRoot(container); - - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - expect(container.querySelector(".paperclip-doc-annotation-highlight")).not.toBeNull(); - expect(container.querySelector(".paperclip-doc-annotation-hit-target")).not.toBeNull(); - const openHighlightCall = setHighlight.mock.calls.find(([name]) => name === "paperclip-doc-annotation-open"); - expect(openHighlightCall).toBeTruthy(); - expect((openHighlightCall?.[1] as MockHighlight).ranges).toHaveLength(1); - - await act(async () => root?.unmount()); - root = null; - expect(deleteHighlight).toHaveBeenCalledWith("paperclip-doc-annotation-open"); - - (globalThis as { CSS?: unknown }).CSS = originalCss; - (globalThis as { Highlight?: unknown }).Highlight = originalHighlight; - }); -}); diff --git a/ui/src/components/DocumentMarkdownBody.test.tsx b/ui/src/components/DocumentMarkdownBody.test.tsx deleted file mode 100644 index 605b6efa008..00000000000 --- a/ui/src/components/DocumentMarkdownBody.test.tsx +++ /dev/null @@ -1,142 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { MemoryRouter, useLocation, useNavigate } from "react-router-dom"; -import { afterEach, describe, expect, it } from "vitest"; -import { ThemeProvider } from "@/context/ThemeContext"; -import { DocumentMarkdownBody } from "./DocumentMarkdownBody"; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; -let root: Root; -let container: HTMLDivElement; -afterEach(async () => { - await act(async () => root?.unmount()); - container?.remove(); -}); - -const body = "![First](/first.png)\n\n![Second][shot]\n\n![Repeated](/first.png)\n\n[shot]: https://example.com/second.png"; -function LocationProbe() { - const location = useLocation(); - const navigate = useNavigate(); - return <>{location.pathname}{location.search}{location.hash}; -} -async function render(hash = "", markdown = body, revisionId?: string, documentIssueId?: string, currentIssueId?: string) { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - await act(async () => { - root.render( - - {markdown} - - - ); - }); -} -async function click(selector: string) { - const element = document.querySelector(selector)!; - expect(element).not.toBeNull(); - await act(async () => element.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); -} -async function key(key: string) { - await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }))); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); -} -function dialog() { return document.querySelector('[role="dialog"]'); } - -describe("document image gallery", () => { - it("keeps fragment links scoped to the saved document's task after the URL changes", async () => { - await render("#document-local", "[Evidence](#document-evidence&thread=note)\n\n[Explicit](#document-brief&documentIssue=other)\n\n[Section](#section)", "old", "owner", "current"); - expect([...container.querySelectorAll(".paperclip-markdown a")].map(link => link.getAttribute("href"))).toEqual([ - "#document-evidence&thread=note&documentIssue=owner", - "#document-brief&documentIssue=other", - "#section", - ]); - }); - - it("opens a clicked occurrence, navigates all rendered images, and updates the URL", async () => { - await render("#document-report&viewer=full&thread=thread-1"); - await click('[aria-label="Open image: Repeated"]'); - expect(dialog()?.textContent).toContain("3 / 3"); - expect(dialog()?.querySelector("img")?.getAttribute("src")).toBe("/first.png"); - expect(container.querySelector("output")?.textContent).toBe("/PAP/issues/example?keep=1#document-report&thread=thread-1&viewer=full&image=3"); - await key("ArrowRight"); - expect(dialog()?.textContent).toContain("1 / 3"); - await click('button[title="Next"]'); - expect(dialog()?.querySelector("img")?.getAttribute("src")).toBe("https://example.com/second.png"); - expect(container.querySelector("output")?.textContent).toContain("image=2"); - await key("ArrowLeft"); - expect(dialog()?.textContent).toContain("1 / 3"); - await click('button[title="Previous"]'); - expect(dialog()?.textContent).toContain("3 / 3"); - await key("Escape"); - expect(dialog()).toBeNull(); - expect(container.querySelector("output")?.textContent).not.toContain("image="); - expect(container.querySelector("output")?.textContent).toContain("viewer=full"); - expect(document.activeElement?.getAttribute("aria-label")).toBe("Open image: Repeated"); - }); - - it("loads a shared image URL for the exact revision and retains it on close", async () => { - await render("#document-report&revision=old&interaction=review&documentIssue=owner&image=2", body, "old", "owner"); - expect(dialog()?.textContent).toContain("2 / 3"); - expect(dialog()?.querySelector("a")?.getAttribute("href")).toBe("https://example.com/second.png"); - await click('button[title="Close"]'); - expect(container.querySelector("output")?.textContent).toContain("#document-report&revision=old&interaction=review&documentIssue=owner"); - expect(dialog()).toBeNull(); - }); - - it("opens a saved owner after the URL has changed to another document", async () => { - await render("#document-local&documentIssue=wrong-owner", body, "old", "owner"); - await click('[aria-label="Open image: First"]'); - expect(dialog()?.textContent).toContain("1 / 3"); - expect(container.querySelector("output")?.textContent).toContain("#document-report&revision=old&documentIssue=owner&image=1"); - await key("ArrowRight"); - expect(container.querySelector("output")?.textContent).toContain("documentIssue=owner&image=2"); - }); - - it("opens an explicit current-task link and keeps review parameters through navigation and reopening", async () => { - await render("#document-report&revision=old&interaction=review&viewer=full&documentIssue=current-task&image=2", body, "old", undefined, "current-task"); - expect(dialog()?.textContent).toContain("2 / 3"); - await key("ArrowRight"); - expect(dialog()?.textContent).toContain("3 / 3"); - await click('button[title="Close"]'); - expect(dialog()).toBeNull(); - await click('[aria-label="Open image: First"]'); - expect(dialog()?.textContent).toContain("1 / 3"); - const url = container.querySelector("output")?.textContent; - expect(url).toContain("revision=old"); - expect(url).toContain("interaction=review"); - expect(url).toContain("viewer=full"); - expect(url).toContain("documentIssue=current-task"); - }); - - it("does not match another task's saved tab to an implicit current-task link", async () => { - await render("#document-report&revision=old&image=2", body, "old", "other-task", "current-task"); - expect(dialog()).toBeNull(); - await click('[aria-label="Open image: First"]'); - expect(dialog()?.textContent).toContain("1 / 3"); - expect(container.querySelector("output")?.textContent).toContain("documentIssue=other-task"); - }); - - it.each(["#document-other&image=1", "#document-report&image=100", "#document-report&image=0", "#document-report&revision=old&image=1"])("does not open an unavailable image target: %s", async (hash) => { - await render(hash); - expect(dialog()).toBeNull(); - }); - - it("opens a single image from the keyboard without navigation controls", async () => { - await render("", "![Only](/only.png)"); - const image = container.querySelector("img")!; - await act(async () => { - image.focus(); - image.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true })); - }); - expect(dialog()?.textContent).toContain("1 / 1"); - expect(dialog()?.querySelector('button[title="Next"]')).toBeNull(); - await click('[role="dialog"]'); - expect(dialog()).toBeNull(); - expect(document.activeElement).toBe(image); - }); -}); diff --git a/ui/src/components/EnvVarEditor.test.tsx b/ui/src/components/EnvVarEditor.test.tsx deleted file mode 100644 index fc0b8515f28..00000000000 --- a/ui/src/components/EnvVarEditor.test.tsx +++ /dev/null @@ -1,127 +0,0 @@ -// @vitest-environment jsdom - -import { createRoot, type Root } from "react-dom/client"; -import { flushSync } from "react-dom"; -import type { CompanySecret, EnvBinding, UserSecretDefinition } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { EnvironmentVariablesEditor } from "./environment-variables-editor"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -const definition: UserSecretDefinition = { - id: "def-1", - companyId: "c1", - key: "PERSONAL_GH_TOKEN", - name: "Personal GitHub token", - description: null, - status: "active", - provider: "local_encrypted", - managedMode: "paperclip_managed", - providerConfigId: null, - providerMetadata: null, - usageGuidance: null, - createdByAgentId: null, - createdByUserId: null, - updatedByAgentId: null, - updatedByUserId: null, - deletedAt: null, - createdAt: new Date(), - updatedAt: new Date(), -}; - -async function act(callback: () => void | Promise) { - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -let container: HTMLDivElement; -let root: Root; - -beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); -}); - -afterEach(() => { - act(() => root.unmount()); - container.remove(); -}); - -function render(props: Partial>) { - root = createRoot(container); - return act(() => { - root.render( - , - ); - }); -} - -describe("EnvironmentVariablesEditor user secret binding", () => { - it("renders an existing user_secret_ref as a User secret row with the definition and requirement", async () => { - const value: Record = { - GH_TOKEN: { type: "user_secret_ref", key: "PERSONAL_GH_TOKEN", required: true }, - }; - await render({ value, userSecretDefinitions: [definition] }); - - const keyInput = container.querySelector('input[placeholder="KEY"]'); - expect(keyInput?.value).toBe("GH_TOKEN"); - // Radix Select triggers render the selected label as text. - expect(container.textContent).toContain("User secret"); - expect(container.textContent).toContain("Personal GitHub token"); - expect(container.textContent).toContain("Required"); - }); - - it("explains user-secret bindings when a user secret row is present", async () => { - await render({ - value: { GH_TOKEN: { type: "user_secret_ref", key: "PERSONAL_GH_TOKEN", required: true } }, - userSecretDefinitions: [definition], - }); - expect(container.textContent).toContain("Personal GitHub token"); - expect(container.textContent).toContain("User secrets resolve from the user responsible for the run."); - }); - - it("keeps working for company secrets when no user definitions are provided", async () => { - const secret: CompanySecret = { - id: "sec-1", - companyId: "c1", - scope: "company", - ownerUserId: null, - userSecretDefinitionId: null, - key: "api_key", - name: "API key", - provider: "local_encrypted", - status: "active", - managedMode: "paperclip_managed", - externalRef: null, - providerConfigId: null, - providerMetadata: null, - latestVersion: 2, - description: null, - lastResolvedAt: null, - lastRotatedAt: null, - deletedAt: null, - createdByAgentId: null, - createdByUserId: null, - createdAt: new Date(), - updatedAt: new Date(), - }; - const value: Record = { - API_KEY: { type: "secret_ref", secretId: "sec-1", version: "latest" }, - }; - await render({ value, secrets: [secret] }); - - const keyInput = container.querySelector('input[placeholder="KEY"]'); - expect(keyInput?.value).toBe("API_KEY"); - expect(container.textContent).toContain("API key"); - }); -}); diff --git a/ui/src/components/FileTree.test.tsx b/ui/src/components/FileTree.test.tsx deleted file mode 100644 index 2bf88810200..00000000000 --- a/ui/src/components/FileTree.test.tsx +++ /dev/null @@ -1,231 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { FileTree, buildFileTree } from "./FileTree"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -describe("FileTree", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - act(() => { - root.unmount(); - }); - container.remove(); - }); - - function row(path: string) { - return container.querySelector(`[data-file-tree-path="${path}"]`) as HTMLDivElement | null; - } - - it("preserves readable plugin error details and retry without exposing raw codes", () => { - const retry = vi.fn(); - const renderError = (message: string) => act(() => root.render( - {}} onToggleDir={() => {}} error={{ message, retry }} />, - )); - renderError("The wiki source was removed. Choose another source."); - expect(container.textContent).toContain("The wiki source was removed. Choose another source."); - act(() => Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Retry")!.click()); - expect(retry).toHaveBeenCalledOnce(); - renderError("source_unavailable"); - expect(container.textContent).not.toContain("source_unavailable"); - }); - - it("selects file rows and expands directory rows", () => { - const onSelectFile = vi.fn(); - const onToggleDir = vi.fn(); - const nodes = buildFileTree({ - "README.md": "", - "docs/guide.md": "", - }); - - act(() => { - root.render( - , - ); - }); - - expect(row("README.md")?.getAttribute("aria-selected")).toBe("true"); - - act(() => { - row("docs/guide.md")?.click(); - }); - expect(onSelectFile).toHaveBeenCalledWith("docs/guide.md"); - - act(() => { - row("docs")?.click(); - }); - expect(onToggleDir).toHaveBeenCalledWith("docs"); - }); - - it("marks partially selected directories as indeterminate", () => { - const nodes = buildFileTree({ - "docs/a.md": "", - "docs/b.md": "", - }); - - act(() => { - root.render( - {}} - onToggleDir={() => {}} - onToggleCheck={() => {}} - />, - ); - }); - - const input = row("docs")?.querySelector("input[type='checkbox']") as HTMLInputElement | null; - expect(input?.checked).toBe(false); - expect(input?.indeterminate).toBe(true); - expect(row("docs")?.getAttribute("aria-checked")).toBe("mixed"); - }); - - it("renders file badges and host-only file extras", () => { - const nodes = buildFileTree({ - "wiki/very-long-page-slug.md": "", - }); - - act(() => { - root.render( - {}} - onToggleDir={() => {}} - fileBadges={{ - "wiki/very-long-page-slug.md": { - label: "fresh", - status: "ok", - tooltip: "Synced", - }, - }} - renderFileExtra={(node) => ( - node.kind === "file" ? {node.name.length} chars : null - )} - />, - ); - }); - - expect(container.textContent).toContain("fresh"); - expect(container.querySelector("[title='Synced']")).not.toBeNull(); - expect(container.querySelector("[data-testid='file-extra']")?.textContent).toBe("22 chars"); - }); - - it("wraps long labels by default and can opt back into truncation", () => { - const nodes = buildFileTree({ - "wiki/extremely-long-page-slug-that-wraps-on-mobile.md": "", - }); - - act(() => { - root.render( - {}} - onToggleDir={() => {}} - />, - ); - }); - - expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("break-all"); - - act(() => { - root.render( - {}} - onToggleDir={() => {}} - wrapLabels={false} - />, - ); - }); - - expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("truncate"); - }); - - it("supports tree keyboard expansion and checkbox toggling", () => { - const onToggleDir = vi.fn(); - const onToggleCheck = vi.fn(); - const nodes = buildFileTree({ - "docs/a.md": "", - }); - - act(() => { - root.render( - {}} - onToggleDir={onToggleDir} - onToggleCheck={onToggleCheck} - />, - ); - }); - - const docsRow = row("docs"); - act(() => { - docsRow?.focus(); - docsRow?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })); - }); - expect(onToggleDir).toHaveBeenCalledWith("docs"); - - act(() => { - docsRow?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true })); - }); - expect(onToggleCheck).toHaveBeenCalledWith("docs", "dir"); - }); - - it("keeps hidden descendants in folder selection and restores a tab stop when filtering", () => { - const nodes = buildFileTree({ "docs/a.md": "", "docs/b.md": "" }); - const props = { nodes, selectedFile: null, expandedDirs: new Set(["docs"]), checkedFiles: new Set(["docs/a.md"]), onSelectFile: () => {}, onToggleDir: () => {} }; - act(() => root.render()); - act(() => row("docs/b.md")?.focus()); - act(() => root.render( {node.name} description} />)); - expect(row("docs/b.md")).toBeNull(); - expect(row("docs")?.getAttribute("aria-checked")).toBe("mixed"); - expect(row("docs")?.tabIndex).toBe(0); - expect(row("docs/a.md")?.textContent).toContain("a.md description"); - }); - - it("blocks mouse and keyboard changes while disabled", () => { - const onToggleDir = vi.fn(); - const onToggleCheck = vi.fn(); - const onSelectFile = vi.fn(); - act(() => root.render()); - act(() => { - row("docs/a.md")?.click(); - row("docs")?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true })); - container.querySelector('[aria-label="Collapse docs"]')?.click(); - }); - expect(onToggleCheck).not.toHaveBeenCalled(); - expect(onSelectFile).not.toHaveBeenCalled(); - expect(onToggleDir).not.toHaveBeenCalled(); - expect(container.querySelector('input[type="checkbox"]')?.disabled).toBe(true); - }); -}); diff --git a/ui/src/components/InlineEntitySelector.test.tsx b/ui/src/components/InlineEntitySelector.test.tsx deleted file mode 100644 index c831fc1d43d..00000000000 --- a/ui/src/components/InlineEntitySelector.test.tsx +++ /dev/null @@ -1,500 +0,0 @@ -// @vitest-environment jsdom - -import { createRoot } from "react-dom/client"; -import { flushSync } from "react-dom"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { Dialog, DialogContent, DialogTitle } from "./ui/dialog"; -import { InlineEntitySelector } from "./InlineEntitySelector"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -describe("InlineEntitySelector", () => { - let container: HTMLDivElement; - let originalMatchMedia: typeof window.matchMedia; - - beforeEach(() => { - originalMatchMedia = window.matchMedia; - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - window.matchMedia = originalMatchMedia; - container.remove(); - document.body.innerHTML = ""; - }); - - it.each([false, true])("allows wheel and touch scrolling outside a parent dialog (mobile: %s)", async (mobile) => { - window.matchMedia = vi.fn().mockImplementation((query: string) => ({ - matches: mobile && query === "(max-width: 40rem)", - media: query, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - })); - const root = createRoot(container); - await act(() => { - root.render( - - - New task - ({ id: `agent-${index}`, label: `Agent ${index}` }))} - placeholder="Assignee" - noneLabel="No assignee" - searchPlaceholder="Search assignees..." - emptyMessage="No assignees found." - onChange={vi.fn()} - triggerTestId="nested-assignee-picker" - openOnFocus={false} - modal - /> - - , - ); - }); - try { - await act(() => { - document.querySelector("[data-testid=nested-assignee-picker]")!.click(); - }); - // Let both real Radix scroll locks install their document listeners. - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - const list = document.querySelector("[data-mobile-entity-picker-list]")!; - expect(list).not.toBeNull(); - expect(document.querySelector("[data-slot=dialog-content]")!.contains(list)).toBe(false); - // jsdom has no layout; supply the geometry of a list with more rows than fit. - list.style.overflowY = "auto"; - Object.defineProperties(list, { - scrollHeight: { configurable: true, value: 1000 }, - clientHeight: { configurable: true, value: 200 }, - }); - const option = list.querySelector("button")!; - const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 }); - option.dispatchEvent(wheel); - expect(wheel.defaultPrevented).toBe(false); - const touch = (type: string, y: number) => { - const event = new Event(type, { bubbles: true, cancelable: true }); - Object.defineProperties(event, { - touches: { value: [{ clientX: 100, clientY: y }] }, - changedTouches: { value: [{ clientX: 100, clientY: y }] }, - }); - option.dispatchEvent(event); - return event; - }; - touch("touchstart", 150); - expect(touch("touchmove", 100).defaultPrevented).toBe(false); - // The background stays locked while the picker is open. - const outsideMove = new Event("touchmove", { bubbles: true, cancelable: true }); - Object.defineProperties(outsideMove, { - touches: { value: [{ clientX: 100, clientY: 100 }] }, - changedTouches: { value: [{ clientX: 100, clientY: 100 }] }, - }); - document.body.dispatchEvent(outsideMove); - expect(outsideMove.defaultPrevented).toBe(true); - } finally { - await act(() => root.unmount()); - } - }); - - it("opens on the next keyboard focus after a desktop outside dismissal", async () => { - const root = createRoot(container); - await act(() => { - root.render(<> - - - ); - }); - try { - const trigger = container.querySelector("[data-testid=desktop-assignee-picker]")!; - const outside = container.querySelector("[data-testid=outside-picker]")!; - await act(() => trigger.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - await act(() => { - outside.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true, cancelable: true })); - outside.focus(); - outside.click(); - }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull(); - expect(document.activeElement).toBe(outside); - await act(() => trigger.focus()); - expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - } finally { - await act(() => root.unmount()); - } - }); - - it("dismisses the mobile project sheet from its backdrop and preserves the task dialog", async () => { - window.matchMedia = vi.fn().mockImplementation((query: string) => ({ - matches: query === "(max-width: 40rem)", - media: query, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - })); - const onChange = vi.fn(); - const root = createRoot(container); - await act(() => { - root.render( - - - New task - - - , - ); - }); - try { - const trigger = document.querySelector('[data-testid="project-picker"]')!; - await act(() => trigger.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - const backdrop = document.querySelector("[data-mobile-entity-picker]")!.parentElement!; - await act(() => { - const pointerDown = new MouseEvent("pointerdown", { bubbles: true, cancelable: true }); - Object.defineProperty(pointerDown, "pointerType", { value: "touch" }); - backdrop.dispatchEvent(pointerDown); - backdrop.click(); - }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull(); - expect(document.querySelector("[data-slot=dialog-content]")).not.toBeNull(); - expect(trigger.textContent).toContain("Board UI"); - expect(document.activeElement).toBe(trigger); - expect(onChange).not.toHaveBeenCalled(); - await act(() => trigger.click()); - expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - } finally { - await act(() => root.unmount()); - } - }); - - it("keeps handled search navigation keys inside the popover", async () => { - const root = createRoot(container); - const onChange = vi.fn(); - const documentKeyDown = vi.fn(); - document.addEventListener("keydown", documentKeyDown); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - - await act(async () => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null; - expect(searchInput).not.toBeNull(); - searchInput?.focus(); - - await act(async () => { - await Promise.resolve(); - }); - - await act(async () => { - searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "ArrowDown" })); - }); - - expect(documentKeyDown).not.toHaveBeenCalled(); - - await act(async () => { - searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Enter" })); - }); - - expect(documentKeyDown).not.toHaveBeenCalled(); - expect(onChange).toHaveBeenCalledWith("agent:agent-1"); - - document.removeEventListener("keydown", documentKeyDown); - act(() => { - root.unmount(); - }); - }); - - it("focuses the search input when opened on coarse pointers", async () => { - window.matchMedia = vi.fn().mockImplementation((query: string) => ({ - matches: query === "(pointer: coarse)" || query === "(max-width: 40rem)", - media: query, - onchange: null, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - addListener: vi.fn(), - removeListener: vi.fn(), - dispatchEvent: vi.fn(), - })); - - const root = createRoot(container); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - - await act(async () => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null; - expect(searchInput).not.toBeNull(); - expect(searchInput?.className).toContain("text-base"); - expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - expect(container.contains(document.querySelector("[data-mobile-entity-picker]"))).toBe(false); - expect(document.querySelector("[data-mobile-entity-picker-header]")?.textContent).toContain("Responsible"); - expect(document.querySelector('button[aria-label="Close selector"]')).not.toBeNull(); - expect(document.activeElement).toBe(searchInput); - - await act(async () => { - (document.querySelector('button[aria-label="Close selector"]') as HTMLButtonElement | null)?.click(); - await Promise.resolve(); - }); - expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("opens on programmatic focus without toggling an open popover closed", async () => { - const root = createRoot(container); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - - await act(async () => { - trigger?.focus(); - await Promise.resolve(); - }); - expect( - document.querySelector('input[placeholder="Search projects..."]'), - ).not.toBeNull(); - - await act(async () => { - trigger?.focus(); - await Promise.resolve(); - }); - expect( - document.querySelector('input[placeholder="Search projects..."]'), - ).not.toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("keeps the no-selection action first when requested", async () => { - const root = createRoot(container); - const onChange = vi.fn(); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement; - await act(() => trigger.click()); - - const options = Array.from( - document.querySelectorAll("[data-mobile-entity-picker-list] > button"), - ); - expect(options.map((option) => option.textContent)).toEqual([ - "No project", - "Project One", - "Project Two", - ]); - - const searchInput = document.querySelector('input[placeholder="Search projects..."]'); - const nativeInputValue = Object.getOwnPropertyDescriptor( - window.HTMLInputElement.prototype, - "value", - )?.set; - await act(() => { - nativeInputValue?.call(searchInput, "Two"); - searchInput?.dispatchEvent(new Event("input", { bubbles: true })); - }); - - const filteredOptions = Array.from( - document.querySelectorAll("[data-mobile-entity-picker-list] > button"), - ); - expect(filteredOptions.map((option) => option.textContent)).toEqual([ - "No project", - "Project Two", - ]); - - await act(() => { - searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Enter" })); - }); - expect(onChange).toHaveBeenCalledWith("project-2"); - - act(() => root.unmount()); - }); - - it("does not open the popover when disabled", async () => { - const root = createRoot(container); - const onChange = vi.fn(); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - expect(trigger?.disabled).toBe(true); - - await act(async () => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - expect(document.querySelector('input[placeholder="Search responsible..."]')).toBeNull(); - expect(onChange).not.toHaveBeenCalled(); - - act(() => { - root.unmount(); - }); - }); - - it("filters options as the user types in the search box", async () => { - const root = createRoot(container); - const onChange = vi.fn(); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - await act(async () => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null; - expect(searchInput).not.toBeNull(); - - const nativeInputValue = Object.getOwnPropertyDescriptor( - window.HTMLInputElement.prototype, - "value", - )?.set; - await act(async () => { - nativeInputValue?.call(searchInput, "design"); - searchInput?.dispatchEvent(new Event("input", { bubbles: true })); - }); - - const optionLabels = Array.from(document.querySelectorAll("[role='dialog'] button, .max-h-56 button")).map( - (el) => el.textContent ?? "", - ); - const joined = optionLabels.join("|"); - expect(joined).toContain("DesignBot"); - expect(joined).not.toContain("CodexCoder"); - - act(() => { - root.unmount(); - }); - }); -}); diff --git a/ui/src/components/InteractionGovernancePanel.test.tsx b/ui/src/components/InteractionGovernancePanel.test.tsx deleted file mode 100644 index d05da735774..00000000000 --- a/ui/src/components/InteractionGovernancePanel.test.tsx +++ /dev/null @@ -1,241 +0,0 @@ -// @vitest-environment jsdom - -import { act as reactAct } from "react"; -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { - ISSUE_THREAD_INTERACTION_KINDS, - type InteractionResolverGovernance, -} from "@paperclipai/shared"; - -// Routine offers are always answered by a person, so they have no audience row. -const INTERACTION_KINDS = ISSUE_THREAD_INTERACTION_KINDS.filter((kind) => kind !== "suggest_routine" && kind !== "propose_responsibility_bar" && kind !== "propose_automation" && kind !== "propose_dashboard_changes"); -import { - GOVERNANCE_UNSET, - InteractionGovernancePanel, - applyGovernanceChange, - toGovernanceSelectValue, -} from "./InteractionGovernancePanel"; -import { TooltipProvider } from "./ui/tooltip"; - -let root: Root | null = null; -let container: HTMLDivElement | null = null; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - if (typeof reactAct === "function") { - await reactAct(callback); - return; - } - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -function renderPanel(governance: InteractionResolverGovernance = {}, onChange = vi.fn()) { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => { - root?.render( - - - , - ); - }); - return { host: container, onChange }; -} - -/** Exact visible text of a closed select trigger (the chevron contributes none). */ -function triggerText(host: HTMLElement, testId: string): string { - const trigger = host.querySelector(`[data-testid="${testId}"]`); - expect(trigger).toBeTruthy(); - return (trigger?.textContent ?? "").replace(/\s+/g, " ").trim(); -} - -afterEach(() => { - if (root) { - act(() => root?.unmount()); - } - container?.remove(); - root = null; - container = null; -}); - -describe("InteractionGovernancePanel", () => { - it("presents Anyone as the visible default for a company with no overrides", () => { - const { host } = renderPanel(); - - const defaultSelect = host.querySelector('[data-testid="governance-request_confirmation-default"]'); - expect(defaultSelect?.textContent).toContain("Anyone (default)"); - const cap = host.querySelector('[data-testid="governance-request_confirmation-cap"]'); - expect(cap?.textContent).toContain("No cap"); - }); - - it("describes the open default without presenting it as board-required", () => { - const { host } = renderPanel(); - const copy = host.textContent ?? ""; - - expect(copy).toContain("Thread interactions are open by default"); - expect(copy).toContain("the board or any agent, including the one that asked"); - expect(copy).not.toContain("Board only"); - expect(copy).not.toContain("always require the board"); - // Governed tool approvals keep their human-only guarantee. - expect(copy).toContain("Tool-approval confirmations always stay"); - expect(copy).toContain("Human only"); - }); - - it("shows a stored narrowing override on the matching row", () => { - const { host } = renderPanel({ - request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" }, - }); - - expect( - host.querySelector('[data-testid="governance-request_confirmation-default"]')?.textContent, - ).toContain("Human only"); - expect( - host.querySelector('[data-testid="governance-request_confirmation-cap"]')?.textContent, - ).toContain("Anyone except creator"); - // Untouched kinds still read as open. - expect( - host.querySelector('[data-testid="governance-suggest_tasks-default"]')?.textContent, - ).toContain("Anyone (default)"); - }); - - /** - * PAP-17297: an empty `` lets Radix portal the selected - * option's whole subtree — label *and* effect sentence — into the closed - * trigger, where `line-clamp-1` clipped it. `toContain` assertions cannot see - * that, so these check the trigger's exact text. - */ - it("shows only the complete selected label in a closed trigger", () => { - const { host } = renderPanel(); - - for (const kind of INTERACTION_KINDS) { - expect(triggerText(host, `governance-${kind}-default`)).toBe("Anyone (default)"); - expect(triggerText(host, `governance-${kind}-cap`)).toBe("No cap"); - } - }); - - it("keeps a narrowed trigger free of the option effect sentence", () => { - const { host } = renderPanel({ - request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" }, - }); - - expect(triggerText(host, "governance-request_confirmation-default")).toBe("Human only"); - expect(triggerText(host, "governance-request_confirmation-cap")).toBe("Anyone except creator"); - // The effect prose belongs to the option list, never the trigger. - expect(host.textContent).not.toContain("New cards wait for a person on the board"); - expect(host.textContent).not.toContain("narrowed to exclude its creator"); - expect(host.textContent).not.toContain("New cards are open"); - }); - - it("still offers the effect sentence inside the open option list", async () => { - const { host } = renderPanel(); - const trigger = host.querySelector( - '[data-testid="governance-request_confirmation-default"]', - ); - expect(trigger).toBeTruthy(); - - await act(() => { - trigger?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); - }); - - const listbox = document.querySelector('[data-slot="select-content"]'); - const listText = listbox?.textContent ?? ""; - expect(listText).toContain("Anyone (default)"); - expect(listText).toContain( - "New cards are open — the board or any agent can respond, including the one that asked.", - ); - expect(listText).toContain("New cards wait for a person on the board. Agents are turned away."); - // Each option keeps a label-only typeahead value so keyboard search does not - // match the effect prose. - expect( - Array.from(listbox?.querySelectorAll('[data-slot="select-item"]') ?? []).length, - ).toBe(3); - // Reflow guard: the popover is capped so long prose wraps instead of - // stretching past a narrow viewport. - expect(listbox?.className).toContain("max-w-(--sz-280px)"); - }); - - it("renders a select for every governable interaction kind", () => { - const { host } = renderPanel(); - expect(host.querySelector('[data-testid="governance-suggest_routine-default"]')).toBeNull(); - expect(host.querySelector('[data-testid="governance-propose_responsibility_bar-default"]')).toBeNull(); - expect(host.querySelector('[data-testid="governance-propose_automation-default"]')).toBeNull(); - expect(host.querySelector('[data-testid="governance-propose_dashboard_changes-default"]')).toBeNull(); - expect(host.querySelectorAll('[data-testid$="-default"]')).toHaveLength( - INTERACTION_KINDS.length, - ); - expect(host.querySelectorAll('[data-testid$="-cap"]')).toHaveLength( - INTERACTION_KINDS.length, - ); - }); - - it("surfaces a save failure", () => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => { - root?.render( - - - , - ); - }); - expect(container.textContent).toContain("Failed to save interaction governance"); - }); -}); - -describe("toGovernanceSelectValue", () => { - it("treats an absent override as the open default", () => { - expect(toGovernanceSelectValue(undefined)).toBe(GOVERNANCE_UNSET); - }); - - it("treats a stored open audience — canonical or legacy alias — as the default", () => { - expect(toGovernanceSelectValue("anyone")).toBe(GOVERNANCE_UNSET); - expect(toGovernanceSelectValue("board_or_agents")).toBe(GOVERNANCE_UNSET); - }); - - it("canonicalizes stored narrowing values, including the legacy board_only alias", () => { - expect(toGovernanceSelectValue("not_creator")).toBe("not_creator"); - expect(toGovernanceSelectValue("human_only")).toBe("human_only"); - expect(toGovernanceSelectValue("board_only")).toBe("human_only"); - }); -}); - -describe("applyGovernanceChange", () => { - it("stores a narrowing override", () => { - expect(applyGovernanceChange({}, "request_confirmation", "defaultPolicy", "human_only")).toEqual({ - request_confirmation: { defaultPolicy: "human_only" }, - }); - }); - - it("clears the override when the open default is re-selected", () => { - const current: InteractionResolverGovernance = { - request_confirmation: { defaultPolicy: "human_only" }, - }; - expect( - applyGovernanceChange(current, "request_confirmation", "defaultPolicy", GOVERNANCE_UNSET), - ).toEqual({}); - // Immutable: the caller's map is untouched. - expect(current.request_confirmation?.defaultPolicy).toBe("human_only"); - }); - - it("keeps a sibling field when only one is cleared", () => { - const current: InteractionResolverGovernance = { - request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" }, - }; - expect(applyGovernanceChange(current, "request_confirmation", "cap", GOVERNANCE_UNSET)).toEqual({ - request_confirmation: { defaultPolicy: "human_only" }, - }); - }); -}); diff --git a/ui/src/components/IssueRow.test.tsx b/ui/src/components/IssueRow.test.tsx deleted file mode 100644 index 0d03ba29ac7..00000000000 --- a/ui/src/components/IssueRow.test.tsx +++ /dev/null @@ -1,968 +0,0 @@ -// @vitest-environment jsdom - -import { act as reactAct } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import type { Issue } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { IssueRow } from "./IssueRow"; -import { StatusIcon } from "./StatusIcon"; -import { TooltipProvider } from "./ui/tooltip"; - -vi.mock("@/lib/router", () => ({ - Link: ({ - children, - className, - to, - disableIssueQuicklook: _disableIssueQuicklook, - issuePrefetch, - ...props - }: React.ComponentProps<"a"> & { to?: string; disableIssueQuicklook?: boolean; issuePrefetch?: Issue | null }) => ( - - {children} - - ), -})); - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -function act(callback: () => void) { - if (typeof reactAct === "function") { - reactAct(callback); - return; - } - - flushSync(callback); -} - -function createIssue(overrides: Partial = {}): Issue { - return { - id: "issue-1", - identifier: "PAP-1", - companyId: "company-1", - projectId: null, - projectWorkspaceId: null, - goalId: null, - parentId: null, - title: "Inbox item", - description: null, - status: "todo", - priority: "medium", - reviewPolicy: null, - assigneeAgentId: null, - assigneeUserId: null, - responsibleUserId: null, - createdByAgentId: null, - createdByUserId: null, - issueNumber: 1, - requestDepth: 0, - billingCode: null, - assigneeAdapterOverrides: null, - executionWorkspaceId: null, - executionWorkspacePreference: null, - executionWorkspaceSettings: null, - checkoutRunId: null, - executionRunId: null, - executionAgentNameKey: null, - executionLockedAt: null, - startedAt: null, - completedAt: null, - cancelledAt: null, - hiddenAt: null, - createdAt: new Date("2026-03-11T00:00:00.000Z"), - updatedAt: new Date("2026-03-11T00:00:00.000Z"), - labels: [], - labelIds: [], - myLastTouchAt: null, - lastExternalCommentAt: null, - isUnreadForMe: false, - ...overrides, - workMode: overrides.workMode ?? "standard", - }; -} - -describe("IssueRow", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - vi.unstubAllGlobals(); - }); - - it("renders the list status glyph at md (16px)", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - // jsdom 30 does not value-match a CSS attribute selector against a - // mixed-case SVG attribute name, so `svg[viewBox="0 0 24 24"]` matches - // nothing. Select the glyph SVGs by attribute presence, then compare the - // viewBox value with getAttribute to keep the exact-value assertion. - const glyphs = Array.from(container.querySelectorAll("svg[viewBox]")).filter( - (svg) => svg.getAttribute("viewBox") === "0 0 24 24", - ); - expect(glyphs.length).toBeGreaterThan(0); - glyphs.forEach((glyph) => { - expect(glyph.getAttribute("width")).toBe("16"); - expect(glyph.getAttribute("height")).toBe("16"); - }); - - act(() => { - root.unmount(); - }); - }); - - it("uses stable canonical identifier and timestamp columns at the trailing edge", () => { - const root = createRoot(container); - - act(() => { - root.render( - Live} - actions={} - trailingMeta="Updated now" - />, - ); - }); - - const row = container.querySelector('[data-slot="task-row"]'); - const leading = row?.querySelector('[data-slot="task-row-leading"]'); - const title = row?.querySelector('[data-slot="task-row-title"]'); - const metadata = row?.querySelector('[data-slot="task-row-metadata"]'); - const identifier = row?.querySelector('[data-slot="task-row-identifier"]'); - const timestamp = row?.querySelector('[data-slot="task-row-timestamp"]'); - const actions = row?.querySelector('[data-slot="task-row-actions"]'); - const link = row?.querySelector('[data-inbox-issue-link]'); - - expect(leading?.querySelector("svg")).not.toBeNull(); - expect(title?.textContent).toContain("Canonical task"); - expect(metadata?.textContent).toBe("Live"); - expect(identifier?.textContent).toBe("PAP-42"); - expect(timestamp?.textContent).toBe("Updated now"); - expect(actions?.textContent).toBe("More"); - expect(identifier?.className).toContain("w-20"); - expect(timestamp?.className).toContain("w-24"); - if (!link || !metadata || !identifier || !timestamp || !actions) throw new Error("Expected canonical task row slots"); - expect(link.contains(actions)).toBe(false); - expect(metadata.compareDocumentPosition(actions) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(actions.compareDocumentPosition(identifier) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(identifier.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(timestamp.nextElementSibling).toBeNull(); - - act(() => root.unmount()); - }); - - it("keeps the canonical archive action within the shared task-row height", () => { - const root = createRoot(container); - - act(() => { - root.render( - undefined} - />, - ); - }); - - const archiveButton = container.querySelector('button[aria-label="Archive"]'); - expect(archiveButton?.className).toContain("h-5"); - expect(archiveButton?.className).toContain("py-0"); - expect(archiveButton?.className).not.toContain("py-1"); - - act(() => root.unmount()); - }); - - it("restores a task independently of its row link", () => { - const root = createRoot(container); - const restore = vi.fn(); - act(() => root.render( - - - , - )); - - const button = container.querySelector('button[aria-label="Restore from archive"]')!; - expect(button.closest("a")).toBeNull(); - act(() => button.click()); - expect(restore).toHaveBeenCalledOnce(); - act(() => root.unmount()); - }); - - it("starts a truncated title reveal on link focus and keeps actions independent", async () => { - const bounds = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 200, 16)); - const createRange = document.createRange.bind(document); - const rangeBounds = vi.spyOn(document, "createRange").mockImplementation(() => Object.assign(createRange(), { - getBoundingClientRect: () => new DOMRect(0, 0, 400, 16), - })); - vi.stubGlobal("ResizeObserver", class { - observe() {} - unobserve() {} - disconnect() {} - }); - const root = createRoot(container); - const title = "Define connector health states, failure recovery, and escalation ownership across teams"; - const onExpand = vi.fn(); - const onArchive = vi.fn(); - const onMarkRead = vi.fn(); - - act(() => { - root.render( - - Expand subtasks} - onArchive={onArchive} - /> - , - ); - }); - - const link = container.querySelector("[data-inbox-issue-link]"); - const expand = container.querySelector('button:not([aria-label])'); - const archive = container.querySelector('button[aria-label="Archive"]'); - expect(link?.href).toContain("/issues/PAP-1"); - expect(link?.contains(expand)).toBe(false); - expect(link?.contains(archive)).toBe(false); - // An inbox callback must not restore the old unread dot or its reserved slot. - expect(container.querySelector('button[aria-label="Mark as read"]')).toBeNull(); - expect(container.querySelector('[data-testid="issue-row-unread-slot"]')).toBeNull(); - - await reactAct(async () => link?.focus()); - expect(document.activeElement).toBe(link); - expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBe("true"); - expect(container.querySelector('[data-slot="task-row-title-text"]')?.textContent).toBe(title); - expect(document.querySelector('[role="tooltip"]')).toBeNull(); - - act(() => link?.dispatchEvent(new MouseEvent("mouseout", { bubbles: true, relatedTarget: document.body }))); - expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBeNull(); - await reactAct(async () => { link?.blur(); link?.focus(); }); - expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBe("true"); - - act(() => { - link?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - expand?.click(); - archive?.click(); - }); - expect(document.querySelector('[role="tooltip"]')).toBeNull(); - expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBeNull(); - expect(onExpand).toHaveBeenCalledTimes(1); - expect(onArchive).toHaveBeenCalledTimes(1); - - act(() => root.unmount()); - bounds.mockRestore(); - rangeBounds.mockRestore(); - }); - - it("preserves the legacy archive action density", () => { - const root = createRoot(container); - - act(() => { - root.render( undefined} />); - }); - - const archiveButton = container.querySelector('button[aria-label="Archive"]'); - expect(archiveButton?.className).toContain("py-1"); - expect(archiveButton?.className).not.toContain("h-5"); - - act(() => root.unmount()); - }); - - it("emphasizes unread canonical titles and overlays the accessible mark-read control", () => { - const root = createRoot(container); - const onMarkRead = vi.fn(); - act(() => { - root.render( - , - ); - }); - - const row = container.querySelector('[data-slot="task-row"]'); - const title = row?.querySelector('[data-slot="task-row-title"]'); - const unreadSlot = row?.querySelector('[data-testid="issue-row-unread-slot"]'); - const markReadButton = unreadSlot?.querySelector('button[aria-label="Mark as read"]'); - expect(row?.getAttribute("data-unread")).toBe("true"); - expect(title?.className).toContain("font-semibold"); - expect(unreadSlot).not.toBeNull(); - expect(unreadSlot?.className).toContain("absolute"); - expect(markReadButton).not.toBeNull(); - expect(markReadButton?.closest("a")).toBeNull(); - - act(() => markReadButton?.click()); - expect(onMarkRead).toHaveBeenCalledTimes(1); - - act(() => root.unmount()); - }); - - it("keeps read and unread rows aligned while allowing a smaller plain-row gutter", () => { - const root = createRoot(container); - act(() => { - root.render( - <> - - - - , - ); - }); - - const rows = Array.from(container.querySelectorAll('[data-slot="task-row"]')); - const unreadSlot = rows[0]?.querySelector('[data-testid="issue-row-unread-slot"]'); - expect(rows).toHaveLength(3); - expect(rows[0]?.className).toBe(rows[2]?.className); - expect(rows[1]?.className).toContain("pl-2 sm:pl-4"); - expect(unreadSlot).not.toBeNull(); - expect(unreadSlot?.className).toContain("absolute"); - expect(unreadSlot?.querySelector('button[aria-label="Mark as read"]')).toBeNull(); - expect(rows[1]?.querySelector('[data-testid="issue-row-unread-slot"]')).toBeNull(); - - act(() => root.unmount()); - }); - - it("preserves task-tree indentation slots in the canonical layout", () => { - const root = createRoot(container); - act(() => { - root.render( - Expand} - />, - ); - }); - - expect(container.querySelectorAll('[data-slot="task-row-tree-guide"]')).toHaveLength(2); - expect(container.querySelector('[data-slot="task-row-leading"]')?.textContent).toContain("Expand"); - for (const connector of container.querySelectorAll('[data-slot="task-row-tree-connector"]')) { - expect(connector.className).toContain("left-7"); - } - act(() => root.unmount()); - }); - - it("keeps editable row controls keyboard-accessible and outside the navigation link", () => { - const root = createRoot(container); - - act(() => { - root.render( - undefined} />} - />, - ); - }); - - const link = container.querySelector("[data-inbox-issue-link]"); - const statusButton = container.querySelector( - 'button[aria-label="Change status (current: Todo)"]', - ); - - expect(link).not.toBeNull(); - expect(statusButton).not.toBeNull(); - expect(statusButton?.tabIndex).toBe(0); - expect(link?.contains(statusButton)).toBe(false); - - act(() => { - root.unmount(); - }); - }); - - it("suppresses accent hover styling when the row is selected", () => { - const root = createRoot(container); - const issue = createIssue(); - - act(() => { - root.render(); - }); - - // The hover wash lives on the ROOT row band (not the overlay link) so the - // tint paints behind the content. Selected rows suppress the accent hover. - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(row).not.toBeNull(); - expect(row?.className).toContain("hover:bg-transparent"); - expect(row?.className).not.toContain("hover:bg-accent/50"); - // The overlay link no longer carries the hover wash. - expect(link?.className ?? "").not.toContain("hover:bg-transparent"); - expect(link?.className ?? "").not.toContain("hover:bg-accent/50"); - - act(() => { - root.unmount(); - }); - }); - - it("neutralizes selected status and unread dot accents", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const markReadButton = container.querySelector('button[aria-label="Mark as read"]'); - const unreadDot = markReadButton?.querySelector("span"); - // Selected rows neutralize the status glyph to muted via `!`-important - // utilities, which override the glyph's inline colour var. The glyph is an - // (SVGAnimatedString className), so match on the class attribute. - const statusGlyph = container.querySelector('svg[class*="text-muted-foreground"]'); - - expect(markReadButton).not.toBeNull(); - expect(markReadButton?.className).toContain("hover:bg-muted/80"); - expect(markReadButton?.className).not.toContain("hover:bg-blue-500/20"); - expect(unreadDot).not.toBeNull(); - expect(unreadDot?.className).toContain("bg-muted-foreground/70"); - expect(unreadDot?.className).not.toContain("bg-blue-600"); - expect(statusGlyph).not.toBeNull(); - expect(statusGlyph?.getAttribute("class")).toContain("!text-muted-foreground"); - expect(statusGlyph?.getAttribute("class")).toContain("!border-muted-foreground"); - - act(() => { - root.unmount(); - }); - }); - - it("reserves the leading dot slot on read rows so unread rows never indent past them", () => { - const root = createRoot(container); - act(() => { - // A read inbox row still supplies `unreadState` (as "hidden"). - root.render(); - }); - - // The desktop dot slot is reserved even when read (empty), so unread rows - // add no column and line up with read rows. - const slot = container.querySelector('[data-testid="issue-row-unread-slot"]'); - expect(slot).not.toBeNull(); - expect(slot?.className).toContain("w-4"); - expect(slot?.className).toContain("sm:inline-flex"); - // In flow, not an absolute overlay. - expect(slot?.className).not.toContain("absolute"); - // Read rows carry no dot button in the slot. - expect(slot?.querySelector('button[aria-label="Mark as read"]')).toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("puts the unread dot in the reserved desktop slot and overlays it on mobile", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - - // Desktop: the dot lives in the reserved leading slot (far left, ahead of - // any leading control such as a parent's collapse caret). - const slot = container.querySelector('[data-testid="issue-row-unread-slot"]'); - expect(slot).not.toBeNull(); - expect(slot?.querySelector('button[aria-label="Mark as read"]')).not.toBeNull(); - - // Mobile: all inbox rows reserve a gutter and the dot stays fully inside - // it, so the control cannot be clipped or indent the status/title. - const mobileDot = container - .querySelector('button[aria-label="Mark as read"].sm\\:hidden, span.sm\\:hidden button[aria-label="Mark as read"]') - ?.closest("span.sm\\:hidden"); - expect(mobileDot).not.toBeNull(); - expect(mobileDot?.className).toContain("absolute"); - expect(mobileDot?.className).toContain("left-0"); - expect(mobileDot?.className).not.toContain("order-first"); - expect(container.firstElementChild?.className).toContain("pl-4"); - - act(() => { - root.unmount(); - }); - }); - - it("preserves the issue detail breadcrumb source and href in the link target", () => { - const root = createRoot(container); - const issue = createIssue(); - const state = { - issueDetailBreadcrumb: { label: "Inbox", href: "/PAP/inbox/mine" }, - issueDetailSource: "inbox", - }; - - act(() => { - root.render(); - }); - - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(link).not.toBeNull(); - expect(link?.getAttribute("to") ?? link?.getAttribute("href")).toBe("/issues/PAP-1"); - - act(() => { - root.unmount(); - }); - }); - - it("opts issue quicklook out for dense inbox rows", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(link).not.toBeNull(); - expect(link?.getAttribute("data-disable-issue-quicklook")).toBe("true"); - - act(() => { - root.unmount(); - }); - }); - - it("passes the visible row issue into the navigation prefetch path", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(link?.getAttribute("data-issue-prefetch-id")).toBe("issue-1"); - - act(() => { - root.unmount(); - }); - }); - - it("renders titleSuffix inline after the issue title", () => { - const root = createRoot(container); - const issue = createIssue({ title: "Parent task" }); - - act(() => { - root.render( - (3 sub-tasks)} - />, - ); - }); - - const titleEl = container.querySelector(".line-clamp-2, .truncate"); - expect(titleEl?.textContent).toContain("Parent task"); - expect(titleEl?.textContent).toContain("(3 sub-tasks)"); - expect(container.querySelector('[data-testid="suffix"]')).not.toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("renders checklist step numbers beside the issue identifier", () => { - const root = createRoot(container); - - act(() => { - root.render( - , - ); - }); - - const metaRow = Array.from(container.querySelectorAll("span.flex.items-center.gap-2")) - .find((element) => element.textContent?.includes("PAP-42")); - - expect(metaRow).not.toBeUndefined(); - expect(metaRow?.textContent?.replace(/\s+/g, "")).toContain("2.1.PAP-42"); - - act(() => { - root.unmount(); - }); - }); - - it("marks the current checklist step without adding a left border", () => { - const root = createRoot(container); - - act(() => { - root.render( - , - ); - }); - - // `aria-current="step"` stays on the overlay link (the focusable target), - // but the current-step wash moved to the ROOT row band alongside the hover - // wash so it paints behind the content. - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - - expect(link).not.toBeNull(); - expect(link?.getAttribute("aria-current")).toBe("step"); - expect(row?.className).toContain("bg-primary/5"); - expect(row?.className).not.toContain("border-l-"); - expect(link?.className ?? "").not.toContain("bg-primary/5"); - - act(() => { - root.unmount(); - }); - }); - - it("does not render a planning mode marker for planning work mode issues", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(link).not.toBeNull(); - expect(link?.textContent).not.toContain("Planning"); - - act(() => { - root.unmount(); - }); - }); - - it("renders without error when titleSuffix is omitted", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const titleEl = container.querySelector(".line-clamp-2, .truncate"); - expect(titleEl?.textContent).toContain("Inbox item"); - - act(() => { - root.unmount(); - }); - }); - - it("flags rows blocked by an assigned-backlog leaf with a parked-work badge", () => { - const root = createRoot(container); - const issue = createIssue({ - blockedBy: [ - { - id: "blocker-1", - identifier: "PAP-2", - title: "Parked child", - status: "backlog", - priority: "high", - assigneeAgentId: "agent-99", - assigneeUserId: null, - }, - ], - }); - - act(() => { - root.render(); - }); - - const badges = container.querySelectorAll('[data-testid="issue-row-parked-blocker"]'); - expect(badges.length).toBeGreaterThan(0); - expect(badges[0]?.textContent).toContain("Blocked by parked work"); - - act(() => { - root.unmount(); - }); - }); - - it("does not show the parked-work badge when assigned blocker is not in backlog", () => { - const root = createRoot(container); - const issue = createIssue({ - blockedBy: [ - { - id: "blocker-1", - identifier: "PAP-2", - title: "Active child", - status: "in_progress", - priority: "high", - assigneeAgentId: "agent-99", - assigneeUserId: null, - }, - ], - }); - - act(() => { - root.render(); - }); - - expect(container.querySelector('[data-testid="issue-row-parked-blocker"]')).toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("renders no bottom divider by default", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - // Dividers are opt-in: without `showDivider` no row-separating border - // renders on either the root band or the overlay link. - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(row).not.toBeNull(); - expect(row?.className).not.toContain("border-b"); - expect(link?.className ?? "").not.toContain("border-b"); - - act(() => { - root.unmount(); - }); - }); - - it("renders an opt-in bottom divider on the row root when showDivider is set", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - // The divider lives on the ROOT row band with `last:border-b-0` so the real - // last row drops its border — it is not on the overlay link. - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(row?.className).toContain("border-b"); - expect(row?.className).toContain("last:border-b-0"); - expect(link?.className ?? "").not.toContain("border-b"); - - act(() => { - root.unmount(); - }); - }); - - it("never renders a horizontal divider in canonical task presentation", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const row = container.querySelector('[data-slot="task-row"]'); - expect(row?.className).not.toContain("border-b"); - - act(() => root.unmount()); - }); - - it("keeps the hover wash on the row root while the overlay link stays a bare positioning layer", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - // Hover wash paints behind the content on the root band... - expect(row?.className).toContain("hover:bg-accent/50"); - expect(link?.className ?? "").not.toContain("hover:bg-accent/50"); - // ...and the overlay link keeps only positioning + focus concerns. - expect(link?.className).toContain("absolute"); - expect(link?.className).toContain("inset-0"); - - act(() => { - root.unmount(); - }); - }); - - describe("recovery chip liveness", () => { - const NOW = new Date("2026-08-18T12:00:00.000Z"); - - beforeEach(() => { - vi.useFakeTimers(); - vi.setSystemTime(NOW); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - function at(offsetMs: number) { - return new Date(NOW.getTime() + offsetMs).toISOString(); - } - - function recoveryIssue(retryAt: string, scheduledRetry: Issue["scheduledRetry"] = null): Issue { - return createIssue({ - status: "in_progress", - scheduledRetry, - activeRecoveryAction: { - id: "action-1", - companyId: "company-1", - sourceIssueId: "issue-1", - recoveryIssueId: null, - kind: "deliberate_wait_without_target", - status: "active", - ownerType: "agent", - ownerAgentId: "agent-owner", - ownerUserId: null, - previousOwnerAgentId: "agent-owner", - returnOwnerAgentId: "agent-owner", - cause: "deliberate_wait_without_target", - fingerprint: "fp", - evidence: {}, - nextAction: "Record a real next step.", - wakePolicy: { - type: "bounded_owner_disposition_repair", - retryAgentId: "agent-owner", - attempt: 1, - maxAttempts: 5, - retryAt, - scheduledRunId: "run-2", - }, - monitorPolicy: null, - attemptCount: 1, - maxAttempts: 5, - timeoutAt: retryAt, - lastAttemptAt: retryAt, - outcome: null, - resolutionNote: null, - resolvedAt: null, - createdAt: at(-10 * 60_000), - updatedAt: at(-10 * 60_000), - }, - }); - } - - function renderChip(issue: Issue): HTMLElement | null { - const root = createRoot(container); - act(() => { - root.render(); - }); - const chip = container.querySelector( - "[data-testid='issue-row-recovery-indicator']", - ); - const snapshot = chip?.cloneNode(true) as HTMLElement | null; - act(() => { - root.unmount(); - }); - return snapshot; - } - - it.each(["working", "retry_scheduled", "failed"] as const)( - "omits %s system interruption feedback without exposing legacy recovery in list rows", - (state) => { - const root = createRoot(container); - const issue = recoveryIssue(at(3 * 60_000)); - issue.interruption = { - intentId: "saved-input", responsibility: "system", state, - nextRetryAt: state === "retry_scheduled" ? at(3 * 60_000) : null, - canRetry: state === "failed", userAction: null, - sourceRunIds: ["run-1"], observedRunId: "run-1", - }; - try { - for (const presentation of ["task", "legacy"] as const) { - act(() => root.render()); - expect(container.textContent).toContain(issue.title); - expect(container.querySelector("[data-inbox-issue-link]")?.getAttribute("href")).toBe("/issues/PAP-1"); - expect(container.textContent).not.toMatch(/Retry available|Thinking|Trying again soon|Recovery in progress/); - expect(container.querySelector("[data-testid='issue-row-recovery-indicator']")).toBeNull(); - } - } finally { - act(() => root.unmount()); - } - }, - ); - - it("shows native export activity from the action even without a scheduled retry", () => { - const issue = recoveryIssue(at(-5 * 60_000)); - Object.assign(issue.activeRecoveryAction!, { - kind: "active_run_watchdog", cause: "native_finalization_invalid", - wakePolicy: { kind: "resume_native_run", runId: "native-run", notBefore: at(-5 * 60_000) }, - nativeRunActivity: { runId: "native-run", status: "running", workspaceOperationId: "export-operation" }, - }); - const chip = renderChip(issue); - expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress"); - expect(chip?.getAttribute("aria-label")).not.toContain("missed"); - }); - - it("stays calm while the next attempt is still ahead", () => { - const chip = renderChip(recoveryIssue(at(3 * 60_000))); - expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress"); - expect(chip?.getAttribute("aria-label")).toContain("next try in 3m"); - }); - - it("warns once the stored attempt came due and never ran", () => { - // The inbox chip must reach the same verdict as the source card, so a parent scanning - // the inbox is not told recovery is running when nothing is. - const chip = renderChip(recoveryIssue(at(-5 * 60_000))); - expect(chip?.getAttribute("data-recovery-state")).toBe("needed"); - const label = chip?.getAttribute("aria-label") ?? ""; - expect(label).toContain("Recovery needed"); - expect(label).toContain("retry missed 5m ago"); - expect(label).not.toContain("next try"); - }); - - it.each(["task", "legacy"] as const)( - "places the recovery chip immediately after the title in %s list rows", - (presentation) => { - const root = createRoot(container); - act(() => { - root.render( - , - ); - }); - - const titleCluster = container.querySelector('[data-slot="task-row-title-cluster"]'); - const title = titleCluster?.querySelector('[data-slot="task-row-title"]'); - const chip = titleCluster?.querySelector('[data-testid="issue-row-recovery-indicator"]'); - expect(titleCluster).not.toBeNull(); - expect(title).not.toBeNull(); - expect(chip).not.toBeNull(); - if (!title || !chip) throw new Error("Expected the title and recovery chip"); - expect(title.compareDocumentPosition(chip) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - - act(() => { - root.unmount(); - }); - }, - ); - - it("stays calm when the overdue attempt is a verified live run", () => { - const chip = renderChip( - recoveryIssue(at(-5 * 60_000), { - runId: "run-2", - status: "running", - agentId: "agent-owner", - agentName: "CodexCoder", - retryOfRunId: null, - scheduledRetryAt: at(-5 * 60_000), - scheduledRetryAttempt: 1, - scheduledRetryReason: null, - }), - ); - expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress"); - expect(chip?.getAttribute("aria-label")).toContain("attempt running now"); - }); - }); -}); diff --git a/ui/src/components/MarkdownEditor.autocomplete.test.tsx b/ui/src/components/MarkdownEditor.autocomplete.test.tsx deleted file mode 100644 index 9e5181e2b4f..00000000000 --- a/ui/src/components/MarkdownEditor.autocomplete.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -// @vitest-environment jsdom - -import { act, useState } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { $getSelection, $isRangeSelection, getNearestEditorFromDOMNode } from "lexical"; -import { buildSkillMentionHref } from "@paperclipai/shared"; -import { MarkdownEditor, type MentionOption } from "./MarkdownEditor"; -import type { SlashCommandOption } from "../context/EditorAutocompleteContext"; - -const mentions: MentionOption[] = [ - { id: "agent:ada", kind: "agent", agentId: "ada", name: "Ada" }, - { id: "user:pat", kind: "user", userId: "pat", name: "Pat" }, - { id: "project:paperclip", kind: "project", projectId: "paperclip", name: "Paperclip" }, - { id: "issue:task", kind: "issue", issueIdentifier: "TST-123", name: "TST-123 Example task" }, -]; - -const commands: SlashCommandOption[] = [ - { - id: "skill:deploy", kind: "skill", skillId: "deploy", key: "deploy", name: "Deploy", - slug: "deploy", description: null, href: buildSkillMentionHref("deploy", "deploy"), aliases: ["deploy"], - }, - { - id: "routine:nightly", kind: "routine", routineId: "nightly", name: "Nightly", - status: "active", href: "routine://nightly", aliases: ["routine:Nightly"], - }, - { id: "action:goal", kind: "action", command: "goal", name: "Goal", description: "Set a goal", aliases: ["goal"] }, -]; - -describe("MarkdownEditor autocomplete separators", () => { - let container: HTMLDivElement; - let root: ReturnType; - let originalRangeRect: typeof Range.prototype.getBoundingClientRect; - - beforeEach(() => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.stubGlobal("ResizeObserver", class { - observe() {} - unobserve() {} - disconnect() {} - }); - originalRangeRect = Range.prototype.getBoundingClientRect; - Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 10, 20); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - }); - - afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - Range.prototype.getBoundingClientRect = originalRangeRect; - vi.restoreAllMocks(); - vi.unstubAllGlobals(); - }); - - it.each([ - ["skill", "/dep", "/deploy", true, ""], - ["routine", "/routine:Nigh", "/routine:Nightly", true, ""], - ["action", "/go", "/goal", false, ""], - ["agent", "@Ada", "@Ada", true, ""], - ["user", "@Pat", "@Pat", true, ""], - ["project", "@Paper", "@Paperclip", true, ""], - ["task", "@TST", "TST-123", true, ""], - ["project after a typed space", "@Paperclip", "@Paperclip", true, " "], - ["routine after typed spaces", "/routine:Nightly", "/routine:Nightly", true, " "], - ])("keeps a space after a completed %s and types outside its link", async (_kind, value, completion, linked, typedSuffix) => { - const onChange = vi.fn(); - function ControlledEditor() { - const [markdown, setMarkdown] = useState(value); - return { - onChange(next); - setMarkdown(next); - }} actionCommands={commands} mentions={mentions} />; - } - await act(async () => { - root.render(); - }); - - const editable = container.querySelector('[contenteditable="true"]')!; - expect(editable).not.toBeNull(); - await act(async () => { - editable.focus(); - const range = document.createRange(); - range.selectNodeContents(editable.querySelector('[data-lexical-text="true"]')!.firstChild!); - range.collapse(false); - const selection = window.getSelection()!; - selection.removeAllRanges(); - selection.addRange(range); - document.dispatchEvent(new Event("selectionchange")); - }); - if (typedSuffix) { - const editor = getNearestEditorFromDOMNode(editable)!; - await act(async () => { - editor.update(() => { - const selection = $getSelection(); - expect($isRangeSelection(selection)).toBe(true); - if ($isRangeSelection(selection)) selection.insertText(typedSuffix); - }); - }); - await act(async () => document.dispatchEvent(new Event("selectionchange"))); - } - await vi.waitFor(() => expect(document.querySelector('[data-testid="mention-autocomplete-menu"]')).not.toBeNull()); - - await act(async () => { - editable.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true })); - }); - await vi.waitFor(() => { - expect(editable.textContent).toBe(`${completion} `); - expect(editable.querySelector("a")?.textContent ?? null).toBe(linked ? completion : null); - const caretPrefix = document.createRange(); - caretPrefix.selectNodeContents(editable); - const selection = window.getSelection()!; - caretPrefix.setEnd(selection.anchorNode!, selection.anchorOffset); - expect(caretPrefix.toString()).toBe(`${completion} `); - }); - expect(onChange.mock.lastCall?.[0]).toMatch(/ $/); - expect(onChange.mock.lastCall?.[0]).not.toContain("\u00a0"); - expect(document.querySelector('[data-testid="mention-autocomplete-menu"]')).toBeNull(); - - const editor = getNearestEditorFromDOMNode(editable)!; - await act(async () => { - document.dispatchEvent(new Event("selectionchange")); - editor.update(() => { - const selection = $getSelection(); - expect($isRangeSelection(selection)).toBe(true); - if ($isRangeSelection(selection)) selection.insertText("next"); - }); - }); - expect(editable.textContent).toBe(`${completion} next`); - expect(editable.querySelector("a")?.textContent ?? null).toBe(linked ? completion : null); - expect(onChange.mock.lastCall?.[0]).toMatch(/ next$/); - expect(onChange.mock.lastCall?.[0]).not.toContain("\u00a0"); - }); -}); diff --git a/ui/src/components/QueryView.test.tsx b/ui/src/components/QueryView.test.tsx deleted file mode 100644 index d3a7990337d..00000000000 --- a/ui/src/components/QueryView.test.tsx +++ /dev/null @@ -1,306 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ApiError } from "@/api/client"; -import { ConnectivityProvider, createConnectivityStore, type ConnectivityStore } from "@/lib/connectivity"; -import { QueryErrorState, QueryView, queryViewKind, useQueryView, type QueryViewState } from "./QueryView"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -const unavailable = () => new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }); -const notFound = () => new ApiError("Issue not found", 404, { error: "Issue not found" }); -const forbidden = () => new ApiError("Forbidden", 403, { error: "Forbidden" }); - -describe("queryViewKind", () => { - const base = { data: undefined, error: null, status: "pending" as const, fetchStatus: "fetching" as const }; - - it("loads, then is ready", () => { - expect(queryViewKind(base)).toBe("loading"); - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "idle" })).toBe("ready"); - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "fetching" })).toBe("ready"); - }); - - it("keeps data through a transient failure (stale) and shows an error only for real failures", () => { - expect(queryViewKind({ ...base, data: 1, status: "error", error: unavailable() })).toBe("stale"); - expect(queryViewKind({ ...base, data: 1, status: "error", error: notFound() })).toBe("error"); - expect(queryViewKind({ ...base, data: 1, status: "error", error: forbidden() })).toBe("error"); - }); - - it("reconnects quietly when nothing has loaded yet and the app is waiting out an outage", () => { - expect(queryViewKind({ ...base, status: "error", error: unavailable() }, "reconnecting")).toBe("reconnecting"); - expect(queryViewKind({ ...base, status: "error", error: unavailable() }, "offline")).toBe("reconnecting"); - expect(queryViewKind({ ...base, status: "error", error: new TypeError("Failed to fetch") }, "reconnecting")).toBe("reconnecting"); - expect(queryViewKind({ ...base, status: "error", error: notFound() }, "reconnecting")).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: new Error("boom") }, "reconnecting")).toBe("error"); - }); - - it("shows retryable copy when a route keeps failing while the server is reachable", () => { - // Nothing would refetch these: the probe loop only runs while the app is - // not online. A placeholder here would never fill in. - expect(queryViewKind({ ...base, status: "error", error: unavailable() })).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: new ApiError("Gateway timeout", 504, "upstream timed out") })).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: new TypeError("Failed to fetch") })).toBe("error"); - }); - - it("shows retryable copy for a route-level blip with no data, but keeps data through it", () => { - const busy = new ApiError("Too many requests", 429, { error: "rate_limited" }); - const worker = new ApiError("WORKER_UNAVAILABLE", 503, { code: "WORKER_UNAVAILABLE", message: "restarting" }); - expect(queryViewKind({ ...base, status: "error", error: busy })).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: worker })).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: busy }, "reconnecting")).toBe("reconnecting"); - expect(queryViewKind({ ...base, data: 1, status: "error", error: busy })).toBe("stale"); - expect(queryViewKind({ ...base, data: 1, status: "error", error: worker })).toBe("stale"); - }); - - it("treats a paused fetch and in-flight transient retries as an outage", () => { - expect(queryViewKind({ ...base, fetchStatus: "paused" })).toBe("reconnecting"); - expect(queryViewKind({ ...base, failureReason: unavailable() })).toBe("reconnecting"); - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "paused" })).toBe("stale"); - expect(queryViewKind({ ...base, data: 1, status: "success", failureReason: unavailable() })).toBe("stale"); - }); - - it("follows the app-wide connectivity state", () => { - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "fetching" }, "reconnecting")).toBe("stale"); - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "idle" }, "reconnecting")).toBe("stale"); - expect(queryViewKind(base, "offline")).toBe("reconnecting"); - // A disabled query is not waiting on the network. - expect(queryViewKind({ ...base, fetchStatus: "idle" }, "reconnecting")).toBe("loading"); - }); - - it("does not treat null data as missing", () => { - expect(queryViewKind({ ...base, data: null, status: "success", fetchStatus: "idle" })).toBe("ready"); - expect(queryViewKind({ ...base, data: null, status: "error", error: unavailable() })).toBe("stale"); - }); -}); - -type Deferred = { promise: Promise; resolve: (value: T) => void; reject: (error: unknown) => void }; -function deferred(): Deferred { - let resolve!: (value: T) => void; - let reject!: (error: unknown) => void; - const promise = new Promise((nextResolve, nextReject) => { - resolve = nextResolve; - reject = nextReject; - }); - return { promise, resolve, reject }; -} - -describe("useQueryView and ", () => { - let container: HTMLDivElement; - let root: Root; - let client: QueryClient; - let store: ConnectivityStore; - let probe: ReturnType Promise<{ reachable: true }>>>; - let attempts: Deferred<{ title: string }>[]; - let fetchCount: number; - let views: QueryViewState<{ title: string }>[]; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - client = new QueryClient({ defaultOptions: { queries: { retry: false, networkMode: "always" } } }); - probe = vi.fn(async () => ({ reachable: true as const })); - store = createConnectivityStore({ probe, browserOnline: true }); - attempts = []; - fetchCount = 0; - views = []; - }); - - afterEach(() => { - act(() => root.unmount()); - container.remove(); - client.clear(); - store.dispose(); - }); - - function Harness({ staleHint = false, notFound }: { staleHint?: boolean; notFound?: React.ReactNode }) { - const query = useQuery({ - queryKey: ["thing"], - queryFn: () => { - const attempt = deferred<{ title: string }>(); - attempts.push(attempt); - fetchCount += 1; - return attempt.promise; - }, - }); - views.push(useQueryView(query)); - return ( - - {(data) =>

{data.title}

} - - ); - } - - function mount(props: { staleHint?: boolean; notFound?: React.ReactNode } = {}) { - act(() => { - root.render( - - - - - , - ); - }); - } - - const last = () => views[views.length - 1]!; - // React Query batches observer notifications on a timer, so flush macrotasks. - const settle = async () => { - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 0)); - await new Promise((resolve) => setTimeout(resolve, 0)); - }); - }; - - it("shows a placeholder, then the data", async () => { - mount(); - expect(last().kind).toBe("loading"); - expect(container.querySelector('[data-query-view="placeholder"]')).not.toBeNull(); - attempts[0]!.resolve({ title: "Loaded" }); - await settle(); - expect(last().kind).toBe("ready"); - expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Loaded"); - }); - - it("keeps loaded data on screen when a refetch fails with a transient error", async () => { - mount({ staleHint: true }); - attempts[0]!.resolve({ title: "Loaded" }); - await settle(); - await act(async () => { - void client.refetchQueries({ queryKey: ["thing"] }); - }); - attempts[1]!.reject(unavailable()); - await settle(); - expect(last().kind).toBe("stale"); - expect(last().data).toEqual({ title: "Loaded" }); - expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Loaded"); - expect(container.querySelector('[data-query-view="stale"]')).not.toBeNull(); - expect(container.querySelector('[data-query-view="error"]')).toBeNull(); - expect(container.querySelector(".text-destructive")).toBeNull(); - }); - - it("shows a quiet placeholder when the first load fails during an outage", async () => { - // The server is down: the probe fails, so the store is reconnecting and - // will refetch every live query on recovery. - probe.mockResolvedValue({ reachable: false, retryAfterMs: null } as unknown as { reachable: true }); - mount(); - attempts[0]!.reject(unavailable()); - store.reportError(unavailable()); - await settle(); - expect(store.getSnapshot().status).toBe("reconnecting"); - expect(last().kind).toBe("reconnecting"); - expect(container.querySelector('[data-query-view="placeholder"]')).not.toBeNull(); - expect(container.querySelector('[data-query-view="error"]')).toBeNull(); - expect(container.textContent).not.toContain("tenant_app_unavailable"); - }); - - it("shows readable copy with Retry when one route keeps failing while the server is reachable", async () => { - // The probe says the server is fine, so no recovery loop will ever refetch - // this query: a placeholder would spin forever. - mount(); - attempts[0]!.reject(unavailable()); - store.reportError(unavailable()); - await settle(); - expect(store.getSnapshot().status).toBe("online"); - expect(last().kind).toBe("error"); - expect(last().errorKind).toBe("transient"); - const alert = container.querySelector('[data-query-view="error"]'); - expect(alert).not.toBeNull(); - expect(alert?.textContent).not.toContain("tenant_app_unavailable"); - expect(alert?.querySelector("button")?.textContent).toContain("Retry"); - expect(container.querySelector('[data-query-view="placeholder"]')).toBeNull(); - await act(async () => { - alert!.querySelector("button")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - expect(fetchCount).toBe(2); - attempts[1]!.resolve({ title: "Recovered" }); - await settle(); - expect(last().kind).toBe("ready"); - expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Recovered"); - }); - - it("shows readable copy and retries for a real error", async () => { - mount(); - attempts[0]!.reject(new ApiError("Request failed: 500", 500, { error: "internal_error" })); - await settle(); - expect(last().kind).toBe("error"); - expect(last().errorKind).toBe("unknown"); - const alert = container.querySelector('[data-query-view="error"]'); - expect(alert?.textContent).toContain("Couldn't load the thing"); - expect(alert?.textContent).not.toContain("internal_error"); - const retry = alert?.querySelector("button"); - expect(retry?.textContent).toContain("Retry"); - await act(async () => { - retry!.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - expect(fetchCount).toBe(2); - attempts[1]!.resolve({ title: "Recovered" }); - await settle(); - expect(last().kind).toBe("ready"); - expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Recovered"); - }); - - it("renders not_found only for a real 404", async () => { - mount({ notFound:

Gone

}); - attempts[0]!.reject(notFound()); - await settle(); - expect(last().errorKind).toBe("not_found"); - expect(container.querySelector('[data-testid="missing"]')?.textContent).toBe("Gone"); - }); - - it("retry probes the server during an outage", async () => { - mount(); - attempts[0]!.reject(unavailable()); - await settle(); - // The failed query made the store suspect an outage and probe; make the probe fail so the store is reconnecting. - probe.mockResolvedValueOnce({ reachable: false, retryAfterMs: null } as unknown as { reachable: true }); - await settle(); - store.reportError(unavailable()); - await settle(); - probe.mockClear(); - act(() => last().retry()); - expect(fetchCount).toBe(2); - if (store.getSnapshot().status !== "online") expect(probe).toHaveBeenCalled(); - }); -}); - -describe("", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - act(() => root.unmount()); - container.remove(); - }); - - it("uses readable copy and leaves out Retry for errors a retry cannot fix", () => { - act(() => { - root.render( undefined} size="inline" />); - }); - expect(container.textContent).toContain("Forbidden"); - expect(container.querySelector("button")).toBeNull(); - - act(() => { - root.render( undefined} />); - }); - expect(container.textContent).not.toContain("access_denied"); - expect(container.textContent).toContain("permission"); - expect(container.querySelector("button")).toBeNull(); - - act(() => { - root.render( undefined} size="page" />); - }); - expect(container.textContent).not.toContain("stale_revision"); - expect(container.querySelector("button")?.textContent).toContain("Retry"); - }); -}); diff --git a/ui/src/components/ScheduleEditor.test.tsx b/ui/src/components/ScheduleEditor.test.tsx deleted file mode 100644 index e7baa766464..00000000000 --- a/ui/src/components/ScheduleEditor.test.tsx +++ /dev/null @@ -1,133 +0,0 @@ -// @vitest-environment jsdom - -import { useState } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { - ScheduleEditor, - buildCron, - getScheduleCronValidation, - parseCronToPreset, -} from "./ScheduleEditor"; - -(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -function Harness({ - initial, - onChange, - onValidityChange, -}: { - initial: string; - onChange?: (value: string) => void; - onValidityChange?: (valid: boolean) => void; -}) { - const [value, setValue] = useState(initial); - return ( - { - setValue(cron); - onChange?.(cron); - }} - /> - ); -} - -function typeCron(input: HTMLInputElement, value: string) { - const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set; - setter?.call(input, value); - input.dispatchEvent(new Event("input", { bubbles: true })); -} - -function act(callback: () => void) { - flushSync(callback); -} - -describe("ScheduleEditor cron helpers", () => { - it("classifies unknown valid 5-field cron expressions as custom", () => { - expect(parseCronToPreset("0 8-18/2 * * 1-5").preset).toBe("custom"); - expect(getScheduleCronValidation("0 8-18/2 * * 1-5").valid).toBe(true); - }); - - it("still recognizes supported presets and emits their expected cron", () => { - expect(parseCronToPreset("0 10 * * 1-5")).toMatchObject({ - preset: "weekdays", - hour: "10", - minute: "0", - }); - expect(buildCron("weekdays", "8", "15", "1", "1")).toBe("15 8 * * 1-5"); - }); - - it("reports partial cron edits as invalid without treating them as presets", () => { - const validation = getScheduleCronValidation("0 8-18/2 *"); - expect(validation.valid).toBe(false); - expect(validation.message).toContain("5 fields"); - }); -}); - -describe("ScheduleEditor", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - document.body.innerHTML = ""; - }); - - function cronInput() { - return container.querySelector('input[aria-label="Cron expression"]'); - } - - it("renders unknown valid cron expressions in Custom with the original text", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - - expect(container.textContent).toContain("Custom (cron)"); - expect(cronInput()?.value).toBe("0 8-18/2 * * 1-5"); - expect(container.textContent).toContain("Valid cron."); - - act(() => root.unmount()); - }); - - it("keeps Custom open while partial edits and pasted valid cron values round-trip through parent state", () => { - const onChange = vi.fn(); - const onValidityChange = vi.fn(); - const root = createRoot(container); - act(() => { - root.render( - , - ); - }); - - act(() => { - typeCron(cronInput()!, "0 8-18/2 *"); - }); - expect(cronInput()?.value).toBe("0 8-18/2 *"); - expect(cronInput()?.getAttribute("aria-invalid")).toBe("true"); - expect(container.textContent).toContain("Use exactly 5 fields"); - expect(onChange).not.toHaveBeenCalledWith("0 8-18/2 *"); - expect(onValidityChange).toHaveBeenLastCalledWith(false); - - act(() => { - typeCron(cronInput()!, "0 8-18/2 * * 1-5"); - }); - expect(cronInput()?.value).toBe("0 8-18/2 * * 1-5"); - expect(cronInput()?.getAttribute("aria-invalid")).toBe("false"); - expect(onChange).toHaveBeenLastCalledWith("0 8-18/2 * * 1-5"); - expect(onValidityChange).toHaveBeenLastCalledWith(true); - - act(() => root.unmount()); - }); -}); diff --git a/ui/src/components/SearchableSelect.test.tsx b/ui/src/components/SearchableSelect.test.tsx deleted file mode 100644 index 4b3d4c5ffbf..00000000000 --- a/ui/src/components/SearchableSelect.test.tsx +++ /dev/null @@ -1,539 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import type { ReactNode } from "react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { SearchableSelect, type SearchableSelectGroup, type SearchableSelectOption } from "./SearchableSelect"; -import { Dialog, DialogContent, DialogTitle } from "./ui/dialog"; -import { - buildReusableExecutionWorkspaceOptionGroups, - reusableWorkspaceOptionMatches, - type ReusableExecutionWorkspaceLike, - type ReusableWorkspaceOption, -} from "@/lib/reusable-execution-workspaces"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -function act(callback: () => void | Promise) { - let result: void | Promise | undefined; - flushSync(() => { - result = callback(); - }); - return result; -} - -async function flush() { - await act(async () => { - await Promise.resolve(); - }); -} - -function render(node: ReactNode, container: HTMLElement) { - const root = createRoot(container); - act(() => { - root.render(node); - }); - return root; -} - -function setInputValue(input: HTMLInputElement, value: string) { - act(() => { - const valueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set; - valueSetter?.call(input, value); - input.dispatchEvent(new InputEvent("input", { bubbles: true, data: value, inputType: "insertText" })); - }); -} - -function keyDown(target: Element, key: string) { - act(() => { - target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })); - }); -} - -function workspace(overrides: Partial): ReusableExecutionWorkspaceLike { - return { - id: overrides.id ?? "workspace-id", - name: overrides.name ?? "Workspace", - cwd: overrides.cwd ?? null, - lastUsedAt: overrides.lastUsedAt ?? "2026-06-24T00:00:00.000Z", - status: overrides.status, - branchName: overrides.branchName, - }; -} - -function buildWorkspaceSelectGroups(workspaces: readonly ReusableExecutionWorkspaceLike[]) { - return buildReusableExecutionWorkspaceOptionGroups(workspaces, { - now: "2026-06-24T12:00:00.000Z", - }).map((group) => ({ - id: group.id, - label: group.label, - options: group.options, - })) satisfies SearchableSelectGroup[]; -} - -describe("SearchableSelect", () => { - let container: HTMLDivElement; - let root: Root | null; - let originalResizeObserver: typeof ResizeObserver | undefined; - - beforeEach(() => { - originalResizeObserver = globalThis.ResizeObserver; - globalThis.ResizeObserver = class ResizeObserver { - observe() {} - unobserve() {} - disconnect() {} - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = null; - }); - - afterEach(() => { - if (root) { - act(() => { - root?.unmount(); - }); - } - globalThis.ResizeObserver = originalResizeObserver!; - container.remove(); - document.body.innerHTML = ""; - }); - - it("renders grouped duplicate options while keeping selection by value", async () => { - const onValueChange = vi.fn(); - const alpha: SearchableSelectOption = { key: "recent:alpha", value: "alpha", label: "Alpha" }; - const groups: SearchableSelectGroup[] = [ - { id: "recent", label: "Recent", options: [alpha] }, - { id: "all", label: "All", options: [{ ...alpha, key: "all:alpha" }] }, - ]; - - root = render( - {option.label}} - />, - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - expect(trigger?.textContent).toContain("Alpha"); - - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - expect(container.querySelector("[data-option-key='recent:alpha']")).not.toBeNull(); - expect(container.querySelector("[data-option-key='all:alpha']")).not.toBeNull(); - expect(container.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - expect(container.querySelector("[data-mobile-entity-picker-header]")?.textContent).toContain("Pick one"); - expect(container.querySelector('button[aria-label="Close selector"]')).not.toBeNull(); - }); - - it("filters options and returns the selected option object", async () => { - const onValueChange = vi.fn(); - const bravo = { key: "all:bravo", value: "bravo", label: "Bravo", searchText: "secondary branch" }; - const groups: SearchableSelectGroup[] = [ - { - id: "all", - label: "All", - options: [ - { key: "all:alpha", value: "alpha", label: "Alpha", searchText: "primary branch" }, - bravo, - ], - }, - ]; - - root = render( - , - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - setInputValue(input!, "sec br"); - await flush(); - - expect(container.textContent).not.toContain("Alpha"); - expect(container.textContent).toContain("Bravo"); - - const bravoItem = Array.from(container.querySelectorAll("[cmdk-item]")).find((item) => item.textContent?.includes("Bravo")); - expect(bravoItem).not.toBeUndefined(); - act(() => { - bravoItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - - expect(onValueChange).toHaveBeenCalledWith("bravo", bravo); - }); - - it("ranks visible label matches ahead of lower-quality search text matches", async () => { - const onValueChange = vi.fn(); - const groups: SearchableSelectGroup[] = [ - { - id: "all", - label: "All", - options: [ - { - key: "all:path-only", - value: "path-only", - label: "Paperclip app", - searchText: "/srv/paperclip/mobile-checkout", - }, - { - key: "all:mobile", - value: "mobile", - label: "Mobile agent chat", - searchText: "/srv/paperclip/agent-chat", - }, - ], - }, - ]; - - root = render( - {option.label}} - />, - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - setInputValue(input!, "mobile"); - await flush(); - - const renderedKeys = Array.from(container.querySelectorAll("[data-option-key]")).map((item) => - item.getAttribute("data-option-key"), - ); - expect(renderedKeys).toEqual(["all:mobile", "all:path-only"]); - - const commandList = container.querySelector("[data-slot='command-list']"); - expect(commandList?.className).toContain("overscroll-contain"); - expect(commandList?.className).toContain("touch-pan-y"); - }); - - it("applies custom filtering before custom scoring", async () => { - const groups: SearchableSelectGroup[] = [ - { - id: "all", - options: [ - { key: "all:alpha", value: "alpha", label: "Alpha", searchText: "visible" }, - { key: "all:hidden", value: "hidden", label: "Hidden", searchText: "visible" }, - ], - }, - ]; - - root = render( - option.value !== "hidden" && option.searchText === query} - scoreOption={() => 0} - renderOption={(option) => {option.label}} - />, - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - setInputValue(input!, "visible"); - await flush(); - - const renderedKeys = Array.from(container.querySelectorAll("[data-option-key]")).map((item) => - item.getAttribute("data-option-key"), - ); - expect(renderedKeys).toEqual(["all:alpha"]); - }); - - it("shows loading, empty, and disabled states", async () => { - const onValueChange = vi.fn(); - - root = render( - , - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - expect(container.textContent).toContain("Loading choices..."); - - act(() => { - root?.render( - , - ); - }); - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - setInputValue(input!, "zzz"); - await flush(); - expect(container.textContent).toContain("Nothing matched."); - - act(() => { - root?.render( - , - ); - }); - expect(container.querySelector("button[role='combobox']")?.hasAttribute("disabled")).toBe(true); - }); - - it("opens on focus and closes with Escape", async () => { - root = render( - , - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - act(() => { - trigger?.focus(); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("true"); - - keyDown(input!, "Escape"); - await flush(); - - expect(container.querySelector("input[placeholder='Search options...']")).toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("false"); - - act(() => { - trigger?.dispatchEvent(new Event("pointerdown", { bubbles: true, cancelable: true })); - trigger?.focus(); - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - expect(container.querySelector("input[placeholder='Search options...']")).not.toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("true"); - - const reopenedInput = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(reopenedInput).not.toBeNull(); - setInputValue(reopenedInput!, "alp"); - await flush(); - - keyDown(reopenedInput!, "Escape"); - await flush(); - - expect(container.querySelector("input[placeholder='Search options...']")).toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("false"); - }); - - it.each([false, true])("dismisses outside a nested worktree picker (modal=%s) without reopening or closing the task", async (modal) => { - const onValueChange = vi.fn(); - root = render( - - - New task - - - - , - container, - ); - await flush(); - const trigger = document.querySelector('button[role="combobox"]')!; - const outside = document.querySelector('[data-testid="outside-worktree"]')!; - act(() => trigger.click()); - // Radix installs its outside pointer listener after the opening event. - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - const picker = document.querySelector("[data-mobile-entity-picker]")!; - const outsideTarget = modal ? picker.parentElement! : outside; - act(() => { - const pointerDown = new MouseEvent("pointerdown", { bubbles: true, cancelable: true }); - Object.defineProperty(pointerDown, "pointerType", { value: modal ? "touch" : "mouse" }); - outsideTarget.dispatchEvent(pointerDown); - if (!modal) outside.focus(); - outsideTarget.click(); - }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull(); - expect(document.querySelector("[data-slot=dialog-content]")).not.toBeNull(); - expect(trigger.getAttribute("aria-expanded")).toBe("false"); - expect(trigger.textContent).toContain("New worktree"); - expect(onValueChange).not.toHaveBeenCalled(); - if (modal) expect(document.activeElement).toBe(trigger); - act(() => { - outside.focus(); - trigger.focus(); - }); - await flush(); - expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - }); - - it("filters workspace options, moves with arrows, and selects the workspace id with Enter", async () => { - const onValueChange = vi.fn(); - const groups = buildWorkspaceSelectGroups([ - workspace({ - id: "workspace-paperclip", - name: "Paperclip app", - cwd: "/srv/paperclip/home/paperclipai/paperclip/.paperclip/worktrees/PAP-11722-new-existing-workspace-selector", - branchName: "feature/reusable-workspaces", - status: "running", - lastUsedAt: "2026-06-24T10:00:00.000Z", - }), - workspace({ - id: "workspace-marketing", - name: "Marketing site", - cwd: "/srv/paperclip/home/marketing-site", - branchName: "landing-refresh", - status: "idle", - lastUsedAt: "2026-06-20T10:00:00.000Z", - }), - ]); - - root = render( - - value="" - groups={groups} - onValueChange={onValueChange} - placeholder="Choose an existing workspace" - searchPlaceholder="Search workspaces..." - filterOption={(option, query) => reusableWorkspaceOptionMatches(option, query)} - disablePortal - renderOption={(option, { selected }) => ( - - {option.label} - - )} - />, - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search workspaces...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - expect(container.textContent).toContain("Recent"); - expect(container.textContent).toContain("All workspaces"); - - setInputValue(input!, "pclip reusable"); - await flush(); - - expect(container.textContent).toContain("Paperclip app"); - expect(container.textContent).not.toContain("Marketing site"); - - const selectedOptionKey = () => ( - container.querySelector("[cmdk-item][aria-selected='true'] [data-option-key]")?.getAttribute("data-option-key") - ); - - expect(selectedOptionKey()).toBe("recent:workspace-paperclip"); - keyDown(input!, "ArrowDown"); - await flush(); - expect(selectedOptionKey()).toBe("all:workspace-paperclip"); - - keyDown(input!, "ArrowUp"); - await flush(); - expect(selectedOptionKey()).toBe("recent:workspace-paperclip"); - - keyDown(input!, "ArrowDown"); - await flush(); - keyDown(input!, "Enter"); - await flush(); - - expect(onValueChange).toHaveBeenCalledWith( - "workspace-paperclip", - expect.objectContaining({ - key: "all:workspace-paperclip", - value: "workspace-paperclip", - workspaceId: "workspace-paperclip", - }), - ); - expect(container.querySelector("input[placeholder='Search workspaces...']")).toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("false"); - - act(() => { - trigger?.focus(); - }); - await flush(); - - expect(container.querySelector("input[placeholder='Search workspaces...']")).toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("false"); - }); -}); diff --git a/ui/src/components/StandaloneBrowserControls.test.tsx b/ui/src/components/StandaloneBrowserControls.test.tsx deleted file mode 100644 index 829ee5ec13e..00000000000 --- a/ui/src/components/StandaloneBrowserControls.test.tsx +++ /dev/null @@ -1,170 +0,0 @@ -// @vitest-environment jsdom - -import { createRoot } from "react-dom/client"; -import { flushSync } from "react-dom"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { TooltipProvider } from "@/components/ui/tooltip"; -import { ToastProvider } from "../context/ToastContext"; -import { StandaloneBrowserControls } from "./StandaloneBrowserControls"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -async function flushReact() { - await act(async () => { - await Promise.resolve(); - await new Promise((resolve) => window.setTimeout(resolve, 0)); - }); -} - -function installMatchMedia(initialMatches: Record = {}) { - type Listener = (event: MediaQueryListEvent) => void; - const queries = new Map }>(); - - function getQuery(query: string) { - let entry = queries.get(query); - if (!entry) { - entry = { matches: initialMatches[query] ?? false, listeners: new Set() }; - queries.set(query, entry); - } - - return { - get matches() { - return entry.matches; - }, - media: query, - addEventListener: (_type: "change", listener: Listener) => { - entry.listeners.add(listener); - }, - removeEventListener: (_type: "change", listener: Listener) => { - entry.listeners.delete(listener); - }, - addListener: (listener: Listener) => { - entry.listeners.add(listener); - }, - removeListener: (listener: Listener) => { - entry.listeners.delete(listener); - }, - } as unknown as MediaQueryList; - } - - Object.defineProperty(window, "matchMedia", { - configurable: true, - value: (query: string) => getQuery(query), - }); - - return { - setMatches(query: string, matches: boolean) { - const entry = queries.get(query) ?? { matches: false, listeners: new Set() }; - entry.matches = matches; - queries.set(query, entry); - entry.listeners.forEach((listener) => listener({ matches, media: query } as MediaQueryListEvent)); - }, - }; -} - -describe("StandaloneBrowserControls", () => { - let container: HTMLDivElement; - const originalMatchMedia = window.matchMedia; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - Object.defineProperty(navigator, "standalone", { configurable: true, value: true }); - }); - - afterEach(() => { - delete (navigator as Navigator & { standalone?: boolean }).standalone; - if (originalMatchMedia) { - Object.defineProperty(window, "matchMedia", { configurable: true, value: originalMatchMedia }); - } else { - Object.defineProperty(window, "matchMedia", { configurable: true, value: undefined }); - } - container.remove(); - document.body.innerHTML = ""; - }); - - it("shows refresh, share, and open-in-browser controls in mobile standalone mode", async () => { - const root = createRoot(container); - - await act(async () => { - root.render( - - - - - , - ); - }); - await flushReact(); - - expect(container.querySelector('[aria-label="Refresh"]')).not.toBeNull(); - expect(container.querySelector('[aria-label="Share"]')).not.toBeNull(); - expect(container.querySelector('[aria-label="Open in Browser"]')).not.toBeNull(); - - await act(async () => { - root.unmount(); - }); - }); - - it("hides controls in normal mobile browser mode", async () => { - Object.defineProperty(navigator, "standalone", { configurable: true, value: false }); - installMatchMedia(); - const root = createRoot(container); - - await act(async () => { - root.render( - - - - - , - ); - }); - await flushReact(); - - expect(container.querySelector('[aria-label="Refresh"]')).toBeNull(); - - await act(async () => { - root.unmount(); - }); - }); - - it("responds to all chromeless display-mode media query changes", async () => { - Object.defineProperty(navigator, "standalone", { configurable: true, value: false }); - const media = installMatchMedia(); - const root = createRoot(container); - - await act(async () => { - root.render( - - - - - , - ); - }); - await flushReact(); - - expect(container.querySelector('[aria-label="Refresh"]')).toBeNull(); - - await act(() => { - media.setMatches("(display-mode: fullscreen)", true); - }); - await flushReact(); - - expect(container.querySelector('[aria-label="Refresh"]')).not.toBeNull(); - - await act(async () => { - root.unmount(); - }); - }); -}); diff --git a/ui/src/components/folders/FolderControls.test.tsx b/ui/src/components/folders/FolderControls.test.tsx deleted file mode 100644 index 6940e0840ae..00000000000 --- a/ui/src/components/folders/FolderControls.test.tsx +++ /dev/null @@ -1,480 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { FolderListResult } from "@paperclipai/shared"; -import { - AllUnfiledBanner, - BulkBar, - DeleteFolderDialog, - FolderFormDialog, - FolderRail, - MobileFolderSheet, - MoveToMenu, - folderSearchValue, - normalizeFolderSelection, -} from "./FolderControls"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -if (!globalThis.PointerEvent) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (globalThis as any).PointerEvent = MouseEvent; -} -if (!Element.prototype.hasPointerCapture) { - Element.prototype.hasPointerCapture = () => false; -} -if (!Element.prototype.scrollIntoView) { - Element.prototype.scrollIntoView = () => undefined; -} - -function act(callback: () => void | Promise) { - let result: void | Promise | undefined; - flushSync(() => { - result = callback(); - }); - return result; -} - -const folderResult: FolderListResult = { - kind: "routine", - allCount: 4, - unfiledCount: 1, - folders: [ - { - id: "folder-reporting", - companyId: "company-1", - kind: "routine", - parentId: null, - name: "Reporting", - slug: "reporting", - systemKey: null, - path: "reporting", - depth: 1, - color: "indigo", - position: 0, - itemCount: 3, - createdAt: new Date("2026-07-01T00:00:00.000Z"), - updatedAt: new Date("2026-07-01T00:00:00.000Z"), - }, - ], -}; - -const skillFolderResult: FolderListResult = { - kind: "skill", - allCount: 8, - unfiledCount: 1, - folders: [ - { - ...folderResult.folders[0]!, - id: "my", - kind: "skill", - name: "my", - slug: "my", - systemKey: "my", - path: "my", - itemCount: 1, - }, - { - ...folderResult.folders[0]!, - id: "engineering", - kind: "skill", - name: "Engineering", - slug: "engineering", - path: "engineering", - itemCount: 3, - }, - { - ...folderResult.folders[0]!, - id: "code-review", - kind: "skill", - parentId: "engineering", - name: "Code Review", - slug: "code-review", - path: "engineering/code-review", - depth: 2, - itemCount: 2, - }, - { - ...folderResult.folders[0]!, - id: "projects", - kind: "skill", - name: "projects", - slug: "projects", - systemKey: "projects", - path: "projects", - itemCount: 2, - }, - { - ...folderResult.folders[0]!, - id: "bundled", - kind: "skill", - name: "bundled", - slug: "bundled", - systemKey: "bundled", - path: "bundled", - itemCount: 1, - }, - ], -}; - -describe("FolderControls", () => { - let container: HTMLDivElement; - let root: Root | null; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = null; - }); - - afterEach(() => { - if (root) { - act(() => { - root?.unmount(); - }); - } - container.remove(); - document.body.innerHTML = ""; - }); - - it("normalizes URL selection values for folder persistence", () => { - expect(normalizeFolderSelection(null)).toBe("all"); - expect(normalizeFolderSelection("unfiled")).toBe("unfiled"); - expect(normalizeFolderSelection("folder-reporting")).toBe("folder-reporting"); - expect(folderSearchValue("all")).toBe(""); - expect(folderSearchValue("unfiled")).toBe("unfiled"); - expect(folderSearchValue("folder-reporting")).toBe("folder-reporting"); - }); - - it("renders All, user folders, and Unfiled with counts and selection callbacks", () => { - const onSelect = vi.fn(); - root = createRoot(container); - - act(() => { - root?.render( - , - ); - }); - - expect(container.textContent).toContain("All routines"); - expect(container.textContent).toContain("Reporting"); - expect(container.textContent).toContain("Unfiled"); - expect(container.textContent).toContain("4"); - expect(container.textContent).toContain("3"); - expect(container.textContent).toContain("1"); - - const reportingButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Reporting"), - ); - expect(reportingButton).toBeTruthy(); - - act(() => { - reportingButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - - expect(onSelect).toHaveBeenCalledWith("folder-reporting"); - }); - - it("marks the active row with aria-current, including virtual Unfiled", () => { - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - const current = container.querySelector('[aria-current="page"]'); - expect(current?.textContent).toContain("Unfiled"); - }); - - it("renames a folder inline via double-click and Enter", () => { - const onRename = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - const nameButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Reporting"), - ); - act(() => { - nameButton?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true })); - }); - - const input = container.querySelector("input"); - expect(input).toBeTruthy(); - expect(input?.value).toBe("Reporting"); - - act(() => { - if (!input) return; - const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; - setter?.call(input, "Monthly reports"); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); - act(() => { - input?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - }); - - expect(onRename).toHaveBeenCalledWith(folderResult.folders[0], "Monthly reports"); - }); - - it("moves via MoveToMenu: Unfiled, a folder, and new-folder chaining", () => { - const onMove = vi.fn(); - const onCreateAndMove = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - - - - - - - - , - ); - }); - - const subTrigger = Array.from(document.querySelectorAll("[data-radix-collection-item]")).find( - (element) => element.textContent?.includes("Move to"), - ); - expect(subTrigger).toBeTruthy(); - act(() => { - subTrigger?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })); - }); - - const menuItems = Array.from(document.querySelectorAll('[role="menuitem"]')); - const unfiledItem = menuItems.find((element) => element.textContent?.includes("Unfiled")); - const folderItem = menuItems.find((element) => element.textContent?.includes("Reporting")); - const newFolderItem = menuItems.find((element) => element.textContent?.includes("New folder")); - expect(unfiledItem).toBeTruthy(); - expect(folderItem).toBeTruthy(); - expect(newFolderItem).toBeTruthy(); - - act(() => { - unfiledItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onMove).toHaveBeenCalledWith(null); - - act(() => { - folderItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onMove).toHaveBeenCalledWith("folder-reporting"); - - act(() => { - newFolderItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onCreateAndMove).toHaveBeenCalled(); - }); - - it("creates a folder through FolderFormDialog and disables submit on empty name", () => { - const onSubmit = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - const submit = Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent === "Create folder", - ) as HTMLButtonElement | undefined; - expect(submit).toBeTruthy(); - expect(submit?.disabled).toBe(true); - - const nameInput = document.querySelector("#folder-name"); - act(() => { - if (!nameInput) return; - const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; - setter?.call(nameInput, "Reporting"); - nameInput.dispatchEvent(new Event("input", { bubbles: true })); - }); - - expect(submit?.disabled).toBe(false); - act(() => { - submit?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onSubmit).toHaveBeenCalledWith({ name: "Reporting", color: expect.any(String) }); - }); - - it("states the forgiving delete behavior and confirms", () => { - const onConfirm = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(document.body.textContent).toContain("3 routines in this folder won't be deleted"); - expect(document.body.textContent).toContain("They'll move to Unfiled"); - - const confirmButton = Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent === "Delete folder", - ); - act(() => { - confirmButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onConfirm).toHaveBeenCalled(); - }); - - it("selects a folder from the mobile sheet and dismisses", () => { - const onSelect = vi.fn(); - const onOpenChange = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(document.body.textContent).toContain("All routines"); - expect(document.body.textContent).toContain("Unfiled"); - - const reportingRow = Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.includes("Reporting"), - ); - act(() => { - reportingRow?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - - expect(onSelect).toHaveBeenCalledWith("folder-reporting"); - expect(onOpenChange).toHaveBeenCalledWith(false); - }); - - it("preserves skill root grouping and child hierarchy in the mobile sheet", () => { - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - const body = document.body.textContent ?? ""; - expect(body.indexOf("My Skills")).toBeLessThan(body.indexOf("Organization")); - expect(body.indexOf("Organization")).toBeLessThan(body.indexOf("Engineering")); - expect(body.indexOf("Engineering")).toBeLessThan(body.indexOf("Code Review")); - expect(body.indexOf("Code Review")).toBeLessThan(body.indexOf("Projects")); - expect(body.indexOf("Projects")).toBeLessThan(body.indexOf("Bundled")); - expect(document.querySelector('[data-folder-id="engineering"] > .pl-3 [data-folder-id="code-review"]')).not.toBeNull(); - }); - - it("persists AllUnfiledBanner dismissal across mounts", () => { - const storageKey = "paperclip:test-folder-nudge"; - window.localStorage.removeItem(storageKey); - const onCreateFolder = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(container.textContent).toContain("Create your first folder"); - - const dismissButton = container.querySelector( - 'button[aria-label="Dismiss folder suggestion"]', - ); - act(() => { - dismissButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - - expect(container.textContent).not.toContain("Create your first folder"); - expect(window.localStorage.getItem(storageKey)).toBe("1"); - - act(() => { - root?.unmount(); - }); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - expect(container.textContent).not.toContain("Create your first folder"); - window.localStorage.removeItem(storageKey); - }); -}); diff --git a/ui/src/components/folders/SkillFolderTree.test.tsx b/ui/src/components/folders/SkillFolderTree.test.tsx deleted file mode 100644 index 53caaea15b7..00000000000 --- a/ui/src/components/folders/SkillFolderTree.test.tsx +++ /dev/null @@ -1,131 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { FolderListResult } from "@paperclipai/shared"; -import { SkillFolderRail } from "./SkillFolderTree"; - -function pointerEvent(type: string, clientX: number) { - const event = new MouseEvent(type, { bubbles: true, clientX }); - Object.defineProperty(event, "pointerId", { value: 1 }); - return event; -} - -const result: FolderListResult = { - kind: "skill", - allCount: 12, - unfiledCount: 2, - folders: [ - { - id: "my-root", - companyId: "company-1", - kind: "skill", - parentId: null, - name: "My Skills", - slug: "my", - systemKey: "my", - path: "my", - depth: 1, - color: null, - position: 0, - itemCount: 4, - createdAt: new Date("2026-07-16T00:00:00.000Z"), - updatedAt: new Date("2026-07-16T00:00:00.000Z"), - }, - { - id: "personal-root", - companyId: "company-1", - kind: "skill", - parentId: "my-root", - name: "Ada", - slug: "ada", - systemKey: "my:user-1", - path: "my/ada", - depth: 2, - color: null, - position: 0, - itemCount: 4, - createdAt: new Date("2026-07-16T00:00:00.000Z"), - updatedAt: new Date("2026-07-16T00:00:00.000Z"), - }, - ], -}; - -describe("SkillFolderRail", () => { - let container: HTMLDivElement; - let root: Root; - const onSelect = vi.fn<(selection: string) => void>(); - - beforeEach(() => { - window.localStorage.clear(); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - onSelect.mockClear(); - flushSync(() => { - root.render( - , - ); - }); - }); - - afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - window.localStorage.clear(); - }); - - it("uses the wider default and persists drag resizing", () => { - const rail = container.firstElementChild as HTMLDivElement; - const separator = container.querySelector('[role="separator"]') as HTMLDivElement; - expect(rail.style.width).toBe("288px"); - separator.setPointerCapture = vi.fn(); - - flushSync(() => { - separator.dispatchEvent(pointerEvent("pointerdown", 288)); - separator.dispatchEvent(pointerEvent("pointermove", 320)); - separator.dispatchEvent(pointerEvent("pointerup", 320)); - }); - - expect(rail.style.width).toBe("320px"); - expect(window.localStorage.getItem("paperclip.skills.folderRail.width")).toBe("320"); - }); - - it("keeps virtual and folder counts on the same grid column", () => { - const allRow = Array.from(container.querySelectorAll("button")) - .find((button) => button.textContent?.includes("All skills")); - const myLabel = Array.from(container.querySelectorAll("button")) - .find((button) => button.textContent?.includes("My Skills")); - const myRow = myLabel?.parentElement; - - expect(allRow?.className).toContain("grid-cols-(--gtc-folder-row-actions)"); - expect(myRow?.className).toContain("grid-cols-(--gtc-folder-row-actions)"); - expect(allRow?.querySelector(".tabular-nums")?.textContent).toBe("12"); - expect(myRow?.querySelector(".tabular-nums")?.textContent).toBe("4"); - }); - - it("selects and toggles a folder when its row label is clicked", () => { - const myLabel = Array.from(container.querySelectorAll("button")) - .find((button) => button.textContent?.includes("My Skills")); - - expect(container.textContent).not.toContain("Ada"); - flushSync(() => myLabel?.click()); - - expect(onSelect).toHaveBeenCalledWith("my-root"); - expect(container.textContent).toContain("Ada"); - expect(container.querySelector('[aria-label="Collapse folder"]')).not.toBeNull(); - }); -}); diff --git a/ui/src/components/mcp-app/McpAppIssueContext.test.tsx b/ui/src/components/mcp-app/McpAppIssueContext.test.tsx deleted file mode 100644 index a6cee8846cd..00000000000 --- a/ui/src/components/mcp-app/McpAppIssueContext.test.tsx +++ /dev/null @@ -1,100 +0,0 @@ -// @vitest-environment jsdom -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { act, type ReactNode } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import type { McpAppViewSummary } from "@paperclipai/shared"; - -const list = vi.fn<(issueId: string) => Promise>(); -vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { list: (issueId: string) => list(issueId) } })); - -const { McpAppIssueProvider, useMcpAppViewsForRun } = await import("./McpAppIssueContext"); - -function view(id: string, runId: string): McpAppViewSummary { - return { - id, issueId: "issue-1", runId, connectionId: "conn-1", applicationName: "Circleback", - toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings", - resourceUri: "ui://circleback/meetings", toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z", - }; -} - -function wrapper(client: QueryClient) { - return ({ children }: { children: ReactNode }) => ( - - {children} - - ); -} - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -async function renderHook(hook: (props: P) => R, options: { wrapper: (props: { children: ReactNode }) => ReactNode; initialProps?: P }) { - const result = { current: undefined as unknown as R }; - const container = document.createElement("div"); - const root = createRoot(container); - const Wrapper = options.wrapper; - function Probe({ props }: { props: P }) { - result.current = hook(props); - return null; - } - const render = (props: P) => act(() => root.render()); - await render(options.initialProps as P); - return { result, rerender: (props: P) => render(props), unmount: () => act(() => root.unmount()) }; -} - -async function waitFor(check: () => void, timeoutMs = 2000) { - const started = Date.now(); - for (;;) { - try { - check(); - return; - } catch (error) { - if (Date.now() - started > timeoutMs) throw error; - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); }); - } - } -} - -afterEach(() => list.mockReset()); - -describe("useMcpAppViewsForRun", () => { - it("refreshes the task's list once when a live run completes another MCP tool call", async () => { - list.mockResolvedValueOnce([]).mockResolvedValueOnce([view("v1", "run-1")]); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const { result, rerender } = await renderHook( - ({ refreshKey }: { refreshKey: string }) => useMcpAppViewsForRun("run-1", { refreshKey }), - { wrapper: wrapper(client), initialProps: { refreshKey: "0:running" } }, - ); - await waitFor(() => expect(list).toHaveBeenCalledTimes(1)); - expect(result.current.views).toEqual([]); - await rerender({ refreshKey: "1:running" }); - await waitFor(() => expect(list).toHaveBeenCalledTimes(2)); - await waitFor(() => expect(result.current.views.map((v) => v.id)).toEqual(["v1"])); - await rerender({ refreshKey: "1:running" }); - expect(list).toHaveBeenCalledTimes(2); - }); - - it("refreshes once for a settled reply newer than the loaded list", async () => { - list.mockResolvedValueOnce([]).mockResolvedValue([view("v1", "run-1")]); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const { result } = await renderHook( - () => useMcpAppViewsForRun("run-1", { notBeforeMs: Date.now() + 60_000 }), - { wrapper: wrapper(client) }, - ); - await waitFor(() => expect(result.current.views.map((v) => v.id)).toEqual(["v1"])); - await new Promise((resolve) => setTimeout(resolve, 20)); - expect(list).toHaveBeenCalledTimes(2); - }); - - it("does not refresh for a reply older than the loaded list", async () => { - list.mockResolvedValue([view("v1", "run-1")]); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const { result } = await renderHook( - () => useMcpAppViewsForRun("run-1", { notBeforeMs: Date.now() - 60_000 }), - { wrapper: wrapper(client) }, - ); - await waitFor(() => expect(result.current.views).toHaveLength(1)); - await new Promise((resolve) => setTimeout(resolve, 20)); - expect(list).toHaveBeenCalledTimes(1); - }); -}); diff --git a/ui/src/components/mcp-app/McpAppTurnViews.test.tsx b/ui/src/components/mcp-app/McpAppTurnViews.test.tsx deleted file mode 100644 index bee89cdb6c6..00000000000 --- a/ui/src/components/mcp-app/McpAppTurnViews.test.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// @vitest-environment jsdom -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import type { McpAppViewSummary } from "@paperclipai/shared"; -import { queryKeys } from "@/lib/queryKeys"; - -const detail = vi.fn(() => new Promise(() => undefined)); -vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { list: vi.fn(), detail: (...args: unknown[]) => detail(...(args as [])), callTool: vi.fn() } })); - -const { McpAppIssueProvider } = await import("./McpAppIssueContext"); -const { McpAppTurnViews } = await import("./McpAppTurnViews"); - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -function views(count: number): McpAppViewSummary[] { - return Array.from({ length: count }, (_, index) => ({ - id: `00000000-0000-4000-8000-00000000000${index}`, issueId: "issue-1", runId: "run-1", connectionId: "conn-1", - applicationName: "Circleback", toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings", - resourceUri: "ui://circleback/meetings", toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z", - })); -} - -let observers: Array<{ callback: IntersectionObserverCallback; targets: Element[] }> = []; -class FakeIntersectionObserver { - targets: Element[] = []; - constructor(public callback: IntersectionObserverCallback) { observers.push(this); } - observe(target: Element) { this.targets.push(target); } - disconnect() { this.targets = []; } - unobserve() {} - takeRecords() { return []; } -} - -async function render(input: number | McpAppViewSummary[]) { - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - client.setQueryData(queryKeys.mcpApps.views("issue-1"), typeof input === "number" ? views(input) : input); - const container = document.createElement("div"); - const root = createRoot(container); - await act(async () => root.render( - - - , - )); - return { container, root }; -} - -afterEach(() => { - observers = []; - detail.mockClear(); - vi.unstubAllGlobals(); -}); - -describe("McpAppTurnViews", () => { - const identityViews = (): McpAppViewSummary[] => views(4).map((view) => ({ - ...view, - id: `profile-${view.id}`, - applicationName: "GitHub", - toolName: "mcp.github:get-me", - upstreamToolName: "get_me", - resourceUri: "ui://github-mcp-server/get-me", - })); - - it("renders no cards or documents for repeated saved GitHub identity lookups", async () => { - vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver); - const { container, root } = await render(identityViews()); - expect(container.childElementCount).toBe(0); - expect(observers).toHaveLength(0); - expect(detail).not.toHaveBeenCalled(); - await act(async () => root.unmount()); - }); - - it("counts only visible widgets toward the per-run limit", async () => { - vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver); - const { container, root } = await render([...identityViews(), ...views(7)]); - expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(5); - expect(container.textContent).not.toContain("Get me"); - const more = [...container.querySelectorAll("button")].find((button) => button.textContent === "Show 2 more"); - expect(more).toBeTruthy(); - await act(async () => more!.click()); - expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(7); - expect(container.textContent).not.toContain("Get me"); - expect(detail).not.toHaveBeenCalled(); - await act(async () => root.unmount()); - }); - - it("loads a view's document only when it nears the viewport", async () => { - vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver); - vi.stubGlobal("navigation", { addEventListener: () => undefined }); - const { container, root } = await render(2); - expect(container.querySelectorAll("[data-testid=mcp-app-view-placeholder]")).toHaveLength(2); - expect(detail).not.toHaveBeenCalled(); - const first = observers[0]!; - await act(async () => first.callback([{ isIntersecting: true, target: first.targets[0]! } as IntersectionObserverEntry], first as unknown as IntersectionObserver)); - expect(detail).toHaveBeenCalledTimes(1); - expect(container.querySelectorAll("[data-testid=mcp-app-view-placeholder]")).toHaveLength(1); - await act(async () => root.unmount()); - }); - - it("shows five views per run and the rest on request", async () => { - vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver); - const { container, root } = await render(7); - expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(5); - const more = [...container.querySelectorAll("button")].find((button) => button.textContent === "Show 2 more")!; - expect(more).toBeTruthy(); - await act(async () => more.click()); - expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(7); - expect(detail).not.toHaveBeenCalled(); - await act(async () => root.unmount()); - }); -}); diff --git a/ui/src/components/mcp-app/McpAppView.test.tsx b/ui/src/components/mcp-app/McpAppView.test.tsx deleted file mode 100644 index c415d48fcf1..00000000000 --- a/ui/src/components/mcp-app/McpAppView.test.tsx +++ /dev/null @@ -1,131 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { messageSent: vi.fn(async () => ({ commentId: "c1" })) } })); -import type { McpAppViewDetail } from "@paperclipai/shared"; -import { McpAppViewContent, useMcpAppMessageProposal, type McpAppViewContentProps } from "./McpAppView"; -import { McpAppFrame } from "./McpAppFrame"; -import { McpAppIssueProvider } from "./McpAppIssueContext"; -import { mcpAppNavigationGuardSupported } from "./mcp-app-host"; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -const detail: McpAppViewDetail = { - id: "view-1", issueId: "issue-1", runId: "run-1", connectionId: "conn-1", applicationName: "Circleback", - toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings", resourceUri: "ui://circleback/meetings", - toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z", - toolResult: { content: [] }, - resource: { uri: "ui://circleback/meetings", html: "

cards

", csp: {}, permissions: {}, prefersBorder: true }, -}; - -async function render(props: Partial = {}) { - const container = document.createElement("div"); - document.body.appendChild(container); - const root = createRoot(container); - await act(async () => root.render( - ({ content: [] })} displayName="Display meetings" {...props} />, - )); - return { container, root }; -} - -function button(label: string): HTMLButtonElement { - const found = [...document.querySelectorAll("button")].find((element) => element.textContent?.trim() === label); - if (!found) throw new Error(`No button "${label}"`); - return found as HTMLButtonElement; -} - -afterEach(() => vi.unstubAllGlobals()); - -describe("McpAppViewContent", () => { - it("does not mount a view where the navigation guard cannot work", async () => { - expect(mcpAppNavigationGuardSupported()).toBe(false); - const { container, root } = await render(); - expect(container.querySelector("iframe")).toBeNull(); - expect(container.textContent).toContain("This browser can't show this app's widget safely."); - await act(async () => root.unmount()); - }); - - it("mounts the view where the Navigation API is available", async () => { - vi.stubGlobal("navigation", { addEventListener: () => undefined }); - const { container, root } = await render(); - expect(container.querySelector("iframe")).not.toBeNull(); - await act(async () => root.unmount()); - }); - - it("shows a view's proposed message under the widget and sends it only on Send", async () => { - vi.stubGlobal("navigation", { addEventListener: () => undefined }); - const onSendProposal = vi.fn(); - const onDismissProposal = vi.fn(); - const { container, root } = await render({ - proposal: { text: "Summarize the Heavybit meeting", status: "pending" }, onSendProposal, onDismissProposal, - }); - const card = container.querySelector("[data-testid=mcp-app-message-proposal]")!; - expect(card.textContent).toContain("Circleback wants to send:"); - expect(card.textContent).toContain("Summarize the Heavybit meeting"); - // The card comes after the widget. - expect(container.querySelector("iframe")!.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(onSendProposal).not.toHaveBeenCalled(); - await act(async () => button("Dismiss").click()); - expect(onDismissProposal).toHaveBeenCalledTimes(1); - await act(async () => button("Send").click()); - expect(onSendProposal).toHaveBeenCalledTimes(1); - await act(async () => root.unmount()); - container.remove(); - }); - - it("shows the view full screen in a dialog, with one frame at a time", async () => { - vi.stubGlobal("navigation", { addEventListener: () => undefined }); - const onDisplayModeChange = vi.fn(); - const { container, root } = await render({ displayMode: "fullscreen", onDisplayModeChange }); - const dialog = document.querySelector("[data-testid=mcp-app-fullscreen]")!; - expect(dialog).not.toBeNull(); - expect(dialog.querySelectorAll("iframe")).toHaveLength(1); - expect(dialog.querySelector("iframe")!.getAttribute("data-display-mode")).toBe("fullscreen"); - expect(document.querySelectorAll("iframe")).toHaveLength(1); - expect(container.querySelector("[data-testid=mcp-app-view-fullscreen-placeholder]")).not.toBeNull(); - await act(async () => button("Exit full screen").click()); - expect(onDisplayModeChange).toHaveBeenCalledWith("inline"); - await act(async () => root.unmount()); - container.remove(); - }); - - it("starts a new frame when the host's capabilities change, so the view handshakes again", async () => { - const container = document.createElement("div"); - const root = createRoot(container); - const frame = (proposeMessage?: (text: string) => Promise) => ( - ({ content: [] })} proposeMessage={proposeMessage} /> - ); - await act(async () => root.render(frame())); - const first = container.querySelector("iframe"); - await act(async () => root.render(frame(async () => undefined))); - expect(container.querySelector("iframe")).not.toBe(first); - await act(async () => root.unmount()); - }); - - it("retries a failed Send with the same request id, so the comment is posted once", async () => { - const sendMessage = vi.fn() - .mockRejectedValueOnce(new Error("Network error")) - .mockResolvedValueOnce(undefined); - let api: ReturnType | null = null; - function Harness() { - api = useMcpAppMessageProposal("issue-1", "view-1"); - return null; - } - const container = document.createElement("div"); - const root = createRoot(container); - await act(async () => root.render()); - let settled = false; - await act(async () => { void api!.proposeMessage!("Summarize m1").then(() => { settled = true; }); }); - await act(async () => { api!.onSend!(); }); - expect(api!.proposal).toMatchObject({ status: "error" }); - expect(settled).toBe(false); - await act(async () => { api!.onSend!(); }); - expect(sendMessage).toHaveBeenCalledTimes(2); - expect(sendMessage.mock.calls[0]![1]).toBe(sendMessage.mock.calls[1]![1]); - expect(settled).toBe(true); - expect(api!.proposal).toBeNull(); - await act(async () => root.unmount()); - }); -}); diff --git a/ui/src/components/task-chat/ComposerFileDropTarget.test.tsx b/ui/src/components/task-chat/ComposerFileDropTarget.test.tsx deleted file mode 100644 index 19ac1465d27..00000000000 --- a/ui/src/components/task-chat/ComposerFileDropTarget.test.tsx +++ /dev/null @@ -1,226 +0,0 @@ -// @vitest-environment jsdom -import { act, type ReactElement } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { MarkdownEditor } from "../MarkdownEditor"; -import { IssueAttachmentsSection } from "../IssueAttachmentsSection"; -import { ArtifactDropzone } from "../artifacts/ArtifactDropzone"; -import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover"; -import { Dialog, DialogContent, DialogTitle } from "../ui/dialog"; -import { ComposerFileDropTarget } from "./ComposerFileDropTarget"; - -let host: HTMLDivElement; -let root: Root; -const file = new File(["image"], "screenshot.png", { type: "image/png" }); -function render(content: ReactElement) { act(() => root.render(content)); } -function drag(type: string, target: EventTarget = document.body, types = ["Files"], relatedTarget: EventTarget | null = null) { - const event = new MouseEvent(type, { bubbles: true, cancelable: true }); - Object.defineProperties(event, { - dataTransfer: { value: { types, files: types.includes("Files") ? [file] : [], items: types.includes("Files") ? [{ kind: "file", type: file.type, getAsFile: () => file }] : [], dropEffect: "none" } }, - relatedTarget: { value: relatedTarget }, - }); - act(() => { target.dispatchEvent(event); }); - return event; -} -const overlay = () => document.querySelector('[data-testid="composer-file-drop-overlay"]'); -beforeEach(() => { vi.stubGlobal("DragEvent", MouseEvent); host = document.createElement("div"); document.body.append(host); root = createRoot(host); }); -afterEach(() => { act(() => root.unmount()); host.remove(); vi.unstubAllGlobals(); }); - -describe("composer screen file drops", () => { - it("accepts a drop outside the composer exactly once and clears the overlay", () => { - const onFiles = vi.fn(); - render(); - expect(drag("dragenter").defaultPrevented).toBe(true); - expect(overlay()?.textContent).toContain("Drop files to attach"); - expect(drag("dragover").defaultPrevented).toBe(true); - const downstream = vi.fn(); - document.body.addEventListener("drop", downstream, { once: true }); - expect(drag("drop").defaultPrevented).toBe(true); - expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - expect(downstream).not.toHaveBeenCalled(); - document.body.removeEventListener("drop", downstream); - expect(overlay()).toBeNull(); - }); - - it("keeps the overlay while moving between children, then clears on exit or cancellation", () => { - render(); - drag("dragenter"); drag("dragenter", host); drag("dragleave", document.body, ["Files"], host); - expect(overlay()).not.toBeNull(); - drag("dragleave", host); - expect(overlay()).toBeNull(); - for (const cancel of ["dragend", "blur"]) { - drag("dragenter"); - act(() => { window.dispatchEvent(new Event(cancel)); }); - expect(overlay()).toBeNull(); - } - }); - - it("clears a nested drag when the pointer leaves the window", () => { - render(); - drag("dragenter"); drag("dragenter", host); - drag("dragleave", document.documentElement); - expect(overlay()).toBeNull(); - }); - - it("preserves description editor file uploads and clears both overlays", async () => { - const onFiles = vi.fn(); const onDropFile = vi.fn().mockResolvedValue(undefined); - render(<> - - ); - const editor = host.querySelector('[contenteditable="true"]')!; - expect(editor).not.toBeNull(); - drag("dragenter"); expect(overlay()).not.toBeNull(); - drag("dragenter", editor); drag("dragover", editor); - expect(overlay()).toBeNull(); - expect(host.textContent).toContain("Drop file to upload"); - const attachment = new File(["notes"], "notes.txt", { type: "text/plain" }); - const event = new MouseEvent("drop", { bubbles: true, cancelable: true }); - Object.defineProperty(event, "dataTransfer", { value: { types: ["Files"], files: [attachment] } }); - await act(async () => { editor.dispatchEvent(event); }); - expect(onDropFile).toHaveBeenCalledExactlyOnceWith(attachment); - expect(onFiles).not.toHaveBeenCalled(); - expect(host.textContent).not.toContain("Drop file to upload"); - expect(overlay()).toBeNull(); - drag("drop"); expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - }); - - it("keeps image drops in the description image plugin", async () => { - const onFiles = vi.fn(); - const uploadImage = vi.fn().mockResolvedValue("/description-image.png"); - render(<> - - ); - const editor = host.querySelector('[contenteditable="true"]')!; - drag("dragenter", editor); expect(overlay()).toBeNull(); - expect(host.textContent).toContain("Drop image to upload"); - await act(async () => { drag("drop", editor); }); - expect(uploadImage).toHaveBeenCalledExactlyOnceWith(file); - expect(onFiles).not.toHaveBeenCalled(); - expect(host.textContent).not.toContain("Drop image to upload"); - }); - - it.each(["parent", "readOnly"])("leaves %s editor drops with the composer", (mode) => { - const onFiles = vi.fn(); const onDropFile = vi.fn(); - render(<> - - ); - drag("drop", host.querySelector(".paperclip-mdxeditor-scope")!); - expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - expect(onDropFile).not.toHaveBeenCalled(); - }); - - it("preserves the task attachments section drop handler", () => { - const onFiles = vi.fn(); const onDrop = vi.fn(); - render(<> - - ); - const label = Array.from(host.querySelectorAll("h3")).find(item => item.textContent === "Attachments")!; - drag("drop", label); - expect(onDrop).toHaveBeenCalledOnce(); expect(onFiles).not.toHaveBeenCalled(); - }); - - it("ignores text and link drags", () => { - const onFiles = vi.fn(); - render(); - expect(drag("dragenter", host, ["text/plain", "text/uri-list"]).defaultPrevented).toBe(false); - expect(drag("drop", host, ["text/plain"]).defaultPrevented).toBe(false); - expect(overlay()).toBeNull(); - expect(onFiles).not.toHaveBeenCalled(); - }); - - it("gives the open dialog exclusive ownership and restores the task on close", () => { - const taskFiles = vi.fn(); const newFiles = vi.fn(); - const content = (open: boolean, enabled = true) => <> - - {open ? New task : null} - ; - render(content(true)); - drag("dragenter"); - expect(overlay()?.textContent).toContain("your new task"); - drag("drop"); - expect(newFiles).toHaveBeenCalledExactlyOnceWith([file]); - expect(taskFiles).not.toHaveBeenCalled(); - render(content(true, false)); - drag("dragenter"); drag("drop"); - expect(overlay()).toBeNull(); - expect(taskFiles).not.toHaveBeenCalled(); - render(content(false)); - drag("drop"); - expect(taskFiles).toHaveBeenCalledExactlyOnceWith([file]); - }); - - it("does not send files to the underlying task while another dialog is open", () => { - const onFiles = vi.fn(); - render(<>Settings); - drag("dragenter"); drag("drop"); - expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled(); - }); - - it.each([false, true])("preserves artifact uploads with an external target: %s", (external) => { - const onFiles = vi.fn(); const onUpload = vi.fn(); - const frame = document.createElement("div"); - const header = document.createElement("button"); - frame.append(header); document.body.append(frame); - try { - render(<> - ); - const destination = external ? header : host.querySelector("[data-artifact-file]")!; - drag("dragenter"); expect(overlay()).not.toBeNull(); - drag("dragenter", destination); drag("dragover", destination); - expect(overlay()).toBeNull(); - expect(document.querySelector("[data-artifact-drop-overlay]")).not.toBeNull(); - expect(drag("drop", destination).defaultPrevented).toBe(true); - expect(onUpload).toHaveBeenCalledExactlyOnceWith([file]); - expect(onFiles).not.toHaveBeenCalled(); - drag("dragenter"); expect(overlay()).not.toBeNull(); drag("drop"); - expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - render(
); - expect(frame.hasAttribute("data-file-drop-target")).toBe(false); - } finally { frame.remove(); } - }); - - it("keeps composer drops available while a portaled picker is open", () => { - const onFiles = vi.fn(); - render(<> - ModelChoose model); - const picker = document.querySelector('[data-slot="popover-content"]')!; - expect(picker.getAttribute("role")).toBe("dialog"); - expect(host.contains(picker)).toBe(false); - drag("dragenter"); expect(overlay()).not.toBeNull(); - expect(drag("drop", picker).defaultPrevented).toBe(true); - expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - }); - - it("prevents browser navigation while the new task is read-only", () => { - const onFiles = vi.fn(); - render(New task - - ); - expect(drag("dragenter").defaultPrevented).toBe(true); - expect(drag("dragover").defaultPrevented).toBe(true); - expect(drag("drop").defaultPrevented).toBe(true); - expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled(); - }); - - it("does not accept drops for a concealed composer", () => { - const onFiles = vi.fn(); - render(
); - drag("dragenter"); drag("drop"); - expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled(); - }); - - it("uses the latest callback and clears on disable and unmount", () => { - const previous = vi.fn(); const next = vi.fn(); - render(); - drag("dragenter"); - render(); - expect(overlay()).toBeNull(); drag("drop"); - render(); - drag("drop"); - expect(next).toHaveBeenCalledExactlyOnceWith([file]); expect(previous).not.toHaveBeenCalled(); - drag("dragenter"); render(
); - expect(overlay()).toBeNull(); - expect(drag("drop").defaultPrevented).toBe(false); - }); -}); diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx deleted file mode 100644 index 2f89c34dfd4..00000000000 --- a/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx +++ /dev/null @@ -1,453 +0,0 @@ -// @vitest-environment jsdom -import { sampleHarnesses } from "@/test-support/harness-availability"; - -import { act, useState, type ComponentProps } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { Agent } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { agentsApi } from "@/api/agents"; -import { ComposerRunSettingsPicker } from "./ComposerRunSettingsPicker"; -import { queryKeys } from "@/lib/queryKeys"; -import type { ComposerRunSettings } from "./composer-run-settings"; -import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort"; -import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; - -const agent = { - id: "a1", companyId: "company-1", name: "Clippy", - role: "Engineering Lead", - adapterType: "codex_local", adapterConfig: { model: "gpt-6-sol" }, -} as unknown as Agent; -const options = [{ id: "agent:a1", label: "Clippy" }]; -const agents = new Map([[agent.id, agent]]); -let container: HTMLDivElement | null = null; -let root: ReturnType | null = null; -globalThis.ResizeObserver = class { - observe() {} - disconnect() {} - unobserve() {} -}; -(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -async function click(label: string) { - const button = document.querySelector(`button[aria-label="${label}"]`) - ?? [...document.querySelectorAll('button[role="option"]')].find((item) => item.textContent?.trim().startsWith(label)); - expect(button).toBeDefined(); - flushSync(() => button!.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); -} - -function render(onAssigneeChange: (value: string) => void, onSettingsChange: () => void, useCatalog = false, props: Partial> = {}, insideDialog = false) { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const picker = - - ; - flushSync(() => root!.render(insideDialog ? New task{picker} : picker)); - return queryClient; -} - -beforeEach(() => localStorage.clear()); -afterEach(() => { - vi.restoreAllMocks(); - flushSync(() => root?.unmount()); - root = null; - container?.remove(); - container = null; -}); - -describe("composer assignee picker", () => { - it.each(["antigravity", "copilot"])("applies the Cloud allowlist to saved %s model settings", async acpxAgent => { - const selectedAgent = { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent, model: "saved-model" } } as Agent; - const client = render(vi.fn(), vi.fn(), false, { agents: new Map([[selectedAgent.id, selectedAgent]]) }); - await act(async () => { - client.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } }); - await new Promise(resolve => setTimeout(resolve, 0)); - }); - expect(document.querySelector('[aria-label="Select model and effort"]') !== null).toBe(acpxAgent === "copilot"); - if (acpxAgent === "copilot") { - await click("Select model and effort"); - expect(document.querySelector('[aria-label="Choose exact model"]')).not.toBeNull(); - } - }); - - it.each([false, true])("allows model and effort changes with a fixed conversation agent (mobile: %s)", async (mobile) => { - const onAssigneeChange = vi.fn(); - const onSettingsChange = vi.fn(); - render(onAssigneeChange, onSettingsChange, false, { allowAssigneeChange: false, mobile, - modelOptionsOverride: [{ id: "gpt-6-astra", label: "GPT-6 Astra" }] }); - expect(container!.querySelector('[aria-label="Select assignee"]')).toBeNull(); - await click("Select model and effort"); - expect(document.querySelector('[aria-label="Choose assignee"]')).toBeNull(); - expect(document.querySelector('input[aria-label="Effort"]')).not.toBeNull(); - await click("Choose exact model"); - await click("GPT-6 Astra"); - expect(onSettingsChange).toHaveBeenLastCalledWith({ model: "gpt-6-astra", effort: "high", fast: false }); - expect(onAssigneeChange).not.toHaveBeenCalled(); - }); - - it.each([false, true])("keeps the trigger stable until the picker closes (mobile: %s)", async (mobile) => { - function ControlledPicker() { - const [settings, setSettings] = useState({ model: "gpt-6-sol", effort: "high", fast: false }); - return setSettings(next! as typeof settings)} - onAssigneeChange={vi.fn()} mobile={mobile} modelOptionsOverride={[{ id: "gpt-6-sol", label: "GPT-6 Sol" }, { id: "gpt-6-astra", label: "GPT-6 Astra" }]} />; - } - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - const queryClient = new QueryClient(); - flushSync(() => root!.render()); - const label = () => container!.querySelector('[data-testid="task-chat-composer-model-label"]')!.textContent; - expect(label()).toBe("GPT-6 Sol"); - await click("Select model and effort"); - expect(label()).toBe("Select model"); - const range = document.querySelector('input[aria-label="Effort"]')!; - flushSync(() => { - Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!.call(range, "1"); - range.dispatchEvent(new Event("input", { bubbles: true })); - }); - expect(range.getAttribute("aria-valuetext")).toBe("Low"); - expect(label()).toBe("Select model"); - expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).not.toContain("Low"); - await click("Choose assignee"); - expect(label()).toBe("Select model"); - await click("Clippy"); - expect(label()).toBe("GPT-6 Sol"); - expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).toContain("Low"); - await click("Select model and effort"); - await click("Choose exact model"); - await click("GPT-6 Astra"); - expect(label()).toBe("Select model"); - if (mobile) await click("Close picker"); - else { - await act(async () => { - document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - await new Promise((resolve) => setTimeout(resolve, 0)); - }); - } - expect(label()).toBe("GPT-6 Astra"); - expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).toContain("Low"); - }); - - it.each([ - { mobile: false, view: "settings" as const }, - { mobile: false, view: "models" as const }, - { mobile: false, view: "agents" as const }, - { mobile: true, view: "settings" as const }, - { mobile: true, view: "models" as const }, - { mobile: true, view: "agents" as const }, - ])("allows wheel and touch scrolling in a nested $view picker (mobile: $mobile)", async ({ mobile, view }) => { - render(vi.fn(), vi.fn(), false, { mobile, initialOpen: true, initialView: view }, true); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - const list = document.querySelector(view === "settings" - ? '[data-testid="composer-run-settings-view"]' - : `[role="listbox"][aria-label="${view === "models" ? "Models" : "Assignees"}"]`)!; - expect(list).not.toBeNull(); - list.style.overflowY = "auto"; - Object.defineProperties(list, { - scrollHeight: { configurable: true, value: 1000 }, - clientHeight: { configurable: true, value: 200 }, - }); - const option = list.querySelector("button")!; - const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 }); - option.dispatchEvent(wheel); - expect(wheel.defaultPrevented).toBe(false); - const touch = (type: string, y: number) => { - const event = new Event(type, { bubbles: true, cancelable: true }); - Object.defineProperties(event, { - touches: { value: [{ clientX: 100, clientY: y }] }, - changedTouches: { value: [{ clientX: 100, clientY: y }] }, - }); - option.dispatchEvent(event); - return event; - }; - touch("touchstart", 150); - expect(touch("touchmove", 100).defaultPrevented).toBe(false); - const outsideWheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 }); - document.body.dispatchEvent(outsideWheel); - expect(outsideWheel.defaultPrevented).toBe(true); - }); - - it.each([ - { adapterType: "claude_local", config: {}, label: "Default" }, - { adapterType: "claude_local", config: { model: "claude-opus-5" }, label: "Claude Opus 5" }, - { adapterType: "claude_local", config: { env: { ANTHROPIC_MODEL: "claude-opus-5" } }, label: "Claude Opus 5" }, - { adapterType: "codex_local", config: {}, label: "Default" }, - ])("labels the $adapterType default honestly", ({ adapterType, config, label }) => { - const defaultAgent = { ...agent, adapterType, adapterConfig: config } as Agent; - render(vi.fn(), vi.fn(), false, { settings: null, agents: new Map([[agent.id, defaultAgent]]), - modelOptionsOverride: [{ id: "claude-opus-5", label: "Claude Opus 5" }] }); - expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe(label); - }); - - it("does not offer effort levels for an unknown Claude default", async () => { - const defaultAgent = { ...agent, adapterType: "claude_local", adapterConfig: {} } as Agent; - render(vi.fn(), vi.fn(), false, { settings: null, agents: new Map([[agent.id, defaultAgent]]), - modelOptionsOverride: [{ id: "claude-opus-5", label: "Claude Opus 5" }] }); - await click("Select model and effort"); - expect(document.querySelector('[aria-label="Effort"]')).toBeNull(); - }); - - it.each([ - { remembered: "high", settings: null, overrides: null, restored: "high" }, - { remembered: "off", settings: null, overrides: null, restored: null }, - { remembered: "high", settings: { model: null, effort: "low", fast: false }, overrides: null, restored: null }, - { remembered: "high", settings: null, overrides: { adapterConfig: { modelReasoningEffort: "low" } }, restored: null }, - ])("restores compatible history ($remembered) without replacing explicit settings", ({ remembered, settings, overrides, restored }) => { - rememberComposerEffort("company-1", remembered); - const onSettingsChange = vi.fn(); - render(vi.fn(), onSettingsChange, false, { settings, overrides }); - if (restored) expect(onSettingsChange).toHaveBeenCalledWith({ model: null, effort: restored, fast: false }); - else expect(onSettingsChange).not.toHaveBeenCalled(); - }); - - it("records effort changes and preserves effort when changing to a compatible model", async () => { - const onSettingsChange = vi.fn(); - render(vi.fn(), onSettingsChange, false, { modelOptionsOverride: [{ id: "gpt-6-astra", label: "GPT-6 Astra" }] }); - await click("Select model and effort"); - const range = document.querySelector('input[aria-label="Effort"]')!; - flushSync(() => { - Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!.call(range, "1"); - range.dispatchEvent(new Event("change", { bubbles: true })); - range.dispatchEvent(new Event("input", { bubbles: true })); - }); - expect(getLastComposerEffort("company-1")).toBe("low"); - await click("Choose exact model"); - await click("GPT-6 Astra"); - expect(onSettingsChange).toHaveBeenLastCalledWith({ model: "gpt-6-astra", effort: "high", fast: false }); - await click("Reset to agent default"); - expect(getLastComposerEffort("company-1")).toBeNull(); - }); - it("lets the assignee and model use the available composer width", () => { - render(vi.fn(), vi.fn()); - const trigger = container!.querySelector('[data-testid="task-chat-composer-assignee"]'); - const assignee = trigger!.querySelector('[data-testid="task-chat-composer-assignee-label"]'); - const model = container!.querySelector('[data-testid="task-chat-composer-model-label"]'); - - expect(trigger?.className).toContain("max-w-full"); - expect(trigger?.className).not.toContain("max-w-64"); - expect(assignee?.className).toContain("min-w-0"); - expect(assignee?.className).not.toContain("max-w-24"); - expect(model?.className).toContain("min-w-0"); - expect(assignee?.className).toContain("truncate"); - expect(model?.className).toContain("truncate"); - }); - - it("finds assignees by their displayed role and harness", async () => { - render(vi.fn(), vi.fn()); - await click("Select assignee"); - const input = document.querySelector('input[aria-label="Search assignees"]'); - expect(input).not.toBeNull(); - const setValue = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!; - for (const query of ["Engineering Lead", "Codex"]) { - flushSync(() => { - setValue.call(input, query); - input!.dispatchEvent(new Event("input", { bubbles: true })); - }); - expect([...document.querySelectorAll('button[role="option"]')] - .some((option) => option.textContent?.includes("Clippy"))).toBe(true); - } - }); - - it("offers the Codex CLI catalog instead of unrelated OpenAI API models", async () => { - vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([ - { id: "gpt-6-sol", label: "GPT-6 Sol" }, - { id: "gpt-5.5", label: "GPT-5.5" }, - ]); - render(vi.fn(), vi.fn(), true); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - await click("Select model and effort"); - await click("Choose exact model"); - const options = [...document.querySelectorAll('button[role="option"]')] - .map((item) => item.textContent ?? ""); - expect(options.some((item) => item.includes("gpt-5.5"))).toBe(true); - expect(options.some((item) => item.includes("gpt-6-sol"))).toBe(true); - expect(options.some((item) => item.includes("gpt-image"))).toBe(false); - expect(options.some((item) => item.includes("text-embedding"))).toBe(false); - expect(document.body.textContent).not.toContain("Loading models…"); - }); - - it("shows an instance-declared Codex model list instead of bundled alternatives", async () => { - const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([ - { id: "private-codex", label: "Private Codex" }, - ]); - render(vi.fn(), vi.fn(), true); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(loadModels).toHaveBeenCalledWith("company-1", "codex_local", { - environmentId: null, - provider: undefined, - }); - await click("Select model and effort"); - await click("Choose exact model"); - const choices = [...document.querySelectorAll('button[role="option"]')] - .map((item) => item.textContent ?? ""); - expect(choices.some((item) => item.includes("Private Codex"))).toBe(true); - expect(choices.some((item) => item.includes("GPT-6 Sol"))).toBe(false); - }); - - it.each(["copilot", "antigravity"])("keeps %s discovery passive during reconnect reconciliation and refreshes on opening", async acpxAgent => { - const copilot = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1", - adapterConfig: { provider: "acpx", acpxAgent, model: "gpt-5.6-luna" } } as Agent; - const loadModels = vi.spyOn(agentsApi, "adapterModels") - .mockResolvedValueOnce([{ id: "gpt-5.6-luna", label: "Copilot Luna" }]) - .mockResolvedValue([{ id: "gpt-5.6-luna", label: "Updated Copilot Luna" }]); - const client = render(vi.fn(), vi.fn(), true, { agents: new Map([[agent.id, copilot]]), settings: null }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(loadModels).not.toHaveBeenCalled(); - await act(async () => { await client.invalidateQueries({ type: "active" }, { cancelRefetch: false }); }); - expect(loadModels).not.toHaveBeenCalled(); - await click("Select model and effort"); - expect(loadModels).toHaveBeenCalledTimes(1); - await act(async () => { await client.invalidateQueries({ type: "active" }, { cancelRefetch: false }); }); - expect(loadModels).toHaveBeenCalledTimes(1); - await act(async () => { - document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - await new Promise((resolve) => setTimeout(resolve, 0)); - }); - await click("Select model and effort"); - expect(loadModels).toHaveBeenCalledTimes(2); - await click("Choose exact model"); - expect(document.body.textContent).toContain("Updated Copilot Luna"); - }); - - it.each([ - { name: "Copilot", acpxAgent: "copilot", provider: "github", method: "api_key", model: "gpt-5.6-luna", label: "Copilot Luna" }, - { name: "Antigravity", acpxAgent: "antigravity", provider: "google", method: "subscription", model: "gemini-exact", label: "Personal Gemini" }, - ] as const)("discovers $name task models with the assignee connection and environment", async ({ acpxAgent, provider, method, model, label }) => { - const binding = { provider, method, mode: "shared", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "33333333-3333-4333-8333-333333333333" } as const; - const selectedAgent = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1", - adapterConfig: { provider: "acpx", acpxAgent, model }, runtimeConfig: { aiConnection: binding } } as Agent; - const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([{ id: model, label }]); - render(vi.fn(), vi.fn(), true, { agents: new Map([[agent.id, selectedAgent]]), settings: null }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(loadModels).not.toHaveBeenCalled(); - await click("Select model and effort"); - expect(loadModels).toHaveBeenCalledWith("company-1", "paperclip_runner", { - environmentId: "daytona-1", provider: "acpx", poolId: undefined, - acpxAgent, agentId: agent.id, aiConnection: binding, - }); - await click("Choose exact model"); - expect(document.body.textContent).toContain(label); - expect(document.body.textContent).not.toContain("Claude Sonnet"); - }); - - it.each(["subscription", "api_key"] as const)("allows an exact Antigravity model absent from its %s catalog", async method => { - const selectedAgent = { ...agent, adapterType: "paperclip_runner", - adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-default" }, - runtimeConfig: { aiConnection: { provider: "google", method, mode: "responsible_user" } } } as Agent; - vi.spyOn(agentsApi, "adapterModels").mockResolvedValue([{ id: "gemini-listed", label: "Listed native model" }]); - const onSettingsChange = vi.fn(); - render(vi.fn(), onSettingsChange, true, { agents: new Map([[agent.id, selectedAgent]]), settings: null, - initialOpen: true, initialView: "models", initialModelSearch: "gemini-custom-exact" }); - await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); - const manual = [...document.querySelectorAll("button")].find(button => button.textContent?.includes("Use exact ID")); - expect(manual?.disabled).toBe(false); - await act(async () => manual!.click()); - expect(onSettingsChange).toHaveBeenLastCalledWith(expect.objectContaining({ model: "gemini-custom-exact" })); - }); - - it("preserves settings when the selected assignee is chosen again", async () => { - const onAssigneeChange = vi.fn(); - const onSettingsChange = vi.fn(); - render(onAssigneeChange, onSettingsChange); - await click("Select assignee"); - await click("Clippy"); - expect(onAssigneeChange).not.toHaveBeenCalled(); - expect(onSettingsChange).not.toHaveBeenCalled(); - expect(document.querySelector('[role="listbox"]')).toBeNull(); - }); - - it("offers No assignee and clears settings when selected", async () => { - const onAssigneeChange = vi.fn(); - const onSettingsChange = vi.fn(); - render(onAssigneeChange, onSettingsChange); - await click("Select assignee"); - await click("No assignee"); - expect(onAssigneeChange).toHaveBeenCalledWith(""); - expect(onSettingsChange).toHaveBeenCalledWith(null); - expect(document.querySelector('[role="listbox"]')).toBeNull(); - }); - - it.each(["", "user:me"])("hides model and effort for %s and opens assignees in one click", async (assigneeValue) => { - const loadModels = vi.spyOn(agentsApi, "adapterModels"); - render(vi.fn(), vi.fn(), true, { - assigneeValue, - currentAssigneeValue: assigneeValue, - options: [...options, { id: "user:me", label: "Me" }], - }); - expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')).toBeNull(); - expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull(); - expect(container!.textContent).not.toContain("Harness default"); - expect(container!.textContent).not.toContain("High"); - await click("Select assignee"); - expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull(); - expect(document.querySelector('[aria-label="Effort"]')).toBeNull(); - expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull(); - expect(document.body.textContent).not.toContain("Choose an agent"); - expect(loadModels).not.toHaveBeenCalled(); - }); - - it.each([false, true])("hides unsupported Muse settings without loading a catalog (mobile: %s)", async (mobile) => { - const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValue([]); - const onSettingsChange = vi.fn(); - const muse = { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "muse", model: "old-model" } } as Agent; - rememberComposerEffort("company-1", "high"); - render(vi.fn(), onSettingsChange, true, { mobile, settings: null, agents: new Map([[muse.id, muse]]) }); - expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull(); - expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')).toBeNull(); - await click("Select assignee"); - expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull(); - expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull(); - expect(document.querySelector('[aria-label="Effort"]')).toBeNull(); - expect(loadModels).not.toHaveBeenCalled(); - expect(onSettingsChange).not.toHaveBeenCalled(); - }); - - it.each([false, true])("removes an open model menu when the same agent switches to Muse (mobile: %s)", async (mobile) => { - const onSettingsChange = vi.fn(); - function ControlledPicker() { - const [muse, setMuse] = useState(false); - const [settings, setSettings] = useState({ model: "gpt-6-sol", effort: "high", fast: true }); - const selectedAgent = muse - ? { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "muse" } } as Agent - : agent; - return <> - - { onSettingsChange(next); setSettings(next); }} onAssigneeChange={vi.fn()} mobile={mobile} - modelOptionsOverride={[{ id: "gpt-6-sol", label: "GPT-6 Sol" }]} /> - ; - } - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - flushSync(() => root!.render()); - await click("Select model and effort"); - await click("Choose exact model"); - expect(document.querySelector('[aria-label="Search or paste a model ID"]')).not.toBeNull(); - await click("Switch to Muse"); - expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull(); - expect(document.querySelector('[aria-label="Search or paste a model ID"]')).toBeNull(); - expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull(); - expect(document.querySelector('[aria-label="Effort"]')).toBeNull(); - expect(document.querySelector('[data-testid="model-unavailable"]')?.textContent).toContain("Muse chooses its model and effort"); - expect(onSettingsChange).toHaveBeenCalledOnce(); - expect(onSettingsChange).toHaveBeenCalledWith(null); - }); - - it("opens the assignee list directly on mobile", async () => { - render(vi.fn(), vi.fn(), false, { mobile: true }); - await click("Select assignee"); - expect(document.querySelector('[data-testid="composer-mobile-dialog"]')).not.toBeNull(); - expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull(); - expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull(); - }); -}); diff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx deleted file mode 100644 index 0f72986da4f..00000000000 --- a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx +++ /dev/null @@ -1,705 +0,0 @@ -// @vitest-environment jsdom - -import { act, type ComponentProps } from "react"; -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { IssueQueuedCommentQueue } from "@paperclipai/shared"; -import { mergePendingIssueQueuedComments } from "@/lib/issue-queued-comment-queue"; -import { ThemeProvider } from "@/context/ThemeContext"; -import { MemoryRouter } from "@/lib/router"; -import { - reorderQueuedMessageEntries, - TaskChatQueuedMessages, -} from "./TaskChatQueuedMessages"; - -function deferred() { - let resolve!: (value: T) => void; - let reject!: (error: Error) => void; - const promise = new Promise((innerResolve, innerReject) => { - resolve = innerResolve; - reject = innerReject; - }); - return { promise, resolve, reject }; -} - -const queue: IssueQueuedCommentQueue = { - issueId: "issue-1", - queueId: "wake-1", - state: "deferred", - targetRunId: "run-1", - revision: "rev-1", - protocol: "paperclip_runner_v1", - steeringDisposition: "available", - entries: ["First queued message", "Second queued message"].map( - (body, position) => ({ - comment: { - id: `comment-${position + 1}`, - companyId: "company-1", - issueId: "issue-1", - authorType: "user", - authorAgentId: null, - authorUserId: "user-1", - body, - presentation: null, - metadata: null, - createdAt: new Date(), - updatedAt: new Date(), - }, - position, - canEdit: true, - canDiscard: true, - }), - ), -}; - -describe("TaskChatQueuedMessages", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - }); - - function render( - overrides: Partial> = {}, - ) { - const props = { - queue, - onEdit: vi.fn(), - onReorder: vi.fn().mockResolvedValue(undefined), - onSteer: vi.fn().mockResolvedValue(undefined), - onDiscard: vi.fn().mockResolvedValue(undefined), - ...overrides, - }; - flushSync(() => root.render()); - return props; - } - - it("keeps saved input visible without duplicating the task status", () => { - const message = "Waiting for the previous environment to stop. Your message will start automatically."; - render({ queue: { ...queue, executionWait: { reason: "remote_cleanup", message } } }); - expect(container.textContent).not.toContain(message); - expect(container.textContent).toContain("First queued message"); - render(); - expect(container.textContent).not.toContain(message); - }); - - it("says why a chat message held in the outbox waits, without offering queue actions", () => { - const message = "CEO reached its daily run limit. Your message is saved and sends automatically when the limit resets at 00:00 UTC."; - render({ queue: { ...queue, queueId: null, targetRunId: null, steeringDisposition: "unsupported", - executionWait: { reason: "heartbeat.daily_run_limit", message }, - entries: queue.entries.slice(0, 1).map(entry => ({ ...entry, canEdit: false, canDiscard: false })) } }); - expect([...container.querySelectorAll('p[role="status"]')].map(node => node.textContent)).toEqual([message]); - expect(container.textContent).toContain("First queued message"); - expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')?.disabled ?? true).toBe(true); - expect(container.querySelector('[data-testid="task-chat-queued-discard-comment-1"]')?.disabled).toBe(true); - }); - - it("renders each queued message once as a compact one-line row", () => { - render(); - const pane = container.querySelector( - '[data-testid="task-chat-queued-messages"]', - ); - expect(pane?.classList).toContain("mx-3"); - expect(pane?.classList).toContain("rounded-b-none"); - expect(pane?.classList).toContain("border-b-0"); - expect(pane?.classList).toContain("-mb-px"); - expect( - container.querySelectorAll('[data-testid^="task-chat-queued-message-"]'), - ).toHaveLength(2); - expect(container.textContent).toContain("First queued message"); - expect(container.textContent).toContain("Second queued message"); - }); - - it("renders queued Markdown and screenshot thumbnails without showing image syntax", () => { - const body = "Check **mobile** and *desktop* with `pnpm verify`.\n\n![mobile.png](/api/attachments/mobile/content)\n![desktop.png](/api/attachments/desktop/content)"; - render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } }); - const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!; - expect(row.querySelector("strong")?.textContent).toBe("mobile"); - expect(row.querySelector("em")?.textContent).toBe("desktop"); - expect(row.querySelector("code")?.textContent).toBe("pnpm verify"); - expect([...row.querySelectorAll("img")].map(img => [img.alt, img.getAttribute("src")])).toEqual([ - ["mobile.png", "/api/attachments/mobile/content"], - ["desktop.png", "/api/attachments/desktop/content"], - ]); - expect(row.textContent).not.toContain("!["); - expect(row.textContent).not.toContain("/api/attachments"); - }); - - it("shows a thumbnail for an image-only queued message", () => { - const body = "![screen.png](/api/attachments/screen/content)"; - render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } }); - expect(container.querySelector('img[alt="screen.png"]')?.getAttribute("src")).toBe("/api/attachments/screen/content"); - expect(container.textContent).not.toContain(body); - }); - - it("only loads local attachment images and counts the remaining screenshots", () => { - const urls = [ - "/api/attachments/first/content", "/api/assets/second/content?download=0", - "/api/attachments/third/content", "/api/attachments/fourth/content", - "https://other.example/api/attachments/pixel/content", "//other.example/pixel.png", - "javascript:alert", "data:image/png;base64,AAAA", "/other/pixel.png", - "/api/attachments/first/content/extra", "/api/attachments/first/content#fragment", - ]; - const body = urls.map((url, index) => `![screen-${index}](${url})`).join("\n"); - render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } }); - const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!; - expect([...row.querySelectorAll("img")].map(image => image.getAttribute("src"))).toEqual(urls.slice(0, 3)); - expect(row.querySelector('[aria-label="Queued images"]')?.textContent).toBe("+1"); - }); - - it("omits inline images from the compact text without exposing their URLs", () => { - const body = "Check ![inline](/api/attachments/inline/content) then **retry**."; - render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } }); - const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!; - expect(row.querySelector("strong")?.textContent).toBe("retry"); - expect(row.textContent).toContain("Check then retry."); - expect(row.textContent).not.toContain("/api/attachments"); - expect(row.querySelector("img")).toBeNull(); - }); - - it.each(["legacy", "native", "native-plan"] as const)("shows a read-only response and sends it only on click for %s", async (runtime) => { - const entry = { ...queue.entries[0], canEdit: false, canDiscard: false, - comment: { ...queue.entries[0].comment, body: 'Accepted: Build the app\n\n{"revision": "v1"}' }, - source: { kind: "interaction" as const, interactionId: "confirmation-1", interactionKind: "request_confirmation", - requiresFreshSession: runtime === "native-plan" } }; - const props = render({ queue: { ...queue, entries: [entry], - protocol: runtime === "legacy" ? "legacy" : "paperclip_runner_v1" }, - onInterrupt: vi.fn().mockResolvedValue(undefined) }); - expect(props.onSteer).not.toHaveBeenCalled(); - expect(props.onInterrupt).not.toHaveBeenCalled(); - expect(container.textContent).toContain("Accepted: Build the app"); - expect(container.textContent).not.toContain('"revision"'); - expect(container.querySelector('[aria-label^="Reorder"]')?.disabled).toBe(true); - expect(container.querySelector('[data-testid^="task-chat-queued-discard-"]')?.disabled).toBe(true); - expect(reorderQueuedMessageEntries([entry, queue.entries[1]], "comment-1", "comment-2")).toBeNull(); - const action = runtime === "native" ? "steer" : "interrupt"; - await act(async () => { container.querySelector(`[data-testid="task-chat-queued-${action}-comment-1"]`)!.click(); }); - if (action === "steer") expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1"); - else expect(props.onInterrupt).toHaveBeenCalledOnce(); - }); - - it("shows a declined connection request as readable text, never its raw JSON receipt (BUG-08)", () => { - const receipt = JSON.stringify({ interactionId: "slack-1", kind: "connection_intent", status: "rejected", - payload: { serviceSlug: "slack", serviceName: "Slack" }, result: { outcome: "declined" } }, null, 2); - const entry = { ...queue.entries[0], canEdit: false, canDiscard: false, - comment: { ...queue.entries[0].comment, id: "slack-1", body: `Rejected: Connect Slack\n\n${receipt}` }, - source: { kind: "interaction" as const, interactionId: "slack-1", interactionKind: "connection_intent", - summary: "Declined: Slack connection" } }; - render({ queue: { ...queue, entries: [entry], steeringDisposition: "temporarily_unavailable" } }); - const row = container.querySelector('[data-testid="task-chat-queued-message-slack-1"]')!; - const hoverAndLabels = [...row.querySelectorAll("[title], [aria-label]")] - .flatMap((element) => [element.getAttribute("title"), element.getAttribute("aria-label")]) - .filter((text): text is string => Boolean(text)); - expect(hoverAndLabels.length).toBeGreaterThan(0); - for (const text of hoverAndLabels) { - expect(text).not.toContain("{"); - expect(text).not.toContain("interactionId"); - } - expect(row.textContent).toContain("Declined: Slack connection"); - expect(row.querySelector('[title="Declined: Slack connection"]')).not.toBeNull(); - }); - - it("reorders the complete queue and rewrites contiguous positions", () => { - const next = reorderQueuedMessageEntries( - queue.entries, - "comment-2", - "comment-1", - ); - - expect(next?.map((entry) => entry.comment.id)).toEqual([ - "comment-2", - "comment-1", - ]); - expect(next?.map((entry) => entry.position)).toEqual([0, 1]); - }); - - it("removes the selected steering row before the provider acknowledges it", async () => { - const acknowledgement = deferred(); - const props = render({ - onSteer: vi.fn().mockReturnValue(acknowledgement.promise), - }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - ) - ?.click(); - await Promise.resolve(); - }); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1"); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).toBeNull(); - expect(container.textContent).toContain("Steering queued message."); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-2"]', - ), - ).not.toBeNull(); - - await act(async () => { - render({ ...props, queue: { ...queue, entries: [...queue.entries] } }); - }); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull(); - - await act(async () => { - acknowledgement.resolve(); - await acknowledgement.promise; - }); - }); - - it("clears the entire interrupt queue immediately and restores it inline on failure", async () => { - let rejectInterrupt!: (error: Error) => void; - const interrupted = new Promise((_, reject) => { rejectInterrupt = reject; }); - const props = render({ queue: { ...queue, protocol: "legacy", steeringDisposition: "unsupported" }, - onInterrupt: vi.fn().mockReturnValue(interrupted) }); - await act(async () => { - container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); - }); - expect(props.onInterrupt).toHaveBeenCalledOnce(); - expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); - await act(async () => { rejectInterrupt(new Error("Connection lost")); await interrupted.catch(() => undefined); }); - expect(container.querySelectorAll('[data-testid^="task-chat-queued-message-"]')).toHaveLength(2); - expect(container.textContent).toContain("Couldn’t interrupt. Message is still queued."); - }); - - it.each(["steer", "interrupt"] as const)("shows a delivery error even when the queue becomes empty while %s is pending", async action => { - const delivery = deferred(); - const props = render({ queue: { ...queue, protocol: action === "interrupt" ? "legacy" : "paperclip_runner_v1" }, - onSteer: vi.fn().mockReturnValue(delivery.promise), onInterrupt: vi.fn().mockReturnValue(delivery.promise) }); - await act(async () => { container.querySelector(`[data-testid="task-chat-queued-${action}-comment-1"]`)!.click(); }); - await act(async () => { render({ ...props, queue: { ...props.queue, revision: "empty-poll", entries: [] } }); }); - await act(async () => { delivery.reject(new Error("Connection lost")); await delivery.promise.catch(() => undefined); }); - const error = action === "steer" ? "Couldn’t steer." : "Couldn’t interrupt."; - expect([...container.querySelectorAll('[role="status"]')].some(status => status.textContent?.includes(error))).toBe(true); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull(); - }); - - it("does not restore a message discarded elsewhere while steering was pending", async () => { - let rejectSteer!: (error: Error) => void; - const delivery = new Promise((_, reject) => { rejectSteer = reject; }); - const props = render({ onSteer: vi.fn().mockReturnValue(delivery) }); - await act(async () => { container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')!.click(); }); - await act(async () => { render({ ...props, queue: { ...queue, revision: "rev-2", entries: [queue.entries[1]] } }); }); - await act(async () => { rejectSteer(new Error("Queue changed")); await delivery.catch(() => undefined); }); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull(); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-2"]')).not.toBeNull(); - expect(container.textContent).toContain("Couldn’t steer."); - }); - - it("keeps a row queued when steering fails and announces the retryable state", async () => { - render({ - onSteer: vi.fn().mockRejectedValue(new Error("steering_timeout")), - }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - ) - ?.click(); - }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).not.toBeNull(); - expect(container.textContent).toContain( - "Couldn’t steer. Message is still queued.", - ); - }); - - it("disables steering when the provider does not advertise it", () => { - render({ queue: { ...queue, steeringDisposition: "unsupported" } }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - )?.disabled, - ).toBe(true); - }); - - it.each(["temporarily_unavailable", "unsupported"] as const)( - "offers an explicit interrupt fallback when native steering is %s", - async (steeringDisposition) => { - const props = render({ - queue: { ...queue, steeringDisposition }, - onInterrupt: vi.fn().mockResolvedValue(undefined), - }); - const interrupt = container.querySelector( - '[data-testid="task-chat-queued-interrupt-comment-1"]', - ); - expect(interrupt).not.toBeNull(); - expect(interrupt!.disabled).toBe(false); - expect(interrupt!.textContent).toContain("Interrupt"); - await act(async () => { interrupt!.click(); }); - expect(props.onInterrupt).toHaveBeenCalledOnce(); - expect(props.onSteer).not.toHaveBeenCalled(); - expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); - }, - ); - - it("keeps same-turn steering when the provider is available, even with an interrupt callback", async () => { - const props = render({ onInterrupt: vi.fn().mockResolvedValue(undefined) }); - expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')).toBeNull(); - await act(async () => { - container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')!.click(); - }); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1"); - expect(props.onInterrupt).not.toHaveBeenCalled(); - }); - - it("waits for authoritative discard acknowledgement before removing the row", async () => { - const acknowledgement = deferred(); - render({ onDiscard: vi.fn().mockReturnValue(acknowledgement.promise) }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ) - ?.click(); - await Promise.resolve(); - }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).not.toBeNull(); - expect(container.textContent).not.toContain("Queued message discarded."); - - await act(async () => { - acknowledgement.resolve(); - await acknowledgement.promise; - }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).toBeNull(); - expect(container.textContent).toContain("Queued message discarded."); - }); - - it.each(["wake-1", null])("keeps a too-late discard visible with an explicit error (queue=%s)", async (queueId) => { - render({ - queue: { ...queue, queueId }, - onDiscard: vi.fn().mockRejectedValue({ - body: { details: { code: "queued_comment_already_dispatching" } }, - }), - }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ) - ?.click(); - }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).not.toBeNull(); - expect(container.textContent).toContain( - "Too late to discard: this message is already being sent.", - ); - }); - - it("shows stale revisions without announcing a discard", async () => { - render({ - onDiscard: vi.fn().mockRejectedValue({ - body: { details: { code: "queued_comment_revision_conflict" } }, - }), - }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ) - ?.click(); - }); - expect(container.textContent).toContain( - "The queue changed in another session. Review it and try again.", - ); - expect(container.textContent).not.toContain("Queued message discarded."); - }); - - it("can discard a saved message while queue acknowledgement is pending", async () => { - const merged = mergePendingIssueQueuedComments({ - issueId: queue.issueId, - authoritativeQueue: queue, - pendingComments: [{ - comment: { ...queue.entries[0].comment, id: "optimistic-next" }, - targetRunId: queue.targetRunId, - }], - fallbackProtocol: queue.protocol, - })!; - expect(merged.queueId).toBeNull(); - const props = render({ queue: merged }); - const discard = container.querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ); - expect(discard?.disabled).toBe(false); - expect(container.querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - )?.disabled).toBe(true); - await act(async () => { discard!.click(); }); - expect(props.onDiscard).toHaveBeenCalledWith("comment-1", "rev-1"); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull(); - }); - - it("keeps another author's saved message protected while acknowledgement is pending", () => { - const props = render({ - queue: { - ...queue, - queueId: null, - entries: [{ ...queue.entries[0], canDiscard: false }], - }, - }); - const discard = container.querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ); - expect(discard?.disabled).toBe(true); - discard!.click(); - expect(props.onDiscard).not.toHaveBeenCalled(); - }); - - it("can discard a local optimistic row before the queue id is acknowledged", async () => { - const optimisticQueue = { - ...queue, - queueId: null, - state: "deferred" as const, - entries: [ - { - ...queue.entries[0], - comment: { - ...queue.entries[0].comment, - id: "optimistic-local-1", - }, - }, - ], - }; - const props = render({ queue: optimisticQueue }); - - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-discard-optimistic-local-1"]', - ) - ?.click(); - }); - - expect(props.onDiscard).toHaveBeenCalledWith("optimistic-local-1", "rev-1"); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-optimistic-local-1"]', - ), - ).toBeNull(); - }); - - it("delivers legacy queued messages to a live target", async () => { - const targetRunId = "run-1"; - const onInterrupt = vi.fn().mockResolvedValue(undefined); - render({ - queue: { - ...queue, - targetRunId, - protocol: "legacy", - steeringDisposition: "unsupported", - }, - onInterrupt, - }); - - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-interrupt-comment-1"]', - ) - ?.click(); - }); - - expect(onInterrupt).toHaveBeenCalledOnce(); - expect( - container.querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - ), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).toBeNull(); - }); - it("keeps deferred sends visible and explains their current wait", async () => { - const saved = { ...queue, targetRunId: null, executionWait: { reason: "decision_pending", message: "Resolve the pending approval before sending." } }; - const onInterrupt = vi.fn().mockResolvedValue(saved); - render({ queue: saved, onInterrupt }); - await act(async () => { container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); }); - expect(container.textContent).toContain("First queued message"); - expect(container.textContent).toContain(saved.executionWait.message); - expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')?.disabled).toBe(false); - }); - it("shows an Interrupt as sent while the stopped turn hands off, with no wait or error text", async () => { - const handoff = { ...queue, targetRunId: null, - executionWait: { reason: "interrupt_handoff", message: "Sending your messages." } }; - const onInterrupt = vi.fn().mockResolvedValue(handoff); - render({ queue: { ...queue, steeringDisposition: "temporarily_unavailable" }, onInterrupt }); - await act(async () => { container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); }); - // A poll during the hand-off still lists the saved messages. - render({ queue: handoff, onInterrupt }); - await act(async () => {}); - expect(container.textContent).not.toContain("First queued message"); - expect(container.textContent).not.toContain("Sending your messages."); - expect(container.textContent).not.toContain("Couldn’t"); - expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); - }); - it("clears a deferred wait message when a refreshed queue finishes sending", async () => { - const saved = { ...queue, targetRunId: null, executionWait: { reason: "decision_pending", message: "Resolve the pending approval before sending." } }; - render({ queue: saved, onInterrupt: vi.fn().mockResolvedValue(saved) }); - await act(async () => { container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); }); - expect(container.textContent).toContain(saved.executionWait.message); - render({ queue: { ...saved, queueId: null, entries: [], state: null, executionWait: null } }); - await act(async () => {}); - expect(container.textContent).not.toContain(saved.executionWait.message); - expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); - }); - it.each(["legacy", "paperclip_runner_v1"] as const)("sends a saved %s queue explicitly after Stop", async (protocol) => { - const onInterrupt = vi.fn().mockResolvedValue(undefined); - render({ queue: { ...queue, targetRunId: null, protocol, steeringDisposition: "temporarily_unavailable" }, onInterrupt }); - expect(onInterrupt).not.toHaveBeenCalled(); - const send = container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]'); - expect(send?.textContent).toBe("Send"); - expect(send?.getAttribute("aria-label")).toBe("Send queued messages"); - expect(send?.disabled).toBe(false); - await act(async () => { send!.click(); }); - expect(onInterrupt).toHaveBeenCalledOnce(); - expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).toBeNull(); - }); - - - describe("automatic steering", () => { - const delay = 5_000; - const fresh = (overrides: Partial = {}): IssueQueuedCommentQueue => { - const at = new Date(Date.now()); - return { ...queue, ...overrides, entries: queue.entries.slice(0, 1).map(entry => ({ - ...entry, comment: { ...entry.comment, createdAt: at, updatedAt: at } })) }; - }; - const advance = async (ms: number) => { await act(async () => { vi.advanceTimersByTime(ms); await Promise.resolve(); }); }; - const countdown = () => container.querySelector('[data-testid="task-chat-queued-auto-steer-comment-1"]'); - - beforeEach(() => { vi.useFakeTimers({ now: new Date("2026-11-07T12:00:00Z") }); }); - afterEach(() => { vi.useRealTimers(); }); - - it("shows a countdown with Edit and Cancel, then steers into the live turn", async () => { - const props = render({ queue: fresh(), autoSteerDelayMs: delay }); - expect(countdown()?.textContent).toContain("Sending in 5s"); - expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).toBeNull(); - await advance(2_100); - expect(countdown()?.textContent).toContain("Sending in 3s"); - expect(props.onSteer).not.toHaveBeenCalled(); - await advance(3_000); - expect(props.onSteer).toHaveBeenCalledOnce(); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1"); - }); - - it("gives a saved edit a full window while another row's countdown keeps the clock running", async () => { - const start = Date.now(); - const twoRows: IssueQueuedCommentQueue = { ...queue, entries: queue.entries.slice(0, 2).map((entry, index) => { - const at = new Date(start + index * 4_000); - return { ...entry, comment: { ...entry.comment, createdAt: at, updatedAt: at } }; - }) }; - // comment-1 counts down first; the person opens it for editing at 1 s. - const props = render({ queue: twoRows, autoSteerDelayMs: delay }); - await advance(1_000); - await act(async () => { render({ ...props, editingCommentId: "comment-1" }); }); - // comment-2 counts down to start + 9 s and keeps the clock ticking past - // comment-1's old deadline. - await advance(5_000); - expect(props.onSteer).not.toHaveBeenCalled(); - const saved = { ...twoRows, revision: "rev-2", entries: twoRows.entries.map((entry, index) => index === 0 - ? { ...entry, comment: { ...entry.comment, body: "Edited", updatedAt: new Date(Date.now()) } } : entry) }; - await act(async () => { render({ ...props, queue: saved, editingCommentId: null }); }); - await advance(500); - expect(props.onSteer).not.toHaveBeenCalledWith("comment-1", expect.anything()); - expect(countdown()?.textContent).toContain("Sending in"); - await advance(5_000); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-2"); - }); - - it("keeps a cancelled message in the queue with its explicit Steer button", async () => { - const props = render({ queue: fresh(), autoSteerDelayMs: delay }); - await act(async () => { - container.querySelector('[data-testid="task-chat-queued-auto-steer-cancel-comment-1"]')?.click(); - await Promise.resolve(); - }); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - expect(countdown()).toBeNull(); - expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).not.toBeNull(); - }); - - it("waits while the message is being edited and restarts from the saved revision", async () => { - const queued = fresh(); - const props = render({ queue: queued, autoSteerDelayMs: delay }); - await act(async () => { - container.querySelector('[data-testid="task-chat-queued-auto-steer-edit-comment-1"]')?.click(); - await Promise.resolve(); - }); - expect(props.onEdit).toHaveBeenCalledWith("comment-1"); - render({ ...props, editingCommentId: "comment-1" }); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - // The save changes the comment; its countdown starts again from that change. - const saved = { ...queued, revision: "rev-2", entries: queued.entries.map(entry => ({ - ...entry, comment: { ...entry.comment, body: "Edited", updatedAt: new Date(Date.now()) } })) }; - await act(async () => { render({ ...props, queue: saved, editingCommentId: null }); }); - expect(countdown()?.textContent).toContain("Sending in 5s"); - await advance(5_100); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-2"); - }); - - it("keeps the ordinary queue while steering is unavailable or unsupported", async () => { - for (const steeringDisposition of ["temporarily_unavailable", "unsupported"] as const) { - const props = render({ queue: fresh({ steeringDisposition }), autoSteerDelayMs: delay }); - expect(countdown()).toBeNull(); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - } - }); - - it("tries each message revision once, then leaves it queued after a failure", async () => { - const props = render({ queue: fresh(), autoSteerDelayMs: delay, onSteer: vi.fn().mockRejectedValue(new Error("rejected")) }); - await advance(5_100); - await advance(10_000); - expect(props.onSteer).toHaveBeenCalledOnce(); - expect(container.textContent).toContain("Couldn’t steer. Message is still queued."); - expect(countdown()).toBeNull(); - }); - - it("never sends someone else’s message or a saved card response automatically", async () => { - const notMine = fresh(); - notMine.entries = notMine.entries.map(entry => ({ ...entry, canEdit: false })); - const card = fresh(); - card.entries = card.entries.map(entry => ({ ...entry, source: { kind: "interaction", summary: "Approved" } as never })); - for (const candidate of [notMine, card]) { - const props = render({ queue: candidate, autoSteerDelayMs: delay }); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - } - }); - - it("stays off unless the caller enables it", async () => { - const props = render({ queue: fresh() }); - expect(countdown()).toBeNull(); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx b/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx deleted file mode 100644 index a79889ab350..00000000000 --- a/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx +++ /dev/null @@ -1,1712 +0,0 @@ -// @vitest-environment jsdom - -import type { ExecutionProjection } from "@paperclipai/shared"; -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ThemeProvider } from "@/context/ThemeContext"; -import { MemoryRouter } from "@/lib/router"; -import { TaskChatRunnerTurn } from "./TaskChatRunnerTurn"; -import { TaskChatRequestHistoryContext } from "./TaskChatComposerTakeoverContext"; -import { transcriptToTaskChatItems } from "./transcript-adapter"; -import type { - TaskChatItem, - TaskChatProviderActivityFamily, - TaskChatProviderActivityItem, - TaskChatRuntimeRequestDecision, - TaskChatRuntimeRequestItem, -} from "./task-chat-model"; - -describe("TaskChatRunnerTurn", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - act(() => root.unmount()); - container.remove(); - }); - - const render = ( - items: TaskChatItem[], - status = "running", - runId: string | null = "run-1", - onRuntimeRequestDecision?: ( - item: TaskChatRuntimeRequestItem, - decision: TaskChatRuntimeRequestDecision, - ) => void, - awaitingContinuation = false, - continuedAfterSteering = false, - execution?: ExecutionProjection, - preparationLabel?: string, - ) => - act(() => - root.render( - - - - - - - , - ), - ); - - it.each([null, "run-1"].flatMap(runId => [false, true].map(projected => ({ runId, projected }))))( - "shows Working and Thinking during ordinary admission (runId=$runId, projected=$projected)", - ({ runId, projected }) => { - render([], "queued", runId, undefined, false, false, projected ? { - phase: "queued", label: "Queued", cause: null, - lastConfirmedActivityAt: null, retryAt: null, attempt: 1, maxAttempts: 3, - recoveryOwner: null, nextAction: null, permittedActions: ["inspect_run"], - predecessorRunId: null, successorRunId: null, - } : undefined); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Working"); - if (!runId) { - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toBe("Working"); - } - const activity = container.querySelector('[data-testid="task-chat-current-activity-label"]'); - expect(activity?.textContent).toBe("Thinking"); - expect(activity?.classList.contains("shimmer-text")).toBe(true); - expect(container.textContent).not.toContain("Queued"); - }, - ); - - it("preserves a specific preparation label before a run ID exists", () => { - render([], "queued", null, undefined, false, false, undefined, "Preparing workspace"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent).toBe("Preparing workspace"); - }); - - it.each([ - ["task_drain", "Waiting for maintenance"], - ["agent_setup_pending", "Waiting for agent setup"], - ["agent_setup_failed", "Agent setup needs attention"], - ["server_restarting", "Waiting for server restart"], - ["previous_run_settling", "Waiting for previous run to stop"], - ["routine_execution_in_progress", "Waiting for PAP-5656 to finish"], - ])("shows the server's %s wait while admission is held", (cause, label) => { - render([], "queued", "run-1", undefined, false, false, { - phase: "queued", label, cause, - lastConfirmedActivityAt: null, retryAt: null, attempt: 1, maxAttempts: 3, - recoveryOwner: null, nextAction: "Starts automatically when maintenance finishes.", - permittedActions: ["inspect_run"], predecessorRunId: null, successorRunId: null, - }); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain(label); - expect(container.textContent?.split(label)).toHaveLength(2); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - expect(container.textContent).not.toContain("Thinking"); - }); - - it("keeps startup feedback briefly, then says a queued turn with no named hold is waiting to start", () => { - vi.useFakeTimers(); - try { - vi.setSystemTime(new Date("2026-11-13T17:39:05Z")); - render([], "queued"); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Working"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent).toBe("Thinking"); - // The fixture's run was queued 2 s before render: the grace ends at +28 s. - act(() => { vi.advanceTimersByTime(27_000); }); - expect(container.textContent).not.toContain("Waiting to start"); - act(() => { vi.advanceTimersByTime(2_000); }); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Waiting to start"); - expect(container.textContent?.split("Waiting to start")).toHaveLength(2); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - expect(container.textContent).not.toContain("Working"); - } finally { - vi.useRealTimers(); - } - }); - - it("does not repeat the agent's waiting line in the turn body", () => { - // The shared header (rendered by the thread) shows the waiting line; the body adds no second line. - act(() => root.render( - - - , - )); - expect(container.textContent).not.toContain("Waiting for Codie"); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - }); - - it("does not call a running turn waiting, however long it runs", () => { - vi.useFakeTimers(); - try { - render([], "running"); - act(() => { vi.advanceTimersByTime(10 * 60_000); }); - expect(container.textContent).not.toContain("Waiting to start"); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Working"); - } finally { - vi.useRealTimers(); - } - }); - - const resolvedQuestion = ( - id: string, - prompt: string, - ): TaskChatRuntimeRequestItem => ({ - id, - kind: "protocol", - surface: "runtime_request", - runId: "run-1", - requestId: id, - requestKind: "user_input", - turnId: "turn-1", - requestType: "input", - status: "resolved", - prompt: "Codex needs your input.", - choices: [], - fields: [], - questionSet: { - schema: "paperclip.question_set.v1", - questions: [ - { id: `${id}-field`, prompt, required: true, answerMode: "text" }, - ], - }, - response: { - schema: "paperclip.question_response.v1", - answers: { [`${id}-field`]: { text: "Answered" } }, - }, - }); - - it("shows a stable Working header with Thinking at the turn tail", () => { - render([], "running"); - expect(container.textContent).toContain("Thinking"); - expect(container.textContent).toContain("Runner"); - expect( - container.querySelector( - '[data-testid="task-chat-runner-disclosure-caret"]', - ), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-current-activity-icon"]', - ), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-current-activity-label"]', - )?.textContent, - ).toBe("Thinking"); - expect( - container.querySelector('[data-testid="task-chat-current-activity"]') - ?.tagName, - ).toBe("DIV"); - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Working for"); - expect(container.textContent).not.toContain("Waiting for transcript"); - const identity = container.querySelector( - '[data-testid="task-chat-agent-identity"]', - ); - const status = container.querySelector( - '[data-testid="task-chat-turn-status-header"]', - ); - const identityRow = container.querySelector( - '[data-testid="task-chat-runner-identity-row"]', - ); - const activity = container.querySelector( - '[data-testid="task-chat-current-activity"]', - ); - expect(identity?.parentElement).toBe(identityRow); - expect(status?.parentElement).toBe(identityRow); - expect(status?.getAttribute("data-turn-position")).toBe("identity"); - expect(identity?.compareDocumentPosition(activity!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING, - ); - expect(activity?.getAttribute("data-turn-position")).toBe("tail"); - expect(activity?.classList.contains("px-1")).toBe(true); - expect(activity?.firstElementChild?.hasAttribute("aria-hidden")).toBe( - false, - ); - }); - - it.each(["reconnecting", "retry_scheduled"] as const)( - "keeps the active turn and Thinking tail visible with a %s projection", - (phase) => { - const execution = { phase } as ExecutionProjection; - render([], "running", "run-1", undefined, false, false, execution); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Working for"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent) - .toBe("Thinking"); - render([], "succeeded", "run-1", undefined, false, false, execution); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Worked"); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - render([], "failed", "run-1", undefined, false, false, execution); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Stopped"); - expect(container.textContent).not.toContain("Reconnecting"); - }, - ); - - it.each(["Muse", "Dot"])("shows Waiting for %s until native acceptance, without a Thinking claim", provider => { - const waiting = { phase: "waiting_for_provider", label: `Waiting for ${provider}` } as ExecutionProjection; - render([], "running", "run-1", undefined, false, false, waiting); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain(`Waiting for ${provider}`); - const tail = container.querySelector('[data-testid="task-chat-current-activity-label"]'); - expect(tail?.textContent).toBe(`Waiting for ${provider}`); - expect(tail?.classList.contains("shimmer-text")).toBe(false); - expect(container.textContent).not.toContain("Working"); - expect(container.textContent).not.toContain("Thinking"); - - // Re-render the same live turn after the native acceptance projection changes. - render([], "running", "run-1", undefined, false, false, - { phase: "working", label: "Working" } as ExecutionProjection); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Working for"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent) - .toBe("Thinking"); - - // A stale waiting projection must never override a terminal run outcome. - render([], "failed", "run-1", undefined, false, false, waiting); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Stopped"); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - expect(container.textContent).not.toContain(`Waiting for ${provider}`); - }); - - it("labels the streaming tail as a continuation after steering", () => { - render([], "running", "run-1", undefined, false, true); - - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Continued after steering · Working for"); - }); - - it("renders completed progress exactly once when the live run returns to Thinking", () => { - const text = "Understood—I’ll use a two-second wait instead."; - const items = transcriptToTaskChatItems( - [ - { - kind: "thinking", - ts: "2026-09-04T13:39:20.000Z", - text: "", - lifecycle: "started", - channel: "summary", - itemId: "reasoning-1", - }, - { - kind: "thinking", - ts: "2026-09-04T13:39:20.100Z", - text: "", - lifecycle: "completed", - channel: "summary", - itemId: "reasoning-1", - }, - { - kind: "assistant", - ts: "2026-09-04T13:39:21.100Z", - text, - channel: "progress", - itemId: "message-1", - }, - ], - { runId: "run-1", agentName: "Runner", running: true }, - ); - - render(items); - - expect(container.textContent?.split(text)).toHaveLength(2); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain(text); - expect( - container.querySelector('[data-testid="task-chat-live-narration"]'), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-current-activity-label"]', - )?.textContent, - ).toBe("Thinking"); - }); - - it("keeps progress mounted above its grouped current command", () => { - render([ - { - id: "p1", - kind: "message", - author: "agent", - text: "Running the exact command now.", - interstitial: true, - channel: "progress", - streaming: true, - }, - { - id: "t1", - kind: "tool", - name: "command", - rawName: "Bash", - target: "for i in 1 2 3 4; do echo STREAM-$i; done", - status: "in_progress", - detail: "STREAM-1\n", - }, - ]); - const commentary = container.querySelector('[data-testid="task-chat-phase-interstitial"]'); - const activity = container.querySelector('[data-testid="task-chat-activity-viewport"]'); - expect(commentary?.textContent).toContain("Running the exact command now."); - expect(activity?.textContent).toContain("Running$ "); - expect(activity?.textContent).toContain("STREAM-$i"); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - expect(commentary?.compareDocumentPosition(activity!)).toBe(Node.DOCUMENT_POSITION_FOLLOWING); - - }); - - it("keeps the timer at the top and moves resumed Thinking below completed activity", () => { - render([ - { - id: "commentary", - kind: "message", - author: "agent", - text: "I’ll inspect the workspace.", - interstitial: true, - channel: "progress", - }, - { - id: "tool", - kind: "tool", - name: "Command", - rawName: "bash", - status: "completed", - }, - { - id: "thinking", - kind: "thinking", - lines: [], - lifecycleOnly: true, - streaming: true, - }, - ]); - - const header = container.querySelector('[data-testid="task-chat-turn-status-header"]'); - const activity = container.querySelector('[data-testid="task-chat-activity-viewport"]'); - expect(header?.textContent).toContain("Working for"); - expect(activity?.textContent).toBe("Thinking"); - expect(header?.compareDocumentPosition(activity!)).toBe(Node.DOCUMENT_POSITION_FOLLOWING); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - - }); - - it("keeps earlier commentary mounted when later commentary streams", () => { - render([ - { - id: "commentary", - kind: "message", - author: "agent", - text: "I’ll inspect the card.", - interstitial: true, - channel: "progress", - transcriptIndex: 1, - }, - { - id: "reasoning", - kind: "thinking", - lines: ["The saved preview can be reused."], - streaming: true, - channel: "summary", - transcriptIndex: 2, - }, - ]); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain("I’ll inspect the card."); - - render([ - { - id: "commentary", - kind: "message", - author: "agent", - text: "I’ll inspect the card.", - interstitial: true, - channel: "progress", - transcriptIndex: 1, - }, - { - id: "reasoning", - kind: "thinking", - lines: ["The saved preview can be reused."], - streaming: true, - channel: "summary", - transcriptIndex: 2, - }, - { - id: "commentary-later", - kind: "message", - author: "agent", - text: "I’ve found the rendering seam.", - interstitial: true, - channel: "progress", - transcriptIndex: 3, - }, - ]); - const commentary = container.querySelectorAll( - '[data-testid="task-chat-phase-interstitial"]', - ); - expect(commentary).toHaveLength(2); - expect(commentary[0]?.textContent).toContain("I’ll inspect the card."); - expect(commentary[1]?.textContent).toContain( - "I’ve found the rendering seam.", - ); - expect( - container.querySelector('[data-testid="task-chat-runner-activity-list"]'), - ).toBeNull(); - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - expect( - container.querySelector('[data-testid="task-chat-runner-activity-list"]') - ?.textContent, - ).toContain("Thought"); - }); - - it("keeps the latest provider-authored reasoning line visible while activity is folded", () => { - render([ - { - id: "reasoning", - kind: "thinking", - lines: ["Inspecting the task state.", "Checking the steering path."], - streaming: true, - channel: "summary", - transcriptIndex: 2, - }, - ]); - - const ticker = container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - ); - expect(ticker?.textContent).toContain("Checking the steering path."); - expect( - container.querySelector('[data-testid="task-chat-runner-activity-list"]'), - ).toBeNull(); - }); - - it("keeps a visible fallback when completion tools are filtered before the final reply", () => { - render([{ id: "finish", kind: "tool", name: "paperclip_finish", status: "in_progress" }]); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')?.textContent).toContain("Thinking"); - expect(container.querySelector('[data-testid="task-chat-activity-phase"]')).toBeNull(); - render([{ id: "finish-provider", kind: "protocol", surface: "provider_activity", family: "tool_execution", eventType: "tool.execution.started", status: "running", title: "Finish", details: [{ label: "Name", value: "paperclip_finish" }], steps: [], links: [], children: [] }]); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')?.textContent).toContain("Thinking"); - expect(container.querySelector('[data-testid="task-chat-activity-phase"]')).toBeNull(); - }); - - it("surfaces native activity transport failure while retrying", () => { - act(() => - root.render( - - - - - , - ), - ); - - expect( - container.querySelector('[data-testid="task-chat-activity-unavailable"]') - ?.textContent, - ).toContain("temporarily unavailable"); - }); - - it("starts a separate activity group at every commentary boundary", () => { - render([ - { - id: "commentary-one", - kind: "message", - author: "agent", - text: "First phase.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-one", - kind: "tool", - name: "Read", - rawName: "read_file", - status: "completed", - }, - { - id: "commentary-two", - kind: "message", - author: "agent", - text: "Second phase.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-two", - kind: "tool", - name: "Bash", - rawName: "bash", - status: "completed", - }, - ]); - const rows = container.querySelectorAll( - '[data-testid="task-chat-turn-timeline-row"]', - ); - expect(rows).toHaveLength(2); - expect(rows[0]?.textContent).toContain("First phase."); - expect(rows[0]?.textContent).toContain("Read file"); - expect(rows[1]?.textContent).toContain("Second phase."); - expect(rows[1]?.textContent).toContain("Ran a command"); - act(() => - rows[0] - ?.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - expect( - rows[0] - ?.querySelector('[data-activity-icon] svg') - ?.parentElement?.classList.contains("size-5"), - ).toBe(true); - }); - - it("keeps internal reasoning nested inside its activity group", () => { - render([ - { - id: "summary", - kind: "thinking", - lines: ["Inspect the current card."], - streaming: false, - channel: "summary", - transcriptIndex: 1, - }, - { - id: "detail", - kind: "thinking", - lines: ["Keep the canonical revision atomic."], - streaming: true, - channel: "detail", - transcriptIndex: 2, - }, - ]); - expect( - container.querySelectorAll('[data-testid="task-chat-thinking"]'), - ).toHaveLength(0); - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - const history = container.querySelector('[data-testid="task-chat-runner-activity-list"]'); - expect(container.querySelector('[data-testid="task-chat-runner-activity-rail"]')).toBeNull(); - expect(history?.querySelectorAll("li")).toHaveLength(2); - expect(history?.textContent).toContain("ThoughtInspect the current card."); - expect(history?.textContent).toContain("ThinkingKeep the canonical revision atomic."); - expect(container.querySelector('[data-testid="task-chat-runner-activity-detail"]')).toBeNull(); - - }); - - it("renders only the current reasoning block as active", () => { - render([ - { - id: "old-reasoning", - kind: "thinking", - lines: ["Inspect the current card."], - streaming: true, - transcriptIndex: 1, - }, - { - id: "read", - kind: "tool", - name: "Read files", - rawName: "Read", - status: "completed", - }, - { - id: "current-reasoning", - kind: "thinking", - lines: ["Verify the updated state."], - streaming: true, - transcriptIndex: 3, - }, - ]); - - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - - expect(container.querySelector('[data-activity-item-id="old-reasoning"]')?.textContent).toContain("ThoughtInspect the current card."); - expect(container.querySelector('[data-activity-item-id="current-reasoning"]')?.textContent).toContain("ThinkingVerify the updated state."); - - }); - - it("does not let a textless reasoning lifecycle remove sticky commentary", () => { - render([ - { - id: "commentary", - kind: "message", - author: "agent", - text: "Old commentary", - interstitial: true, - channel: "progress", - transcriptIndex: 1, - }, - { - id: "reasoning", - kind: "thinking", - lines: [], - lifecycleOnly: true, - streaming: true, - transcriptIndex: 2, - }, - ]); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain("Old commentary"); - expect( - container.querySelector('[data-testid="task-chat-current-activity"]'), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - )?.textContent, - ).toBe("Thinking"); - }); - - it("keeps the within-turn plan in activity history without rendering a Plan document preview", () => { - const activity: TaskChatProviderActivityItem = { - id: "live-plan", - kind: "protocol", - surface: "provider_activity", - family: "plan", - eventType: "plan.updated", - status: "running", - title: "Plan", - details: [{ label: "Revision", value: "4" }], - steps: [ - { - id: "one", - label: "Extract the shared preview", - status: "in_progress", - }, - ], - links: [], - children: [], - transcriptIndex: 1, - }; - render([activity]); - expect( - container.querySelector('[data-testid="task-chat-live-plan-preview"]'), - ).toBeNull(); - const disclosure = container.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ); - expect(disclosure?.getAttribute("aria-label")).toContain("Expand 1 activity"); - act(() => disclosure?.click()); - const history = container.querySelector( - '[data-testid="task-chat-runner-activity-list"]', - ); - expect(history?.textContent).toContain("Updating the plan"); - expect( - history?.querySelector('[data-activity-family="plan"]'), - ).not.toBeNull(); - expect( - history - ?.querySelector('[data-activity-icon] svg') - ?.parentElement?.classList.contains("size-5"), - ).toBe(true); - }); - - it("shows canonical web research as the current Codex-style activity", () => { - render([ - { - id: "research-1", - kind: "protocol", - surface: "provider_activity", - family: "research", - eventType: "research.started", - status: "running", - title: "Research", - summary: "site:openai.com model guide GPT-5.4", - details: [ - { label: "Query", value: "site:openai.com model guide GPT-5.4" }, - ], - steps: [], - links: [], - children: [], - }, - ]); - - const activity = container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - ); - expect(activity?.textContent).toContain("Searching the web"); - expect(activity?.textContent).toContain( - "site:openai.com model guide GPT-5.4", - ); - expect(activity?.querySelector("[data-activity-family]")?.getAttribute("data-activity-family")).toBe("research"); - }); - - it("has a purpose-built current-activity presentation for every provider family", () => { - const cases: Array<{ - family: TaskChatProviderActivityFamily; - eventType: string; - status: TaskChatProviderActivityItem["status"]; - expected: string; - details?: TaskChatProviderActivityItem["details"]; - }> = [ - { - family: "plan", - eventType: "plan.updated", - status: "running", - expected: "Updating the plan", - }, - { - family: "tool_execution", - eventType: "tool.execution.started", - status: "running", - expected: "Running an unnamed tool", - }, - { - family: "research", - eventType: "research.started", - status: "running", - expected: "Searching the web", - details: [{ label: "Action", value: "search" }], - }, - { - family: "delegation", - eventType: "delegation.started", - status: "running", - expected: "Starting a subagent", - details: [{ label: "Action", value: "spawn" }], - }, - { - family: "model_identity", - eventType: "model.route.changed", - status: "informational", - expected: "Switched models", - }, - { - family: "context", - eventType: "context.compacted", - status: "completed", - expected: "Compacted context", - }, - { - family: "artifact", - eventType: "artifact.generated", - status: "running", - expected: "Generating an artifact", - }, - { - family: "review", - eventType: "review.mode.changed", - status: "informational", - expected: "Entered review mode", - details: [{ label: "State", value: "entered" }], - }, - { - family: "hook", - eventType: "hook.started", - status: "running", - expected: "Running a hook", - }, - { - family: "memory", - eventType: "memory.citation.referenced", - status: "informational", - expected: "Referenced memory", - }, - { - family: "safety", - eventType: "safety.review.started", - status: "running", - expected: "Auto-reviewing", - }, - { - family: "terminal", - eventType: "terminal.input.sent", - status: "informational", - expected: "Sent terminal input", - }, - { - family: "wait", - eventType: "wait.started", - status: "running", - expected: "Waiting", - }, - { - family: "provider_notice", - eventType: "provider.notice.recorded", - status: "informational", - expected: "Provider notice", - }, - ]; - - expect(cases.map((entry) => entry.family)).toEqual([ - "plan", - "tool_execution", - "research", - "delegation", - "model_identity", - "context", - "artifact", - "review", - "hook", - "memory", - "safety", - "terminal", - "wait", - "provider_notice", - ] satisfies TaskChatProviderActivityFamily[]); - - for (const entry of cases) { - render([ - { - id: `provider-${entry.family}`, - kind: "protocol", - surface: "provider_activity", - family: entry.family, - eventType: entry.eventType, - status: entry.status, - title: entry.family, - details: entry.details ?? [], - steps: [], - links: [], - children: [], - }, - ]); - const activity = container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - ); - expect(activity?.querySelector("[data-activity-family]")?.getAttribute("data-activity-family"), entry.family).toBe( - entry.family, - ); - expect(activity?.textContent, entry.family).toContain(entry.expected); - } - }); - - it("shows provider failures and interruptions instead of a successful past-tense label", () => { - const provider = ( - status: "failed" | "interrupted", - ): TaskChatProviderActivityItem => ({ - id: `research-${status}`, - kind: "protocol", - surface: "provider_activity", - family: "research", - eventType: "research.completed", - status, - title: "Research", - details: [], - steps: [], - links: [], - children: [], - }); - render([provider("failed")]); - expect( - container.querySelector('[data-testid="task-chat-activity-viewport"]') - ?.textContent, - ).toContain("Web search failed"); - render([provider("interrupted")]); - expect( - container.querySelector('[data-testid="task-chat-activity-viewport"]') - ?.textContent, - ).toContain("Web search stopped"); - }); - - it("surfaces workspace changes and file references as current activity", () => { - render([ - { - id: "workspace-change", - kind: "protocol", - surface: "workspace_change", - changeSetId: "change-1", - revision: 1, - source: "harness_reported", - complete: false, - files: [], - totals: { files: 2, additions: 3, deletions: 1 }, - patchArtifactRef: null, - }, - ]); - const card = container.querySelector( - '[data-testid="task-chat-workspace-change"]', - ); - expect(card).not.toBeNull(); - expect( - card?.closest('[data-testid="task-chat-activity-phase"]'), - ).toBeNull(); - - render([ - { - id: "workspace-file", - kind: "protocol", - surface: "workspace_file", - referenceId: "file-1", - source: "runner_verified", - path: "ui/src/App.tsx", - displayName: "App.tsx", - mediaType: "text/typescript", - presentation: "code", - line: 42, - preview: null, - previewTruncated: false, - }, - ]); - const activity = container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - ); - expect(activity?.textContent).toContain("Referenced a file"); - expect(activity?.textContent).toContain("ui/src/App.tsx:42"); - const icon = activity?.querySelector( - '[data-activity-icon] svg', - ); - expect(icon).not.toBeNull(); - expect(icon?.parentElement?.classList.contains("size-5")).toBe(true); - expect(icon?.parentElement?.classList.contains("justify-center")).toBe( - true, - ); - }); - - it("streams the final response in its durable slot and settles the disclosure", () => { - render( - [ - { - id: "p1", - kind: "message", - author: "agent", - text: "Checking.", - interstitial: true, - channel: "progress", - }, - { - id: "f1", - kind: "message", - author: "agent", - authorName: "Runner", - text: "Completed successfully.", - channel: "final", - streaming: true, - }, - ], - "succeeded", - ); - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain("Completed successfully."); - expect( - container.querySelectorAll('[data-testid="task-chat-agent-avatar"]'), - ).toHaveLength(1); - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Worked for"); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain("Checking."); - }); - - it("collapses progress text repeated verbatim by the final response", () => { - const repeated = "BASELINE-DONE"; - render( - [ - { - id: "progress", - kind: "message", - author: "agent", - text: repeated, - interstitial: true, - channel: "progress", - }, - { - id: "tool", - kind: "tool", - name: "Command", - status: "completed", - }, - { - id: "final", - kind: "message", - author: "agent", - text: repeated, - channel: "final", - }, - ], - "succeeded", - ); - - expect(container.textContent?.split(repeated)).toHaveLength(2); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]'), - ).toBeNull(); - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain(repeated); - }); - - it("clears provider wait prose when the run is accepted as yielded", () => { - const providerWait: TaskChatItem = { - id: "provider-wait", - kind: "message", - author: "agent", - authorName: "Runner", - text: "Waiting for Review browser RTS plan.", - channel: "final", - streaming: false, - }; - render([providerWait], "succeeded"); - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).not.toBeNull(); - - render( - [ - providerWait, - { - id: "result", - kind: "protocol", - surface: "run_result", - disposition: "yielded", - summary: "Waiting for Review browser RTS plan.", - objectiveSatisfied: false, - verification: [], - remainingWork: [], - blocker: null, - artifacts: [], - }, - ], - "succeeded", - ); - - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).toBeNull(); - }); - - it("clears provider wait prose as soon as interaction authority is known", () => { - const providerWait: TaskChatItem = { - id: "provider-wait-before-result", - kind: "message", - author: "agent", - authorName: "Runner", - text: "Waiting for structured input.", - channel: "final", - streaming: false, - }; - render([providerWait], "running"); - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).not.toBeNull(); - - render([providerWait], "running", "run-1", undefined, true); - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).toBeNull(); - }); - - it("waits for settlement before using a structured result fallback", () => { - const items: TaskChatItem[] = [ - { - id: "result", - kind: "protocol", - surface: "run_result", - disposition: "done", - summary: "Structured fallback.", - objectiveSatisfied: true, - verification: [], - remainingWork: [], - blocker: null, - artifacts: [], - }, - ]; - - render(items, "running"); - - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).toBeNull(); - }); - - it("lets a shorter provider final replace a structured result fallback", () => { - const result: TaskChatItem = { - id: "result", - kind: "protocol", - surface: "run_result", - disposition: "done", - summary: "A much longer structured summary fallback.", - objectiveSatisfied: true, - verification: [], - remainingWork: [], - blocker: null, - artifacts: [], - }; - - render([result], "succeeded"); - expect(container.textContent).toContain( - "A much longer structured summary fallback.", - ); - - render( - [ - result, - { - id: "provider-final", - kind: "message", - author: "agent", - text: "Done.", - channel: "final", - streaming: false, - }, - ], - "succeeded", - ); - - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain("Done."); - expect(container.textContent).not.toContain( - "A much longer structured summary fallback.", - ); - }); - - it("collapses terminal reasoning to the existing Worked summary", () => { - render( - [ - { - id: "reasoning", - kind: "thinking", - lines: ["Provider-authored trace"], - channel: "summary", - transcriptIndex: 1, - }, - ], - "succeeded", - ); - expect( - container.querySelector('[data-testid="task-chat-live-narration"]'), - ).toBeNull(); - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Worked for"); - expect( - container.querySelector('[data-testid="task-chat-activity-phase-toggle"]') - ?.textContent, - ).toContain("Thought"); - }); - - it("keeps final text mounted through a transient replay gap", () => { - render([ - { - id: "f1", - kind: "message", - author: "agent", - authorName: "Runner", - text: "Completed successfully.", - channel: "final", - streaming: true, - }, - ]); - render([ - { id: "t1", kind: "tool", name: "Paperclip_finish", status: "completed" }, - ]); - - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain("Completed successfully."); - expect( - container.querySelectorAll('[data-testid="task-chat-final-response"]'), - ).toHaveLength(1); - }); - - it("clears replay-latched final text when the next run takes over the lane", () => { - render( - [ - { - id: "f1", - kind: "message", - author: "agent", - authorName: "Runner", - text: "First answer.", - channel: "final", - }, - ], - "running", - "run-1", - ); - render([], "running", "run-2"); - - expect(container.textContent).not.toContain("First answer."); - expect( - container.querySelector('[data-testid="task-chat-current-activity"]') - ?.textContent, - ).toContain("Thinking"); - }); - - it("omits runner lifecycle and token noise while preserving useful history", () => { - render([ - { - id: "session", - kind: "marker", - variant: "session_start", - label: "Session started", - detail: "session-id", - }, - { - id: "start", - kind: "marker", - variant: "turn_boundary", - label: "Turn started", - }, - { - id: "usage", - kind: "usage", - usage: { - used: 10_520, - size: 0, - inputTokens: 10_254, - outputTokens: 266, - }, - }, - { - id: "tool", - kind: "tool", - name: "Paperclip_finish", - rawName: "paperclip_finish", - target: "reportedWorkDisposition: done", - status: "completed", - }, - { - id: "interrupt", - kind: "marker", - variant: "interrupted", - label: "Interrupted", - }, - { - id: "complete", - kind: "marker", - variant: "turn_boundary", - label: "Turn completed", - }, - ]); - - expect(container.textContent).not.toContain("Paperclip_finish"); - expect(container.textContent).toContain("Interrupted"); - expect(container.textContent).not.toContain("Session started"); - expect(container.textContent).not.toContain("Turn started"); - expect(container.textContent).not.toContain("Turn completed"); - expect(container.textContent).not.toContain("10,520"); - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - expect( - container - .querySelector('[data-activity-icon] svg') - ?.parentElement?.classList.contains("size-5"), - ).toBe(true); - }); - - it("keeps a compact pending runtime entry without duplicating composer controls", async () => { - const onDecision = vi.fn(); - render( - [ - { - id: "request", - kind: "protocol", - surface: "runtime_request", - runId: "run-1", - requestId: "request-1", - requestKind: "command_approval", - turnId: "turn-1", - requestType: "permission", - status: "pending", - prompt: "Allow command?", - choices: [{ key: "accept", label: "Allow once" }], - fields: [], - }, - ], - "running", - "run-1", - onDecision, - ); - - expect( - container.querySelector( - '[data-testid="task-chat-runtime-request-marker"]', - ), - ).toBeNull(); - expect( - container.querySelector('[data-testid="task-chat-runtime-request"]'), - ).toBeNull(); - expect(container.querySelector('[data-testid="task-chat-pending-runtime-request"]')?.textContent).toContain("Allow command?"); - expect(onDecision).not.toHaveBeenCalled(); - }); - - it("keeps a resolved question as a compact expandable receipt outside folded activity", () => { - render( - [ - { - id: "resolved-request", - kind: "protocol", - surface: "runtime_request", - runId: "run-1", - requestId: "request-1", - requestKind: "runtime", - turnId: "turn-1", - requestType: "input", - status: "resolved", - prompt: "Codex needs your input.", - choices: [], - fields: [], - questionSet: { - schema: "paperclip.question_set.v1", - questions: [ - { - id: "goal", - prompt: "What should the server do?", - required: true, - answerMode: "text", - }, - ], - }, - response: { - schema: "paperclip.question_response.v1", - answers: { goal: { text: "Serve a small JSON API." } }, - }, - }, - ], - "succeeded", - ); - - const receipt = container.querySelector( - '[data-testid="task-chat-runtime-request"]', - ); - const history = receipt?.querySelector( - '[data-testid="task-chat-runtime-request-history"]', - ); - expect(receipt?.open).toBe(false); - expect(receipt?.querySelector("summary")?.textContent).toBe( - "Questions answered", - ); - expect(history?.closest(".tc-turn-fold")).toBeNull(); - expect(history?.textContent).toContain("What should the server do?"); - expect(history?.textContent).toContain("Serve a small JSON API."); - }); - - it("renders the DOT-217 mixed turn in exact transcript order", () => { - render( - [ - { - id: "commentary-1", - kind: "message", - author: "agent", - text: "I’ll inspect the workspace first.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-1", - kind: "tool", - name: "Read", - rawName: "read_file", - status: "completed", - }, - { - id: "tool-2", - kind: "tool", - name: "Read", - rawName: "read_file", - status: "completed", - }, - { - id: "commentary-2", - kind: "message", - author: "agent", - text: "I need the first product choices.", - interstitial: true, - channel: "progress", - }, - resolvedQuestion("questions-1", "Which core loop?"), - { - id: "commentary-3", - kind: "message", - author: "agent", - text: "Now I’ll pin down the simulation.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-3", - kind: "tool", - name: "Search", - rawName: "web_search", - status: "completed", - }, - resolvedQuestion("questions-2", "How should time work?"), - { - id: "commentary-4", - kind: "message", - author: "agent", - text: "The final implementation shape is clear.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-4", - kind: "tool", - name: "Bash", - rawName: "bash", - status: "completed", - }, - { - id: "final", - kind: "message", - author: "agent", - text: "The plan is ready.", - channel: "final", - }, - ], - "succeeded", - ); - - const timeline = container.querySelector( - '[data-testid="task-chat-turn-timeline"]', - ); - const rows = Array.from( - timeline?.querySelectorAll( - '[data-testid="task-chat-turn-timeline-row"]', - ) ?? [], - ); - expect(rows.map((row) => row.getAttribute("data-timeline-row-id"))).toEqual( - [ - "commentary-1:phase", - "commentary-2:phase", - "questions-1", - "commentary-3:phase", - "questions-2", - "commentary-4:phase", - ], - ); - expect(rows[0]?.textContent).toContain("Read file"); - expect(rows[2]?.textContent).toContain("Questions answered"); - expect(rows[3]?.textContent).toContain("Searched the web"); - expect(rows[5]?.textContent).toContain("Ran commands"); - const worked = container.querySelector( - '[data-testid="task-chat-turn-status-header"]', - ); - const identityRow = container.querySelector( - '[data-testid="task-chat-runner-identity-row"]', - ); - const identity = container.querySelector( - '[data-testid="task-chat-agent-identity"]', - ); - const final = container.querySelector( - '[data-testid="task-chat-final-response"]', - ); - expect(worked?.getAttribute("data-turn-position")).toBe("identity"); - expect(worked?.parentElement).toBe(identityRow); - expect(identity?.parentElement).toBe(identityRow); - expect(identityRow?.classList.contains("items-center")).toBe(true); - expect(worked?.classList.contains("border-b")).toBe(false); - expect(worked?.compareDocumentPosition(timeline!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING, - ); - expect(timeline?.compareDocumentPosition(final!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING, - ); - }); - - it("expands a grouped live phase without hiding its commentary", () => { - render([ - { - id: "thinking-empty", - kind: "thinking", - lines: [], - streaming: false, - lifecycleOnly: true, - }, - { - id: "commentary", - kind: "message", - author: "agent", - text: "Checking the current implementation.", - interstitial: true, - channel: "progress", - }, - { - id: "tool", - kind: "tool", - name: "Read", - rawName: "read_file", - target: "ui/src/App.tsx", - status: "completed", - detail: "export function App() {}", - }, - ]); - - const disclosure = container.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ); - expect(disclosure?.getAttribute("aria-expanded")).toBe("false"); - expect( - container.querySelectorAll('[data-testid="task-chat-thinking"]'), - ).toHaveLength(0); - - act(() => disclosure?.click()); - - expect(disclosure?.getAttribute("aria-expanded")).toBe("true"); - expect( - container.querySelector('[data-testid="task-chat-runner-activity-list"]'), - ).not.toBeNull(); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain("Checking the current implementation."); - expect(container.textContent).toContain("ui/src/App.tsx"); - }); - - it("preserves an open phase while the live run becomes terminal", () => { - const items: TaskChatItem[] = [ - { - id: "tool", - kind: "tool", - name: "Search", - rawName: "web_search", - target: "smoked pork shoulder", - status: "in_progress", - }, - ]; - render(items); - const disclosure = container.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ); - act(() => disclosure?.click()); - expect(disclosure?.getAttribute("aria-expanded")).toBe("true"); - - render( - [{ ...items[0], kind: "tool", status: "completed" } as TaskChatItem], - "succeeded", - ); - - const settled = container.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ); - expect(settled?.getAttribute("aria-expanded")).toBe("true"); - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Worked for"); - }); - - it("resets phase disclosure state when a different run takes over", () => { - const items: TaskChatItem[] = [ - { - id: "tool", - kind: "tool", - name: "Read", - rawName: "read_file", - target: "ui/src/App.tsx", - status: "completed", - }, - ]; - render(items, "running", "run-1"); - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - expect( - container - .querySelector('[data-testid="task-chat-activity-phase-toggle"]') - ?.getAttribute("aria-expanded"), - ).toBe("true"); - - render(items, "running", "run-2"); - - expect( - container - .querySelector('[data-testid="task-chat-activity-phase-toggle"]') - ?.getAttribute("aria-expanded"), - ).toBe("false"); - }); - - it("renders a failed terminal disclosure without treating prose as status authority", () => { - render( - [ - { - id: "final", - kind: "message", - author: "agent", - text: "I finished the draft.", - channel: "final", - }, - { - id: "tool", - kind: "tool", - name: "Command", - rawName: "bash", - target: "pnpm test", - status: "failed", - }, - ], - "failed", - ); - - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Stopped after"); - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain("I finished the draft."); - }); -}); diff --git a/ui/src/components/task-chat/TaskMessageScroller.test.tsx b/ui/src/components/task-chat/TaskMessageScroller.test.tsx deleted file mode 100644 index 83b64236d03..00000000000 --- a/ui/src/components/task-chat/TaskMessageScroller.test.tsx +++ /dev/null @@ -1,686 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { TaskMessageScroller } from "./TaskMessageScroller"; -import { TaskChatScrollNavigation } from "./scroll-navigation"; - -const PILL_SELECTOR = 'button[aria-label="Scroll to latest"]'; - -/** - * jsdom has no layout, so scroll geometry is faked per element: scrollHeight / - * clientHeight are pinned and scrollTop is backed by a plain variable. - */ -function fakeGeometry(el: HTMLElement, { scrollHeight = 1000, clientHeight = 400, clamp = false } = {}) { - let scrollTop = 0; - Object.defineProperty(el, "scrollHeight", { value: scrollHeight, configurable: true }); - Object.defineProperty(el, "clientHeight", { value: clientHeight, configurable: true }); - Object.defineProperty(el, "scrollTop", { - get: () => scrollTop, - set: (v: number) => { - scrollTop = clamp ? Math.max(0, Math.min(v, el.scrollHeight - el.clientHeight)) : v; - }, - configurable: true, - }); -} - -function fakeResizableGeometry( - el: HTMLElement, - { scrollHeight = 1000, clientHeight = 400 } = {}, -) { - let currentClientHeight = clientHeight; - let scrollTop = 0; - Object.defineProperty(el, "scrollHeight", { - value: scrollHeight, - configurable: true, - }); - Object.defineProperty(el, "clientHeight", { - get: () => currentClientHeight, - configurable: true, - }); - Object.defineProperty(el, "scrollTop", { - get: () => scrollTop, - set: (value: number) => { - scrollTop = value; - }, - configurable: true, - }); - return { - setClientHeight(value: number) { - currentClientHeight = value; - }, - }; -} - -/** - * Scroll/wheel are continuous-priority events, so React flushes the resulting - * state updates asynchronously — wait a macrotask after dispatching. - */ -function flushEvents() { - return new Promise((resolve) => { - setTimeout(resolve); - }); -} - -describe("TaskMessageScroller", () => { - let container: HTMLDivElement; - let root: Root; - - function render(contentKey: unknown = 0) { - flushSync(() => { - root.render( - -
messages
-
, - ); - }); - } - - function scroller(): HTMLDivElement { - return container.querySelector('[data-testid="task-chat-scroller"]')!; - } - - function pill(): HTMLButtonElement | null { - return container.querySelector(PILL_SELECTOR); - } - - /** - * Wait for the pill to reach a state, rather than for a fixed number of turns. - * `flushEvents` yields exactly one macrotask, which is enough on an idle - * machine and not when the suite runs many workers in parallel — React - * flushes continuous-priority updates asynchronously, so the DOM read can - * land before the state does. Sites that dereference `pill()!` turn that into - * a hard failure rather than a retry. - */ - async function waitForPill(present: boolean): Promise { - await vi.waitFor(() => - present ? expect(pill()).not.toBeNull() : expect(pill()).toBeNull(), - ); - } - - /** Set scrollTop and fire a scroll event, like a user or the browser would. */ - async function scrollTo(el: HTMLElement, top: number) { - el.scrollTop = top; - el.dispatchEvent(new Event("scroll", { bubbles: true })); - await flushEvents(); - } - - async function dispatch(el: HTMLElement, event: Event) { - el.dispatchEvent(event); - await flushEvents(); - } - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - document.documentElement.style.removeProperty("--motion-scrollbar-idle-delay"); - vi.useRealTimers(); - vi.unstubAllGlobals(); - }); - - it("loads one older page on upward scroll, keeps the status slot, and pauses after failure", async () => { - let release!: () => void; - const load = vi.fn(() => new Promise(resolve => { release = resolve; })); - const history = { hasMore: true, loading: false, error: false, load }; - const update = (tick: number) => flushSync(() => root.render( -
saved messages
, - )); - update(0); - fakeGeometry(scroller()); - update(1); - expect(load).not.toHaveBeenCalled(); - await scrollTo(scroller(), 400); - expect(load).not.toHaveBeenCalled(); - await scrollTo(scroller(), 150); - expect(load).toHaveBeenCalledTimes(1); - await scrollTo(scroller(), 100); - scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 })); - await flushEvents(); - expect(load).toHaveBeenCalledTimes(1); - const status = container.querySelector('[data-testid="chat-history-status"]'); - history.loading = true; - update(2); - expect(container.querySelector('[data-testid="chat-history-status"]')).toBe(status); - expect(status?.textContent).toBe("Loading earlier messages…"); - release(); - await flushEvents(); - history.loading = false; - history.error = true; - update(3); - await scrollTo(scroller(), 50); - expect(load).toHaveBeenCalledTimes(1); - expect(status?.textContent).toContain("Earlier messages couldn’t load."); - (status?.querySelector('button') as HTMLButtonElement).click(); - expect(load).toHaveBeenCalledTimes(2); - release(); - await flushEvents(); - history.error = false; - history.hasMore = false; - update(4); - await scrollTo(scroller(), 0); - expect(load).toHaveBeenCalledTimes(2); - }); - - it("follows a late image resize in the message body after the history status", () => { - const observers: { targets: Set; resize: () => void }[] = []; - vi.stubGlobal("ResizeObserver", class { - targets = new Set(); - constructor(callback: ResizeObserverCallback) { observers.push({ targets: this.targets, resize: () => callback([], this as unknown as ResizeObserver) }); } - observe(target: Element) { this.targets.add(target); } - disconnect() {} - }); - const update = (tick: number) => flushSync(() => root.render( -
image content
, - )); - update(0); fakeGeometry(scroller(), { clamp: true }); update(1); - const body = container.querySelector('[data-testid="image-body"]')!; - Object.defineProperty(scroller(), "scrollHeight", { value: 1400, configurable: true }); - for (const observer of observers) if (observer.targets.has(body)) observer.resize(); - expect(scroller().scrollTop).toBe(1000); - }); - - it("keeps following when content grows before the previous scroll event is delivered", async () => { - render(0); - fakeGeometry(scroller(), { clamp: true }); - render(1); - expect(scroller().scrollTop).toBe(600); - Object.defineProperty(scroller(), "scrollHeight", { value: 1400, configurable: true }); - await dispatch(scroller(), new Event("scroll", { bubbles: true })); - expect(scroller().scrollTop).toBe(1000); - expect(pill()).toBeNull(); - scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 })); - Object.defineProperty(scroller(), "scrollHeight", { value: 1600, configurable: true }); - await scrollTo(scroller(), 900); - render(2); - expect(scroller().scrollTop).toBe(900); - await waitForPill(true); - }); - - it("retains the reading anchor when a resize scroll event precedes the next width reflow", async () => { - const resize: (() => void)[] = []; - vi.stubGlobal("ResizeObserver", class { - constructor(callback: ResizeObserverCallback) { resize.push(() => callback([], this as unknown as ResizeObserver)); } - observe() {} - disconnect() {} - }); - let width = 400, rowTop = 100; - flushSync(() => root.render( -
{ - if (!node) return; - const viewport = node.parentElement!; - fakeGeometry(viewport, { clamp: true }); - Object.defineProperty(viewport, "clientWidth", { get: () => width, configurable: true }); - viewport.getBoundingClientRect = () => ({ top: 0, bottom: 400 } as DOMRect); - }}> -
{ - if (node) node.getBoundingClientRect = () => ({ top: rowTop - scroller().scrollTop, bottom: rowTop + 100 - scroller().scrollTop, height: 100 } as DOMRect); - }}>Saved reply
-
-
)); - await scrollTo(scroller(), 150); - width = 500; rowTop = 80; - for (const callback of resize) callback(); - expect(scroller().scrollTop).toBe(130); - rowTop = 70; - await dispatch(scroller(), new Event("scroll", { bubbles: true })); - for (const callback of resize) callback(); - expect(scroller().scrollTop).toBe(120); - width = 600; rowTop = 60; - await dispatch(scroller(), new Event("scroll", { bubbles: true })); - for (const callback of resize) callback(); - expect(rowTop - scroller().scrollTop).toBe(-50); - expect(pill()).not.toBeNull(); - }); - - it("retains upward intent when content reconciles before the scroll event", async () => { - const load = vi.fn(); - const update = (tick: number) => flushSync(() => root.render( -
saved messages
, - )); - update(0); fakeGeometry(scroller()); update(1); - await scrollTo(scroller(), 400); - scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -1000 })); - scroller().scrollTop = 0; - update(2); - await dispatch(scroller(), new Event("scroll", { bubbles: true })); - expect(load).toHaveBeenCalledTimes(1); - }); - - it("holds a short conversation when an upward wheel gesture loads history", async () => { - const load = vi.fn().mockResolvedValue(undefined); - const update = (tick: number) => flushSync(() => root.render( -
short conversation
, - )); - update(0); - fakeGeometry(scroller(), { scrollHeight: 200, clientHeight: 400, clamp: true }); - update(1); - await scrollTo(scroller(), 0); - scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 })); - await flushEvents(); - expect(load).toHaveBeenCalledTimes(1); - Object.defineProperty(scroller(), "scrollHeight", { value: 1200, configurable: true }); - update(2); - expect(scroller().scrollTop).toBe(0); - }); - - it("pages short conversations with touch and keyboard gestures", async () => { - const load = vi.fn().mockResolvedValue(undefined); - const update = (tick: number) => flushSync(() => root.render( -
short conversation
, - )); - update(0); fakeGeometry(scroller(), { scrollHeight: 200, clientHeight: 400, clamp: true }); update(1); - await scrollTo(scroller(), 0); - const touch = (type: string, y: number) => { - const event = new Event(type, { bubbles: true }); - Object.defineProperty(event, "touches", { value: [{ clientY: y }] }); - scroller().dispatchEvent(event); - }; - touch("touchstart", 100); touch("touchmove", 200); touch("touchmove", 250); - await flushEvents(); - expect(load).toHaveBeenCalledTimes(1); - scroller().dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Home" })); - await flushEvents(); - expect(load).toHaveBeenCalledTimes(2); - }); - - it("does not measure historical rows on each streaming update while following the bottom", () => { - let initialized = false; - let rowMeasurements = 0; - const update = (tick: number) => flushSync(() => root.render( - -
{ - if (node && !initialized) { - fakeGeometry(node.parentElement!, { scrollHeight: 20000, clientHeight: 400 }); - initialized = true; - } - }}> - {Array.from({ length: 200 }, (_, index) =>
{ - if (node) node.getBoundingClientRect = () => { - rowMeasurements++; - const top = index * 100 - scroller().scrollTop; - return { top, bottom: top + 100, height: 100 } as DOMRect; - }; - }}>History {index}
)} -

Live response {tick}

-
-
, - )); - update(0); - rowMeasurements = 0; - for (let tick = 1; tick <= 30; tick++) update(tick); - expect(container.textContent).toContain("Live response 30"); - expect(scroller().scrollTop).toBe(20000); - expect(rowMeasurements).toBe(0); - }); - - it("applies same-task hash changes and restores each history entry without remounting", async () => { - let initialized = false; - function navigate(key: string, hash: string, restore = false) { - flushSync(() => root.render( - - -
{ - if (node && !initialized) { - fakeGeometry(node.parentElement!); - initialized = true; - } - }}> - {[100, 500].map((top, index) =>
{ - if (node) node.getBoundingClientRect = () => ({ top: top - scroller().scrollTop, bottom: top + 100 - scroller().scrollTop, height: 100 } as DOMRect); - }}>Comment {index}
)} -
-
-
, - )); - } - navigate("desktop-entry-one", "#nav-comment-0"); - const viewport = scroller(); - expect(viewport.scrollTop).toBe(100); - await scrollTo(viewport, 150); - navigate("desktop-entry-two", "#nav-comment-1"); - expect(scroller()).toBe(viewport); - expect(viewport.scrollTop).toBe(500); - navigate("desktop-entry-one", "#nav-comment-0", true); - expect(viewport.scrollTop).toBe(150); - navigate("desktop-entry-one", "#nav-comment-1", true); - expect(viewport.scrollTop).toBe(500); - }); - - it.each([[false, "none"], [false, "wheel"], [false, "pointer"], [true, "none"], [true, "wheel"], [true, "pointer"]] as const)("positions a late hash target unless the reader moved on (restore=%s, readerMoved=%s)", async (restore, readerMoved) => { - let initialized = false; - const show = (targetReady: boolean) => flushSync(() => root.render( - - -
{ - if (node && !initialized) { fakeGeometry(node.parentElement!, { clamp: true }); initialized = true; } - }}> - Saved conversation - {targetReady ?
{ - if (node) node.getBoundingClientRect = () => ({ top: 100 - scroller().scrollTop, bottom: 200 - scroller().scrollTop, height: 100 } as DOMRect); - }}>Linked comment
: null} -
-
-
, - )); - show(false); - if (readerMoved !== "none") { - await scrollTo(scroller(), 300); - await dispatch(scroller(), readerMoved === "wheel" ? new WheelEvent("wheel", { bubbles: true, deltaY: -100 }) : new Event("pointerdown", { bubbles: true })); - } - show(true); - expect(scroller().scrollTop).toBe(readerMoved === "none" ? 100 : 300); - }); - - it("does not replace a saved reading position with a hidden route's geometry", async () => { - function mount(restore: boolean) { - flushSync(() => root.render( - - -
{ if (node) fakeGeometry(node.parentElement!); }}>Saved messages
-
-
, - )); - } - mount(false); - const viewport = scroller(); - await scrollTo(viewport, 150); - Object.defineProperty(viewport, "clientHeight", { value: 0, configurable: true }); - await scrollTo(viewport, 0); - flushSync(() => root.render(null)); - mount(true); - expect(scroller().scrollTop).toBe(150); - }); - - it("restores bottom-follow on Back after the viewport and message heights change", () => { - const configured = new WeakSet(); - function mount(restore: boolean, scrollHeight: number, clientHeight: number) { - flushSync(() => root.render( - - -
{ - const viewport = node?.parentElement; - if (viewport && !configured.has(viewport)) { - fakeGeometry(viewport, { scrollHeight, clientHeight }); - let top = 0; - Object.defineProperty(viewport, "scrollTop", { - configurable: true, - get: () => top, - set: (value: number) => { - top = Math.max(0, Math.min(value, viewport.scrollHeight - viewport.clientHeight)); - }, - }); - configured.add(viewport); - } - }}>Latest response
-
-
, - )); - } - mount(false, 1000, 400); - flushSync(() => root.render(null)); - // Rotation changed wrapping and the available message viewport while away. - mount(true, 2000, 500); - expect(scroller().scrollTop).toBe(1500); - expect(pill()).toBeNull(); - Object.defineProperty(scroller(), "scrollHeight", { value: 2400, configurable: true }); - mount(true, 2400, 500); - expect(scroller().scrollTop).toBe(1900); - }); - - it("renders children inside the scroll container, pill hidden, scrolled to bottom on mount", () => { - render(); - const el = scroller(); - expect(el.textContent).toContain("messages"); - expect(pill()).toBeNull(); - // Mount effect pins to the bottom. - expect(el.scrollTop).toBe(el.scrollHeight); - }); - - it("extends only the streamlined scroll box through the page gutter", () => { - render(); - const el = scroller(); - const frame = el.parentElement; - - expect(frame?.className).toBe("relative min-h-0 flex-1"); - expect(el.classList).toContain("-right-4"); - expect(el.classList).toContain("pr-4"); - expect(el.classList).toContain("md:-right-6"); - expect(el.classList).toContain("md:pr-6"); - expect(el.classList).not.toContain("right-0"); - }); - - it("shows the scrollbar only while scroll activity is recent", () => { - vi.useFakeTimers(); - document.documentElement.style.setProperty("--motion-scrollbar-idle-delay", "600ms"); - render(); - const el = scroller(); - fakeGeometry(el); - - expect(el.className).toContain("scrollbar-while-scrolling"); - expect(el.getAttribute("data-scroll-active")).toBeNull(); - - el.scrollTop = 100; - el.dispatchEvent(new Event("scroll", { bubbles: true })); - expect(el.getAttribute("data-scroll-active")).toBe("true"); - - vi.advanceTimersByTime(599); - expect(el.getAttribute("data-scroll-active")).toBe("true"); - vi.advanceTimersByTime(1); - expect(el.getAttribute("data-scroll-active")).toBeNull(); - }); - - it("contains horizontal overflow so no scrollbar appears above the composer", () => { - render(); - - expect(scroller().classList).toContain("overflow-x-hidden"); - expect(scroller().classList).toContain("overflow-y-auto"); - }); - - it("auto-follows content instantly while pinned", async () => { - render(1); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 600); // bottom: 1000 - 600 - 400 = 0 → pinned - await waitForPill(false); // pinned state settled before content grows - render(2); - expect(el.scrollTop).toBe(1000); - expect(pill()).toBeNull(); - }); - - it("holds position and shows the icon-only pill when scrolled up", async () => { - render(1); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 100); // 500px from bottom → unpinned - await waitForPill(true); - const btn = pill(); - expect(btn).not.toBeNull(); - expect(btn!.className).toContain("tc-scroll-pill-in"); - expect(btn!.className).toContain("size-8"); - expect(btn!.className).toContain("bottom-7"); - expect(btn!.className).not.toContain("bottom-3"); - expect(btn!.className).not.toContain("-translate-x-1/2"); - // Icon-only: no visible text. - expect(btn!.textContent).toBe(""); - // New content must not yank the held position. - render(2); - expect(el.scrollTop).toBe(100); - }); - - it("follows a shrinking viewport while pinned so a growing composer cannot cover the latest text", async () => { - let triggerResize = () => {}; - vi.stubGlobal( - "ResizeObserver", - class { - constructor(callback: ResizeObserverCallback) { - triggerResize = () => - callback([], this as unknown as ResizeObserver); - } - observe() {} - disconnect() {} - }, - ); - render(); - const el = scroller(); - const geometry = fakeResizableGeometry(el); - triggerResize(); - await scrollTo(el, 600); - - geometry.setClientHeight(200); - triggerResize(); - - expect(el.scrollTop).toBe(el.scrollHeight); - expect(pill()).toBeNull(); - }); - - it("holds a reader's position when the composer grows while they are scrolled up", async () => { - let triggerResize = () => {}; - vi.stubGlobal( - "ResizeObserver", - class { - constructor(callback: ResizeObserverCallback) { - triggerResize = () => - callback([], this as unknown as ResizeObserver); - } - observe() {} - disconnect() {} - }, - ); - render(); - const el = scroller(); - const geometry = fakeResizableGeometry(el); - triggerResize(); - await scrollTo(el, 100); - await waitForPill(true); - - geometry.setClientHeight(200); - triggerResize(); - - expect(el.scrollTop).toBe(100); - expect(pill()).not.toBeNull(); - }); - - it("small drifts within the pin threshold do not show the pill", async () => { - render(); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 560); // 40px from bottom, threshold is 48 - expect(pill()).toBeNull(); - }); - - it("clicking the pill smooth-scrolls, ignores intermediate scroll events, re-pins on arrival", async () => { - vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false })); - render(1); - const el = scroller(); - fakeGeometry(el); - const scrollToSpy = vi.fn(); - el.scrollTo = scrollToSpy as unknown as typeof el.scrollTo; - - await scrollTo(el, 100); - await waitForPill(true); - const btn = pill()!; - btn.click(); - await flushEvents(); - expect(scrollToSpy).toHaveBeenCalledWith({ top: 1000, behavior: "smooth" }); - - // Intermediate glide positions fire scroll events; they must not unpin - // (i.e. the easing flag swallows them and the pill state stays put). - await scrollTo(el, 250); - await scrollTo(el, 400); - expect(pill()).not.toBeNull(); - - // Arrival within the threshold re-pins and hides the pill (immediately - // here: no matchMedia in jsdom → reduced-motion/unmount-now path). - vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: true })); - await scrollTo(el, 600); - expect(pill()).toBeNull(); - - // Re-pinned: content growth follows instantly again. - render(2); - expect(el.scrollTop).toBe(1000); - }); - - it("finishes following at the new bottom when content changes during the latest glide", async () => { - vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false })); - render(1); - const el = scroller(); - fakeGeometry(el); - el.scrollTo = vi.fn() as unknown as typeof el.scrollTo; - await scrollTo(el, 100); - await waitForPill(true); - pill()!.click(); - await flushEvents(); - await scrollTo(el, 250); - render(2); - expect(el.scrollTop).toBe(1000); - }); - - it("a wheel gesture during the glide cancels easing and stays unpinned", async () => { - vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false })); - render(1); - const el = scroller(); - fakeGeometry(el); - el.scrollTo = vi.fn() as unknown as typeof el.scrollTo; - - await scrollTo(el, 100); - await waitForPill(true); - pill()!.click(); - await flushEvents(); - await dispatch(el, new Event("wheel", { bubbles: true })); - - // Easing cancelled → user is unpinned, pill visible, content holds. - expect(pill()).not.toBeNull(); - render(2); - expect(el.scrollTop).toBe(100); - - // Scroll events far from the bottom now behave normally (still unpinned). - await scrollTo(el, 200); - expect(pill()).not.toBeNull(); - }); - - it("plays the exit animation before unmounting when motion is enabled", async () => { - vi.stubGlobal( - "matchMedia", - vi.fn().mockReturnValue({ matches: false }), // motion allowed - ); - render(); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 100); - await vi.waitFor(() => expect(pill()?.className).toContain("tc-scroll-pill-in")); - - // Scrolling back to the bottom starts the exit animation but keeps the - // pill mounted until animationend. - await scrollTo(el, 600); - await vi.waitFor(() => expect(pill()?.className).toContain("tc-scroll-pill-out")); - const exiting = pill(); - expect(exiting).not.toBeNull(); - - // jsdom has no window.AnimationEvent, so React's vendor-prefix detection - // maps onAnimationEnd to "webkitAnimationEnd" here (real browsers get the - // unprefixed event). - await dispatch(exiting!, new Event("webkitAnimationEnd", { bubbles: true })); - await waitForPill(false); - }); - - it("unmounts immediately on hide under prefers-reduced-motion", async () => { - vi.stubGlobal( - "matchMedia", - vi.fn().mockReturnValue({ matches: true }), // reduce - ); - render(); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 100); - await waitForPill(true); - await scrollTo(el, 600); - await waitForPill(false); // no animationend needed - }); -}); diff --git a/ui/src/context/CompanyContext.test.tsx b/ui/src/context/CompanyContext.test.tsx index 2a269243317..5a92cbd0dd9 100644 --- a/ui/src/context/CompanyContext.test.tsx +++ b/ui/src/context/CompanyContext.test.tsx @@ -223,7 +223,7 @@ describe("CompanyProvider", () => { root = createRoot(container); queryClient = new QueryClient({ defaultOptions: { - queries: { retry: false }, + queries: { retry: false, retryDelay: 0 }, }, }); mockAuthApi.getSession.mockResolvedValue(null); @@ -508,8 +508,8 @@ describe("CompanyProvider", () => { }); await flushReact(); // Past the bounded retries, so the failure has actually settled. - await act(async () => { - await new Promise((resolve) => window.setTimeout(resolve, 1200)); + await vi.waitFor(() => { + expect(captured?.companyListUnavailable).toBe(true); }); await flushReact(); @@ -549,13 +549,12 @@ describe("CompanyProvider", () => { queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2")); }); await flushReact(); - await act(async () => { - await new Promise((resolve) => window.setTimeout(resolve, 1200)); + await vi.waitFor(() => { + expect(seen).toEqual([null, "company-1", null, "company-2"]); }); await flushReact(); expect(captured?.companyListUnavailable).toBe(false); - expect(seen).toEqual([null, "company-1", null, "company-2"]); }); // The failure flag must not outlive the failure. A later success — a focus @@ -571,13 +570,11 @@ describe("CompanyProvider", () => { queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2")); }); await flushReact(); - await act(async () => { - await new Promise((resolve) => window.setTimeout(resolve, 1200)); + await vi.waitFor(() => { + expect(captured?.companyListUnavailable).toBe(true); }); await flushReact(); - expect(captured?.companyListUnavailable).toBe(true); - // This account genuinely owns no companies, and the request says so. mockCompaniesApi.list.mockResolvedValue([]); await act(async () => { diff --git a/ui/src/features/connections/AwsRoleSetup.test.tsx b/ui/src/features/connections/AwsRoleSetup.test.tsx deleted file mode 100644 index da18b886ae7..00000000000 --- a/ui/src/features/connections/AwsRoleSetup.test.tsx +++ /dev/null @@ -1,233 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { AgentSetupProgress, AgentSetupProgressHandoff, AwsConnectionSetup } from "@paperclipai/shared"; -import type { AgentSetupProgressClient } from "@/components/AgentSetupProgress"; -import { AwsRoleSetup, awsAgentSetupPrompt, awsCliCommands, awsSetupErrorMessage, type AwsRoleSetupClient } from "./AwsRoleSetup"; -import { ApiError } from "@/api/client"; - -vi.mock("@/api/tools", () => ({ toolsApi: {} })); -vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => ({ userId: "user-1", settled: true, current: true }) })); - -const READY: AwsConnectionSetup = { - available: true, - issuer: "https://acme.paperclip.app/oidc/companies/company-1", - audience: "sts.amazonaws.com", - subject: "connection:conn-1", - providerHost: "acme.paperclip.app/oidc/companies/company-1", - roleName: "paperclip-conn-1", - savedRoleArn: null, - accessLevel: "read_only", - trustPolicy: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: { Federated: "arn:aws:iam::ACCOUNT_ID:oidc-provider/acme.paperclip.app/oidc/companies/company-1" } }] }, - cloudFormationTemplate: "{\"Resources\":{}}\n", - cloudFormationConsoleUrl: "https://console.aws.amazon.com/cloudformation/home#/stacks/create", - issuerPublished: true, -}; -const ROLE_ARN = "arn:aws:iam::123456789012:role/paperclip-conn-1"; -type Ready = Extract; - -function setInput(input: HTMLInputElement, value: string) { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value); - input.dispatchEvent(new Event("input", { bubbles: true })); -} - -describe("AwsRoleSetup", () => { - let container: HTMLDivElement; - let root: Root; - beforeEach(() => { - (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - window.sessionStorage.clear(); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - vi.restoreAllMocks(); - }); - - async function render(setup: AwsConnectionSetup, props: Partial[0]> = {}) { - const client: AwsRoleSetupClient = { setup: vi.fn(async () => setup) }; - const onTest = vi.fn(); - await act(async () => { - root.render( - - - , - ); - }); - await act(async () => { await Promise.resolve(); }); - return { client, onTest }; - } - const button = (text: string) => [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === text); - - it("shows only the agent setup by default, then tests with the pasted role ARN", async () => { - const { client, onTest } = await render(READY); - expect(client.setup).toHaveBeenCalledWith("conn-1", undefined); - expect(container.querySelector('button[aria-label="Set it up with your agent"]')).not.toBeNull(); - expect(container.textContent).toContain("Or do it by hand"); - expect(container.textContent).not.toContain("Download template"); - const test = () => button("Test connection")!; - expect(test().disabled).toBe(true); - const input = container.querySelector("#aws-role-arn")!; - await act(async () => { setInput(input, "not-an-arn"); }); - expect(container.textContent).toContain("Use the full role ARN"); - expect(test().disabled).toBe(true); - await act(async () => { setInput(input, ` ${ROLE_ARN} `); }); - expect(test().disabled).toBe(false); - await act(async () => { test().click(); }); - expect(onTest).toHaveBeenCalledWith(ROLE_ARN); - }); - - it("fills in a role ARN saved earlier", async () => { - await render({ ...READY, savedRoleArn: ROLE_ARN } as AwsConnectionSetup); - expect(container.querySelector("#aws-role-arn")!.value).toBe(ROLE_ARN); - expect(button("Test connection")?.disabled).toBe(false); - }); - - it("shows CloudFormation and IAM steps by hand, with CLI commands that read the account", async () => { - await render(READY); - await act(async () => { button("Or do it by hand")?.click(); }); - expect(container.textContent).toContain("With CloudFormation"); - expect(container.textContent).toContain("copy RoleArn from its Outputs tab"); - expect(container.textContent).toContain("replacing ACCOUNT_ID with your AWS account ID"); - const cli = container.querySelector('textarea[aria-label="AWS CLI commands"]')!.value; - expect(cli).toContain("ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)"); - expect(cli).toContain("arn:aws:iam::${ACCOUNT_ID}:oidc-provider/"); - expect(cli).toContain("--role-name paperclip-conn-1"); - expect(cli).toContain("arn:aws:iam::aws:policy/ReadOnlyAccess"); - expect(cli).toContain("aws iam get-role --role-name paperclip-conn-1 --query Role.Arn --output text"); - }); - - it("gives the user's agent a prompt that deploys this connection's template and reports the role ARN", () => { - const prompt = awsAgentSetupPrompt(READY as Ready); - expect(prompt).toContain("aws sts get-caller-identity"); - expect(prompt).toContain("--stack-name paperclip-conn-1 "); - expect(prompt).toContain("CAPABILITY_NAMED_IAM"); - expect(prompt).toContain("RoleArn output"); - expect(prompt).toContain("connection:conn-1"); - expect(prompt).toContain((READY as Ready).cloudFormationTemplate.trimEnd()); - expect(prompt).not.toContain("AccessPolicyArn="); - const full = awsAgentSetupPrompt({ ...READY, accessLevel: "full" } as Ready); - expect(full).toContain("ask me which managed policy"); - expect(full).toContain("AccessPolicyArn="); - }); - - it("updates the connection's role on reconnect, checks its account, with CLI commands that paste as is", async () => { - const setup = { ...READY, savedRoleArn: ROLE_ARN, accessLevel: "full" } as Ready; - await render(setup); - expect(container.textContent).toContain("It updates the existing role"); - await act(async () => { button("Or do it by hand")?.click(); }); - expect(container.textContent).toContain("Update the role"); - const roleRow = [...container.querySelectorAll("div")].find((d) => d.firstElementChild?.textContent === "Role name"); - expect(roleRow?.querySelector("code")?.textContent).toBe("paperclip-conn-1"); - const cli = awsCliCommands(setup); - expect(cli).toContain("if aws iam get-role --role-name paperclip-conn-1"); - expect(cli).toContain("aws iam update-assume-role-policy --role-name paperclip-conn-1"); - expect(cli).toContain("|| aws iam create-open-id-connect-provider"); - expect(cli).toContain("REPLACE_WITH_POLICY_ARN"); - expect(cli).not.toMatch(/<[^<>\n]*>/); - const prompt = awsAgentSetupPrompt(setup); - expect(prompt).toContain(`Update the AWS IAM role ${ROLE_ARN}`); - // The agent stops when the CLI is signed in to another account than the role's. - expect(prompt).toContain("The role is in account 123456789012: if the CLI uses a different account"); - expect(prompt).toContain("creates the stack, or updates it if it already exists"); - expect(prompt).toContain("If the stack paperclip-conn-1 already exists and its value is true"); - expect(prompt).toContain("keep true so the stack keeps owning its provider. Otherwise run `aws iam list-open-id-connect-providers`"); - }); - - it("asks for the access policy when the connection has full access", async () => { - await render({ ...READY, accessLevel: "full" } as AwsConnectionSetup); - await act(async () => { button("Or do it by hand")?.click(); }); - expect(container.textContent).toContain("Set AccessPolicyArn to the managed policy agents should have"); - expect(container.textContent).not.toContain("so it needs no edits"); - }); - - it("downloads the template generated for this connection", async () => { - await render(READY); - await act(async () => { button("Or do it by hand")?.click(); }); - const createObjectURL = vi.fn(() => "blob:template"); - const revokeObjectURL = vi.fn(); - Object.assign(URL, { createObjectURL, revokeObjectURL }); - let downloaded = ""; - vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) { downloaded = this.download; }); - await act(async () => { [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Download template"))?.click(); }); - expect(downloaded).toBe("paperclip-aws-paperclip-conn-1.json"); - expect(createObjectURL).toHaveBeenCalledOnce(); - expect(revokeObjectURL).toHaveBeenCalledWith("blob:template"); - }); - - it("adds live progress reporting to the prompt and shows the agent's checklist", async () => { - const progress: AgentSetupProgress = { - id: "11111111-1111-4111-8111-111111111111", companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", - status: "waiting", items: [], summary: null, expiresAt: new Date(Date.now() + 6 * 3600_000).toISOString(), createdAt: "2026-11-23T14:00:00.000Z", updatedAt: "2026-11-23T14:00:00.000Z", - }; - const base = `https://acme.paperclip.app/api/agent-setup-progress/${progress.id}`; - const handoff: AgentSetupProgressHandoff = { progress, token: "pcsp_test", urls: { checklist: `${base}/checklist`, item: `${base}/items/{key}`, finish: `${base}/finish` } }; - // Live updates are covered in AgentSetupProgress.test.tsx; here the agent has not reported yet. - const progressClient: AgentSetupProgressClient = { create: vi.fn(async () => handoff), get: vi.fn(async () => progress) }; - await render(READY, { companyId: "company-1", progressClient }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - // Creating the checklist is asynchronous: wait for it rather than assume one tick is enough. - await vi.waitFor(() => expect(container.textContent).toContain("Paste the prompt into your agent. Its steps appear here as it works.")); - expect(progressClient.create).toHaveBeenCalledWith("company-1", { purpose: "aws_connection", subjectId: "conn-1" }); - const prompt = awsAgentSetupPrompt(READY as Ready, "PROGRESS"); - expect(prompt).toContain("Also put it in your finish summary"); - // Progress reporting comes first, so the agent sets its checklist before it starts. - expect(prompt.indexOf("PROGRESS")).toBeLessThan(prompt.indexOf("Steps:")); - }); - - it("says when live progress is unavailable, keeps the prompt, and tries again", async () => { - const create = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce({ - progress: { id: "11111111-1111-4111-8111-111111111111", companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", - status: "waiting", items: [], summary: null, expiresAt: new Date(Date.now() + 3600_000).toISOString(), - createdAt: "2026-11-23T14:00:00.000Z", updatedAt: "2026-11-23T14:00:00.000Z" }, - token: "pcsp_test", urls: { checklist: "https://x/checklist", item: "https://x/items/{key}", finish: "https://x/finish" }, - }); - const progressClient: AgentSetupProgressClient = { create, get: vi.fn(async () => { throw new Error("unused"); }) }; - await render(READY, { companyId: "company-1", progressClient }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - await vi.waitFor(() => expect(container.textContent).toContain("Live progress isn’t available")); - expect(container.querySelector('button[aria-label="Set it up with your agent"]')).not.toBeNull(); - await act(async () => { button("Try again")?.click(); }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(create).toHaveBeenCalledTimes(2); - expect(container.textContent).not.toContain("Live progress isn’t available"); - await vi.waitFor(() => expect(container.textContent).toContain("Paste the prompt into your agent.")); - }); - - it("points to the access-key method when AWS cannot reach this instance, without starting a checklist", async () => { - const progressClient: AgentSetupProgressClient = { create: vi.fn(), get: vi.fn() }; - await render({ available: false, reason: "loopback" }, { companyId: "company-1", progressClient }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - // No prompt can carry a checklist here, so none is created. - expect(progressClient.create).not.toHaveBeenCalled(); - expect(container.textContent).toContain("Use an access key instead"); - expect(container.textContent).toContain("runs on this computer only"); - expect(button("Test connection")?.disabled).toBe(true); - }); - - it("shows the server's AWS message even when setup reports it with a gateway status", () => { - const message = "AWS refused this connection's role. Check that the role exists and trusts this connection."; - const awsError = new ApiError(message, 502, { error: message, code: "aws_role_access_denied", details: { code: "aws_role_access_denied" } }); - expect(awsSetupErrorMessage(awsError)).toBe(message); - const other = new ApiError("Bad Gateway", 502, { error: "upstream", details: { code: "mcp_remote_fetch_failed" } }); - expect(awsSetupErrorMessage(other)).not.toContain("upstream"); - }); - - it("explains a failed test in place", async () => { - await render(READY, { error: "AWS refused this connection's role. Check that the role exists and trusts this connection." }); - expect(container.textContent).toContain("AWS didn’t accept the connection yet"); - expect(container.textContent).toContain("AWS refused this connection's role"); - }); - - it("asks to save the connection again instead of showing steps for an old address", async () => { - await render({ available: false, reason: "address_changed" }); - expect(container.textContent).toContain("Save the connection again"); - expect(container.textContent).not.toContain("Create it with CloudFormation"); - expect(button("Test connection")?.disabled).toBe(true); - }); -}); diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx deleted file mode 100644 index 598c6fcb012..00000000000 --- a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx +++ /dev/null @@ -1,929 +0,0 @@ -// @vitest-environment jsdom - -import { act as reactAct, useState, type ReactNode } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { - ConnectionIntentInteraction, - ToolConnection, -} from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ApiError } from "@/api/client"; -import { - connectedConnectionIntentInteraction, - issueThreadInteractionFixtureMeta, - pendingConnectionIntentInteraction, - retryConnectionIntentInteraction, -} from "@/fixtures/issueThreadInteractionFixtures"; -import { ConnectionIntentInteractionBody } from "./ConnectionIntentInteractionBody"; - -const emailConnectMock = vi.hoisted(() => vi.fn()); -const emailSetupMock = vi.hoisted(() => vi.fn()); -const emailListMock = vi.hoisted(() => vi.fn()); -const emailControlMock = vi.hoisted(() => vi.fn()); -const emailCredentialsMock = vi.hoisted(() => vi.fn()); -vi.mock("@/api/email", () => ({ emailApi: { - credentials: (...args: unknown[]) => emailCredentialsMock(...args), - list: (...args: unknown[]) => emailListMock(...args), - control: (...args: unknown[]) => emailControlMock(...args), - connect: (...args: unknown[]) => emailConnectMock(...args), - setup: (...args: unknown[]) => emailSetupMock(...args), -} })); - -const credentialRender = vi.hoisted(() => vi.fn()); -const routedCredentialRender = vi.hoisted(() => vi.fn()); -const setupOptionsMock = vi.hoisted(() => vi.fn()); -const completeMock = vi.hoisted(() => vi.fn()); -const declineMock = vi.hoisted(() => vi.fn()); -const setPhaseMock = vi.hoisted(() => vi.fn()); -const getAgentMock = vi.hoisted(() => vi.fn()); -const updateAgentMock = vi.hoisted(() => vi.fn()); -const setDefaultMock = vi.hoisted(() => vi.fn()); -vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: { setDefault: (...args: unknown[]) => setDefaultMock(...args) } })); -const adoptMock = vi.hoisted(() => vi.fn()); -const installMock = vi.hoisted(() => vi.fn()); -vi.mock("@/api/tools", () => ({ toolsApi: { - getConnectionInstalls: async () => ({ installs: [] }), - putConnectionInstalls: (...args: unknown[]) => installMock(...args), -} })); - -vi.mock("@/api/agents", () => ({ agentsApi: { - adoptAiConnection: (...args: unknown[]) => adoptMock(...args), - get: (...args: unknown[]) => getAgentMock(...args), - update: (...args: unknown[]) => updateAgentMock(...args), -} })); - -vi.mock("@/api/connection-intents", () => ({ - connectionIntentsApi: { - setupOptions: (...args: unknown[]) => setupOptionsMock(...args), - complete: (...args: unknown[]) => completeMock(...args), - decline: (...args: unknown[]) => declineMock(...args), - setPhase: (...args: unknown[]) => setPhaseMock(...args), - }, -})); - -vi.mock("@/components/ai-connections/AiConnectionCredentialStep", () => ({ - AiConnectionCredentialStep: (props: { connectionId?: string; name: string; hideName?: boolean; fixedMethod?: boolean; onComplete: (result: {connectionId: string; grantId: string; method: "api_key"}) => void; onCancel: () => void }) => { credentialRender(props); return
- {!props.hideName && {props.name}}{String(props.fixedMethod)} - - -
; }, -})); - -vi.mock("@/components/ai-connections/AiProviderSetup", () => ({ - AiProviderSetup: (props: { reconnect: { id: string }; onComplete: (binding: { connectionId: string; grantId: string; method: "api_key" }) => void; onCancel: () => void }) => { - routedCredentialRender(props); - return
- - -
; - }, -})); - -vi.mock("./ConnectionSetupFlow", () => ({ - ConnectionSetupFlow: (props: { - requestedAgentId?: string; - requiredAgentId?: string; - existingConnections?: ToolConnection[]; - onUseExisting?: (id: string) => Promise; - onComplete?: (completion: { connectionId: string } | { resolvedByCallback: true }) => void; - onPhaseChange?: (phase: "needs_retry") => void; - onCancel?: () => void; - }) => ( -
- {props.requestedAgentId} - {props.requiredAgentId} - - {props.existingConnections?.length ?? 0} - - {props.existingConnections?.map((connection) => ( - - ))} - - - - -
- ), -})); - -( - globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } -).IS_REACT_ACT_ENVIRONMENT = true; - -let root: Root | null = null; -let host: HTMLDivElement | null = null; -let queryClient: QueryClient; - -async function act(callback: () => void | Promise) { - await reactAct(callback); -} - -async function flush() { - await act(async () => { - await Promise.resolve(); - await new Promise((resolve) => window.setTimeout(resolve, 0)); - }); -} - -async function waitForAssertion(assertion: () => void, attempts = 20) { - let lastError: unknown; - for (let attempt = 0; attempt < attempts; attempt += 1) { - await flush(); - try { - assertion(); - return; - } catch (error) { - lastError = error; - } - } - throw lastError; -} - -function terminal( - status: ConnectionIntentInteraction["status"], - outcome: "declined" | "superseded" | "expired", -): ConnectionIntentInteraction { - return { - ...pendingConnectionIntentInteraction, - id: `interaction-${outcome}`, - status, - resolvedAt: new Date("2026-08-26T12:00:00.000Z"), - result: { version: 1, outcome }, - } as ConnectionIntentInteraction; -} - -function renderNode(node: ReactNode) { - host = document.createElement("div"); - document.body.appendChild(host); - root = createRoot(host); - queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, - }); - void act(() => { - root?.render( - - {node} - , - ); - }); - return host; -} - -function renderBody( - interaction: ConnectionIntentInteraction = pendingConnectionIntentInteraction, - currentUserId: - string | null = issueThreadInteractionFixtureMeta.currentUserId, -) { - return renderNode( - , - ); -} - -function button(label: string) { - return Array.from(document.body.querySelectorAll("button")).find( - (candidate) => candidate.textContent?.trim() === label || (label === "Connect / Use existing" && candidate.textContent?.trim() === "Connect"), - ) as HTMLButtonElement | undefined; -} - -it("explains all-agent defaults consistently on compact connector cards", () => { - renderNode(); - expect(document.body.textContent).toContain("New connections default to all agents"); - expect(document.body.textContent).not.toContain("Access is added only for this agent"); -}); - -beforeEach(() => { - sessionStorage.clear(); - emailCredentialsMock.mockReset().mockResolvedValue([]); - emailListMock.mockReset().mockResolvedValue([]); - emailControlMock.mockReset().mockResolvedValue({}); - emailConnectMock.mockReset().mockResolvedValue({ id: "email-account" }); - emailSetupMock.mockReset().mockResolvedValue({ connectionId: "email-inbox" }); - setDefaultMock.mockReset(); - getAgentMock.mockReset(); - updateAgentMock.mockReset(); - installMock.mockReset(); - adoptMock.mockReset(); - setupOptionsMock.mockReset(); - completeMock.mockReset(); - declineMock.mockReset(); - setPhaseMock.mockReset(); - setupOptionsMock.mockResolvedValue({ - requestedAgentId: - pendingConnectionIntentInteraction.payload.requestingAgentId, - existingConnections: [], - }); - completeMock.mockResolvedValue({}); - declineMock.mockResolvedValue({}); - setPhaseMock.mockResolvedValue({}); -}); - -afterEach(async () => { - if (root) await act(() => root?.unmount()); - await queryClient.cancelQueries(); - queryClient.clear(); - host?.remove(); - document.body - .querySelectorAll("[data-radix-focus-guard]") - .forEach((node) => node.remove()); - root = null; - host = null; -}); - -describe("ConnectionIntentInteractionBody states and audience", () => { - it("opens the saved chat authentication step without another setup form", async () => { - const interaction = { ...pendingConnectionIntentInteraction, payload: { ...pendingConnectionIntentInteraction.payload, - purpose: "channel" as const, serviceSlug: "slack", serviceName: "Slack", phase: "authorizing" as const, - savedSetup: { endpointId: "endpoint", connectionId: "connection" } } }; - setupOptionsMock.mockResolvedValue({ version: 1, interaction, requestedAgentId: interaction.payload.requestingAgentId, - existingConnections: [], service: { service: "slack", name: "Slack", methods: [], state: "needs_user_action" }, - chatSetup: { endpointId: "endpoint", connectionId: "connection", path: "/ACME/apps/chat/connect?provider=slack&resume=endpoint" } }); - renderBody(interaction); - await waitForAssertion(() => - expect(document.querySelector('a')?.getAttribute("href")).toBe("/ACME/apps/chat/connect?provider=slack&resume=endpoint"), - ); - expect(document.querySelector('[data-testid="shared-connection-setup"]')).toBeNull(); - expect(completeMock).not.toHaveBeenCalled(); - }); - - it.each([ - [pendingConnectionIntentInteraction, "Connect"], - [ - { - ...pendingConnectionIntentInteraction, - payload: { - ...pendingConnectionIntentInteraction.payload, - phase: "authorizing", - }, - }, - "Continue setup", - ], - [retryConnectionIntentInteraction, "Try again"], - [connectedConnectionIntentInteraction, "Notion connected"], - [terminal("rejected", "declined"), "Connection declined"], - [terminal("expired", "superseded"), "Request superseded"], - [terminal("expired", "expired"), "Connection request expired"], - ] as const)("renders the %s state", (interaction, expected) => { - renderBody(interaction as ConnectionIntentInteraction); - expect(document.body.textContent).toContain(expected); - }); - - it("shows the stored reason on an expired request", () => { - // The server writes what actually expired the request and what to do next. - // A generic "no longer active" line left the reader with no next step. - const reason = "The task was reassigned before the connection request was answered, so the Notion connection is still not connected. Reconnect it or choose an available connection."; - renderBody({ - ...terminal("expired", "expired"), - result: { version: 1, outcome: "expired", reason }, - } as ConnectionIntentInteraction); - expect(document.body.textContent).toContain(reason); - expect(document.body.textContent).not.toContain("This request is no longer active."); - }); - - it("shows non-addressees only the waiting state and never loads setup", () => { - renderBody(pendingConnectionIntentInteraction, "other-user"); - expect(document.body.textContent).toContain("Waiting for Carol"); - expect(button("Connect / Use existing")).toBeUndefined(); - expect(button("Not now")).toBeUndefined(); - expect(setupOptionsMock).not.toHaveBeenCalled(); - expect(document.body.innerHTML).not.toMatch( - /authorizationUrl|bearer|credential/i, - ); - }); -}); - -describe("ConnectionIntentInteractionBody dialog behavior", () => { - it("verifies inline OAuth callback hints against durable server acceptance", async () => { - const options = { requestedAgentId: pendingConnectionIntentInteraction.payload.requestingAgentId, existingConnections: [], interaction: pendingConnectionIntentInteraction }; - setupOptionsMock.mockResolvedValue(options); - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - const readsBeforeMessage = setupOptionsMock.mock.calls.length; - await act(() => button("Simulate OAuth callback")?.click()); - await flush(); - expect(setupOptionsMock.mock.calls.length).toBeGreaterThan(readsBeforeMessage); - expect(document.querySelector('[role="dialog"]')).not.toBeNull(); - expect(completeMock).not.toHaveBeenCalled(); - setupOptionsMock.mockResolvedValue({ ...options, interaction: connectedConnectionIntentInteraction }); - await act(() => button("Simulate OAuth callback")?.click()); - await waitForAssertion(() => expect(document.querySelector('[role="dialog"]')).toBeNull()); - expect(completeMock).not.toHaveBeenCalled(); - }); - - it("passes existing choices and requires the requester without locking tool setup to that agent", async () => { - let resolveSetup!: (value: unknown) => void; - setupOptionsMock.mockReturnValue( - new Promise((resolve) => { - resolveSetup = resolve; - }), - ); - renderBody(); - - await act(() => button("Connect / Use existing")?.click()); - expect(document.body.textContent).toContain("Loading connection options…"); - - await act(async () => { - resolveSetup({ - requestedAgentId: "agent-requesting", - existingConnections: [ - { id: "connection-one", name: "Carol's Notion" }, - { id: "connection-two", name: "Team Notion" }, - ], - }); - }); - await flush(); - - expect( - document.querySelector('[data-testid="requested-agent"]')?.textContent, - ).toBe(""); - expect(document.querySelector('[data-testid="required-agent"]')?.textContent).toBe("agent-requesting"); - expect(document.body.textContent).toContain("New connections default to all agents"); - expect(document.body.textContent).not.toContain("Access is added only for this agent"); - expect( - document.querySelector('[data-testid="existing-count"]')?.textContent, - ).toBe("2"); - expect(button("Use Carol's Notion")).toBeDefined(); - expect(button("Use Team Notion")).toBeDefined(); - expect(button("Connect new")).toBeDefined(); - }); - - it("keeps a load failure open with readable copy and recovers through the query retry", async () => { - setupOptionsMock.mockRejectedValueOnce(new ApiError("Request failed: 500", 500, { error: "internal_error" })); - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - - expect(document.querySelector('[data-query-view="error"]')).not.toBeNull(); - expect(document.body.textContent).toContain("Couldn't load connection setup"); - expect(document.body.textContent).not.toContain("internal_error"); - expect(document.body.textContent).not.toContain("Request failed: 500"); - setupOptionsMock.mockResolvedValueOnce({ - requestedAgentId: "agent-requesting", - existingConnections: [], - }); - await act(() => button("Retry")?.click()); - await flush(); - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).not.toBeNull(); - expect(document.querySelector('[data-query-view="error"]')).toBeNull(); - }); - - it("keeps loaded setup options usable when a refetch fails during an outage", async () => { - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).not.toBeNull(); - - setupOptionsMock.mockRejectedValue( - new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }), - ); - await act(async () => { - await queryClient.invalidateQueries(); - }); - await flush(); - - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).not.toBeNull(); - expect(document.querySelector('[data-query-view="error"]')).toBeNull(); - expect(document.body.textContent).not.toContain("Paperclip is restarting."); - expect(document.body.textContent).not.toContain("Couldn't load connection setup"); - }); - - it("completes an existing connection, closes, restores focus, and invalidates each task query once", async () => { - setupOptionsMock.mockResolvedValue({ - requestedAgentId: "agent-requesting", - existingConnections: [{ id: "connection-one", name: "Carol's Notion" }], - }); - renderBody(); - const trigger = button("Connect / Use existing")!; - const invalidation = vi.spyOn(queryClient, "invalidateQueries"); - - await act(() => trigger.click()); - await flush(); - await act(() => button("Use Carol's Notion")?.click()); - await flush(); - - expect(completeMock).toHaveBeenCalledWith( - pendingConnectionIntentInteraction.id, - "connection-one", - ); - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).toBeNull(); - await waitForAssertion(() => - expect(document.activeElement).toBe( - document.querySelector( - '[data-testid="connection-intent-focus-target"]', - ), - ), - ); - expect(invalidation).toHaveBeenCalledTimes(2); - expect(invalidation).toHaveBeenCalledWith({ - queryKey: ["issues", "interactions"], - }); - expect(invalidation).toHaveBeenCalledWith({ - queryKey: ["issues", "detail"], - }); - }); - - it("restores focus when completion remounts the intent in a different task host", async () => { - setupOptionsMock.mockResolvedValue({ - requestedAgentId: "agent-requesting", - existingConnections: [{ id: "connection-one", name: "Carol's Notion" }], - }); - const acceptedInteraction = { - ...pendingConnectionIntentInteraction, - status: "accepted", - resolvedAt: new Date("2026-08-26T12:00:00.000Z"), - result: { - version: 1, - outcome: "connected", - connectionId: "connection-one", - }, - } as ConnectionIntentInteraction; - let showAcceptedInteraction!: () => void; - - function RemountingTaskHost() { - const [interaction, setInteraction] = useState( - pendingConnectionIntentInteraction, - ); - showAcceptedInteraction = () => setInteraction(acceptedInteraction); - return ( - - ); - } - - completeMock.mockImplementation(async () => { - showAcceptedInteraction(); - return acceptedInteraction; - }); - renderNode(); - - await act(() => button("Connect / Use existing")?.click()); - await flush(); - await act(() => button("Use Carol's Notion")?.click()); - - await waitForAssertion(() => { - const target = document.getElementById( - `connection-intent-focus-target-${acceptedInteraction.id}`, - ); - expect(document.body.textContent).toContain("Notion connected"); - expect(document.activeElement).toBe(target); - }); - }); - - it("keeps the dialog open and surfaces completion failures", async () => { - completeMock.mockRejectedValue(new Error("install commit failed")); - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - await act(() => button("Connect new")?.click()); - await flush(); - - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).not.toBeNull(); - expect( - document.body.querySelector('[role="alert"]')?.textContent, - ).toContain("install commit failed"); - }); - - it("declines once with pending controls disabled and invalidates each task query once", async () => { - let finishDecline!: () => void; - declineMock.mockReturnValue( - new Promise((resolve) => { - finishDecline = resolve; - }), - ); - renderBody(); - const invalidation = vi.spyOn(queryClient, "invalidateQueries"); - const decline = button("Not now")!; - - await act(() => decline.click()); - await flush(); - expect(decline.disabled).toBe(true); - decline.click(); - expect(declineMock).toHaveBeenCalledTimes(1); - await act(async () => finishDecline()); - await flush(); - - expect(invalidation).toHaveBeenCalledTimes(2); - }); - - it("turns shared-flow retry signals into the server-authored retry phase", async () => { - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - await act(() => button("Simulate retry")?.click()); - await flush(); - expect(setPhaseMock).toHaveBeenCalledWith( - pendingConnectionIntentInteraction.id, - "needs_retry", - ); - }); -}); - - -describe("AI repair inside the card", () => { - const interaction: ConnectionIntentInteraction = { ...pendingConnectionIntentInteraction, payload: { ...pendingConnectionIntentInteraction.payload, purpose: "ai" } }; - const connection = { id: "selected-account", name: "My Codex account", provider: "openai", method: "api_key", ownership: "personal", ownerName: "Dotta", status: "revoked" }; - it.each(["openrouter", "bedrock", "gateway"] as const)("retains the selected %s route through task-card account repair", async kind => { - const routing = kind === "bedrock" - ? { kind, protocol: "bedrock", region: "us-east-1", auth: "bearer", models: [] } - : { kind, protocol: "responses", auth: "bearer", models: [], ...(kind === "gateway" ? { baseUrl: "https://gateway.example/v1" } : {}) }; - const routedConnection = { ...connection, provider: kind === "bedrock" ? "anthropic" : kind === "openrouter" ? "openrouter" : "openai", routing }; - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection: routedConnection, canReconnect: true } }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - expect(document.querySelector('[data-testid="shared-ai-credentials"]')).toBeNull(); - expect(routedCredentialRender.mock.lastCall![0]).toMatchObject({ companyId: interaction.companyId, agentId: interaction.payload.requestingAgentId, reconnect: routedConnection }); - await act(() => button("Reconnect routed account")!.click()); - expect(completeMock).toHaveBeenCalledWith(interaction.id, connection.id); - }); - - it.each([false, true])("requires atomic validated legacy adoption (validation fails: %s)", async (fails) => { - const binding = { provider: "openai", method: "subscription", mode: "responsible_user" }; - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: binding, aiConnectionRequiresAdoption: true }); - if (fails) adoptMock.mockRejectedValue(new Error("Connection test failed")); - else adoptMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); - await waitForAssertion(() => expect(button("Connect OpenAI")).toBeDefined()); - await act(() => button("Connect OpenAI")!.click()); - await act(() => button("Reconnect selected account")!.click()); - expect(adoptMock).not.toHaveBeenCalled(); - expect(document.body.textContent).toContain("Use your OpenAI account"); - expect(document.body.textContent).toContain("Your account is connected."); - expect(document.body.textContent).toContain("This replaces the agent’s existing authentication"); - await act(() => button("Use connection and continue")!.click()); - await flush(); - expect(adoptMock).toHaveBeenCalledWith(interaction.payload.requestingAgentId, interaction.id, "new-ai-account", interaction.companyId); - expect(updateAgentMock).not.toHaveBeenCalled(); - expect(installMock).not.toHaveBeenCalled(); - expect(completeMock).not.toHaveBeenCalled(); - if (fails) expect(document.querySelector('[role="alert"]')?.textContent).toContain("Connection test failed"); - }); - it.each(["anthropic", "openai"])("connects a missing %s default directly in the task", async (provider) => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider, method: "api_key", mode: "responsible_user" } }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); await flush(); - const providerName = provider === "anthropic" ? "Claude" : "OpenAI"; - await waitForAssertion(() => expect(document.body.textContent).toContain(`Connect your ${providerName} account`)); - expect(document.body.textContent).toContain("needs your own AI connection"); - await act(() => button(`Connect ${providerName}`)!.click()); - expect(document.querySelector('[role="dialog"]')).toBeNull(); - expect(document.querySelector('[data-testid="shared-connection-setup"]')).toBeNull(); - expect(document.querySelector('[data-testid="shared-ai-credentials"]')).not.toBeNull(); - expect(credentialRender.mock.lastCall![0]).toMatchObject({ provider, hideName: true, ownership: "personal", agentIds: [interaction.payload.requestingAgentId], allAgents: false }); - expect(credentialRender.mock.lastCall![0].connectionId).toBeUndefined(); - expect(credentialRender.mock.lastCall![0].fixedMethod).toBeUndefined(); - expect(document.body.textContent).toContain("the task will resume automatically"); - await act(() => button("Reconnect selected account")!.click()); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-ai-account"); - }); - it("reuses authentication inline, preserves the selected account, cancels with focus, and completes", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: true } }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); - await flush(); - await act(() => button("Fix connection")!.click()); - expect(document.querySelector('[role="dialog"]')).toBeNull(); - expect(document.querySelector('[data-testid="ai-connection-inline-repair"]')?.textContent).not.toContain("My Codex account"); - expect(credentialRender.mock.lastCall![0]).toMatchObject({ name: "My Codex account", hideName: true, fixedMethod: false, connectionId: "selected-account" }); - await act(() => button("Cancel repair")!.click()); - await waitForAssertion(() => expect(document.activeElement?.getAttribute("data-testid")).toBe("connection-intent-focus-target")); - expect(completeMock).not.toHaveBeenCalled(); - await act(() => button("Fix connection")!.click()); - await act(() => button("Reconnect selected account")!.click()); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "selected-account"); - }); - it.each(["responsible_user", "delegated", "shared"] as const)("selects a different authentication method for a %s binding before resuming", async (mode) => { - const binding = { provider: "openai", method: "api_key", mode, ...(mode !== "responsible_user" ? { connectionId: connection.id, grantId: "old-grant" } : {}) }; - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: binding, aiRepair: { connection: { ...connection, grantId: "old-grant" }, canReconnect: true } }); - getAgentMock.mockResolvedValue({ id: interaction.payload.requestingAgentId, runtimeConfig: { aiConnection: binding, heartbeat: { enabled: true } } }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); - await flush(); - if (mode === "responsible_user") { - expect(setDefaultMock).toHaveBeenCalledWith(interaction.companyId, "new-grant"); - expect(updateAgentMock).not.toHaveBeenCalled(); - } else { - expect(updateAgentMock).toHaveBeenCalledWith(interaction.payload.requestingAgentId, { runtimeConfig: { heartbeat: { enabled: true }, aiConnection: { ...binding, method: "subscription", connectionId: "new-subscription", grantId: "new-grant" } } }, interaction.companyId); - expect(setDefaultMock).not.toHaveBeenCalled(); - } - expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-subscription"); - }); - it("keeps a failed account switch pending and retries the saved account", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, aiRepair: { connection, canReconnect: true } }); - setDefaultMock.mockRejectedValueOnce(new Error("Could not select this account")); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); - await flush(); - expect(completeMock).not.toHaveBeenCalled(); - expect(document.querySelector('[role="alert"]')?.textContent).toContain("Could not select this account"); - await act(() => button("Retry using this connection")!.click()); - await flush(); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-subscription"); - }); - it("clears an account-selection retry when its setup is abandoned", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, aiRepair: { connection, canReconnect: true } }); - setDefaultMock.mockRejectedValueOnce(new Error("Could not select this account")); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); - await flush(); - expect(button("Retry using this connection")).toBeDefined(); - await act(() => button("Cancel repair")!.click()); - await act(() => button("Fix connection")!.click()); - expect(button("Retry using this connection")).toBeUndefined(); - expect(document.querySelector('[role="alert"]')).toBeNull(); - expect(completeMock).not.toHaveBeenCalled(); - }); - it("keeps a late credential save after cancellation from accepting the request", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: true } }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - const abandoned = credentialRender.mock.lastCall![0]; - await act(() => button("Cancel repair")!.click()); - await act(() => button("Fix connection")!.click()); - await act(() => abandoned.onComplete({ connectionId: connection.id, grantId: "grant", method: "api_key" })); - expect(completeMock).not.toHaveBeenCalled(); - }); - it("offers continuation for the restored account without another login", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [connection], aiRepair: { connection, canReconnect: true } }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - expect(document.querySelector('[data-testid="shared-ai-credentials"]')).toBeNull(); - await act(() => button("Continue task")!.click()); - expect(completeMock).toHaveBeenCalledWith(interaction.id, connection.id); - }); - it("does not let another user reconnect the owner's account", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: false } }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - expect(document.body.textContent).toContain("Dotta must reconnect My Codex account"); - expect(document.querySelector('[data-testid="shared-ai-credentials"]')).toBeNull(); - }); - it("shows a withdrawn AI request as terminal without another setup action", () => { - renderBody({ ...interaction, status: "cancelled", resolvedAt: new Date() }); - expect(document.body.textContent).toContain("Connection request withdrawn"); - expect(document.body.textContent).not.toContain("This task can’t run"); - expect(button("Fix connection")).toBeUndefined(); - expect(document.querySelector('[data-testid="connection-intent-terminal"]')).not.toBeNull(); - expect(setupOptionsMock).not.toHaveBeenCalled(); - expect(credentialRender).not.toHaveBeenCalled(); - }); - it("does not promise to run without credentials when declined", () => { - renderBody({ ...interaction, status: "rejected" }); - expect(document.body.textContent).toContain("The task still needs a working AI connection"); - expect(document.body.textContent).not.toContain("can continue without it"); - }); -}); - -describe("AgentMail inline setup", () => { - const interaction: ConnectionIntentInteraction = { - ...pendingConnectionIntentInteraction, - payload: { ...pendingConnectionIntentInteraction.payload, purpose: "channel", serviceSlug: "agentmail", serviceName: "AgentMail" }, - }; - async function clickReadyButton(label: string) { - await waitForAssertion(() => expect(button(label)?.disabled).toBe(false)); - await act(() => button(label)!.click()); - await flush(); - } - async function enterKey() { - await waitForAssertion(() => expect(document.querySelector('input[type="password"]')).not.toBeNull()); - const input = document.querySelector('input[type="password"]') as HTMLInputElement; - await act(() => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "fixture-api-key"); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); - } - it("shows only the key inline, saves company access for this agent and completes after inbox setup", async () => { - renderBody(interaction); - await flush(); - expect(document.querySelector('[role="dialog"]')).toBeNull(); - await waitForAssertion(() => expect(document.querySelectorAll("input")).toHaveLength(1)); - expect(document.querySelector('a[href="https://console.agentmail.to/dashboard/api-keys"]')).not.toBeNull(); - expect(document.querySelector('[role="radiogroup"], select')).toBeNull(); - expect(button("Connect AgentMail")?.disabled).toBe(true); - await enterKey(); - await clickReadyButton("Connect AgentMail"); - expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, { - apiKey: "fixture-api-key", grantKind: "organization", allAgents: false, - agentIds: [interaction.payload.requestingAgentId], idempotencyKey: interaction.id, - }); - expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, { - assignedAgentId: interaction.payload.requestingAgentId, credentialConnectionId: "email-account", - receiveMode: "websocket", idempotencyKey: interaction.id, - }); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); - }); - it("keeps invalid credentials retryable and does not create an inbox or accept the request", async () => { - emailConnectMock.mockRejectedValueOnce(new Error("AgentMail request failed (401)")); - renderBody(interaction); await flush(); await enterKey(); - await clickReadyButton("Connect AgentMail"); - expect(document.querySelector('[role="alert"]')?.textContent).toContain("401"); - expect(emailSetupMock).not.toHaveBeenCalled(); - expect(completeMock).not.toHaveBeenCalled(); - await clickReadyButton("Connect AgentMail"); - expect(completeMock).toHaveBeenCalledTimes(1); - }); - it("retries inbox setup without asking for or saving the key again", async () => { - emailSetupMock.mockRejectedValueOnce(new Error("Inbox setup unavailable")); - renderBody(interaction); await flush(); await enterKey(); - await clickReadyButton("Connect AgentMail"); - expect(completeMock).not.toHaveBeenCalled(); - expect(document.querySelector('input[type="password"]')).toBeNull(); - await clickReadyButton("Finish setup"); - expect(emailConnectMock).toHaveBeenCalledTimes(1); - expect(emailSetupMock).toHaveBeenCalledTimes(2); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); - }); - it("can choose another key after a saved key fails, retiring an empty draft and preserving the retry identity", async () => { - emailCredentialsMock.mockResolvedValue([{ id: "saved-account", label: "Saved key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]); - emailSetupMock.mockRejectedValueOnce(new Error("Inbox already assigned")) - .mockRejectedValueOnce(new Error("Temporary provider failure")); - emailListMock.mockResolvedValue([{ id: interaction.id, address: null, status: "draft" }]); - renderBody(interaction); await flush(); - await waitForAssertion(() => expect(button("Connect AgentMail")?.disabled).toBe(false)); - expect((document.querySelector("select") as HTMLSelectElement)?.value).toBe("saved-account"); - expect(emailConnectMock).not.toHaveBeenCalled(); - await clickReadyButton("Connect AgentMail"); - expect(emailConnectMock).not.toHaveBeenCalled(); - await clickReadyButton("Change API key"); - expect(emailControlMock).toHaveBeenCalledWith(interaction.id, "remove"); - await enterKey(); - await clickReadyButton("Connect AgentMail"); - const next = emailSetupMock.mock.calls[1][1].idempotencyKey; - expect(next).not.toBe(interaction.id); - expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ idempotencyKey: next })); - expect(sessionStorage.getItem(`paperclip.agentmail-inline:${interaction.companyId}:${interaction.id}`)).not.toContain("fixture-api-key"); - await act(() => root!.unmount()); host!.remove(); queryClient.clear(); - renderBody(interaction); await flush(); - await clickReadyButton("Finish setup"); - expect(emailSetupMock.mock.calls[2][1].idempotencyKey).toBe(next); - expect(emailConnectMock).toHaveBeenCalledTimes(1); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); - }); - it("does not switch keys after an inbox address is allocated", async () => { - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "saved-account", readyConnectionId: null } }); - emailListMock.mockResolvedValue([{ id: interaction.id, address: "reserved@example.test", status: "draft" }]); - renderBody(interaction); await flush(); - await clickReadyButton("Change API key"); - expect(document.body.textContent).toContain("reserved@example.test is already reserved"); - expect(emailControlMock).not.toHaveBeenCalled(); - expect(document.querySelector('input[type="password"]')).toBeNull(); - }); - it("recovers the server-saved account when refresh interrupted its response", async () => { - const resumedInteraction = { ...interaction, id: "a381e91e-7127-427d-9d2d-519d4deba89f" }; - sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${resumedInteraction.id}`, JSON.stringify({ - setupRequestId: resumedInteraction.id, credentialId: null, inboxConnectionId: null, selectedCredentialId: "", - })); - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "server-saved-account", readyConnectionId: null } }); - renderBody(resumedInteraction); await flush(); - expect(document.querySelector('input[type="password"]')).toBeNull(); - await clickReadyButton("Finish setup"); - expect(emailConnectMock).not.toHaveBeenCalled(); - expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ - credentialConnectionId: "server-saved-account", idempotencyKey: resumedInteraction.id, - })); - }); - it("keeps a different saved-key selection when recovering an interrupted save", async () => { - const resumedInteraction = { ...interaction, id: "a381e91e-7127-427d-9d2d-519d4deba89f" }; - sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${resumedInteraction.id}`, JSON.stringify({ - setupRequestId: resumedInteraction.id, credentialId: null, inboxConnectionId: null, selectedCredentialId: "selected-account", - })); - emailCredentialsMock.mockResolvedValue([{ id: "selected-account", label: "My selected key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]); - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "earlier-account", readyConnectionId: null } }); - renderBody(resumedInteraction); await flush(); - await waitForAssertion(() => expect((document.querySelector('select') as HTMLSelectElement)?.value).toBe("selected-account")); - await clickReadyButton("Connect AgentMail"); - expect(emailConnectMock).not.toHaveBeenCalled(); - expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ - credentialConnectionId: "selected-account", idempotencyKey: resumedInteraction.id, - })); - }); - it("does not restore an abandoned server account after the user changes keys", async () => { - const replacementRequestId = "a381e91e-7127-427d-9d2d-519d4deba89f"; - sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${interaction.id}`, JSON.stringify({ - setupRequestId: replacementRequestId, credentialId: null, inboxConnectionId: null, selectedCredentialId: "", - })); - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "abandoned-account", readyConnectionId: null } }); - renderBody(interaction); await flush(); await enterKey(); - await clickReadyButton("Connect AgentMail"); - expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ idempotencyKey: replacementRequestId })); - expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ - credentialConnectionId: "email-account", idempotencyKey: replacementRequestId, - })); - }); - it("resumes a saved account after reload and retries acceptance without recreating the inbox", async () => { - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "email-account", readyConnectionId: "email-inbox" } }); - completeMock.mockRejectedValueOnce(new Error("Retry completion")); - renderBody(interaction); await flush(); - await clickReadyButton("Continue"); - await clickReadyButton("Continue"); - expect(emailConnectMock).not.toHaveBeenCalled(); - expect(emailSetupMock).not.toHaveBeenCalled(); - expect(completeMock).toHaveBeenCalledTimes(2); - }); - it("declines without provider requests and hides credentials from other viewers", async () => { - renderBody(interaction); await flush(); - await clickReadyButton("Not now"); - expect(declineMock).toHaveBeenCalledWith(interaction.id); - expect(emailConnectMock).not.toHaveBeenCalled(); - expect(emailSetupMock).not.toHaveBeenCalled(); - await act(() => root!.render()); - expect(document.querySelector('input')).toBeNull(); - }); - it("can decline even when inbox setup options fail to load", async () => { - setupOptionsMock.mockRejectedValue(new Error("Email setup is unavailable")); - renderBody(interaction); - await waitForAssertion(() => expect(document.body.textContent).toContain("Email setup is unavailable")); - await clickReadyButton("Not now"); - expect(declineMock).toHaveBeenCalledWith(interaction.id); - expect(emailConnectMock).not.toHaveBeenCalled(); - }); -}); - -describe("embedded agent access request", () => { - const accessRequest = { - connectionId: "22222222-2222-4222-8222-222222222222", - connectionName: "Saved Composio", - tools: [ - { catalogEntryId: "33333333-3333-4333-8333-333333333333", toolName: "COMPOSIO_SEARCH_TOOLS", versionHash: "v1", permission: "allowed" as const }, - { catalogEntryId: "44444444-4444-4444-8444-444444444444", toolName: "COMPOSIO_MANAGE_CONNECTIONS", versionHash: "v1", permission: "ask_first" as const }, - ], - }; - const interaction: ConnectionIntentInteraction = { ...pendingConnectionIntentInteraction, payload: { ...pendingConnectionIntentInteraction.payload, serviceName: "Composio", accessRequest } }; - - it("shows the exact tool permissions before granting inline without a setup modal", async () => { - setupOptionsMock.mockResolvedValue({ canGrantAccess: true }); - getAgentMock.mockResolvedValue({ id: interaction.payload.requestingAgentId, name: "Researcher" }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted", result: { version: 1, outcome: "connected", connectionId: accessRequest.connectionId } }); - renderBody(interaction); - await waitForAssertion(() => expect(button("Grant access")?.disabled).toBe(false)); - expect(document.body.textContent).toContain("Grant Researcher access to “Saved Composio”?"); - expect(document.body.querySelector('[data-slot="agent-avatar"]')?.getAttribute("aria-label")).toBe("Researcher"); - expect(Array.from(document.body.querySelectorAll('ul[aria-label="Tool permissions"] li'), row => row.textContent)).toEqual([ - "COMPOSIO_SEARCH_TOOLSAllowed", - "COMPOSIO_MANAGE_CONNECTIONSAsk first", - ]); - expect(completeMock).not.toHaveBeenCalled(); - await act(() => button("Grant access")?.click()); - await waitForAssertion(() => expect(completeMock).toHaveBeenCalledWith(interaction.id, accessRequest.connectionId)); - expect(document.body.querySelector('[role="dialog"]')).toBeNull(); - }); - - it("keeps errors visible and does not allow a non-manager to grant", async () => { - setupOptionsMock.mockResolvedValue({ canGrantAccess: false }); - renderBody(interaction); - await waitForAssertion(() => expect(document.body.textContent).toContain("Connection manager required")); - expect(button("Grant access")?.disabled).toBe(true); - expect(completeMock).not.toHaveBeenCalled(); - }); - - it("supports declining and displays permission errors on the card", async () => { - setupOptionsMock.mockResolvedValue({ canGrantAccess: true }); - completeMock.mockRejectedValue(new Error("Tools changed. Request access again.")); - renderBody(interaction); - await waitForAssertion(() => expect(button("Grant access")?.disabled).toBe(false)); - await act(() => button("Grant access")?.click()); - await waitForAssertion(() => expect(document.body.querySelector('[role="alert"]')?.textContent).toContain("Tools changed")); - await act(() => button("Not now")?.click()); - await waitForAssertion(() => expect(declineMock).toHaveBeenCalledWith(interaction.id)); - }); - - it("shows resolved access and does not expose controls to other users", () => { - renderBody({ ...interaction, status: "accepted", result: { version: 1, outcome: "connected", connectionId: accessRequest.connectionId } }); - expect(document.body.textContent).toContain("Composio access granted"); - expect(button("Grant access")).toBeUndefined(); - }); -}); diff --git a/ui/src/features/connections/GoogleWorkspaceServices.test.tsx b/ui/src/features/connections/GoogleWorkspaceServices.test.tsx deleted file mode 100644 index 3ff82f854ae..00000000000 --- a/ui/src/features/connections/GoogleWorkspaceServices.test.tsx +++ /dev/null @@ -1,245 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { googleWorkspaceSelectedScopes, type ToolConnection } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { GoogleWorkspaceServicesDialog } from "./GoogleWorkspaceServices"; -import { GOOGLE_WORKSPACE_PRIVACY_POLICY_URL, googleWorkspaceDataUseDisclosure } from "./googleWorkspaceDisclosure"; - -const listGrants = vi.hoisted(() => vi.fn()); -vi.mock("@/api/tools", () => ({ toolsApi: { listConnectionGrants: listGrants } })); -vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null })); - -describe("Workspace service consent", () => { - let root: Root; - let container: HTMLDivElement; - let client: QueryClient; - const onContinue = vi.fn(); - const onCancel = vi.fn(); - const existing = { id: "workspace-account", status: "active", credentialPolicy: "per_user", config: {} } as ToolConnection; - const flush = async () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); }; - const click = async (name: string) => { - const button = [...document.querySelectorAll("button")].find(item => item.textContent === name)!; - await act(async () => { button.click(); }); - await flush(); - }; - async function render(connection?: ToolConnection) { - await act(async () => { root.render( - - ); }); - await flush(); - await flush(); - } - beforeEach(() => { - vi.clearAllMocks(); - listGrants.mockResolvedValue({ currentUserId: "me", grants: [] }); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - }); - afterEach(async () => { - await act(async () => { root.unmount(); }); - client.clear(); - container.remove(); - }); - - it("defaults all three groups to write and submits only their selections", async () => { - await render(); - expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["true", "true", "true"]); - expect([...document.querySelectorAll("select")].map(item => item.value)).toEqual(["write", "write", "write"]); - expect(listGrants).not.toHaveBeenCalled(); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith({ gmail: "write", drive: "write", calendar: "write" }); - }); - - it("restores the current user's saved request, not an organization or another user's broader grant", async () => { - listGrants.mockResolvedValue({ currentUserId: "me", grants: [ - { kind: "organization", providerTenant: { oauth: { requestedScopes: ["https://www.googleapis.com/auth/documents"] } } }, - { kind: "user", subjectUserId: "other", providerTenant: { oauth: { requestedScopes: ["https://www.googleapis.com/auth/calendar.events"] } } }, - { kind: "user", subjectUserId: "me", providerTenant: { oauth: { - requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], - scopes: ["https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/documents"], - } } }, - ] }); - await render(existing); - expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["true", "false", "false"]); - expect(document.querySelector("select")?.value).toBe("read"); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); - }); - - it("restores a cold draft's selected services after declined OAuth", async () => { - await render({ ...existing, companyId: "company-1", status: "draft", config: { - workspaceSetup: { - version: 1, companyId: "company-1", connectionId: existing.id, - actorType: "user", actorId: "me", grantKind: "user", subjectId: "me", - requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], - }, - oauth: { scopes: ["https://www.googleapis.com/auth/documents"] }, - } }); - expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["true", "false", "false"]); - expect(document.querySelector("select")?.value).toBe("read"); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); - }); - - it.each([undefined, "another-user"])("requires a deliberate choice for an unbound draft (%s)", async (actorId) => { - await render({ ...existing, companyId: "company-1", status: "draft", config: { - ...(actorId ? { workspaceSetup: { - version: 1, companyId: "company-1", connectionId: existing.id, - actorType: "user", actorId, grantKind: "user", subjectId: "me", - requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], - } } : {}), - oauth: { scopes: ["https://www.googleapis.com/auth/documents"] }, - } }); - expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["false", "false", "false"]); - const proceed = [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!; - expect(proceed.disabled).toBe(true); - expect(onContinue).not.toHaveBeenCalled(); - }); - - it("blocks on grant-load failure and retries without broadening the saved request", async () => { - listGrants.mockRejectedValueOnce(new Error("unavailable")); - await render(existing); - expect(document.body.textContent).toContain("Could not load your saved service access"); - expect(document.querySelector('[role="switch"]')).toBeNull(); - expect(onContinue).not.toHaveBeenCalled(); - listGrants.mockResolvedValue({ currentUserId: "me", grants: [] }); - await click("Try again"); - await flush(); - const continueButton = [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!; - expect(continueButton.disabled).toBe(true); - await click("Cancel"); - expect(onCancel).toHaveBeenCalledWith({}); - expect(onContinue).not.toHaveBeenCalled(); - }); - - it("restores only the addressed user's pending services on a saved draft", async () => { - listGrants.mockResolvedValue({ currentUserId: "me", grants: [] }); - await render({ ...existing, status: "draft", config: { oauth: { pendingWorkspaceServiceRequests: { - me: { requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], requestedAt: "2026-10-26T10:00:00Z" }, - other: { requestedScopes: ["https://www.googleapis.com/auth/documents"], requestedAt: "2026-10-26T10:00:00Z" }, - } } } }); - await click("Continue"); - expect(listGrants).toHaveBeenCalledWith(existing.id); - expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); - }); - - it.each([true, false])("uses pending consent only when newer than the saved grant (newer: %s)", async newer => { - listGrants.mockResolvedValue({ currentUserId: "me", grants: [{ - kind: "user", subjectUserId: "me", updatedAt: "2026-10-26T10:00:00Z", - providerTenant: { oauth: { requestedScopes: googleWorkspaceSelectedScopes({ drive: "write" }), consentedAt: "2026-10-26T10:00:00Z" } }, - }] }); - await render({ ...existing, config: { oauth: { pendingWorkspaceServiceRequests: { - me: { requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], requestedAt: newer ? "2026-10-26T11:00:00Z" : "2026-10-26T09:00:00Z" }, - } } } }); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith(newer ? { gmail: "read" } : { drive: "write" }); - }); - it.each([false, true])("preserves pending service choices through token refresh (legacy grant: %s)", async legacy => { - listGrants.mockResolvedValue({ currentUserId: "me", grants: [{ - kind: "user", subjectUserId: "me", createdAt: "2026-10-26T10:00:00Z", updatedAt: "2026-10-26T12:00:00Z", - providerTenant: { oauth: { requestedScopes: googleWorkspaceSelectedScopes({ drive: "write" }), - ...(legacy ? {} : { consentedAt: "2026-10-26T10:00:00Z" }), refreshedAt: "2026-10-26T12:00:00Z" } }, - }] }); - await render({ ...existing, config: { oauth: { pendingWorkspaceServiceRequests: { - me: { requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], requestedAt: "2026-10-26T11:00:00Z" }, - } } } }); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); - }); - -}); - -const GMAIL_SEND_NOTE = "Google's permission screen also mentions sending email; Paperclip does not send email."; - -describe("Google Workspace data-use disclosure", () => { - const use = [ - "Agents read this content only to do the tasks you give them.", - "To do that, the content is sent to the AI model provider configured for your workspace.", - "It is not used to train general AI models.", - "Results are saved in the task and its run history. They stay there until you delete them, even after you disconnect.", - ]; - - it.each([ - [{ gmail: "read" }, ["Gmail: agents can read and search your email."]], - [{ gmail: "write" }, ["Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email."]], - [{ drive: "read" }, ["Drive: agents can read and search your files, Docs, Sheets and Slides."]], - [{ drive: "write" }, ["Drive: agents can read and search your files, Docs, Sheets and Slides. They can also create files and edit Docs, Sheets and Slides."]], - [{ calendar: "read" }, ["Calendar: agents can see your calendars, events and free/busy times."]], - [{ calendar: "write" }, ["Calendar: agents can see your calendars, events and free/busy times. They can also create, change and delete events, and respond to invitations."]], - ] as const)("describes only the selected service (%o)", (selection, access) => { - expect(googleWorkspaceDataUseDisclosure(selection)).toEqual({ access, use }); - }); - - it("lists every selected service in picker order and always explains sharing", () => { - const disclosure = googleWorkspaceDataUseDisclosure({ calendar: "read", gmail: "write", drive: "read" }); - expect(disclosure.access.map(line => line.split(":")[0])).toEqual(["Gmail", "Drive", "Calendar"]); - expect(disclosure.use).toContain("To do that, the content is sent to the AI model provider configured for your workspace."); - }); - - it("never claims Gmail can send: read only never mentions sending, read & write only says Paperclip does not send", () => { - const text = (gmail: "read" | "write") => { - const { access, use } = googleWorkspaceDataUseDisclosure({ gmail }); - return [...access, ...use].join(" "); - }; - expect(text("read")).not.toMatch(/send/i); - expect(text("write")).toContain("Paperclip does not send email."); - expect(text("write").replace(GMAIL_SEND_NOTE, "")).not.toMatch(/send/i); - }); - - it("says nothing with no services selected", () => { - expect(googleWorkspaceDataUseDisclosure({})).toEqual({ access: [], use: [] }); - }); -}); - -describe("Workspace picker disclosure", () => { - let root: Root; - let container: HTMLDivElement; - const flush = async () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); }; - beforeEach(() => { - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - }); - afterEach(async () => { - await act(async () => { root.unmount(); }); - container.remove(); - }); - async function render(initial?: Record) { - await act(async () => { root.render( - - ); }); - await flush(); - } - const disclosure = () => document.querySelector('[aria-label="How Paperclip uses your Google data"]'); - - it("shows the selected services, sharing and privacy policy before Continue", async () => { - await render({ gmail: "write", calendar: "read" }); - const block = disclosure()!; - expect(block.textContent).toContain("Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email."); - expect(block.textContent).toContain("Calendar: agents can see your calendars, events and free/busy times."); - expect(block.textContent).not.toContain("Drive"); - expect(block.textContent!.replace(GMAIL_SEND_NOTE, "")).not.toMatch(/\bsend/i); - expect(block.textContent).toContain("the content is sent to the AI model provider configured for your workspace"); - const link = block.querySelector("a")!; - expect(link.getAttribute("href")).toBe(GOOGLE_WORKSPACE_PRIVACY_POLICY_URL); - expect(GOOGLE_WORKSPACE_PRIVACY_POLICY_URL).toBe("https://paperclip.ing/privacy"); - expect(link.getAttribute("target")).toBe("_blank"); - expect(link.getAttribute("rel")).toContain("noopener"); - expect(link.textContent).toContain("Limited Use"); - const footer = document.querySelector("footer")!; - expect(block.compareDocumentPosition(footer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - }); - - it("follows the selection as services are turned off", async () => { - await render({ drive: "read" }); - expect(disclosure()!.textContent).toContain("Drive: agents can read and search your files"); - const toggle = document.querySelector("#workspace-service-drive")!; - await act(async () => { toggle.click(); }); - expect(disclosure()).toBeNull(); - expect(document.body.textContent).toContain("Select at least one service to continue."); - }); -}); diff --git a/ui/src/features/connections/MachineSignInSetup.test.tsx b/ui/src/features/connections/MachineSignInSetup.test.tsx deleted file mode 100644 index 6dcb9b52ebb..00000000000 --- a/ui/src/features/connections/MachineSignInSetup.test.tsx +++ /dev/null @@ -1,161 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import type { ConnectToolAppResult, MachineSignInSetupResult } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { MachineSignInSetup, type MachineSignInClient } from "./MachineSignInSetup"; - -vi.mock("@/api/tools", () => ({ toolsApi: {} })); - -const draft = { - connectionId: "connection-1", - connection: {}, - machineSignIn: { - connectionId: "connection-1", method: "paperclip_key", clientId: null, issuer: "https://auth.example", tokenUrl: "https://auth.example/token", - scopes: [], hasClientSecret: false, lastTokenAt: null, pendingPublicKey: null, - publicKey: { keyId: "kid-1", algorithm: "RS256", pem: "-----BEGIN PUBLIC KEY-----\nabc\n-----END PUBLIC KEY-----\n", jwk: { kty: "RSA", kid: "kid-1" }, createdAt: "2026-11-13T00:00:00Z" }, - }, -} as unknown as MachineSignInSetupResult; - -describe("Machine sign-in setup", () => { - let root: Root; - let container: HTMLDivElement; - const flush = async () => { await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); }; - const button = (name: string) => [...container.querySelectorAll("button")].find((item) => item.textContent === name); - const click = async (name: string) => { await act(async () => { button(name)!.click(); }); await flush(); }; - const type = async (id: string, value: string) => { - const input = container.querySelector(`#${id}`)!; - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); - }; - - beforeEach(() => { - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - }); - afterEach(() => { - act(() => root.unmount()); - container.remove(); - }); - - it("creates a key, shows the public key to register, then tests with the client ID", async () => { - const client: MachineSignInClient = { - create: vi.fn(async () => draft), - test: vi.fn(async () => ({ connectionId: "connection-1" }) as ConnectToolAppResult), - status: vi.fn(), - }; - const onConnected = vi.fn(); - await act(async () => { - root.render( undefined} onConnected={onConnected} />); - }); - expect(container.textContent).toContain("Paperclip key (recommended)"); - await click("Create key"); - expect(client.create).toHaveBeenCalledWith("company-1", { link: "https://mcp.example/mcp", method: "paperclip_key" }); - expect(container.textContent).toContain("Register this public key"); - expect(container.querySelector("textarea")?.value).toContain("BEGIN PUBLIC KEY"); - expect(button("Test connection")?.disabled).toBe(true); - await type("machine-sign-in-client-id-confirm", "paperclip-automation"); - await click("Test connection"); - expect(client.test).toHaveBeenCalledWith("connection-1", { clientId: "paperclip-automation", scopes: "" }); - expect(onConnected).toHaveBeenCalled(); - }); - - it("keeps the draft and shows the provider's answer when the test fails", async () => { - const client: MachineSignInClient = { - create: vi.fn(async () => draft), - test: vi.fn(async () => { throw new Error("The provider didn't accept Paperclip's key."); }), - status: vi.fn(), - }; - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - await type("machine-sign-in-client-id-confirm", "wrong"); - await click("Test connection"); - expect(container.textContent).toContain("Machine sign-in didn’t work"); - expect(container.textContent).toContain("The provider didn't accept Paperclip's key."); - expect(container.textContent).toContain("Register this public key"); - }); - - it("asks for the client ID and secret together for a client secret", async () => { - const client: MachineSignInClient = { - create: vi.fn(async () => ({ ...draft, machineSignIn: { ...draft.machineSignIn, method: "client_secret" as const, publicKey: null } })), - test: vi.fn(async () => ({}) as ConnectToolAppResult), - status: vi.fn(), - }; - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - expect(button("Test connection")?.disabled).toBe(true); - await type("machine-sign-in-client-id", "id-1"); - await type("machine-sign-in-client-secret", "secret-1"); - await click("Test connection"); - expect(client.create).toHaveBeenCalledWith("company-1", expect.objectContaining({ method: "client_secret", clientId: "id-1", clientSecret: "secret-1", applicationId: "app-1" })); - expect(client.test).toHaveBeenCalledWith("connection-1", { clientId: "id-1", scopes: "" }); - }); - - it("lets a wrong secret be replaced after a failed test", async () => { - const secretDraft = { ...draft, machineSignIn: { ...draft.machineSignIn, method: "client_secret" as const, publicKey: null, clientId: "id-1", hasClientSecret: true, scopes: ["a.read"] } }; - const client: MachineSignInClient = { - create: vi.fn(), - test: vi.fn(async () => { throw new Error("The provider didn't accept the client ID and secret."); }), - status: vi.fn(), - }; - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - await click("Test connection"); - expect(container.querySelector("#machine-sign-in-client-secret-replace")).not.toBeNull(); - await type("machine-sign-in-client-secret-replace", "fixed-secret"); - await type("machine-sign-in-scopes-confirm", ""); - await click("Test connection"); - expect(client.test).toHaveBeenLastCalledWith("connection-1", { clientId: "id-1", scopes: "", clientSecret: "fixed-secret" }); - }); - - it("resumes the key draft this tab started instead of creating another", async () => { - sessionStorage.setItem("paperclip.machine-sign-in-draft.v2:company-1:new:https://mcp.example/mcp", "connection-1"); - let finish!: (value: typeof draft.machineSignIn) => void; - const client: MachineSignInClient = { - create: vi.fn(), - test: vi.fn(), - status: vi.fn(() => new Promise((resolve) => { finish = resolve; })), - }; - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - // No second draft can be started while the saved one loads. - expect(button("Create key")?.disabled).toBe(true); - await act(async () => { finish(draft.machineSignIn); }); - await flush(); - expect(client.status).toHaveBeenCalledWith("connection-1"); - expect(container.textContent).toContain("Register this public key"); - expect(client.create).not.toHaveBeenCalled(); - sessionStorage.clear(); - }); - - it("never resumes a draft started for a different app", async () => { - const client: MachineSignInClient = { - create: vi.fn(async () => draft), - test: vi.fn(), - status: vi.fn(async () => draft.machineSignIn), - }; - // App A's setup creates a key draft in this tab, then the admin leaves it. - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - await click("Create key"); - await act(async () => root.unmount()); - root = createRoot(container); - // Setup for app B at the same address starts fresh instead of adopting A's draft. - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - await flush(); - expect(client.status).not.toHaveBeenCalled(); - await click("Create key"); - expect(client.create).toHaveBeenLastCalledWith("company-1", expect.objectContaining({ applicationId: "app-b" })); - sessionStorage.clear(); - }); -}); diff --git a/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.test.tsx b/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.test.tsx deleted file mode 100644 index 24e053f8fb5..00000000000 --- a/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.test.tsx +++ /dev/null @@ -1,100 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import type { ToolConnection } from "@paperclipai/shared"; -import type { ConnectionSetupFlowProps } from "../ConnectionSetupFlow"; -import { ApiError } from "@/api/client"; -import { toolsApi } from "@/api/tools"; -import { RemoteMcpProductionSetup } from "./RemoteMcpProductionSetup"; -import type { RemoteMcpSetupState } from "./types"; - -vi.mock("@/api/tools", () => ({ toolsApi: { getConnectionInstalls: vi.fn() } })); -vi.mock("@/api/agents", () => ({ agentsApi: { list: vi.fn(async () => []) } })); -vi.mock("@/api/companies-query", () => ({ resolveAccountUserId: async () => null })); -vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company" }) })); -vi.mock("@/lib/router", () => ({ useNavigate: () => vi.fn(), useSearchParams: () => [new URLSearchParams(), vi.fn()] })); -vi.mock("../ConnectionSetupFlow", () => ({ readConnectionIntentOAuthOutcome: () => null })); -vi.mock("../ConnectionInstructions", () => ({ ConnectionInstructionsEditor: () => null })); -vi.mock("./RemoteMcpConnectionSetup", () => ({ - RemoteMcpConnectionSetup: ({ state }: { state: RemoteMcpSetupState }) => ( -
{state.allAgents ? "all agents" : state.agentIds.join(",")}
- ), -})); - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -const connection = { - id: "connection-1", companyId: "company", name: "Composio", status: "active", - credentialPolicy: "organization", authKind: "oauth", config: { url: "https://connect.composio.dev/mcp" }, -} as unknown as ToolConnection; -let root: Root; -let container: HTMLDivElement; -let client: QueryClient; - -function render(props: Partial & { connection?: ToolConnection } = {}) { - act(() => root.render( - - - , - )); -} - -beforeEach(() => { - vi.mocked(toolsApi.getConnectionInstalls).mockReset(); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); -}); - -it("restores a task's saved draft audience before installations exist", async () => { - vi.mocked(toolsApi.getConnectionInstalls).mockResolvedValue({ installs: [] } as never); - render({ connection: { ...connection, status: "draft" }, interactionId: "intent", requiredAgentId: "agent-1", - setupAccess: { connectionId: connection.id, access: { agentIds: ["agent-1"] } } }); - await vi.waitFor(() => expect(container.querySelector('[data-testid="remote-mcp-setup"]')?.textContent).toBe("agent-1")); - await act(async () => { await client.invalidateQueries(); }); - expect(container.querySelector('[data-testid="remote-mcp-setup"]')?.textContent).toBe("agent-1"); -}); -afterEach(() => { - act(() => root.unmount()); - client.clear(); - container.remove(); -}); - -it("keeps saved access on screen when a refetch fails during an outage", async () => { - vi.mocked(toolsApi.getConnectionInstalls).mockResolvedValue({ installs: [{ targetType: "agent", targetId: "agent-1" }] } as never); - render(); - await vi.waitFor(() => expect(container.querySelector('[data-testid="remote-mcp-setup"]')?.textContent).toBe("agent-1")); - - vi.mocked(toolsApi.getConnectionInstalls).mockRejectedValue( - new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }), - ); - await act(async () => { - await client.invalidateQueries(); - }); - - expect(container.querySelector('[data-testid="remote-mcp-setup"]')?.textContent).toBe("agent-1"); - expect(container.querySelector('[data-query-view="error"]')).toBeNull(); - expect(container.textContent).not.toContain("Paperclip is restarting."); - expect(container.textContent).not.toContain("Loading saved access"); -}); - -it("shows readable copy with a retry when saved access cannot be loaded", async () => { - vi.mocked(toolsApi.getConnectionInstalls) - .mockRejectedValueOnce(new ApiError("Request failed: 500", 500, { error: "internal_error" })) - .mockResolvedValue({ installs: [] } as never); - render(); - await vi.waitFor(() => expect(container.querySelector('[data-query-view="error"]')).not.toBeNull()); - expect(container.textContent).toContain("Couldn't load saved access"); - expect(container.textContent).not.toContain("internal_error"); - expect(container.textContent).not.toContain("Request failed: 500"); - expect(container.querySelector('[data-testid="remote-mcp-setup"]')).toBeNull(); - - act(() => (container.querySelector('[data-query-view="error"] button') as HTMLButtonElement).click()); - await vi.waitFor(() => expect(container.querySelector('[data-testid="remote-mcp-setup"]')).not.toBeNull()); - expect(toolsApi.getConnectionInstalls).toHaveBeenCalledTimes(2); - expect(container.querySelector('[data-query-view="error"]')).toBeNull(); -}); diff --git a/ui/src/hooks/useRecentTaskOpenWarmup.test.tsx b/ui/src/hooks/useRecentTaskOpenWarmup.test.tsx index 7a95e90ff96..411f8771220 100644 --- a/ui/src/hooks/useRecentTaskOpenWarmup.test.tsx +++ b/ui/src/hooks/useRecentTaskOpenWarmup.test.tsx @@ -34,7 +34,7 @@ function bootstrapItem(index: number, companyId = "company-1"): IssueChatBootstr } /** Long enough for two frames and the idle fallback timer. */ -const settle = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 400)); }); +const settle = () => act(async () => { await vi.advanceTimersByTimeAsync(400); }); let container: HTMLDivElement; let root: Root; @@ -57,6 +57,7 @@ function render(props: { companyId?: string | null; userId?: string | null; task } beforeEach(() => { + vi.useFakeTimers(); resetIssueChatBootstrapsForTest(); chatBootstrap.mockReset(); chatBootstrap.mockImplementation(async (_companyId: string, ids: string[]) => ({ @@ -208,7 +209,6 @@ describe("useRecentTaskOpenWarmup", () => { it("warms Recents again on a navigation once the earlier warm may have been dropped", async () => { // The sidebar stays mounted for hours; unread cache entries are dropped after five minutes. - vi.useFakeTimers({ toFake: ["Date"] }); render({ tasks: tasks(2), navigationKey: "/PAP/inbox" }); await settle(); expect(chatBootstrap).toHaveBeenCalledTimes(1); diff --git a/ui/src/lib/recent-selections.test.ts b/ui/src/lib/recent-selections.test.ts index 197698cbc41..5e9ddd6c4fa 100644 --- a/ui/src/lib/recent-selections.test.ts +++ b/ui/src/lib/recent-selections.test.ts @@ -1,5 +1,3 @@ -// @vitest-environment jsdom - import { beforeEach, describe, expect, it } from "vitest"; import { getRecentAssigneeIds, diff --git a/ui/src/lib/responsibility-outline-v2.test.ts b/ui/src/lib/responsibility-outline-v2.test.ts index 121347ff608..fd89b83699d 100644 --- a/ui/src/lib/responsibility-outline-v2.test.ts +++ b/ui/src/lib/responsibility-outline-v2.test.ts @@ -1,4 +1,3 @@ -// @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from "vitest"; import { areaDealFlow, @@ -135,10 +134,10 @@ describe("collapsed areas in storage", () => { }); it("never throws when storage is blocked", () => { - vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { + vi.spyOn(localStorage, "getItem").mockImplementation(() => { throw new Error("blocked"); }); - vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + vi.spyOn(localStorage, "setItem").mockImplementation(() => { throw new Error("blocked"); }); expect(readCollapsedAreas("owner").size).toBe(0); diff --git a/ui/src/lib/task-browsers-refresh.test.ts b/ui/src/lib/task-browsers-refresh.test.ts index ae5c931cc40..bfc9b979388 100644 --- a/ui/src/lib/task-browsers-refresh.test.ts +++ b/ui/src/lib/task-browsers-refresh.test.ts @@ -1,4 +1,3 @@ -// @vitest-environment jsdom import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { QueryClient, QueryObserver } from "@tanstack/react-query"; import type { TaskBrowser } from "@paperclipai/shared"; diff --git a/ui/src/pages/apps/TailscaleConnector.test.tsx b/ui/src/pages/apps/TailscaleConnector.test.tsx index 4350429d9c5..8fa3a028d77 100644 --- a/ui/src/pages/apps/TailscaleConnector.test.tsx +++ b/ui/src/pages/apps/TailscaleConnector.test.tsx @@ -165,12 +165,21 @@ describe("Tailscale network connector", () => { it("stops polling and gives a recovery action when the sign-in deadline passes", async () => { fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]); fixture.deviceLogin.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() - 1).toISOString() }); - render();await settle(); - expect(container.textContent).toContain("Sign-in expired"); - expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')).toBeNull(); - await new Promise(resolve => setTimeout(resolve, 2100)); - expect(fixture.deviceLogin).toHaveBeenCalledOnce(); - expect(button("Cancel sign-in")).toBeDefined(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval"] }); + try { + render(); + for (let i = 0; i < 6; i++) { + await Promise.resolve(); + await vi.advanceTimersByTimeAsync(1); + } + expect(container.textContent).toContain("Sign-in expired"); + expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')).toBeNull(); + await vi.advanceTimersByTimeAsync(2100); + expect(fixture.deviceLogin).toHaveBeenCalledOnce(); + expect(button("Cancel sign-in")).toBeDefined(); + } finally { + vi.useRealTimers(); + } }); it.each(["cancelled", "failed"])("explains %s consent and retries the same saved connection", async outcome => { diff --git a/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx b/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx index 63f270db535..658cdd215b8 100644 --- a/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx +++ b/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx @@ -105,8 +105,13 @@ async function openAndRun(testEntry = entry) { await renderDialog(testEntry); const button = [...document.body.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === "Run"); expect(button).toBeTruthy(); - await act(() => button!.click()); - await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 260)); }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + try { + await act(() => button!.click()); + await act(async () => { await vi.advanceTimersByTimeAsync(260); }); + } finally { + vi.useRealTimers(); + } await flushReact(); } From 11cfe0910da6e5c5ec188aba4355f390cc1165b1 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:17:27 -0600 Subject: [PATCH 3/9] fix(connections): keep a finished setup checklist on screen when the app refreshes queries (#22715) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - "Set it up with your agent" screens give the person's own agent a setup checklist to fill in, shown live on the page (#22626, AWS role setup first) > - Testing it end to end on staging, the agent's updates appeared within 0.3–0.6 seconds and the page showed "Your agent set up AWS" with the role ARN, then a few seconds later replaced it with a blank new checklist > - When the live connection reconnects or the tab becomes visible again, the app refreshes every query on screen. The checklist's handoff query refetched, found no checklist in storage (a finished one is removed so it is never reused), and created a new one > - This pull request makes a refetch keep the checklist the page already has; only Start again, or a finished checklist from an earlier visit, makes a new one > - The benefit is that a finished setup stays on screen with its summary until the person moves on ## Linked Issues or Issue Description Refs #22626 (the setup checklist this fixes). **Subsystem affected** Connections (agent-guided setup), UI. **Problem or motivation** On paperclip.staging, after the agent finished, the AWS setup step showed "Your agent set up AWS" and the role ARN to paste, then about 7 seconds later went back to "Paste the prompt into your agent" with a new, empty checklist. The page's network log showed a second `POST /api/companies/{companyId}/agent-setup-progress`. The person loses the role ARN they were about to copy. **Proposed solution** The handoff query's fetch returns the handoff already in the cache unless the page asked to replace it (`renew`). Creating a checklist stays a deliberate action. **Alternatives considered** - Excluding the handoff key from the live reconcile (`LIVE_EVENT_FREE_QUERY_KEYS`): covers that one caller but not any other broad invalidation. Guarding the fetch covers them all. - Keeping a finished checklist in storage: it would then be reused by a later visit, which #22626 deliberately avoids (a finished checklist takes no more updates). ## What Changed - `ui/src/components/AgentSetupProgress.tsx`: the handoff query's `queryFn` returns the cached handoff unless `renew` set a one-shot `replacing` flag. - `ui/src/components/AgentSetupProgress.test.tsx`: regression test. A checklist finishes, then every active query is invalidated (as the live reconcile does); the checklist is created once and "Your agent set up AWS" with the role ARN stays. ## Verification - New test fails on master (`create` called twice) and passes with the fix (red/green). - `AgentSetupProgress.test.tsx` and `AwsRoleSetup.test.tsx`: 26 passed. UI typecheck clean. - Staging reproduction (before this fix), paperclip.staging on 980caf1: the agent's requests with only the prompt's token (no Paperclip sign-in) were accepted through the Cloud front door: 401 without the token, 200 for set/update/finish, 409 for an update after finishing. The page showed each update 603 ms, 567 ms and 326 ms after the request, then replaced the finished checklist about 7.5 s later. To re-run on staging after deploy. ## Risks - Low. One query's fetch function; creation paths (first open, Start again, earlier-visit renewal, another account) keep their tests. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, Claude in Chrome against paperclip.staging). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- ui/src/components/AgentSetupProgress.test.tsx | 38 +++++++++++++++++++ ui/src/components/AgentSetupProgress.tsx | 10 +++++ ui/src/lib/live-reconcile.test.ts | 3 ++ ui/src/lib/live-reconcile.ts | 3 ++ 4 files changed, 54 insertions(+) diff --git a/ui/src/components/AgentSetupProgress.test.tsx b/ui/src/components/AgentSetupProgress.test.tsx index 02ca7e10ab5..44e1ad8c925 100644 --- a/ui/src/components/AgentSetupProgress.test.tsx +++ b/ui/src/components/AgentSetupProgress.test.tsx @@ -169,6 +169,44 @@ describe("agent setup progress", () => { const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); const token = () => container.querySelector('[data-testid="token"]')?.textContent; + it("keeps a finished checklist on screen when the app refreshes every query", async () => { + const done: AgentSetupProgress = { ...WAITING, status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1", + items: [{ key: "create-role", title: "Create the role", status: "done", detail: null }] }; + const create = vi.fn().mockResolvedValue(HANDOFF); + let status: "waiting" | "done" = "waiting"; + const client: AgentSetupProgressClient = { create, get: vi.fn(async () => status === "done" ? done : WAITING) }; + await act(async () => { root.render(); }); + await flush(); + status = "done"; + await act(async () => { await queryClient.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); }); + await vi.waitFor(() => expect(container.textContent).toContain("Your agent set up AWS")); + // The live connection reconnects or the tab returns: the app refreshes every query on screen. + await act(async () => { await queryClient.invalidateQueries({ type: "active" }); }); + await flush(); + expect(create).toHaveBeenCalledOnce(); + expect(token()).toBe("pcsp_token"); + expect(container.textContent).toContain("Your agent set up AWS"); + expect(container.textContent).toContain("Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1"); + }); + + it("still creates a fresh checklist when Start again's first create fails and its retry succeeds", async () => { + const failedAttempt: AgentSetupProgress = { ...WAITING, status: "failed", summary: "Stopped: no permission", + items: [{ key: "deploy", title: "Create the role", status: "failed", detail: "iam:CreateRole denied" }] }; + const second: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_after_retry", progress: { ...WAITING, id: "88888888-8888-4888-8888-888888888888" } }; + const create = vi.fn().mockResolvedValueOnce(HANDOFF).mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(second); + const client: AgentSetupProgressClient = { create, get: vi.fn(async (id: string) => id === ID ? failedAttempt : second.progress) }; + // The app's queries retry a failed request; this one retries once, at once. + const retrying = new QueryClient({ defaultOptions: { queries: { retry: 1, retryDelay: 0 } } }); + await act(async () => { root.render(); }); + await flush(); + await act(async () => { await retrying.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); }); + await vi.waitFor(() => expect(container.textContent).toContain("Your agent couldn’t finish setting up AWS")); + const startAgain = [...container.querySelectorAll("button")].find((b) => b.textContent === "Start again")!; + await act(async () => { startAgain.click(); }); + await vi.waitFor(() => expect(token()).toBe("pcsp_after_retry")); + expect(create).toHaveBeenCalledTimes(3); + }); + it("offers a fresh checklist after a failed attempt, and opening the step again later starts fresh", async () => { const failedAttempt: AgentSetupProgress = { ...WAITING, status: "failed", summary: "Stopped: no permission", items: [{ key: "deploy", title: "Create the role", status: "failed", detail: "iam:CreateRole denied" }] }; diff --git a/ui/src/components/AgentSetupProgress.tsx b/ui/src/components/AgentSetupProgress.tsx index d077052552d..00dda6d30d9 100644 --- a/ui/src/components/AgentSetupProgress.tsx +++ b/ui/src/components/AgentSetupProgress.tsx @@ -73,12 +73,21 @@ export function useAgentSetupProgress({ const accountFailed = !accountOverride && account.failed; const handoffKey = ["agent-setup-progress-handoff", accountId, companyId ?? null, purpose, subjectId ?? null] as const; const storageKey = agentSetupHandoffStorageKey(accountId, companyId, purpose, subjectId); + // Set by renew and kept until a new checklist is created, so a retry of a failed create still + // creates rather than returning the checklist being replaced. + const replacing = useRef(false); const handoffQuery = useQuery({ queryKey: handoffKey, queryFn: async () => { + // Any other refetch (the app refreshes every query on screen when its live connection + // reconnects or the tab returns) keeps the checklist on screen. A finished one is no longer + // in storage, so falling through here would replace it with a blank checklist. + const current = queryClient.getQueryData<{ handoff: AgentSetupProgressHandoff; fromEarlierVisit: boolean }>(handoffKey); + if (current && !replacing.current) return current; // A handoff found in this tab's storage came from an earlier visit; a created one is new. const stored = storedAgentSetupHandoff(storageKey); const handoff = stored ?? await client.create(companyId!, { purpose, ...(subjectId ? { subjectId } : {}) }); + replacing.current = false; storeAgentSetupHandoff(storageKey, handoff); return { handoff, fromEarlierVisit: Boolean(stored) }; }, @@ -115,6 +124,7 @@ export function useAgentSetupProgress({ return; } storeAgentSetupHandoff(storageKey, null); + replacing.current = true; void handoffQuery.refetch(); }; diff --git a/ui/src/lib/live-reconcile.test.ts b/ui/src/lib/live-reconcile.test.ts index 03ad50a9916..a2b7743f6f2 100644 --- a/ui/src/lib/live-reconcile.test.ts +++ b/ui/src/lib/live-reconcile.test.ts @@ -17,6 +17,7 @@ describe("live reconcile scope", () => { queryKeys.workspacePreferences.mine("user-1"), queryKeys.sidebarPreferences.companyOrder("user-1"), queryKeys.sidebarPreferences.projectOrder("company-1", "user-1"), + ["agent-setup-progress-handoff", "user-1", "company-1", "aws_connection", "conn-1"], ]) { expect(isLiveReconciledQuery({ queryKey }), JSON.stringify(queryKey)).toBe(false); } @@ -31,6 +32,8 @@ describe("live reconcile scope", () => { queryKeys.projects.all("company-1"), ["plugins", "company-1"], ["instance-admin"], + // The checklist's progress still reconciles; only its prompt token and URLs do not. + queryKeys.agentSetupProgress("progress-1"), ]) { expect(isLiveReconciledQuery({ queryKey }), JSON.stringify(queryKey)).toBe(true); } diff --git a/ui/src/lib/live-reconcile.ts b/ui/src/lib/live-reconcile.ts index c00da7bba36..14302cc480f 100644 --- a/ui/src/lib/live-reconcile.ts +++ b/ui/src/lib/live-reconcile.ts @@ -21,6 +21,9 @@ export const LIVE_EVENT_FREE_QUERY_KEYS: readonly QueryKey[] = [ queryKeys.plugins.uiContributions, ["workspace-preferences"], ["sidebar-preferences"], + // A setup checklist's prompt token and URLs: created once per setup, never changed by an event + // (the checklist's progress has its own key and does reconcile). + ["agent-setup-progress-handoff"], ]; /** How long the reads above stay fresh. A window-focus refetch runs at most this often. */ From 4daeab5c764d2154de2bbaef9c40a0a710415fbf Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:41:16 -0600 Subject: [PATCH 4/9] Add count, newest-first and lean run reads to customer-success inspection (#22781) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud can inspect a tenant stack read-only through the customer-success inspection API > - That API can only list rows in id order. It has no totals, and each run row holds large JSON columns > - A customer-success agent must page every run of a stack to find the latest run or the failed-run total > - That is too slow and too large for a refresh across many stacks > - This pull request adds a `count` operation, a creation-time `order` for lists, and a lean `summary` view for runs > - The benefit is one small read per metric, with the same read-only, company-scoped rules ## Linked Issues or Issue Description **Subsystem affected** Server: the customer-success inspection API (`/api/customer-success/v1`) and its shared query contract. **Problem or motivation** Customer-success inspection reads cannot answer summary questions. To get the latest run, the run count or the failed-run count, a reader must page through every run. Each run row can be hundreds of KB, because it holds the result, usage, context snapshot and runner profile. **Proposed solution** Add read-only summary reads to the inspection contract: a `count` that groups by status, a newest-first or oldest-first `order` for `list`, and a `summary` view of runs without the large JSON columns. **Alternatives considered** Paging all runs with a smaller page size. That still reads every large row. A new aggregated endpoint outside the reader catalog. That would skip the existing catalog, permit and transaction rules. ## What Changed - `packages/shared/src/customer-success.ts`: add the `count` operation, `order` (`newest`/`oldest`, `list` only), `view` (`summary`, `runs` list/get only), `InspectionCount`, and `inspectionReadPath()`. The parser rejects these fields where they do not apply. - `server/src/services/customer-success-inspection.ts`: `count` returns `{total, byStatus}` (grouped by the reader's `status` column, or `byStatus: null`). `order` sorts by `createdAt`, then id. `view: "summary"` selects the `RUN_SUMMARY_COLUMNS` allowlist and adds `durationMs`. All reads stay in the same read-only, repeatable-read transaction and keep the existing run redaction. - `server/src/routes/customer-success.ts`: serve the same handler on `/read` and the new `/read-v2`. `/read` refuses queries that use the new features. A tenant without `/read-v2` answers 404, so Cloud fails closed with `tenant_inspection_version_unsupported`. - `server/src/__tests__/customer-success.test.ts`: tests for counts, company scope, newest-first paging, the summary allowlist and duration, parser bounds, and the path split. - `server/src/__tests__/customer-success-cloud.test.ts`: the registry double now has the batch reads (`getStacks`, `getAccounts`) that the current Cloud broker uses. The test also runs a count and a newest-first summary read end to end. - `server/src/__tests__/openapi-routes.test.ts`: list `/read-v2` with the other inspection protocol routes. - `doc/CUSTOMER-SUCCESS-INSPECTION.md`: document the summary reads and the path split. ## Verification - `cd server && pnpm exec vitest run src/__tests__/customer-success.test.ts src/__tests__/openapi-routes.test.ts src/__tests__/customer-success-run-liveness.test.ts`: 78 tests pass. - Red check: the new count/order/summary test fails against the previous service (`Unsupported inspection operation`). - Coordinated qualification with a local build of the Cloud broker branch: `PAPERCLIP_INSPECTION_CLOUD_DIST=… pnpm exec vitest run src/__tests__/customer-success-cloud.test.ts` passes, including the count and newest-first summary reads over `/read-v2`. ## Risks - Low risk. The new features are read-only and use the existing catalog, company boundary, permit check and read-only transaction. - The summary view is an allowlist. A new run column stays out of the summary until someone adds it. - Mixed versions are safe in both orders. An older Cloud never sends the new fields. A newer Cloud sends them only to `/read-v2`, and an older tenant answers 404 there. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits) and extended thinking. ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Paperclip Co-authored-by: Claude Opus 5.5 --- doc/CUSTOMER-SUCCESS-INSPECTION.md | 21 ++- packages/shared/src/customer-success.ts | 44 ++++- .../__tests__/customer-success-cloud.test.ts | 19 +- server/src/__tests__/customer-success.test.ts | 173 ++++++++++++++++++ server/src/__tests__/openapi-routes.test.ts | 1 + server/src/routes/customer-success.ts | 15 +- .../services/customer-success-inspection.ts | 95 +++++++++- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 8 files changed, 355 insertions(+), 15 deletions(-) diff --git a/doc/CUSTOMER-SUCCESS-INSPECTION.md b/doc/CUSTOMER-SUCCESS-INSPECTION.md index bd27a2ad95c..d3fddfca430 100644 --- a/doc/CUSTOMER-SUCCESS-INSPECTION.md +++ b/doc/CUSTOMER-SUCCESS-INSPECTION.md @@ -1,7 +1,7 @@ # Cloud customer-success inspection support -Paperclip exposes `/api/customer-success/v1/run-authority`, `/run-liveness` and -`/read` for the coordinated Cloud inspection broker. This foundation supports one registered +Paperclip exposes `/api/customer-success/v1/run-authority`, `/run-liveness`, +`/read` and `/read-v2` for the coordinated Cloud inspection broker. This foundation supports one registered Paperclip agent; bot creation, scheduling, scoring and reporting are separate. The authority endpoint is disabled unless @@ -67,6 +67,23 @@ pass through Cloud; ranges cap at 1 MiB, JSON at 2 MiB, and lists at 100 rows. Remote or unsnapshotted resources report unavailable; large content requires pagination or download ranges. No storage credentials or bypass URLs are issued. +Summary reads keep a fleet-wide refresh cheap: + +- `count` takes a catalogued `resource`, `companyId` and optional `parentId`, + and returns `{total, byStatus}`: counts grouped by the reader's `status` + column, or `byStatus: null` when it has none. No row content is read out. +- `order` (`list` only) is `newest` or `oldest` by creation time, with the table's + primary key as tie-breaker so offset pages never repeat or skip rows. Without it, lists keep their original id order. +- `view: "summary"` (`list`/`get` on `runs` only) returns an allowlist of ids, + status, error code, retry counters and timestamps plus a computed + `durationMs`, and leaves out the large JSON columns (result, usage, context + snapshot, runner profile). `RUN_SUMMARY_COLUMNS` is the allowlist. + +Queries that use `count`, `order` or `view` are served only on `/read-v2` +(`inspectionReadPath` picks the path); `/read` refuses them. A tenant that +predates them answers 404 on `/read-v2`, so Cloud fails closed with +`tenant_inspection_version_unsupported` instead of misreading the query. + Existing config/event/run redactions and path/symlink/secret-file/size restrictions remain in use. Authentication account/session, secret, private-key/encrypted-key and raw provider-trace tables/readers are excluded. Identity-enabled trace diff --git a/packages/shared/src/customer-success.ts b/packages/shared/src/customer-success.ts index a2d02aaa822..cf22017ffdd 100644 --- a/packages/shared/src/customer-success.ts +++ b/packages/shared/src/customer-success.ts @@ -65,10 +65,28 @@ export const INSPECTION_RESOURCES = [ "threads", ] as const; export type InspectionResource = (typeof INSPECTION_RESOURCES)[number]; +export const INSPECTION_ORDERS = ["newest", "oldest"] as const; +export type InspectionOrder = (typeof INSPECTION_ORDERS)[number]; +export const INSPECTION_VIEWS = ["summary"] as const; +export type InspectionView = (typeof INSPECTION_VIEWS)[number]; +/** The tenant path for queries that use only the original (version 1) features. */ +export const INSPECTION_READ_PATH = "/read"; +/** + * The tenant path for queries that use `count`, `order` or `view`. A tenant + * that predates them answers 404 here, so Cloud fails closed with + * `tenant_inspection_version_unsupported` instead of misreading the query. + */ +export const INSPECTION_EXTENDED_READ_PATH = "/read-v2"; +export interface InspectionCount { + total: number; + /** Counts grouped by the resource's `status` column, or null when it has none. */ + byStatus: Record | null; +} export interface InspectionQuery { operation: | "list" | "get" + | "count" | "instructions.file" | "skills.file" | "runs.log" @@ -85,6 +103,10 @@ export interface InspectionQuery { limit?: number; offset?: number; range?: { start: number; end: number }; + /** `list` only: order by creation time instead of by id. */ + order?: InspectionOrder; + /** `list`/`get` on `runs` only: leave out the large JSON columns. */ + view?: InspectionView; context?: { projectId?: string; workspaceId?: string; @@ -129,6 +151,11 @@ export function canonicalJson(value: unknown): string { } throw new Error("Invalid JSON value"); } +export function inspectionReadPath(query: InspectionQuery): string { + return query.operation === "count" || query.order !== undefined || query.view !== undefined + ? INSPECTION_EXTENDED_READ_PATH + : INSPECTION_READ_PATH; +} export function parseInspectionQuery(value: unknown): InspectionQuery { if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid inspection query"); @@ -144,6 +171,8 @@ export function parseInspectionQuery(value: unknown): InspectionQuery { "limit", "offset", "range", + "order", + "view", "context", ]); if (Object.keys(q).some((k) => !allowed.has(k))) @@ -152,6 +181,7 @@ export function parseInspectionQuery(value: unknown): InspectionQuery { ![ "list", "get", + "count", "instructions.file", "skills.file", "runs.log", @@ -169,11 +199,21 @@ export function parseInspectionQuery(value: unknown): InspectionQuery { if (q.resource !== undefined && !INSPECTION_RESOURCES.includes(q.resource)) throw new Error("Unsupported inspection resource"); if (q.operation === "get" && !q.resourceId) throw new Error("resourceId required"); - if (["get", "list"].includes(q.operation) && !q.resource) throw new Error("resource required"); + if (["get", "list", "count"].includes(q.operation) && !q.resource) + throw new Error("resource required"); if (!(q.operation === "list" && q.resource === "companies") && !q.companyId) throw new Error("companyId required"); - if (!["get", "list"].includes(q.operation) && !q.resourceId) + if (!["get", "list", "count"].includes(q.operation) && !q.resourceId) throw new Error("resourceId required"); + if (q.operation === "count" && q.resourceId !== undefined) + throw new Error("count does not take resourceId"); + if (q.order !== undefined && (q.operation !== "list" || !INSPECTION_ORDERS.includes(q.order))) + throw new Error("Invalid order"); + if ( + q.view !== undefined && + (!["list", "get"].includes(q.operation) || q.resource !== "runs" || !INSPECTION_VIEWS.includes(q.view)) + ) + throw new Error("Invalid view"); if ( q.path !== undefined && (typeof q.path !== "string" || q.path.length > 1024 || q.path.includes("\0")) diff --git a/server/src/__tests__/customer-success-cloud.test.ts b/server/src/__tests__/customer-success-cloud.test.ts index c1557a7ce22..25dcc5a9bd3 100644 --- a/server/src/__tests__/customer-success-cloud.test.ts +++ b/server/src/__tests__/customer-success-cloud.test.ts @@ -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( diff --git a/server/src/__tests__/customer-success.test.ts b/server/src/__tests__/customer-success.test.ts index 19b48f979b2..1f05481faf0 100644 --- a/server/src/__tests__/customer-success.test.ts +++ b/server/src/__tests__/customer-success.test.ts @@ -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>; 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> }; + 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> }; + 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; + 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 }, diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index 46ccf86ebe2..f2c90f8c260 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -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. diff --git a/server/src/routes/customer-success.ts b/server/src/routes/customer-success.ts index 94083ffd5db..66e8731be33 100644 --- a/server/src/routes/customer-success.ts +++ b/server/src/routes/customer-success.ts @@ -1,9 +1,11 @@ import { createPublicKey, verify } from "node:crypto"; -import { Router } from "express"; +import { Router, type Request as ExpressRequest, type Response as ExpressResponse } from "express"; import type { Db } from "@paperclipai/db"; import { canonicalJson, + inspectionReadPath, parseInspectionQuery, + INSPECTION_READ_PATH, INSPECTION_AUDIENCE, INSPECTION_PERMIT_TYPE, INSPECTION_HEADER, @@ -180,7 +182,10 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options: if (!match) throw forbidden("Managed run bearer required"); res.json(await customerSuccessRunAuthority(db, match[1])); }); - router.post("/read", async (req, res) => { + // `/read` serves the original query features; `/read-v2` also serves + // count, order and view. Cloud picks the path from the query, so a tenant + // without `/read-v2` answers 404 and Cloud fails closed. + const read = async (req: ExpressRequest, res: ExpressResponse) => { if (process.env.PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_ENABLED !== "true") throw forbidden("Inspection is disabled"); if (req.headers.authorization || req.headers.cookie) @@ -209,6 +214,8 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options: } if (canonicalJson(query) !== canonicalJson(permit.query)) throw forbidden("Inspection parameters do not match permit"); + if (req.path === INSPECTION_READ_PATH && inspectionReadPath(query) !== INSPECTION_READ_PATH) + throw forbidden("This inspection query needs the extended read path"); // Replay fencing and all inspection state live in Cloud. No tenant receipt. const consumed = await fetch(`${origin}/v1/customer-success/permits/consume`, { method: "POST", @@ -223,7 +230,9 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options: if (body === null) throw unprocessable("Inspection response is too large; use pagination or a byte range"); res.type("application/json").send(body); - }); + }; + router.post("/read", read); + router.post("/read-v2", read); // Cloud run liveness check for inspection authority. Cloud asks with its // own signed, stack-addressed, 60-second question; no agent credential, // identity key, actor, session or activity is involved. diff --git a/server/src/services/customer-success-inspection.ts b/server/src/services/customer-success-inspection.ts index 63b5b49f1ce..caac018b04a 100644 --- a/server/src/services/customer-success-inspection.ts +++ b/server/src/services/customer-success-inspection.ts @@ -1,7 +1,7 @@ import fs from "node:fs/promises"; import { constants } from "node:fs"; -import { and, eq, getTableColumns, type SQL } from "drizzle-orm"; -import type { AnyPgTable, AnyPgColumn } from "drizzle-orm/pg-core"; +import { and, asc, count, desc, eq, getTableColumns, type SQL } from "drizzle-orm"; +import { getTableConfig, type AnyPgTable, type AnyPgColumn } from "drizzle-orm/pg-core"; import * as schema from "@paperclipai/db"; import type { Db } from "@paperclipai/db"; import { @@ -31,6 +31,42 @@ export interface CustomerSuccessInspectionOptions { pluginWorkerManager?: PluginWorkerManager; } +/** + * The `summary` view of a run: status, timestamps, ids and error codes, never + * the large JSON columns (result, usage, context snapshot, runner profile...), + * which make a full run row 170-540 KB. An allowlist, so a new column stays out + * until someone adds it here. + */ +export const RUN_SUMMARY_COLUMNS = [ + "id", + "companyId", + "agentId", + "issueId", + "scopeKind", + "invocationSource", + "triggerDetail", + "status", + "errorCode", + "exitCode", + "runtimeMode", + "driverKind", + "retryOfRunId", + "processLossRetryCount", + "scheduledRetryAttempt", + "continuationAttempt", + "livenessState", + "startedAt", + "finishedAt", + "createdAt", + "updatedAt", +] as const; + +function durationMs(row: Record): number | null { + const started = row.startedAt instanceof Date ? row.startedAt.getTime() : null; + const finished = row.finishedAt instanceof Date ? row.finishedAt.getTime() : null; + return started !== null && finished !== null ? Math.max(0, finished - started) : null; +} + // This is a reviewed catalog of readers, not a proxy for existing GET routes. // Select credentials out of queries; never load encrypted identity records. interface Reader { @@ -109,6 +145,13 @@ export const inspectionReaders: Record = { threads: { table: schema.chatConversations, parent: "endpointId" }, }; +/** The table's primary key columns: a stable tie-breaker for ordered pages. */ +export function primaryKeyColumns(table: AnyPgTable): AnyPgColumn[] { + const config = getTableConfig(table); + const single = config.columns.filter((column) => column.primary); + return single.length ? single : (config.primaryKeys[0]?.columns ?? []); +} + async function ownRow(tx: Db, table: AnyPgTable, companyId: string, id: string) { const columns = getTableColumns(table) as Record; const [row] = await tx @@ -157,7 +200,7 @@ export async function readCustomerSuccessResource( .where(eq(schema.companies.id, q.companyId)); if (!company) throw notFound("Inspection company not found"); } - if (q.operation === "list" || q.operation === "get") { + if (q.operation === "list" || q.operation === "get" || q.operation === "count") { const reader = inspectionReaders[q.resource!]; const all = getTableColumns(reader.table) as Record; const columns = Object.fromEntries( @@ -180,6 +223,7 @@ export async function readCustomerSuccessResource( const { inArray } = await import("drizzle-orm"); if (!memberships.length) { if (q.operation === "get") throw notFound("Inspection resource not found"); + if (q.operation === "count") return { total: 0, byStatus: all.status ? {} : null }; return { items: [], nextOffset: null }; } predicates.push( @@ -200,13 +244,51 @@ export async function readCustomerSuccessResource( throw unprocessable("This reader does not accept parentId"); predicates.push(eq(all[reader.parent], q.parentId)); } + if (q.operation === "count") { + // Totals only: no row content leaves the database. + if (!all.status) { + const [{ total }] = await tx + .select({ total: count() }) + .from(reader.table) + .where(and(...predicates)); + return { total: Number(total), byStatus: null }; + } + const groups = await tx + .select({ status: all.status, total: count() }) + .from(reader.table) + .where(and(...predicates)) + .groupBy(all.status); + const byStatus: Record = {}; + let total = 0; + for (const group of groups) { + byStatus[String(group.status)] = Number(group.total); + total += Number(group.total); + } + return { total, byStatus }; + } const limit = q.operation === "get" ? 1 : Math.max(1, q.limit ?? 25); - const order = all[reader.id ?? "id"] ?? all.createdAt ?? all.companyId; + const idColumn = all[reader.id ?? "id"]; + let orderBy: SQL[] | AnyPgColumn[]; + if (q.order) { + if (!all.createdAt) throw unprocessable("This resource has no creation time to order by"); + const direction = q.order === "newest" ? desc : asc; + // Rows written together share createdAt; the full primary key keeps + // offset pages from repeating or skipping them. + orderBy = [all.createdAt, ...primaryKeyColumns(reader.table)].map((column) => direction(column)); + } else { + orderBy = [idColumn ?? all.createdAt ?? all.companyId]; + } + const selected = + q.view === "summary" + ? Object.fromEntries( + RUN_SUMMARY_COLUMNS.filter((key) => columns[key]).map((key) => [key, columns[key]]), + ) + : columns; let rows = await tx - .select(columns) + .select(selected) .from(reader.table) .where(and(...predicates)) - .orderBy(order) + .orderBy(...orderBy) .limit(limit + (q.operation === "get" ? 0 : 1)) .offset(q.offset ?? 0); if (q.resource === "agents") @@ -245,6 +327,7 @@ export async function readCustomerSuccessResource( q.companyId!, rows as Array<{ id: string }>, ); + if (q.view === "summary") rows = rows.map((r) => ({ ...r, durationMs: durationMs(r) })); // Match the existing structured event/config redaction, without scanning // prose, documents, instructions, skill contents, or workspace files. if ( diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index a98da2aef16..e96931b7fe5 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -241,7 +241,7 @@ "packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c", "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe", - "packages/shared/src/customer-success.ts": "a2d02aaa8223164c0eae4267b2a6da82242eaa6f", + "packages/shared/src/customer-success.ts": "cf22017ffdd45123c1879f13c71c17516b8479a5", "packages/shared/src/decision-models.ts": "a07aefd87d2fae34283ce21a0334d57e2108aa7e", "packages/shared/src/decision.test.ts": "d0783d18613c73102f662e8a5da795ff6e7faed5", "packages/shared/src/document-anchors.test.ts": "6805d149ad66d91f2e3ba4841f82e9af05bf5d83", From 6385c171fa769469c4211c01ba49b25b11eab59d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:47:32 -0600 Subject: [PATCH 5/9] fix(connections): show only the privacy policy link in the Google Workspace picker (#22795) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The built-in Google Workspace connection lets agents use Gmail, Drive (with Docs, Sheets and Slides) and Calendar > - Before Google consent, the user chooses services in the "Connect Google Workspace" picker > - On Nov 17, #21998 added two text sections to this picker: "What agents can do" and "How your data is used" > - On Nov 24, the owner decided that this screen must show only the privacy policy link and no other explanatory text > - This pull request removes the two sections and keeps the privacy policy link directly under the service rows > - The benefit is a short picker that matches the owner decision, for new setup and reconnect, in the Apps flow and the task-hosted flow ## Linked Issues or Issue Description Refs #22634 **What happened?** The "Connect Google Workspace" picker shows a "What agents can do" section and a "How your data is used" section with bullet sentences. The text changes with the selected services. The owner does not want this text on the screen. **What did you expect to happen?** The picker shows the title, the three service rows (each with its access select and switch), the privacy policy link, and Cancel / Continue. It shows no other explanatory text for any selection. **Steps to reproduce** 1. Open Apps and start a Google Workspace connection, or reconnect an existing one. 2. Look at the service picker with all services on, with read only, and with one service on. 3. See the two text sections above the footer. ## What Changed - `ui/src/features/connections/GoogleWorkspaceServices.tsx`: remove the `DataUseDisclosure` block. The privacy policy link ("Read our privacy policy, including how we meet Google's Limited Use requirements", `https://paperclip.ing/privacy`, new tab) now sits directly under the service rows for every selection, including no selection. The "Select at least one service to continue." status stays. The screen-reader description "Choose the Google services to connect." stays. The URL constant `GOOGLE_WORKSPACE_PRIVACY_POLICY_URL` moves into this file. - `ui/src/features/connections/googleWorkspaceDisclosure.ts`: deleted. Nothing else used the copy builder. - `ui/src/features/connections/GoogleWorkspaceServices.test.tsx` (new; the earlier suite was removed in #22729): for all services read & write, all read only, one service, and no service, the dialog has no section headings, no lists and none of the removed sentences. The link has its text, href and new-tab target. The dialog keeps its accessible description. Continue stays disabled with no service and submits the chosen services. - `ui/storybook/stories/connection-setup/google-workspace-services.stories.tsx`: the `ProductionPickerReadOnly` play test now checks that the removed text is absent and the link is present. - Docs: `doc/memory/google-connector-memory.md` gets a dated Nov 24 decision row with the risk. `doc/plans/2026-11-17-google-workspace-production-checklist.md` no longer claims a disclosure in the picker. `doc/plans/2026-11-17-google-workspace-code-fixes.md` item 1 records the removal. The dialog now contains, from top to bottom: the Google Workspace logo and the title "Connect Google Workspace"; Gmail, Drive ("Docs, Sheets, and Slides") and Calendar rows, each with a "Read only / Read & write" select and a switch; the privacy policy link; the empty-selection status (only with no service on); Cancel and Continue in one footer row. ## Verification - Red first: the new test ran against the old picker and 4 of 5 tests failed (removed text present; link absent with no selection). After the change all 5 pass. - `cd ui && npx vitest run src/features/connections src/pages/apps/AppDetail.test.tsx src/pages/apps/AppsConnect.test.tsx`: 8 files, 55 tests pass. - `cd ui && node ../scripts/run-tsc.mjs -b`: no errors. - `node scripts/check-token-gates.mjs`: all gates clean. `node scripts/check-test-budget.mjs --files ui/src/features/connections/GoogleWorkspaceServices.test.tsx`: pass. `node scripts/storybook-catalog.mjs`: pass. - `pnpm verify` exits 2 (a global CI input changed: `doc/memory/google-connector-memory.md`). Required CI supplies the broad coverage. - Headless Playwright against Storybook dev, `ProductionPicker` at 1280x900 (dark and light) and `ProductionPickerMobile` at 375x812: the dialog text is only the title, the rows, the link, and Cancel / Continue. No horizontal scroll at 375 px. The link sits under the last row with the normal dialog gap, and the footer follows it. - Before: see the screenshots in #21998. After: the same dialog without the two text sections. ## Risks - Policy risk: Google's user data policy may expect a disclosure inside the product, before consent, that says what data the app uses and how. A privacy policy link alone may not satisfy a Google reviewer. This is a recorded owner decision. If a reviewer asks, restore a short statement above the link. The memory doc and the production checklist record this risk. - Low code risk. The change is UI-only. Selection, requested scopes, OAuth and saved state do not change. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, headless browser). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- doc/memory/google-connector-memory.md | 3 +- .../2026-11-17-google-workspace-code-fixes.md | 5 +- ...7-google-workspace-production-checklist.md | 8 +- .../GoogleWorkspaceServices.test.tsx | 81 +++++++++++++++++++ .../connections/GoogleWorkspaceServices.tsx | 31 ++----- .../connections/googleWorkspaceDisclosure.ts | 35 -------- .../google-workspace-services.stories.tsx | 12 ++- 7 files changed, 106 insertions(+), 69 deletions(-) create mode 100644 ui/src/features/connections/GoogleWorkspaceServices.test.tsx delete mode 100644 ui/src/features/connections/googleWorkspaceDisclosure.ts diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index 0b154384aff..546bd7e9a09 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -49,13 +49,14 @@ Last updated: November 23, 2026 (evening). | Nov 23 | **Security lab: TAC Security (recommended, not yet engaged)** | Google's discounted Tier 2 partner. Plan about $2,000 for year one including a retest. Confirm with a quote; Google assigns the tier. | | Nov 23 | **A tool refuses an argument it does not know** | All 36 tools fail before any request to Google and name the accepted arguments. Found live: `list_threads` ignored a filter and returned unfiltered mail. | | Nov 23 | **A cancelled or abandoned first sign-in leaves no connection** | Cancel removes the draft; a closed tab leaves a hidden draft that the next attempt reuses. Applies to every sign-in connector. | +| Nov 24 | **The service picker shows no explanatory text, only the privacy policy link** | Owner decision. This removes the in-product data-use disclosure added on Nov 17 ([#21998](https://github.com/paperclipai/paperclip/pull/21998)). Risk noted by the coordinator: Google's user data policy may expect an in-product disclosure before consent; if a reviewer asks, restore a short statement above the link. | ## What has shipped | PR | What it does | Merged commit | | --- | --- | --- | | [#21996](https://github.com/paperclipai/paperclip/pull/21996) | Plan docs: this file, the production checklist and the code-fix plan. | `12cb18e17d` | -| [#21998](https://github.com/paperclipai/paperclip/pull/21998) | Data-use disclosure in the service picker, shown just before Google consent. Every Google Workspace sign-in start goes through the picker, including four sign-in paths on the app page (Reconnect, Connect as me, Connect organization identity, dedicated-agent connect). The Gmail read & write line says Google's screen also mentions sending and that Paperclip does not send. | `b124ad0674` | +| [#21998](https://github.com/paperclipai/paperclip/pull/21998) | Data-use disclosure in the service picker, shown just before Google consent. Every Google Workspace sign-in start goes through the picker, including four sign-in paths on the app page (Reconnect, Connect as me, Connect organization identity, dedicated-agent connect). The Gmail read & write line says Google's screen also mentions sending and that Paperclip does not send. Removed on Nov 24 by owner decision (see "Decisions"); the picker keeps the privacy policy link. | `b124ad0674` | | [#21999](https://github.com/paperclipai/paperclip/pull/21999) | Prompt-injection screening now also covers resource reads through a named gateway, the one path that was not screened. Applies to every connector, not only Google. | `65eac24876` | | [#22001](https://github.com/paperclipai/paperclip/pull/22001) | Scope lock. `GOOGLE_WORKSPACE_SUBMITTED_SCOPES` is the hand-written list of 14, and `workspace.all` uses it. Paperclip-managed Google methods outside the 14 (Gmail archive, Chat, People, Workspace Search) are no longer offered for new setup or reconnect through Paperclip's Google app; saved ones keep refreshing and running. | `66ac5d7aa0` | | [#22000](https://github.com/paperclipai/paperclip/pull/22000) | REST tool set part 1: the folder `server/src/google-workspace-rest-tools/` with Gmail `get_message`, `search_threads` and `create_draft`. Nothing calls it yet; the switch comes in a later PR. | `a29658b5b7` | diff --git a/doc/plans/2026-11-17-google-workspace-code-fixes.md b/doc/plans/2026-11-17-google-workspace-code-fixes.md index 3c1a1dc698b..d646d262a39 100644 --- a/doc/plans/2026-11-17-google-workspace-code-fixes.md +++ b/doc/plans/2026-11-17-google-workspace-code-fixes.md @@ -17,7 +17,7 @@ change in fix 2, the deploy order is app first, then broker (see fix 10). | # | Fix | Size | Blocks submission | Status | | --- | --- | --- | --- | --- | -| 1 | Data-use disclosure in the picker | Small | Yes | Done, [#21998](https://github.com/paperclipai/paperclip/pull/21998) | +| 1 | Data-use disclosure in the picker | Small | Yes | Done, [#21998](https://github.com/paperclipai/paperclip/pull/21998); removed Nov 24 by owner decision | | 2 | Lock the managed scope set to 14 | Small to medium | Yes | Done in the app, [#22001](https://github.com/paperclipai/paperclip/pull/22001) | | 3 | Take `gmail.modify` off the Paperclip-managed client | Small | Yes | Done, [#22001](https://github.com/paperclipai/paperclip/pull/22001) | | 4 | Confirm injection screening on Google results | Check, then small | Yes | Done, [#21999](https://github.com/paperclipai/paperclip/pull/21999) | @@ -36,6 +36,9 @@ four sign-in paths on the app page. The Gmail read & write line says Google's screen also mentions sending and that Paperclip does not send. The plan below is kept for reference. +**Removed** (Nov 24) by owner decision. The picker keeps only the privacy +policy link, which names Google's Limited Use requirements. + **Confirmed gap.** `ServicePicker` in `ui/src/features/connections/GoogleWorkspaceServices.tsx` shows three service rows and Cancel / Continue. Its only description is screen-reader text. Google diff --git a/doc/plans/2026-11-17-google-workspace-production-checklist.md b/doc/plans/2026-11-17-google-workspace-production-checklist.md index 081a87de2d5..9fed8d06fc2 100644 --- a/doc/plans/2026-11-17-google-workspace-production-checklist.md +++ b/doc/plans/2026-11-17-google-workspace-production-checklist.md @@ -59,8 +59,12 @@ Decisions and the details behind them are kept in the ## 2. Product and code (see the code-fix plan) -- [x] Data-use disclosure shown in the picker immediately before Google consent - (Nov 17, [#21998](https://github.com/paperclipai/paperclip/pull/21998)). +- [ ] Data-use disclosure in the picker immediately before Google consent. + Added Nov 17 ([#21998](https://github.com/paperclipai/paperclip/pull/21998)), + then removed on Nov 24 by owner decision. The picker now shows only the + service rows and a link to the privacy policy and its Limited Use + statement. If a Google reviewer asks for an in-product disclosure, + restore a short statement above the link. - [ ] Limited Use statement published and linked from the picker. - [x] Help page: how to disconnect and how to delete stored Google data (Nov 17, [#22010](https://github.com/paperclipai/paperclip/pull/22010): diff --git a/ui/src/features/connections/GoogleWorkspaceServices.test.tsx b/ui/src/features/connections/GoogleWorkspaceServices.test.tsx new file mode 100644 index 00000000000..94af67a8922 --- /dev/null +++ b/ui/src/features/connections/GoogleWorkspaceServices.test.tsx @@ -0,0 +1,81 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import type { GoogleWorkspaceServiceSelection } from "@paperclipai/shared"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { GoogleWorkspaceServicesDialog } from "./GoogleWorkspaceServices"; + +vi.mock("@/api/tools", () => ({ toolsApi: { listConnectionGrants: vi.fn() } })); +vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null })); + +const removedText = [ + "What agents can do", + "How your data is used", + "agents can read and search your email", + "agents can read and search your files", + "agents can see your calendars", + "Paperclip does not send email", + "Agents read this content only to do the tasks you give them.", + "sent to the AI model provider configured for your workspace", + "It is not used to train general AI models.", + "Results are saved in the task and its run history", +]; + +describe("Google Workspace service picker", () => { + let root: Root; + let container: HTMLDivElement; + let client: QueryClient; + const onContinue = vi.fn(); + + async function render(initial?: GoogleWorkspaceServiceSelection) { + await act(async () => { root.render( + + ); }); + } + + beforeEach(() => { + vi.clearAllMocks(); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + client = new QueryClient(); + }); + afterEach(async () => { + await act(async () => { root.unmount(); }); + client.clear(); + container.remove(); + }); + + it.each<[string, GoogleWorkspaceServiceSelection | undefined]>([ + ["all services with read & write", undefined], + ["all services read only", { gmail: "read", drive: "read", calendar: "read" }], + ["a single service", { calendar: "write" }], + ["no services", {}], + ])("shows only the service rows and the privacy policy link for %s", async (_label, initial) => { + await render(initial); + const dialog = document.querySelector('[role="dialog"]')!; + for (const text of removedText) expect(dialog.textContent).not.toContain(text); + expect(dialog.querySelector("h3")).toBeNull(); + expect(dialog.querySelector("ul")).toBeNull(); + expect(document.querySelectorAll('[role="switch"]')).toHaveLength(3); + const link = [...dialog.querySelectorAll("a")].find(item => item.textContent?.includes("Limited Use"))!; + expect(link.textContent).toBe("Read our privacy policy, including how we meet Google's Limited Use requirements (opens in a new tab)"); + expect(link.getAttribute("href")).toBe("https://paperclip.ing/privacy"); + expect(link.getAttribute("target")).toBe("_blank"); + const description = document.getElementById(dialog.getAttribute("aria-describedby") ?? ""); + expect(description?.textContent).toBe("Choose the Google services to connect."); + }); + + it("keeps Continue disabled with no services and submits the chosen services", async () => { + await render({}); + const disabled = [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!; + expect(disabled.disabled).toBe(true); + expect(document.querySelector('[role="status"]')?.textContent).toBe("Select at least one service to continue."); + await act(async () => { root.unmount(); }); + root = createRoot(container); + await render({ gmail: "read" }); + await act(async () => { [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!.click(); }); + expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); + }); +}); diff --git a/ui/src/features/connections/GoogleWorkspaceServices.tsx b/ui/src/features/connections/GoogleWorkspaceServices.tsx index e3c3ddf00f9..35052237688 100644 --- a/ui/src/features/connections/GoogleWorkspaceServices.tsx +++ b/ui/src/features/connections/GoogleWorkspaceServices.tsx @@ -8,10 +8,11 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } f import { NativeSelect } from "@/components/ui/select"; import { ToggleSwitch } from "@/components/ui/toggle-switch"; import { AppLogo } from "@/pages/apps/AppLogo"; -import { GOOGLE_WORKSPACE_PRIVACY_POLICY_URL, googleWorkspaceDataUseDisclosure } from "./googleWorkspaceDisclosure"; import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; import { cn } from "@/lib/utils"; +export const GOOGLE_WORKSPACE_PRIVACY_POLICY_URL = "https://paperclip.ing/privacy"; + export function GoogleWorkspaceServiceFields({ value, onChange }: { value: GoogleWorkspaceServiceSelection; onChange: (value: GoogleWorkspaceServiceSelection) => void; @@ -100,25 +101,6 @@ export function GoogleWorkspaceServicesDialog(props: DialogProps) { return ; } -function DataUseDisclosure({ selection }: { selection: GoogleWorkspaceServiceSelection }) { - const { access, use } = googleWorkspaceDataUseDisclosure(selection); - return
-
-

What agents can do

-
    {access.map(line =>
  • {line}
  • )}
-
-
-

How your data is used

-
    {use.map(line =>
  • {line}
  • )}
-
-

- - Read our privacy policy, including how we meet Google's Limited Use requirements (opens in a new tab) - -

-
; -} - function ServicePicker({ onContinue, onCancel, initial = GOOGLE_WORKSPACE_DEFAULT_SELECTION }: DialogProps) { const [selection, setSelection] = useState(initial); const empty = Object.keys(selection).length === 0; @@ -129,9 +111,12 @@ function ServicePicker({ onContinue, onCancel, initial = GOOGLE_WORKSPACE_DEFAUL Choose the Google services to connect. - {empty - ?

Select at least one service to continue.

- : } +

+ + Read our privacy policy, including how we meet Google's Limited Use requirements (opens in a new tab) + +

+ {empty &&

Select at least one service to continue.

}