From b63445c8f1ec7c6dafe25fb7f7e1a72c9eba319e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:56:35 +0000 Subject: [PATCH] fix(e2e): save hiring task intents at the submit boundary (#23400) ## Thinking Path > - Paperclip manages work by AI agents. > - Its product journeys verify hiring and task delegation through chat. > - Cleanup uses saved creation intents to track possible writes. > - The hiring journey saves each task intent before browser preparation. > - A navigation or editor failure can therefore leave an intent for a request that was never sent. > - This pull request saves the intent after message validation and before Send. > - Cleanup can retain strict write protection without treating failed preparation as a possible task creation. ## Linked Issues or Issue Description **What happened?** The hiring journey can save a review-task intent even when a browser failure stops the third chat request before submission. Cleanup then reports an uncertain creation outcome. A controlled navigation failure reproduces this tracking defect. The original retained browser exception is unavailable; this change does not claim its cause. **Expected behavior** Browser preparation must not register a task write. The creation intent must be saved before submission can create work. A failed intent save must stop submission. A send with a possible committed write must retain the intent. **Steps to reproduce** Inject a navigation failure before the review request after the checklist completes. The original code records the review intent despite making only two sends. The new code preserves the checklist receipt and records no review intent. **Paperclip version or commit** Reproduced from source at `5a9c06b315d9612022908b7fc189f30bac3619af`. **Deployment mode** Linux source checkout, focused workflow tests, and Chromium against the real production composer. The paid hosted acceptance case remains pending until merge. Related earlier hiring coverage and spacing fixes: #18351 and #22825. ## What Changed - Save delegated-task intents through an awaited callback after the exact mention chips are verified and before the browser clicks Send. - Cover failed review navigation, failed intent persistence, rejected mentions, and a send failure after the intent boundary. - Keep handoff references and task name in one typed object. A handoff without its intent name is no longer representable. - Keep the existing ownership, initial assignment, saved-body, seven-run, budget, and cleanup checks. - Document the submission boundary. ## Verification - Red: the new review-navigation regression failed because the old flow saved the review intent without sending that request. - Green: 78 focused flow and evidence tests pass. - All 8 real-composer Chromium checks pass. They cover both composer modes, exact saved messages, failed intent persistence, page loss after persistence, and rejected agent/project mentions. - `pnpm test:e2e:runner:typecheck` passes. - `pnpm verify --explain` could not select checks because the managed Git storage guard rejects `git ls-files`. Even the suggested shallow fetch fails. This unavailable check is not a pass. The source was compared with master through the repository API before publication. - Original head `6914c4b` passed [CI](https://github.com/paperclipai/paperclip/actions/runs/46723605434) and Greptile 5/5 with Low impact. Typecheck, four support shards, six Runner package shards, static checks, and aggregate verification passed. Build was skipped by the test-only path policy. - Review head `cd7b03f36d6d9fcac37cf80906fad2f7cd167958` passes the 78 focused tests, all 8 browser checks, and runner E2E typecheck. Its first browser attempt could not start because the resumed sandbox lacked Chromium; installation restored the check, which then passed. The current head passed [CI](https://github.com/paperclipai/paperclip/actions/runs/46727370488), including Typecheck + Release Registry, four support shards, six Runner package shards, static checks, and aggregate verification. Build is skipped by the test-only path policy. Greptile, Feynman and Ponytail each gave this head 5/5, with Low impact from Greptile. The actionable thread is resolved. Hosted acceptance must run only `hire-delegate-reuse` after merge. ## Risks The callback and Send cannot form one atomic operation. A failure after intent persistence still keeps the intent and the existing uncertain-write protection. This patch does not manufacture absence proof for old retained manifests. The original browser error remains unknown. ## Model Used OpenAI GPT-6 through Codex, with reasoning, shell tools, source editing, and Chromium. The runtime does not expose a more specific backend model revision or context size. ## 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 --- tests/runner-e2e/PRODUCT-JOURNEYS.md | 5 +++ .../runner-e2e/hire-delegate-composer.spec.ts | 35 +++++++++++++++++-- .../hire-delegate-composer.ts | 3 +- .../hire-delegate-flow.test.ts | 29 +++++++++++++-- .../product-journeys/hire-delegate-flow.ts | 12 +++---- 5 files changed, 72 insertions(+), 12 deletions(-) diff --git a/tests/runner-e2e/PRODUCT-JOURNEYS.md b/tests/runner-e2e/PRODUCT-JOURNEYS.md index 9ea5d2d39ea..e16eb5d3f79 100644 --- a/tests/runner-e2e/PRODUCT-JOURNEYS.md +++ b/tests/runner-e2e/PRODUCT-JOURNEYS.md @@ -583,6 +583,11 @@ outlives the original campaign deadline fails without making a decision. The hire-delegate-reuse observer applies the same exact-session retry wait to lead and hired-agent runs. Its idle check still requires every run to succeed. +For each delegated task, the journey saves its creation intent after the exact +mention chips are ready and before it clicks Send. Navigation or editor failures +before that boundary do not leave an intent for an unsubmitted request. A failed +intent save stops the send. Once submission can occur, the intent remains subject +to the existing creation-receipt and uncertain-outcome cleanup checks. A journey failure from a hosted API call keeps its fixed code, such as `api_status_500` or `api_request_failed`; other errors stay `journey_operation_failed`. diff --git a/tests/runner-e2e/hire-delegate-composer.spec.ts b/tests/runner-e2e/hire-delegate-composer.spec.ts index d5a599edf65..08539bfe366 100644 --- a/tests/runner-e2e/hire-delegate-composer.spec.ts +++ b/tests/runner-e2e/hire-delegate-composer.spec.ts @@ -27,7 +27,13 @@ test("raw fill escapes mention syntax in the real production composer", async ({ for (const [review, mode] of [[false, "production"], [true, "streamlined"]] as const) { test(`normal mention controls preserve the exact ${review ? "review" : "checklist"} body in ${mode} composer`, async ({ page }) => { const key = mode; await open(page, key, "valid", mode); const text = message(review); - await sendHireHandoffMessage(page, text, references, Date.now() + 10_000); + let intentSaved = false; + await sendHireHandoffMessage(page, text, references, Date.now() + 10_000, async () => { + expect(await saved(page, key)).toEqual([]); + await expect(page.locator('a[data-mention-kind]')).toHaveCount(2); + intentSaved = true; + }); + expect(intentSaved).toBe(true); await expect.poll(async () => (await saved(page, key)).length).toBe(1); expect(await saved(page, key)).toEqual([{ id: "1", body: text }]); }); @@ -35,7 +41,8 @@ for (const [review, mode] of [[false, "production"], [true, "streamlined"]] as c for (const variant of ["wrong-agent", "duplicate", "missing-project"] as const) { test(`normal mention controls reject ${variant} without sending`, async ({ page }) => { await open(page, variant, variant); - const send = sendHireHandoffMessage(page, message(), references, Date.now() + (variant === "missing-project" ? 5_000 : 10_000)); + let intentSaved = false; + const send = sendHireHandoffMessage(page, message(), references, Date.now() + (variant === "missing-project" ? 5_000 : 10_000), async () => { intentSaved = true; }); if (variant !== "missing-project") await expect(send).rejects.toMatchObject({ code: variant === "wrong-agent" ? "hire_handoff_mention_mismatch" : "hire_handoff_mention_ambiguous", }); @@ -44,6 +51,30 @@ for (const variant of ["wrong-agent", "duplicate", "missing-project"] as const) await expect(page.locator('a[data-mention-kind="agent"]')).toHaveCount(1); await expect(page.locator('a[data-mention-kind="project"]')).toHaveCount(0); } + expect(intentSaved).toBe(false); expect(await saved(page, variant)).toEqual([]); }); } + +test("a failed intent save stops submission after valid composer preparation", async ({ page }) => { + await open(page, "intent-save-failed"); + const failure = new Error("intent_save_failed"); + let attempts = 0; + await expect(sendHireHandoffMessage(page, message(true), references, Date.now() + 10_000, async () => { + attempts++; + throw failure; + })).rejects.toBe(failure); + expect(attempts).toBe(1); + expect(await saved(page, "intent-save-failed")).toEqual([]); +}); + +test("page loss after intent persistence keeps the intent without replaying Send", async ({ page }) => { + await open(page, "page-loss-after-intent"); + const intents: string[] = []; + await expect(sendHireHandoffMessage(page, message(true), references, Date.now() + 10_000, async () => { + intents.push("review"); + await page.close(); + })).rejects.toThrow(/closed/); + expect(intents).toEqual(["review"]); + expect(await saved(page, "page-loss-after-intent")).toEqual([]); +}); diff --git a/tests/runner-e2e/product-journeys/hire-delegate-composer.ts b/tests/runner-e2e/product-journeys/hire-delegate-composer.ts index 97607109665..ab13d9accd4 100644 --- a/tests/runner-e2e/product-journeys/hire-delegate-composer.ts +++ b/tests/runner-e2e/product-journeys/hire-delegate-composer.ts @@ -2,7 +2,7 @@ import { expect, type Page } from "@playwright/test"; import { parseAgentMentionHref, parseProjectMentionHref } from "../../../packages/shared/src/project-mentions.js"; import { JourneyError } from "./types.js"; -export async function sendHireHandoffMessage(page: Page, text: string, references: Readonly<{ teammate: string; project: string }>, deadlineAt: number) { +export async function sendHireHandoffMessage(page: Page, text: string, references: Readonly<{ teammate: string; project: string }>, deadlineAt: number, beforeSubmit?: () => Promise) { const timeout = () => { const remaining = Math.min(5_000, deadlineAt - Date.now()); if (remaining <= 0) throw new JourneyError("failed", "hire_handoff_editor_not_ready"); @@ -54,5 +54,6 @@ export async function sendHireHandoffMessage(page: Page, text: string, reference if (suffix) await editable.pressSequentially(suffix); const hrefs = await editable.locator("a[data-mention-kind]").evaluateAll(nodes => nodes.map(node => node.getAttribute("href"))); if (JSON.stringify(hrefs) !== JSON.stringify(tokens.map(token => token.href))) throw new JourneyError("failed", "hire_handoff_mention_mismatch"); + await beforeSubmit?.(); await page.getByTestId("task-chat-composer-send").last().click({ timeout: timeout() }); } diff --git a/tests/runner-e2e/product-journeys/hire-delegate-flow.test.ts b/tests/runner-e2e/product-journeys/hire-delegate-flow.test.ts index 8bfbc140fb2..e0551b32e4d 100644 --- a/tests/runner-e2e/product-journeys/hire-delegate-flow.test.ts +++ b/tests/runner-e2e/product-journeys/hire-delegate-flow.test.ts @@ -11,7 +11,10 @@ import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSes vi.mock("@playwright/test", () => ({ expect: (value: unknown) => Object.assign(expect(value), { toBeVisible: async () => {}, toHaveURL: async (predicate: (url: URL) => boolean) => { expect(predicate(new URL((value as Row).currentUrl ?? "https://qa.example.test/QA/issues/QA-2"))).toBe(true); } }) })); vi.mock("../chat-flow.js", () => ({ sendChatMessage: vi.fn(), readChatOutputDocument: vi.fn() })); -vi.mock("./hire-delegate-composer.js", () => ({ sendHireHandoffMessage: (page: any, text: string) => sendChatMessage(page, text) })); +vi.mock("./hire-delegate-composer.js", () => ({ sendHireHandoffMessage: async (page: any, text: string, _references: unknown, _deadlineAt: number, beforeSubmit?: () => Promise) => { + await beforeSubmit?.(); + await sendChatMessage(page, text); +} })); type Row = Record; const directories: string[] = []; afterEach(async () => { vi.mocked(sendChatMessage).mockReset(); await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true }))); }); @@ -203,7 +206,7 @@ it("ends a missing saved result at the original deadline without a click or repl { id: "review", identifier: "QA-2", title: "Saved review" }, Date.now() + 10, { companyId: "company", chatId: "chat", runId: "callback" })).toBe(false); }); -it.each(["stale", "foreign", "truncated", "late-reply", "wrong-author", "activity-linked", "foreign-run", "contradictory-run", "extra-run", "fallback", "fallback-changed", "fallback-subscription", "fallback-subscription-wrong-method", "creation-backlog-reassigned"])("re-reads %s callback task state while preserving strict scope and seven-run accounting", async snapshot => { +it.each(["stale", "foreign", "truncated", "late-reply", "wrong-author", "activity-linked", "foreign-run", "contradictory-run", "extra-run", "fallback", "fallback-changed", "fallback-subscription", "fallback-subscription-wrong-method", "creation-backlog-reassigned", "review-navigation-failed"])("re-reads %s callback task state while preserving strict scope and seven-run accounting", async snapshot => { const fallback = snapshot.startsWith("fallback"), subscription = snapshot.startsWith("fallback-subscription"); const provider = subscription ? "codex" : "opencode", accountProvider = subscription ? "openai" : "openrouter", method = subscription ? "subscription" : "api_key"; const campaignId = "journey-1-deadbeef", names = hireDelegateNames(campaignId), binding = fallback @@ -300,7 +303,11 @@ it.each(["stale", "foreign", "truncated", "late-reply", "wrong-author", "activit throw new Error(route); }, async post() { return { id: "project", companyId: "company", name: names.project }; } }; const visited: string[] = []; - const page: Row = { currentUrl: "https://qa.example.test/QA/chats/lead", async goto(url: string) { page.currentUrl = url; }, async reload() {}, + const navigationError = new Error("review_navigation_failed"); + const page: Row = { currentUrl: "https://qa.example.test/QA/chats/lead", async goto(url: string) { + if (snapshot === "review-navigation-failed" && sent === 2) throw navigationError; + page.currentUrl = url; + }, async reload() {}, locator(selector: string) { const comment = comments.find(row => selector === `[id=${JSON.stringify(`comment-${row.id}`)}]`); return { async isVisible() { return Boolean(comment); }, locator(selector: string) { @@ -316,6 +323,14 @@ it.each(["stale", "foreign", "truncated", "late-reply", "wrong-author", "activit const directory = await mkdtemp(path.join(os.tmpdir(), "hire-completion-")); directories.push(directory); const execution = hireDelegateReuse(context, { async own(row: Row) { owned.push(row); } } as unknown as TargetSession, campaignId, evidence, { deadlineAt: Date.now() + 10_000, directory, capture: async () => {} }); + if (snapshot === "review-navigation-failed") { + await expect(execution).rejects.toBe(navigationError); + expect(sent).toBe(2); + expect(owned.some(row => row.name === names.checklist)).toBe(true); + expect(owned.some(row => row.name === names.review)).toBe(false); + expect(tasks.map(task => task.id)).toEqual(["task-2"]); + return; + } if (["foreign", "wrong-author", "foreign-run", "contradictory-run", "extra-run", "fallback-changed", "fallback-subscription-wrong-method", "creation-backlog-reassigned"].includes(snapshot)) { const code = snapshot === "creation-backlog-reassigned" ? "hire_initial_assignee_mismatch" : snapshot === "foreign" ? "hire_resource_scope_mismatch" : snapshot === "wrong-author" ? "hire_completion_reply_mismatch" : snapshot === "extra-run" ? "hire_requested_turn_mismatch" : snapshot === "fallback-changed" ? "hire_native_binding_mismatch" @@ -371,3 +386,11 @@ it("retains an exact failed message comparison before grading, without retaining expect(raw).not.toContain("Hire exactly one"); expect(sendChatMessage).toHaveBeenCalledTimes(1); }); + +it("keeps the delegated creation intent when a send fails after the submission boundary", async () => { + const f = await fixture(); + await expect(f.run()).rejects.toBe(f.stop); + expect(f.owned).toContainEqual({ kind: "issue", name: hireDelegateNames("journey-1-deadbeef").checklist, + journeyId: "hire-delegate-reuse" }); + expect(sendChatMessage).toHaveBeenCalledTimes(2); +}); diff --git a/tests/runner-e2e/product-journeys/hire-delegate-flow.ts b/tests/runner-e2e/product-journeys/hire-delegate-flow.ts index f7f11003d20..ce140569d1e 100644 --- a/tests/runner-e2e/product-journeys/hire-delegate-flow.ts +++ b/tests/runner-e2e/product-journeys/hire-delegate-flow.ts @@ -176,11 +176,13 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target const bodyReceipt = (body: unknown) => typeof body === "string" ? { byteSize: Buffer.byteLength(body), sha256: createHash("sha256").update(body).digest("hex"), } : null; - const turn = async (text: string, count: number, handoff?: ReturnType) => { + const turn = async (text: string, count: number, handoff?: { references: ReturnType; taskName: string }) => { await page.goto(chatUrl, { waitUntil: "domcontentloaded" }); const before = await api.get(chatPath); const prior = before ? await api.get(`/api/issues/${before.id}/comments?order=asc`) : []; - if (handoff) await sendHireHandoffMessage(page, text, handoff, options.deadlineAt); + if (handoff) await sendHireHandoffMessage(page, text, handoff.references, options.deadlineAt, async () => { + await session.own({ kind: "issue", name: handoff.taskName, journeyId: "hire-delegate-reuse" }); + }); else await sendChatMessage(page, text); const state = await waitForIdle(count); const comments = await api.get(`/api/issues/${state.chat.id}/comments?order=asc`); @@ -200,8 +202,7 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target check("one-attributed-native-hire", state.tasks.length === 0); const handoff = hireHandoffMentions(scope!, hiredId!, hired, project); const marker = `HIRE${campaignId.replace(/[^a-z0-9]/gi, "")}`; - await session.own({ kind: "issue", name: names.checklist, journeyId: "hire-delegate-reuse" }); - state = await turn(`Have the existing ${handoff.teammate} write a concise launch checklist as a saved Paperclip document with the line "Reference: ${marker}". Create exactly one task titled ${names.checklist} in ${handoff.project}, already assigned to that teammate when it is created. Link the result here and let the teammate complete it. Do not hire another agent.`, 4, handoff); + state = await turn(`Have the existing ${handoff.teammate} write a concise launch checklist as a saved Paperclip document with the line "Reference: ${marker}". Create exactly one task titled ${names.checklist} in ${handoff.project}, already assigned to that teammate when it is created. Link the result here and let the teammate complete it. Do not hire another agent.`, 4, { references: handoff, taskName: names.checklist }); const first = state.tasks.find(task => task.title === names.checklist); check("first-delegated-task-complete", typeof first?.identifier === "string" && state.tasks.length === 1); const readOutput = async (task: Row, token: string, runs: Row[]) => { @@ -213,8 +214,7 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target const firstOutput = await readOutput(first!, marker, state.runs); const originalTask = mutableIssueSnapshot(await api.get(`/api/issues/${first!.id}`)); check("checklist-authored-by-hired-run"); - await session.own({ kind: "issue", name: names.review, journeyId: "hire-delegate-reuse" }); - state = await turn(`Have the existing ${handoff.teammate} review the checklist on ${first!.identifier} and write a separate saved review document with the line "Reference: REVIEW${marker}". Create exactly one task titled ${names.review} in ${handoff.project}, already assigned to that same teammate when it is created. Include the actual checklist in the handoff. Preserve the original checklist and task. Link the completed review here. Do not hire another agent.`, 7, handoff); + state = await turn(`Have the existing ${handoff.teammate} review the checklist on ${first!.identifier} and write a separate saved review document with the line "Reference: REVIEW${marker}". Create exactly one task titled ${names.review} in ${handoff.project}, already assigned to that same teammate when it is created. Include the actual checklist in the handoff. Preserve the original checklist and task. Link the completed review here. Do not hire another agent.`, 7, { references: handoff, taskName: names.review }); const second = state.tasks.find(task => task.title === names.review); check("same-teammate-reused", typeof second?.identifier === "string" && state.tasks.length === 2 && state.tasks.every(task => taskNames.includes(task.title))); const reviewOutput = await readOutput(second!, `REVIEW${marker}`, state.runs);