diff --git a/tests/runner-e2e/product-journeys/chat-continuity-flow.test.ts b/tests/runner-e2e/product-journeys/chat-continuity-flow.test.ts index f69c7f69bcf..c86cb4070c5 100644 --- a/tests/runner-e2e/product-journeys/chat-continuity-flow.test.ts +++ b/tests/runner-e2e/product-journeys/chat-continuity-flow.test.ts @@ -24,16 +24,30 @@ afterEach(async () => { }); async function fixture(options: { preexisting?: boolean; intentFails?: boolean; sendFails?: boolean; foreignRun?: boolean; compactRuns?: boolean; unrelatedActivity?: number; ignoreActivityScope?: boolean; priorAgentStatus?: string; mixedAgentHistory?: boolean; - provisioningActor?: "board" | "owned-agent" } = {}) { + provisioningActor?: "board" | "owned-agent"; pendingReset?: "queued" | "running"; unmarkedReset?: "succeeded" | "failed" | "cancelled" } = {}) { const f = options.compactRuns ? compactChatContinuityFixture() : chatContinuityFixture(); const directory = await mkdtemp(path.join(os.tmpdir(), "chat-continuity-flow-")); directories.push(directory); let stage = options.preexisting ? 0 : -1; const messages: string[] = [], actions: string[] = []; + let resetPrepared = false; const realTimeout = globalThis.setTimeout; vi.spyOn(globalThis, "setTimeout").mockImplementation(((callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => - realTimeout(callback, delay === 1000 ? 0 : delay, ...args)) as typeof setTimeout); + realTimeout(() => { + if (delay === 1000 && stage === 3) resetPrepared = true; + callback(...args); + }, delay === 1000 ? 0 : delay)) as typeof setTimeout); const current = () => f.points[stage]!; + const observedRuns = () => { + const runs = structuredClone(current().runs); + if (stage === 3 && (options.unmarkedReset || options.pendingReset && !resetPrepared)) { + const reset = runs.find(run => run.id === "run-2")!; + delete reset.contextSnapshot.conversationReset; + reset.resultJson = null; + reset.status = options.unmarkedReset ?? options.pendingReset; + } + return runs; + }; const companyActivity = [ ...Array.from({ length: options.unrelatedActivity ?? 0 }, (_, index) => ({ id: `unrelated-${index}`, companyId: f.scope.companyId, agentId: "other-agent", runId: "other-run", action: "project.created", entityType: "project", entityId: `other-project-${index}` })), @@ -52,9 +66,11 @@ async function fixture(options: { preexisting?: boolean; intentFails?: boolean; return companyRuns.filter(run => run.agentId === f.scope.agentId).slice(0, 1); } if (route === "/api/companies/company/chats/agent") return stage < 0 ? null : structuredClone(current().chat); - if (route === "/api/issues/chat/runs") return current().runs.map(run => ({ runId: run.id, agentId: run.agentId, status: run.status, - contextIssueId: run.contextSnapshot.issueId, wakeCommentId: run.contextSnapshot.wakeCommentId, - resultJson: run.contextSnapshot.conversationReset ? { conversationReset: true } : {} })); + if (route === "/api/issues/chat/runs") { + return observedRuns().map(run => ({ runId: run.id, agentId: run.agentId, status: run.status, + contextIssueId: run.contextSnapshot.issueId, wakeCommentId: run.contextSnapshot.wakeCommentId, + resultJson: run.contextSnapshot.conversationReset ? { conversationReset: true } : {} })); + } if (route === "/api/issues/chat/comments?order=asc") return structuredClone(current().comments); if (route === "/api/companies/company/issues?view=index&assigneeAgentId=agent&includeAgentCreatedTasks=true&limit=2") return []; if (route === "/api/companies/company/activity?agentId=agent&limit=500") { @@ -63,7 +79,7 @@ async function fixture(options: { preexisting?: boolean; intentFails?: boolean; if (/\/api\/heartbeat-runs\/run-\d\/events\?/.test(route)) return structuredClone(current().events ?? []); const id = route.match(/^\/api\/heartbeat-runs\/(run-\d)$/)?.[1]; if (id) { - const run = structuredClone(current().runs.find(row => row.id === id)!); + const run = observedRuns().find(row => row.id === id)!; if (options.foreignRun) run.nativeIssueId = "foreign"; return run; } @@ -100,6 +116,31 @@ async function fixture(options: { preexisting?: boolean; intentFails?: boolean; { directory, deadlineAt: Date.now() + 10_000 }) }; } describe("chat continuity journey controls", () => { + it.each(["queued", "running"] as const)("waits for a %s reset to receive its control-plane marker", async pendingReset => { + const f = await fixture({ pendingReset }); + await f.run(); + expect(f.messages).toEqual([f.scenario.remember, f.scenario.recall, "/new", f.scenario.fresh]); + expect(f.evidence.checks).toHaveLength(9); + expect(f.evidence.checks.every(check => check.passed)).toBe(true); + const saved = JSON.parse(await readFile(path.join(f.directory, "chat-continuity.json"), "utf8")); + expect(saved.points.find((point: { phase: string }) => point.phase === "reset").runs[2]).toMatchObject({ + status: "succeeded", contextSnapshot: { conversationReset: true }, + }); + }); + it("rejects a completed extra provider run in place of the reset", async () => { + const f = await fixture({ unmarkedReset: "succeeded" }); + await expect(f.run()).rejects.toThrow("chat_continuity_extra_run"); + expect(f.messages).toEqual([f.scenario.remember, f.scenario.recall, "/new"]); + expect(f.evidence.checks.every(check => !check.passed)).toBe(true); + }); + it.each(["failed", "cancelled"] as const)("rejects a %s extra run before another poll or user message", async unmarkedReset => { + const f = await fixture({ unmarkedReset }); + await expect(f.run()).rejects.toThrow("chat_continuity_run_mismatch"); + expect(f.messages).toEqual([f.scenario.remember, f.scenario.recall, "/new"]); + const runs = f.get.mock.calls.filter(([route]) => route === "/api/heartbeat-runs/run-2"); + expect(runs).toHaveLength(1); + expect(f.evidence.checks.every(check => !check.passed)).toBe(true); + }); it("uses ordinary user messages once, owns the fresh chat before dispatch, and retains the independently graded result", async () => { const f = await fixture(); await f.run(); diff --git a/tests/runner-e2e/product-journeys/chat-continuity-flow.ts b/tests/runner-e2e/product-journeys/chat-continuity-flow.ts index fe2a2301371..66c415acdc7 100644 --- a/tests/runner-e2e/product-journeys/chat-continuity-flow.ts +++ b/tests/runner-e2e/product-journeys/chat-continuity-flow.ts @@ -83,7 +83,12 @@ export async function runChatContinuity(context: JourneyContext, session: Target if (state) { const providerRuns = state.runs.filter(run => !chatContinuityResetRun(run)); const resetRuns = state.runs.filter(chatContinuityResetRun); - if (providerRuns.length > providerCount || resetRuns.length > resetCount) throw new JourneyError("failed", "chat_continuity_extra_run"); + // Reset identity is written during preparation. A queued/running reset + // has no marker yet, so classify excess work only after it settles. + const completedProviderRuns = providerRuns.filter(run => run.status === "succeeded"); + if (completedProviderRuns.length > providerCount || resetRuns.length > resetCount) { + throw new JourneyError("failed", "chat_continuity_extra_run"); + } const ready = providerRuns.length === providerCount && resetRuns.length === resetCount && state.runs.every(run => run.status === "succeeded") && providerRuns.every(run => run.nativePhase === "committed") diff --git a/tests/runner-e2e/product-journeys/repository-continuation-flow.test.ts b/tests/runner-e2e/product-journeys/repository-continuation-flow.test.ts new file mode 100644 index 00000000000..f3190b0a8d7 --- /dev/null +++ b/tests/runner-e2e/product-journeys/repository-continuation-flow.test.ts @@ -0,0 +1,105 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { JourneyContext, JourneyEvidence, TargetSession } from "./types.js"; +import { repositoryContinuationSource } from "./repository-continuation-contract.js"; + +const mocks = vi.hoisted(() => ({ create: vi.fn() })); +vi.mock("../user-actions.js", async original => ({ + ...await original(), createTaskThroughUi: mocks.create, +})); +import { runRepositoryContinuation } from "./repository-continuation-flow.js"; + +const directories: string[] = []; +afterEach(async () => { + vi.restoreAllMocks(); + vi.resetAllMocks(); + for (const directory of directories.splice(0)) await rm(directory, { recursive: true, force: true }); +}); + +async function fixture(options: { exhausted?: boolean; neverCompletes?: boolean; lateRetry?: boolean; succeeds?: boolean } = {}) { + let now = Date.now(); + vi.spyOn(Date, "now").mockImplementation(() => now); + const realTimeout = globalThis.setTimeout; + vi.spyOn(globalThis, "setTimeout").mockImplementation(((callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => + realTimeout(() => { + if (delay === 1000) now += 1000; + callback(...args); + }, delay === 1000 ? 0 : delay)) as typeof setTimeout); + const directory = await mkdtemp(path.join(os.tmpdir(), "repository-recovery-")); + directories.push(directory); + const deadlineAt = Date.now() + 5_000; + const run = { id: "run", companyId: "company", agentId: "agent", nativeIssueId: "task", runtimeMode: "native", + finishedAt: new Date(Date.now() - 1_000).toISOString(), status: "failed", nativePhase: "retryable_failure", errorCode: "native_session_interrupted", + contextSnapshot: { issueId: "task", paperclipEnvironment: { id: "environment" } }, + runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "model" } } }, + execution: { phase: "retry_scheduled", cause: "native_session_interrupted", attempt: options.exhausted ? 3 : 1, + maxAttempts: 3, recoveryOwner: "agent", retryAt: new Date(Date.now() + (options.lateRetry ? 6_000 : 1_000)).toISOString() } }; + let observations = 0; + const get = vi.fn(async (route: string) => { + if (route === "/api/projects/project") return { companyId: "company", workspaces: [{ id: "primary", isPrimary: true, + repoUrl: repositoryContinuationSource.url, repoRef: repositoryContinuationSource.commit }] }; + if (route === "/api/issues/task") { + observations += 1; + return { id: "task", companyId: "company", assigneeAgentId: "agent", projectId: "project", status: options.succeeds && observations > 1 ? "done" : "in_progress" }; + } + if (route === "/api/issues/task/runs") return [{ runId: "run" }]; + if (route === "/api/heartbeat-runs/run") { + // Prove the observer keeps reading the same native run after its scheduled retry. + if (observations > 1 && options.succeeds) return { ...structuredClone(run), status: "succeeded", nativePhase: "committed", + resultJson: { finalizationPhase: "committed" } }; + if (observations > 1 && !options.neverCompletes) throw new Error("same-run recovery observed again"); + return structuredClone(run); + } + if (route === "/api/issues/task/workspace") throw new Error("recovered workspace reached"); + if (route.endsWith("/comments?order=asc") || route.endsWith("/interactions")) return []; + throw new Error(`Unexpected read: ${route}`); + }); + mocks.create.mockResolvedValue({ issueId: "task" }); + const context = { api: { origin: "https://qa.example.test", get, post: vi.fn(async () => ({ id: "project" })) }, page: {}, + company: { id: "company", issuePrefix: "QA" }, environmentId: "environment", + agent: { id: "agent", name: "Agent", runtimeMode: "native", provider: "opencode", model: "model" } } as unknown as JourneyContext; + const evidence = { checks: [] } as unknown as JourneyEvidence; + const promise = runRepositoryContinuation(context, { own: vi.fn() } as unknown as TargetSession, "journey-1234567890123-abcdef12", evidence, + { directory, deadlineAt }); + return { promise, directory, get, evidence }; +} + +it("keeps observing an eligible same-run retry under the original repository deadline", async () => { + const f = await fixture(); + const assertion = expect(f.promise).rejects.toThrow("same-run recovery observed again"); + await assertion; + expect(f.get.mock.calls.filter(([route]) => route === "/api/heartbeat-runs/run")).toHaveLength(2); + const saved = JSON.parse(await readFile(path.join(f.directory, "repository-latest-task.json"), "utf8")); + expect(saved.taskRuns[0]).toMatchObject({ id: "run", status: "failed", execution: { phase: "retry_scheduled" } }); + expect(f.evidence.checks).toEqual([]); +}); + +it("still rejects an exhausted recovery", async () => { + const f = await fixture({ exhausted: true }); + await expect(f.promise).rejects.toThrow("agent_run_failed"); +}); + +it("does not extend the campaign deadline for a recovery that never completes", async () => { + const f = await fixture({ neverCompletes: true }); + const assertion = expect(f.promise).rejects.toThrow("repository_task_not_completed"); + await assertion; +}); + +it("reaches the workspace oracle after the same run recovers successfully", async () => { + const f = await fixture({ succeeds: true }); + await expect(f.promise).rejects.toThrow("recovered workspace reached"); + const saved = JSON.parse(await readFile(path.join(f.directory, "repository-latest-task.json"), "utf8")); + expect(saved.currentIssue.status).toBe("done"); + expect(saved.taskRuns).toHaveLength(1); + expect(saved.taskRuns[0]).toMatchObject({ id: "run", status: "succeeded", nativePhase: "committed" }); + expect(f.get.mock.calls.some(([route]) => route === "/api/issues/task/workspace")).toBe(true); + expect(mocks.create).toHaveBeenCalledTimes(1); +}); + +it("rejects a retry scheduled after the original campaign deadline", async () => { + const f = await fixture({ lateRetry: true }); + await expect(f.promise).rejects.toThrow("agent_run_failed"); + expect(f.get.mock.calls.filter(([route]) => route === "/api/heartbeat-runs/run")).toHaveLength(1); +}); diff --git a/tests/runner-e2e/product-journeys/repository-continuation-flow.ts b/tests/runner-e2e/product-journeys/repository-continuation-flow.ts index 89b4db416df..67a3f5082c5 100644 --- a/tests/runner-e2e/product-journeys/repository-continuation-flow.ts +++ b/tests/runner-e2e/product-journeys/repository-continuation-flow.ts @@ -61,7 +61,7 @@ export async function runRepositoryContinuation(context: JourneyContext, session .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)) || String(a.id).localeCompare(String(b.id))); const state = { currentIssue, taskRuns, comments, interactions, attachments: [] }; await retain("repository-latest-task.json", state); - validateAgentTaskState(context, created.issueId, state, 2); + validateAgentTaskState(context, created.issueId, state, 2, [], options.deadlineAt); if (currentIssue.projectId !== project.id) throw new JourneyError("failed", "repository_project_binding_mismatch"); return state; };