Files
PaperClipAI/tests/runner-e2e/product-journeys/chat-continuity-flow.test.ts
T
DottaandPaperclip caaa013a69 fix(e2e): wait for reset preparation and repository recovery (#23288)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product E2E tests check real user work through the app and native
agents.
> - A chat reset gets its reset marker during run preparation.
> - The observer can count that active reset as extra model work before
preparation ends.
> - The repository observer also omits the deadline needed to recognize
a scheduled same-run recovery.
> - This pull request keeps both observations open until the existing
bounded transition completes.
> - The final success checks still require the original run counts,
saved results, and evidence.

## Linked Issues or Issue Description

**What happened?**

The chat observer can throw `chat_continuity_extra_run` while `/new` is
queued or running without its reset marker. The repository observer
throws `agent_run_failed` for an exact-session recovery that the server
has already scheduled.

**Expected behavior**

Observe each transition under the original campaign deadline. Require
the same final reset receipt, model turn count, completed repository
runs, and artifact checks. An active or failed run must never count as a
pass.

**Steps to reproduce**

1. Return an unmarked queued or running reset between the second model
reply and the completed reset receipt.
2. Run the chat journey observer. Before this change it reports extra
model work.
3. Return a bound native repository run with `retryable_failure` and an
eligible `retry_scheduled` projection. Before this change the observer
rejects it before its scheduled recovery.

Related: https://github.com/paperclipai/paperclip/pull/18784 and
https://github.com/paperclipai/paperclip/pull/22826. The latter adds the
shared recovery rule. This change supplies the repository caller's
missing deadline.

## What Changed

- Count excess unmarked provider runs after they succeed. Keep the
existing reset count, scope, run cap, deadline and final grading checks.
- Supply the repository campaign deadline to the existing native
recovery validator.
- Add observer regressions for queued and running reset preparation,
completed extra work, immediate failed/cancelled rejection, scheduled
repository recovery through success, exhausted or late recovery and the
original deadline.

## Verification

- Chat regression before the fix: 2 failed and 16 passed. Both failures
report `chat_continuity_extra_run`.
- Repository regression before the fix: 2 failed and 1 passed. Both
failures report `agent_run_failed`.
- After the fixes: 109 tests pass in five affected observer, grading and
recovery files.
- `pnpm test:e2e:runner:typecheck` passes on the final source.
- `pnpm verify` cannot select tests because the managed Git storage
guard rejects `git ls-files`. The focused command above supplies local
test evidence. Final-head CI 46425283547 passes the selected Runner
support, package, static, typecheck, policy and verification gates.
General/build jobs are path-skipped.
- The real observer functions ran with simulated API/browser boundaries.
No new hosted provider run or deployment was made. A fresh hosted
journey with the reviewed harness is still required for staging
acceptance.

## Risks

The chat observer can wait longer before it rejects active extra work.
The original deadline and four-run cap still bound it. A completed extra
provider run remains fatal. Failed or cancelled chat runs already fail
in the reader before the excess-work predicate; tests prove first-read
rejection with no new message. Repository recovery uses the existing
shared eligibility rules; terminal, exhausted, foreign or late recovery
still fails. This change does not repair or explain an underlying
provider timeout. No prompt, grading rule, test selection, budget, pin
or production behavior changes.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning and code execution. The exact
model build is not exposed in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 15:51:39 +00:00

222 lines
14 KiB
TypeScript

import { afterEach, describe, 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 { chatContinuityFixture, compactChatContinuityFixture } from "./chat-continuity.test-fixture.js";
const mocks = vi.hoisted(() => ({ send: vi.fn(), reply: vi.fn(), capture: vi.fn() }));
vi.mock("../chat-flow.js", () => ({ sendChatMessage: mocks.send }));
vi.mock("../native-task-reply.js", async importOriginal => ({
...await importOriginal<typeof import("../native-task-reply.js")>(), readBoundTaskFinalReply: mocks.reply,
}));
vi.mock("./product-screenshot.js", () => ({ captureProductScreenshot: mocks.capture }));
vi.mock("@playwright/test", () => ({ expect: (locator: { isVisible(): Promise<boolean> }) => ({
async toBeVisible() { expect(await locator.isVisible()).toBe(true); },
}) }));
import { runChatContinuity } from "./chat-continuity-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: { preexisting?: boolean; intentFails?: boolean; sendFails?: boolean; foreignRun?: boolean;
compactRuns?: boolean; unrelatedActivity?: number; ignoreActivityScope?: boolean; priorAgentStatus?: string; mixedAgentHistory?: boolean;
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(() => {
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}` })),
...(options.provisioningActor ? [{ id: "provisioned-agent", companyId: f.scope.companyId,
agentId: options.provisioningActor === "board" ? null : f.scope.agentId, runId: null,
action: "agent.created", entityType: "agent", entityId: f.scope.agentId }] : []),
];
const companyRuns = Array.from({ length: options.unrelatedActivity ?? 0 }, (_, index) => ({ id: `unrelated-run-${index}`,
companyId: f.scope.companyId, agentId: "other-agent", status: "succeeded" }));
if (options.priorAgentStatus) companyRuns.push({ id: "prior-owned-run", companyId: f.scope.companyId, agentId: f.scope.agentId, status: options.priorAgentStatus });
const get = vi.fn(async (route: string) => {
if (route === "/api/instance/settings/experimental") return { enableAgentChat: true };
if (route === "/api/companies/company/heartbeat-runs?agentId=agent&limit=1&summary=true") {
actions.push("history");
if (options.mixedAgentHistory) return [{ id: "foreign-run", companyId: "foreign-company", agentId: "other-agent", status: "running" }];
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 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") {
return (options.ignoreActivityScope ? companyActivity : companyActivity.filter(row => row.agentId === f.scope.agentId)).slice(0, 500);
}
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 = observedRuns().find(row => row.id === id)!;
if (options.foreignRun) run.nativeIssueId = "foreign";
return run;
}
throw new Error(`unexpected GET ${route}`);
});
const page = { goto: vi.fn(async (_url: string) => { actions.push("navigate"); }), reload: vi.fn(async () => { actions.push("reload"); }),
getByTestId: vi.fn(() => ({ isVisible: async () => true })) };
const own = vi.fn(async (resource: { id?: string }) => {
actions.push(resource.id ? "receipt" : "intent");
if (options.intentFails && !resource.id) throw new Error("ownership intent failed");
});
const context = { page, api: { get, origin: "https://qa.example.test" },
company: { id: f.scope.companyId, issuePrefix: "QA" }, user: { id: f.scope.userId, name: "QA" },
environmentId: f.scope.environmentId, agent: { id: f.scope.agentId, name: f.scope.agentName,
provider: f.scope.provider, model: f.scope.model, runtimeMode: "native" } } as unknown as JourneyContext;
const evidence: JourneyEvidence = { outcome: "passed", startingState: "recipe", phases: [], checks: [], resourceDisposition: "released", privacy: "private" };
mocks.send.mockImplementation(async (_page, message: string) => {
actions.push("send"); messages.push(message);
if (options.sendFails) throw new Error("uncertain send response");
const index = [f.scenario.remember, f.scenario.recall, f.scenario.reset, f.scenario.fresh].indexOf(message);
expect(index).toBe(messages.length - 1);
stage = [0, 2, 3, 4][index]!;
});
mocks.reply.mockImplementation(async input => {
await input.page.reload();
const data = await input.load();
expect(data.run.id).toBe(input.runId);
const point = f.points.find(point => point.reply?.runId === input.runId)!;
return structuredClone(point.reply!);
});
mocks.capture.mockResolvedValue(undefined);
return { ...f, context, evidence, own, directory, messages, actions, page, get, companyActivity,
run: () => runChatContinuity(context, { own } as unknown as TargetSession, f.scope.campaignId, evidence,
{ 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();
expect(f.messages).toEqual([f.scenario.remember, f.scenario.recall, "/new", f.scenario.fresh]);
expect(f.actions.indexOf("intent")).toBeLessThan(f.actions.indexOf("send"));
expect(f.actions.indexOf("history")).toBeLessThan(f.actions.indexOf("intent"));
expect(f.own).toHaveBeenCalledTimes(2);
expect(f.own.mock.calls[0]![0]).toMatchObject({ journeyId: "chat-continuity", freshChat: { absent: true, userId: f.scope.userId } });
expect(f.own.mock.calls[1]![0]).toMatchObject({ id: "chat", journeyId: "chat-continuity" });
expect(f.evidence.checks).toHaveLength(9);
expect(f.evidence.checks.every(check => check.passed)).toBe(true);
expect(mocks.reply).toHaveBeenCalledTimes(5);
expect(mocks.capture).toHaveBeenCalledTimes(6);
expect(f.page.goto.mock.calls.flat().every(url => typeof url !== "string" || url.startsWith("https://qa.example.test/"))).toBe(true);
const saved = JSON.parse(await readFile(path.join(f.directory, "chat-continuity.json"), "utf8"));
expect(saved.points.map((point: { phase: string }) => point.phase)).toEqual(["initial", "returned", "recalled", "reset", "fresh", "reopened"]);
expect(saved.checks.every((check: { passed: boolean }) => check.passed)).toBe(true);
});
it("accepts compact details with original reset summaries despite more than 500 unrelated company events", async () => {
const f = await fixture({ compactRuns: true, unrelatedActivity: 750 });
await f.run();
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.every((point: { activity: unknown[] }) => point.activity.length === 0)).toBe(true);
expect(saved.points[5].resetReceipts[0]).toMatchObject({ source: "issue-runs", runId: "run-2", agentId: f.scope.agentId,
contextIssueId: "chat", wakeCommentId: "user-2", resultJson: { conversationReset: true } });
expect(saved.points[5].runs[2].resultJson).toBeNull();
});
it.each([1, 750])("rejects an ignored agent filter instead of filtering %s unrelated global activity rows", async unrelatedActivity => {
const f = await fixture({ unrelatedActivity, ignoreActivityScope: true });
await expect(f.run()).rejects.toThrow("chat_continuity_observation_incomplete");
expect(f.messages).toEqual([f.scenario.remember]);
});
it("accepts board provisioning whose created entity is the owned agent, rather than treating its entity id as the actor", async () => {
const f = await fixture({ provisioningActor: "board", unrelatedActivity: 750 });
expect(f.companyActivity.at(-1)).toMatchObject({ action: "agent.created", agentId: null, entityId: f.scope.agentId });
await f.run();
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.every((point: { activity: unknown[] }) => point.activity.length === 0)).toBe(true);
});
it("rejects creation attributed to the fresh owned agent even if that activity predates the first send", async () => {
const f = await fixture({ provisioningActor: "owned-agent" });
await expect(f.run()).rejects.toThrow("chat_continuity_evidence_failed");
expect(f.evidence.checks.find(check => check.id === "chat-no-unrequested-work")?.passed).toBe(false);
});
it.each(["succeeded", "running", "queued", "failed"])("rejects prior %s work on a reused agent before any send", async priorAgentStatus => {
const f = await fixture({ priorAgentStatus, unrelatedActivity: 750 });
await expect(f.run()).rejects.toThrow("fresh_chat_agent_required");
expect(f.messages).toEqual([]);
expect(f.own).not.toHaveBeenCalled();
});
it("rejects mixed or foreign agent history before any send", async () => {
const f = await fixture({ mixedAgentHistory: true });
await expect(f.run()).rejects.toThrow("chat_continuity_agent_history_scope_mismatch");
expect(f.messages).toEqual([]);
expect(f.own).not.toHaveBeenCalled();
});
it.each(["preexisting", "intentFails"] as const)("does not dispatch model work when %s rejects ownership", async option => {
const f = await fixture({ [option]: true });
await expect(f.run()).rejects.toThrow();
expect(f.messages).toEqual([]);
expect(f.evidence.checks.every(check => !check.passed)).toBe(true);
});
it("never replays an uncertain send", async () => {
const f = await fixture({ sendFails: true });
await expect(f.run()).rejects.toThrow("uncertain send response");
expect(f.messages).toEqual([f.scenario.remember]);
expect(mocks.send).toHaveBeenCalledTimes(1);
expect(f.evidence.checks.some(check => !check.passed)).toBe(true);
});
it("rejects a foreign native run before sending another message", async () => {
const f = await fixture({ foreignRun: true });
await expect(f.run()).rejects.toThrow("chat_continuity_run_mismatch");
expect(f.messages).toEqual([f.scenario.remember]);
expect(f.evidence.checks.some(check => !check.passed)).toBe(true);
});
});