From 3c5b117ccae6af7ef46518766a4ca637ba2f771c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:31:17 -0600 Subject: [PATCH] fix(native): post the agent's reply when the result commit worker finishes the run (#22043) 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 > - A person sends a message on a task, an agent run starts, and the agent answers with a task comment > - A native run normally finishes in its live heartbeat, which commits the result and posts the reply in one pass > - The result commit worker also commits native results. It races the live heartbeat as soon as the workspace save succeeds, and it often wins > - That worker skipped reply presentation and left the reply to the presentation worker, which often posted it many minutes later > - The task showed its new status (for example "blocked") with no reply, so the person thought the message did not run > - This pull request makes the result commit worker post the reply in the same pass > - The benefit is that the reply appears when the run finishes, whichever path finishes it ## Linked Issues or Issue Description **What happened?** A person commented on a task. A run started one second later, and the agent wrote its answer in about one minute. The run finished and the task changed to "blocked", but no reply appeared for 8.5 minutes. The person checked the task and saw no answer. **Expected behavior** The agent's reply appears on the task when the run finishes. **Steps to reproduce** 1. Run a native agent on a task. The agent reports a result (for example `blocked`) with a final reply. 2. The live heartbeat saves the workspace. The result commit worker commits the result before the heartbeat's own finalizer does. 3. The run is "succeeded" and the task status changes, but the task has no reply. 4. The reply appears only when the presentation worker later picks up the run. **Evidence** On one staging company, 135 recent succeeded runs had a reply comment: | Path that finished the run | Runs | Reply delay after the run ended | | --- | --- | --- | | Live heartbeat (reply posted inline) | 90 | 1–16 s | | Result commit worker (reply left to the presentation worker) | 45 | 0 s – 3,864 s; 29 of 45 took over 30 s | All 45 slow-path runs have no live completion write (no exit code, no log size). Traces confirm that the live `execution.native_finalize` and `completion.*` steps did not run for these runs. **Paperclip version or commit** `master` at 904c01d1a3 **Deployment mode** Hosted (staging cloud). The defect is in server finalization, so it applies to all deployment modes that use the native runtime. ## What Changed - The result commit worker no longer passes `skipNativeResponsePresentation`. After it commits and projects the run, it runs the same idempotent reply presentation step that the live heartbeat and the retry paths use. - The presentation worker stays the retry owner. If the inline attempt fails or is refused, the run stays a presentation candidate, as before. - Review responses are still left to their own worker (`skipNativeReviewResponse` is unchanged). ## Verification - Red/green test in `server/src/services/native-runtime/native-blocked-reply-recovery.test.ts`: "posts the agent's reply when the result commit worker finishes the run instead of the heartbeat". It drives the real `nativeResultCommitWork` worker for a blocked run whose workspace save succeeded. - Red on `master`: the task is blocked and the run succeeded, but the task has no comment. - Green with this change: the agent's final reply is posted once, and the presentation worker has no remaining candidate. - `cd server && npx vitest run src/services/native-runtime/native-blocked-reply-recovery.test.ts src/__tests__/native-result-commit-work.test.ts`: 26/26 pass. - `pnpm verify` on the change. ## Risks - Low risk. The presentation step is idempotent: it locks the run, records `presentationDecision.commentId`, and never posts twice. The live heartbeat and the retry paths already call it inline. - The result commit worker does slightly more work per committed run (one presentation transaction, typically 30–500 ms on staging). - Not addressed here: why the result commit worker wins the race against the live heartbeat in about a third of runs. The reply no longer depends on that race. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, browser, code execution) in Claude Code. ## 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 Refs #21169 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../native-blocked-reply-recovery.test.ts | 25 +++++++++++++++++-- .../native-result-commit-work.ts | 5 +++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/server/src/services/native-runtime/native-blocked-reply-recovery.test.ts b/server/src/services/native-runtime/native-blocked-reply-recovery.test.ts index edf767ec755..d2cd9016ad0 100644 --- a/server/src/services/native-runtime/native-blocked-reply-recovery.test.ts +++ b/server/src/services/native-runtime/native-blocked-reply-recovery.test.ts @@ -2,12 +2,13 @@ import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { agents, companies, completionContracts, createDb, heartbeatRunEvents, heartbeatRuns, issueComments, issues, - nativeRunFinalizations, statusDecisions, workAssessments, type Db } from "@paperclipai/db"; + nativeRunFinalizations, statusDecisions, workAssessments, workspaceOperations, type Db } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js"; import { NativeRunCoordinatorStore } from "./native-run-coordinator-store.js"; import { finalizeNativeRun, recordNativeFinalizationFailure } from "./native-run-finalizer.js"; import { nativeResponsePresentationWork } from "./native-response-presentation-work.js"; +import { nativeResultCommitWork } from "./native-result-commit-work.js"; const external = resolveExternalTestDatabaseUrl("PAPERCLIP_NATIVE_BLOCKED_REPLY_TEST_DATABASE_URL"); const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); @@ -23,7 +24,7 @@ describe.skipIf(!support.supported)("blocked task reply after a retried workspac const summary = "Blocked: the deploy key for the staging bucket was revoked. Please re-issue it so I can finish the upload."; const finalReply = "I could not finish the upload because the staging deploy key was revoked. Please re-issue it."; - async function blockedRun(options: { finalReply?: boolean; source?: string } = {}) { + async function blockedRun(options: { finalReply?: boolean; source?: string; workspaceSaved?: boolean } = {}) { const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); const sessionId = randomUUID(), runnerId = randomUUID(); await db.insert(companies).values({ id: companyId, name: "Blocked reply fixture", issuePrefix: companyId.slice(0, 8) }); @@ -51,6 +52,13 @@ describe.skipIf(!support.supported)("blocked task reply after a retried workspac if (options.finalReply) await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 90, eventType: "item.completed", payload: { prpEvent: { runId, normalizedSessionId: sessionId, turnId: "upload-turn", sourceEventId: "upload-final", payload: { kind: "agentMessage", channel: "final", providerPhase: "final", text: finalReply } } } }); + if (options.workspaceSaved) { + // The live heartbeat saved the workspace, then the result commit worker + // committed the result before the heartbeat's own finalizer did. + await db.insert(workspaceOperations).values({ companyId, issueId, heartbeatRunId: runId, + phase: "workspace_finalize", status: "succeeded" }); + return { companyId, agentId, issueId, runId }; + } await recordNativeFinalizationFailure({ db, runId, error: new Error("native_workspace_sync_out_failed"), failureScope: "workspace", projectRunStatus: true }); return { companyId, agentId, issueId, runId }; @@ -98,6 +106,19 @@ describe.skipIf(!support.supported)("blocked task reply after a retried workspac expect(await comments(f.issueId)).toHaveLength(1); }); + it("posts the agent's reply when the result commit worker finishes the run instead of the heartbeat", async () => { + const f = await blockedRun({ finalReply: true, workspaceSaved: true }); + const work = nativeResultCommitWork(db); + const [entry] = await work.load({ companyId: f.companyId, issueId: f.issueId }); + expect(entry).toMatchObject({ id: f.runId }); + await expect(work.check(entry)).resolves.toBeNull(); + + expect((await issue(f.issueId)).status).toBe("blocked"); + expect((await run(f.runId)).status).toBe("succeeded"); + expect(await comments(f.issueId)).toEqual([expect.objectContaining({ body: finalReply, createdByRunId: f.runId })]); + expect(await nativeResponsePresentationWork(db).load({ companyId: f.companyId, issueId: f.issueId })).toEqual([]); + }); + it("presents a channel task's blocker from the worker instead of recording a publication failure", async () => { const f = await blockedRun({ source: "chat:slack" }); await retryCopyBack(f.runId, { skipNativeResponsePresentation: true }); diff --git a/server/src/services/native-runtime/native-result-commit-work.ts b/server/src/services/native-runtime/native-result-commit-work.ts index a39de93647c..41750feb276 100644 --- a/server/src/services/native-runtime/native-result-commit-work.ts +++ b/server/src/services/native-runtime/native-result-commit-work.ts @@ -86,8 +86,11 @@ export function nativeResultCommitWork(db: Db, finalize = finalizeNativeRun) { if (!run) return null; if (signal?.aborted) throw new Error("Native result commit stopped"); try { + // This worker often finishes a run in place of its live heartbeat. Post + // the agent's reply in the same pass, as the heartbeat would; the + // presentation worker remains the retry owner if this attempt fails. await finalize({ db, runId: current.id, workspaceFinalizeStatus: "succeeded", projectRunStatus: true, - onlyWhenDue: true, skipNativeResponsePresentation: true, skipNativeReviewResponse: true, + onlyWhenDue: true, skipNativeReviewResponse: true, preserveProviderAttempt: Boolean(readNativeWorkspaceSyncReference(run.profile?.nativeWorkspaceSync)), }); } catch (error) {