From 1916b4f18e1037b1af6e37aec7b4a8c643d6544e Mon Sep 17 00:00:00 2001 From: marshall Date: Wed, 25 Nov 2026 13:31:09 -0800 Subject: [PATCH] fix(native): never post an earlier conversation turn's reply after a later turn started (#21803) 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 > - People talk to agents in agent chats. Each message starts a native run, a "turn", for the chat's agent > - When a turn ends with a committed reply but no posted comment, committed-reply recovery posts that reply later > - Recovery treats an unposted turn as the current turn when the task holds no execution run. A later turn holds that run only while it runs > - So when a later turn fails at setup, or finishes, an earlier turn's reply qualifies again. Recovery then posts it as a new message, days late > - This pull request makes recovery skip a turn when a later turn of the same agent on the task has started > - The benefit is that a person never sees an old reply as a new message ## Linked Issues or Issue Description No public issue exists. Bug description: **What happened?** On a hosted instance, old agent replies appeared in agent chats as new comments, 2 to 8 days after their runs ended. In each case, a new run of the same agent on the same task had just started or failed at setup. Each posted comment had the old run as `createdByRunId`, and its `presentationDecision` had `commentAction: create` and the reason code `committed_task_response_recovered`. Some of the old replies had been shown before by another run. Others had never been shown. Cause: `recoverCommittedNativeChatResponseInScope` in `native-run-finalizer.ts` and the pending-presentation query in `native-response-presentation-query.ts` accept an unposted conversation turn as current when `issues.executionRunId` is null or the run itself. A later turn releases `executionRunId` when it fails at setup or finishes. After that, every earlier unposted turn of the same conversation generation passes the check again. **Expected behavior** Recovery posts a turn's reply only while that turn is still the latest started turn of the conversation. An earlier turn's reply is never posted after a later turn started. **Steps to reproduce** 1. Commit a native conversation turn with a final reply and no posted comment. 2. Insert a later run of the same agent for the same task. Give it status `failed` (setup failure), `running`, or `succeeded`. 3. Set the task's `executionRunId` to null. 4. Call `recoverCommittedNativeChatResponse`. Before this change, it returns `true` and posts the earlier reply. **Paperclip version or commit** Reproduced in tests on `master` at `cec8c2b3f4`. Related: #18465 and #20204 added committed-reply recovery. This PR keeps their behavior for the current turn. ## What Changed - `native-run-finalizer.ts`: new `laterConversationTurnStarted`. Committed-reply recovery treats a conversation turn as current only when no later run of the same agent on the task has started. Three later runs do not count: a `queued` wake that has not started, a discarded queued message (`cancelled` with no `startedAt`), and a context compaction run (it keeps the same session). One shared condition, `laterConversationTurn`, is used by recovery and by the pending-presentation query. The query compares the stored `createdAt` values in SQL, because a JavaScript `Date` drops microseconds. - `native-response-presentation-query.ts`: the pending-presentation candidates query has the same `NOT EXISTS` condition. It uses the existing `heartbeat_runs_company_ctx_issue_created_idx` index. - `agent-chat-response-recovery.test.ts`: new tests for a later turn that failed at setup, is running, or finished, with `yielded`, `done`, and held (pending approval) turns. New tests show that the reply still posts when the only later run is a queued wake, a discarded queued message, or a context compaction run. ## Verification - Red before the fix, green after: `never posts an earlier turn's reply after a later turn of the conversation started (...)` in `server/src/services/native-runtime/agent-chat-response-recovery.test.ts`. - Without the source change: 5 failed, 65 passed (70). - With the source change: 70 passed (70). - Red before the review fix, green after: `still posts the reply when the only later run is a discarded queued message` and `... is a context compaction run`. On the first commit: 2 failed. Now: the file has 72 passed (72). - `pnpm verify` returned exit 2 (an opaque setup dependency), so CI supplies broad coverage. - Focused related suites (`committed-chat-response-authority`, `idle-native-finalization`, `chat-monitor-continuation`, `presentation-ownership-read`, `native-blocked-reply-recovery`, `native-response-publication-retry`, `paperclip-control-plane-port`, `native-workspace-queued-wake-recovery`, `native-run-finalizer-telemetry`): 340 passed (10 files, with the recovery test file). After that run, a type-only change moved the shared alias; the recovery test file passed again on the final revision (72 passed). - `pnpm --filter @paperclipai/server typecheck`: passed on the first commit. On the final revision, the local run was stopped by the shared memory limit of this machine. CI typecheck covers the final revision. - Not run locally: `chat-channels.integration.test.ts` (did not finish in 25 minutes on this machine). CI runs it. - Not run: a live chat on a hosted instance. ## Risks - Low risk. The change only removes cases where recovery posts a reply. The current turn still recovers its reply. - A turn whose reply did not post before a later turn started now never posts that reply by recovery. The later turn answers the conversation instead. - No migration and no API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in a Claude Code agent 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 - [ ] 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: lucktastic <13757243+lucktastic@users.noreply.github.com> Co-authored-by: Paperclip Co-authored-by: Claude Opus 5.5 Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> --- .../agent-chat-response-recovery.test.ts | 39 +++++++++++++++++++ .../native-response-presentation-query.ts | 21 +++++++++- .../native-runtime/native-run-finalizer.ts | 17 +++++++- 3 files changed, 75 insertions(+), 2 deletions(-) diff --git a/server/src/services/native-runtime/agent-chat-response-recovery.test.ts b/server/src/services/native-runtime/agent-chat-response-recovery.test.ts index 829cbdbe6f2..7f456a32922 100644 --- a/server/src/services/native-runtime/agent-chat-response-recovery.test.ts +++ b/server/src/services/native-runtime/agent-chat-response-recovery.test.ts @@ -656,6 +656,45 @@ describe.skipIf(!support.supported)("committed Agent Chat reply recovery", () => expect(await comments(f.runId)).toHaveLength(1); expect(await issue(f.issueId)).toMatchObject({ status: "in_progress", conversationState: "active" }); }); + it.each([ + ["failed at setup", "failed", "yielded"], ["running", "running", "yielded"], ["finished", "succeeded", "yielded"], + ["failed at setup", "failed", "done"], ["failed at setup", "failed", "pending approval"], + ] as const)( + "never posts an earlier turn's reply after a later turn of the conversation started (later turn %s, %s)", async (_, status, turn) => { + // The earlier turn ended without a presented reply. A later turn of the + // same conversation then started and no longer holds the execution run. + const f = turn === "pending approval" ? await heldTurn(turn) : await fixture(true, { disposition: turn }); + const [earlier] = await db.select({ createdAt: heartbeatRuns.createdAt }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + const laterAt = new Date(earlier.createdAt.getTime() + 60_000); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status, runtimeMode: "native", + nativeIssueId: f.issueId, responsibleUserId: f.userId, createdAt: laterAt, + ...(status === "failed" ? { errorCode: "setup_failed", finishedAt: laterAt } : { startedAt: laterAt }), + ...(status === "succeeded" ? { finishedAt: laterAt } : {}), + contextSnapshot: { issueId: f.issueId, source: "issue.comment", conversationSessionGeneration: 0 } }); + await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, f.issueId)); + const work = nativeResponsePresentationWork(db); + for (const entry of await work.load(f.input)) await expect(work.check(entry)).resolves.toBeNull(); + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false); + expect(await comments(f.runId)).toEqual([]); + }, + ); + it.each([ + ["a queued wake that has not started", { status: "queued" }, {}], + ["a discarded queued message", { status: "cancelled", errorCode: "queued_comment_discarded" }, {}], + ["a context compaction run", { status: "succeeded" }, { contextCompactionRequestId: "compaction-request" }], + ] as const)("still posts the reply when the only later run is %s", async (_, run, context) => { + const f = await fixture(); + const [earlier] = await db.select({ createdAt: heartbeatRuns.createdAt }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + const laterAt = new Date(earlier.createdAt.getTime() + 60_000); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, ...run, runtimeMode: "native", + responsibleUserId: f.userId, createdAt: laterAt, + ...(run.status === "cancelled" ? { finishedAt: laterAt } : {}), + ...(run.status === "succeeded" ? { startedAt: laterAt, finishedAt: laterAt } : {}), + contextSnapshot: { issueId: f.issueId, source: "issue.comment", conversationSessionGeneration: 0, ...context } }); + await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, f.issueId)); + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(true); + expect(await comments(f.runId)).toEqual([expect.objectContaining({ body: f.reply })]); + }); it("does not duplicate a reply under concurrent recovery", async () => { const f = await fixture(); expect((await Promise.all([recoverCommittedNativeChatResponse(db, f.input), recoverCommittedNativeChatResponse(db, f.input)])).sort()) diff --git a/server/src/services/native-runtime/native-response-presentation-query.ts b/server/src/services/native-runtime/native-response-presentation-query.ts index 2a2157855d9..c68a94aecba 100644 --- a/server/src/services/native-runtime/native-response-presentation-query.ts +++ b/server/src/services/native-runtime/native-response-presentation-query.ts @@ -1,10 +1,25 @@ import { alias, QueryBuilder } from "drizzle-orm/pg-core"; import { nativeEffectiveRunTerminalStateSql } from "./native-accepted-outcome.js"; -import { and, asc, eq, exists, gt, inArray, isNotNull, isNull, ne, notExists, or, sql } from "drizzle-orm"; +import { and, asc, eq, exists, gt, inArray, isNotNull, isNull, ne, notExists, or, sql, type SQL } from "drizzle-orm"; import { chatActions, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, statusDecisions, statusDecisionEffects } from "@paperclipai/db"; import type { NativeResponsePresentationScope } from "../native-response-presentation-notifications.js"; const laterDecisions = alias(statusDecisions, "later_status_decisions"); +export const laterTurns = alias(heartbeatRuns, "later_conversation_turns"); + +/** A later run of the turn's agent on the task that started a new turn. A + * queued wake, a discarded queued message, and context compaction do not. */ +export function laterConversationTurn(issueId: SQL | string) { + return and( + eq(laterTurns.companyId, heartbeatRuns.companyId), + sql`${laterTurns.contextSnapshot}->>'issueId' = ${issueId}`, + gt(laterTurns.createdAt, heartbeatRuns.createdAt), + eq(laterTurns.agentId, heartbeatRuns.agentId), ne(laterTurns.status, "queued"), + or(ne(laterTurns.status, "cancelled"), isNotNull(laterTurns.startedAt)), + sql`not coalesce(jsonb_typeof(${laterTurns.contextSnapshot}->'contextCompactionRequestId') = 'string' + and ${laterTurns.contextSnapshot}->>'contextCompactionRequestId' ~ '[^[:space:]]', false)`, + ); +} export function nativeResponsePresentationCandidates(scope?: NativeResponsePresentationScope, after?: string, runId?: string) { const db = new QueryBuilder(); @@ -54,6 +69,10 @@ export function nativeResponsePresentationCandidates(scope?: NativeResponsePrese sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issues.id}::text`, sql`jsonb_typeof(${heartbeatRuns.contextSnapshot}->'conversationSessionGeneration') = 'number'`, sql`${heartbeatRuns.contextSnapshot}->>'conversationSessionGeneration' = ${issues.conversationSessionGeneration}::text`, + // A later turn that started replaced this one, even after it + // released the execution run (for example, it failed at setup). + notExists(db.select({ id: laterTurns.id }).from(laterTurns) + .where(laterConversationTurn(sql`${issues.id}::text`))), exists(db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and( eq(heartbeatRunEvents.companyId, heartbeatRuns.companyId), eq(heartbeatRunEvents.runId, heartbeatRuns.id), eq(heartbeatRunEvents.agentId, heartbeatRuns.agentId), eq(heartbeatRunEvents.eventType, "item.completed"), diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 8ec0e7acbf2..a150b252acf 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -48,6 +48,7 @@ import { COMPLETION_REVIEW_STAGE_REASON, completionReviewStageEntry } from "../i import { randomUUID } from "node:crypto"; import { preserveNativeWorkspaceExportLease } from "./native-workspace-export-resume.js"; import { and, desc, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; +import { laterConversationTurn, laterTurns } from "./native-response-presentation-query.js"; import type { Db } from "@paperclipai/db"; import { agentWakeupRequests, @@ -998,6 +999,19 @@ async function hasLaterAppliedStatusDecision(db: Db, input: { return Boolean(later); } +// A later turn of the conversation that started replaced this turn, even after +// it released the execution run (for example, it failed at setup). +async function laterConversationTurnStarted(db: Db, run: { + id: string; companyId: string; agentId: string; issueId: string; +}) { + // Compare stored timestamps; a JavaScript Date drops their microseconds. + const [turn] = await db.select({ id: laterTurns.id }).from(laterTurns) + .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId), + eq(heartbeatRuns.agentId, run.agentId))) + .where(laterConversationTurn(run.issueId)).limit(1); + return Boolean(turn); +} + /** Recover only the already accepted answer. Neither issue disposition nor * provider state is repaired here; an unsafe native session stays quarantined. */ export async function repairCommittedNativeChatResponse( @@ -1209,7 +1223,8 @@ async function recoverCommittedNativeChatResponseInScope( && (!issue.executionRunId || issue.executionRunId === run.id) && run.contextSnapshot?.issueId === issue.id && typeof run.contextSnapshot.conversationSessionGeneration === "number" - && run.contextSnapshot.conversationSessionGeneration === issue.conversationSessionGeneration; + && run.contextSnapshot.conversationSessionGeneration === issue.conversationSessionGeneration + && !(await laterConversationTurnStarted(tx, { ...run, issueId: issue.id })); // A deferred ordinary-task review still needs its recorded final reply. // Publishing that reply must not resolve the interaction or the task. // A task woken by an external chat message (for example a GitHub review