From 8ec4b84e1c92ddacea3a43864292db39b7fee269 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 1 Oct 2026 14:43:02 -0500 Subject: [PATCH] fix(chat): resume messages after failed runs without duplicate delivery (#14857) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A user can send a new message after a native run fails. > - The server checks that the old execution has stopped before it starts a fresh turn. > - A failed run can retain a result accepted before checkpoint or cleanup failed. > - The continuation gate treated that saved result as active recovery and held the new message forever. > - This pull request removes that false liveness signal while retaining controller, process, environment, and authorization checks. > - Live staging then exposed a second defect: chat admission created a successor without consuming the original deferred receipt, so completion delivered the message again. > - Consume that exact receipt atomically with admission, while preserving separate turns for later chat messages. ## Linked Issues or Issue Description **What happened?** A new user message stayed in the queue with `controller_settling` after the previous run had reached `terminal_failure`. The old coordinator had no lease owner but still had a `resultId`. Its remote environment had a verified stop receipt. **Expected behavior** Start one fresh turn after execution has stopped and normal admission checks pass. Preserve the failed run and its accepted result as history. **Steps to reproduce** 1. Accept a native result, then fail checkpoint or cleanup and exhaust recovery. 2. Retain the result ID on the terminal failure record and stop the execution environment. 3. Send a new user message. Before this fix, it waits forever for the finished controller. **Paperclip version or commit** Reproduced in a database-backed regression test on `26900655b`. **Deployment mode** Server with a native runner and remote sandbox. Local process stop checks also apply. Related: https://github.com/paperclipai/paperclip/pull/14775. Searched existing PRs for retained-result continuation fixes; no duplicate found. ## What Changed - Remove the retained-result veto for terminal failures. - Keep controller ownership, successor, process, environment cleanup, pending decision, and ordinary admission checks. - Add regressions for retained results, active execution, missing stop evidence, and delayed remote cleanup. - Atomically consume the resumed receipt in agent chat, even though chat does not coalesce other queued messages. - Reproduce completion-time duplicate promotion, race cleanup against periodic recovery, and prove a subsequent chat message keeps its own turn. - Document that a saved result does not make a terminal failure active. - Keep exhausted workspace export on its separate repair path, tested through the production finalizer. ## Verification - Red: retained-result admission failed with `controller_settling` before the original fix. The new chat-specific regression then reproduced duplicate promotion when the first reply finished. - Green: 406 tests across native continuation, workspace-export recovery, and the wake-queue module passed on `cbc531cc0`. - The chat regressions exercise real Postgres transactions, simultaneous recovery callbacks, successful completion, the production queue-drain use case, and repeated drain attempts. A distinct follow-up remains a separate turn. - `pnpm -r typecheck` and `pnpm build` passed on `cbc531cc0`. - The earlier full local test run encountered a timeout and follow-on failure in unchanged AI connection-adoption tests; all 50 tests passed on isolated rerun. That local run was stopped after the full CI test matrix passed on the earlier head. - All 54 CI checks passed on `cbc531cc0` (2 skipped), including the full test matrix and browser shards. One unchanged interaction-route test returned HTTP 500 on its first CI attempt; its full 84-test file passed locally, and the failed shard passed on one targeted rerun. - Greptile reviewed `cbc531cc0`: 5/5, no unresolved findings. - Live staging first verified that the original saved message resumes and receives a successful response; that test exposed the duplicate now covered above. - Deployed exact commit `cbc531cc0410e1ef6e8811c6c5c014c3528351ed` to the affected staging workspace; deployment verification, health, authentication, and startup recovery passed. - Submitted a fresh message through the browser. The agent replied in 39 seconds; server records show exactly one successful run, native phase `committed`, no error, and an empty queue. A later check more than a minute after completion found no duplicate run. ## Risks The change affects admission after native execution failure and consumption of a resumed deferred receipt. A fresh turn must never overlap the prior execution, and consuming one chat receipt must not absorb later messages. Tests retain the controller, process, and remote-stop guards. This change does not migrate data, apply an old result, or reset the old retry budget. ## Model Used OpenAI Codex (GPT-6). The exact runtime model identifier and context window are not exposed in this session. Used reasoning, repository inspection, code execution, database-backed tests, and browser inspection. ## 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 --- doc/execution-semantics.md | 2 + .../explicit-native-continuation.test.ts | 186 ++++++++++++++++++ .../services/explicit-native-continuation.ts | 6 +- server/src/services/heartbeat.ts | 8 +- 4 files changed, 200 insertions(+), 2 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index fb1c1cae671..df10f22d84d 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -482,6 +482,8 @@ The handshake failure code is distinct from a session-identity mismatch. A timeo An explicit recovery action is a typed liveness repair path for a source issue. It is the recovery primitive; the action can be rendered directly on the source issue or backed by a separate recovery issue when the repair needs its own work item. +A terminal native failure can retain a result accepted before checkpoint or cleanup failed. That result is historical evidence, not a live controller. New user input may start a fresh turn after the controller and execution environment have stopped and ordinary admission checks pass. Preserve the failed run, its result, and its recovery budget. Do not commit the old result, infer action outcomes, or replay the failed turn. A message saved while cleanup is pending must be reconsidered after verified cleanup and delivered once. Admission must consume its deferred receipt in the same transaction that creates the new run, including in agent chat, where later messages keep their separate turns. Completing that run must not promote the consumed receipt again. Workspace-export repair retains its separate saved-result recovery path. + A new user message can continue a terminal native run whose process fields were cleared before local stop receipts existed. Admission must verify the exact run, runner, workspace, and provider session in the retained suspended state, with no active provider turn, pending tool call, or undelivered output. Missing or mismatched state keeps the hold. A later recorded process launch also keeps the hold until its stop is verified. Normal assignment, decision, controller, environment cleanup, and active-run gates still apply. The message starts one fresh conversation turn; it does not replay the failed run, reset its recovery budget, or certify unknown action outcomes. The task thread exposes the existing guarded Retry action for failed or timed-out legacy conversation runs. Where the server supports an explicit new attempt after a stopped legacy conversation, the thread must not hide that action solely because the old run still has a recovery-needed projection. Native and process recovery holds, pending decisions, active execution, and other retry gates remain in force. When a gate hides Retry, the thread says the message is preserved instead of promising an unavailable action. This presentation change does not rewrite historical outcomes or certify prior actions. diff --git a/server/src/services/explicit-native-continuation.test.ts b/server/src/services/explicit-native-continuation.test.ts index 3c8c8691370..d7aae395d6f 100644 --- a/server/src/services/explicit-native-continuation.test.ts +++ b/server/src/services/explicit-native-continuation.test.ts @@ -1,3 +1,6 @@ +import { instanceSettingsService } from "./instance-settings.js"; +import { createPostgresWakeQueueAdapter } from "../modules/wake-queue/adapters/postgres.js"; +import { createReleaseIssueExecution } from "../modules/wake-queue/application/use-cases.js"; import * as nativeExecutor from "./native-runtime/native-session-executor.js"; import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js"; import { recordNativeLocalProcessStop, hasNativeLocalProcessStop, PROCESS_START_REQUESTED } from "./native-local-process-stop.js"; @@ -19,6 +22,7 @@ import { buildExecutionContinuation } from "./execution-continuation.js"; import { heartbeatService, persistHeartbeatRunProcessMetadata, type HeartbeatEnvironmentRuntime } from "./heartbeat.js"; import { getExecutionBlocker } from "./execution-blocker.js"; import { createDurableChatWakeupRequest } from "./durable-chat-wakeup.js"; +import { recordNativeFinalizationFailure } from "./native-runtime/native-run-finalizer.js"; const support = await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)("explicit native conversation continuation", () => { let database: Awaited>; @@ -1029,6 +1033,188 @@ const support = await getEmbeddedPostgresTestSupport(); expect(await getExecutionBlocker(db, f.companyId, f.issueId)).not.toBeNull(); } }); + async function seedResultBeforeTerminalFailure(f: Fixture) { + const contractId = randomUUID(), resultId = randomUUID(); + await db.insert(completionContracts).values({ id: contractId, companyId: f.companyId, issueId: f.issueId, + revision: 1, schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", + risk: "standard", completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal", + contractJson: {}, canonicalSha256: contractId, createdByActorType: "system", createdByActorId: "test" }); + await db.update(heartbeatRuns).set({ completionContractId: contractId, errorCode: "provider_transport_failed" }) + .where(eq(heartbeatRuns.id, f.sourceRunId)); + // Dickens returned a result before checkpoint/suspension failed. Accepting + // that result did not commit its disposition or make the failed run live. + await db.insert(nativeRunResults).values({ id: resultId, companyId: f.companyId, issueId: f.issueId, + runId: f.sourceRunId, completionContractId: contractId, serverFingerprint: resultId, + schemaStatus: "accepted", canonicalSha256: resultId, + resultJson: { terminal: { runTerminalState: "succeeded", reportedWorkDisposition: "blocked" } } }); + await db.update(nativeRunFinalizations).set({ resultId, failureCode: "native_session_retry_exhausted" }) + .where(eq(nativeRunFinalizations.runId, f.sourceRunId)); + await db.update(issueRecoveryActions).set({ status: "active", cause: "native_session_retry_exhausted", + evidence: { runId: f.sourceRunId, coordinatorAttempt: 3, sourceFailureCode: "provider_transport_failed" }, + }).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); + return resultId; + } + it.each(["stopped", "controller", "successor", "still_committing", "live_process", "identity_missing"])( + "continues after terminal failure with a retained result only when execution stopped (%s)", async scenario => { + const f = await seed(), resultId = await seedResultBeforeTerminalFailure(f); + await db.update(nativeRunFinalizations).set({ + phase: scenario === "still_committing" ? "result_accepted" : "terminal_failure", + leaseOwner: scenario === "controller" ? "active-controller" : null, + failureDetail: scenario === "successor" ? { successorRunId: randomUUID() } : null, + }).where(eq(nativeRunFinalizations.runId, f.sourceRunId)); + if (scenario === "live_process" || scenario === "identity_missing") { + await db.update(heartbeatRuns).set({ processPid: scenario === "live_process" ? process.pid : null }) + .where(eq(heartbeatRuns.id, f.sourceRunId)); + } + const result = await admit(f); + expect(result).toEqual(scenario === "stopped" ? { previousRunId: f.sourceRunId, commentId: f.commentId } : null); + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toEqual(scenario === "stopped" ? null : expect.anything()); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.sourceRunId)); + expect(coordinator).toMatchObject({ resultId, attempt: 3, + phase: scenario === "still_committing" ? "result_accepted" : "terminal_failure" }); + const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.sourceRunId)); + expect(source).toMatchObject({ status: "failed", errorCode: "provider_transport_failed" }); + const [savedResult] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, resultId)); + expect(savedResult.resultJson).toEqual({ terminal: { runTerminalState: "succeeded", reportedWorkDisposition: "blocked" } }); + }); + it.each(["task", "chat", "chat_with_next_message"])("delivers a queued %s message exactly once after a retained-result failure and delayed remote stop", async kind => { + const f = await seed(), resultId = await seedResultBeforeTerminalFailure(f); + const settings = instanceSettingsService(db); + const experimental = await settings.getExperimental(); + await settings.updateExperimental({ enableAgentChat: true }); + try { + if (kind !== "task") await db.update(issues).set({ conversationAgentId: f.agentId, + conversationUserId: "board", conversationState: "active", + }).where(eq(issues.id, f.issueId)); + // Occupy the agent slot so admission is real without launching a provider. + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" }); + const lease = { id: randomUUID(), companyId: f.companyId, heartbeatRunId: f.sourceRunId, + provider: "daytona", providerLeaseId: "dickens-stopped-sandbox" }; + await db.insert(environmentLeases).values({ ...lease, status: "active", leasePolicy: "ephemeral" }); + const heartbeat = heartbeatService(db); + const wake = await heartbeat.wakeup(f.agentId, { + source: "on_demand", triggerDetail: "manual", reason: "issue_commented", + requestedByActorType: "user", requestedByActorId: "board", + payload: { issueId: f.issueId, commentId: f.commentId }, + contextSnapshot: { source: "issue.comment", issueId: f.issueId, wakeCommentId: f.commentId }, + }); + expect(wake).toBeNull(); + const [waiting] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId)); + expect(waiting).toMatchObject({ status: "deferred_issue_execution", runId: null, + payload: { executionWait: { reason: "remote_cleanup" } } }); + let nextCommentId: string | null = null; + let nextWakeId: string | null = null; + if (kind === "chat_with_next_message") { + nextCommentId = randomUUID(); + nextWakeId = randomUUID(); + await db.insert(issueComments).values({ id: nextCommentId, companyId: f.companyId, issueId: f.issueId, + authorType: "user", authorUserId: "board", body: "A separate follow-up." }); + await db.insert(agentWakeupRequests).values({ id: nextWakeId, companyId: f.companyId, agentId: f.agentId, + source: "on_demand", triggerDetail: "manual", reason: "issue_commented", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: "board", payload: { + issueId: f.issueId, commentId: nextCommentId, + _paperclipWakeContext: { source: "issue.comment", issueId: f.issueId, wakeCommentId: nextCommentId, wakeReason: "issue_commented" }, + }, + }); + } + const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.sourceRunId)); + await heartbeat.resumeRemoteStopComments(source); + expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "queued")))).toHaveLength(0); + await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success", + metadata: { remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }) }, + }).where(eq(environmentLeases.id, lease.id)); + // Cleanup and periodic recovery can race to dispatch the same receipt. + await Promise.all([heartbeat.resumeRemoteStopComments(source), heartbeat.resumeRemoteStopComments(source)]); + const successors = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "queued"))); + expect(successors).toHaveLength(1); + expect(successors[0].contextSnapshot).toMatchObject({ forceFreshSession: true, previousRunId: f.sourceRunId, wakeCommentId: f.commentId }); + if (nextWakeId) { + expect(successors[0].contextSnapshot?.wakeCommentIds).not.toContain(nextCommentId); + const [nextWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, nextWakeId)); + expect(nextWake.status).toBe("deferred_issue_execution"); + } + // Complete the admitted turn and run the same transactional queue drain + // used by finalization. A stale receipt must not create another turn. + await db.update(heartbeatRuns).set({ status: "succeeded", startedAt: new Date(), finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, successors[0].id)); + await db.update(issues).set({ executionRunId: successors[0].id, status: "in_progress" }) + .where(eq(issues.id, f.issueId)); + const release = createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { + resolveResponsibleUserId: async () => "board", + getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }), + resolveSessionBeforeForWakeup: async () => null, + }), + recovery: { escalateStrandedAssignedIssue: async () => {}, escalateStrandedRecoveryIssueInPlace: async () => {} }, + }); + const drained = await release({ companyId: f.companyId, runId: successors[0].id, now: new Date(), suppressImmediateRecovery: true }); + expect(drained.outcome.kind).toBe(nextWakeId ? "promoted" : "released"); + await heartbeat.resumeRemoteStopComments(source); + await release({ companyId: f.companyId, runId: successors[0].id, now: new Date(), suppressImmediateRecovery: true }); + const afterDrain = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "queued"))); + expect(afterDrain).toHaveLength(nextWakeId ? 1 : 0); + if (nextWakeId) { + expect(afterDrain[0]).toMatchObject({ wakeupRequestId: nextWakeId, contextSnapshot: { wakeCommentId: nextCommentId } }); + expect(afterDrain[0].contextSnapshot?.wakeCommentIds ?? []).not.toContain(f.commentId); + } + const [delivered] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, waiting.id)); + expect(delivered).toMatchObject({ status: "coalesced", runId: successors[0].id }); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.sourceRunId)); + expect(coordinator).toMatchObject({ phase: "terminal_failure", resultId, attempt: 3 }); + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull(); + } finally { + await settings.updateExperimental({ enableAgentChat: experimental.enableAgentChat }); + } + }); + it("keeps exhausted workspace export on its own repair path after the sandbox stops", async () => { + const f = await seed(), resultId = await seedResultBeforeTerminalFailure(f); + await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); + await db.update(nativeRunFinalizations).set({ phase: "result_accepted", attempt: 1, failureCode: null, failureDetail: null }) + .where(eq(nativeRunFinalizations.runId, f.sourceRunId)); + await db.update(heartbeatRuns).set({ status: "running", nativePhase: "result_accepted", finishedAt: null }) + .where(eq(heartbeatRuns.id, f.sourceRunId)); + const lease = { id: randomUUID(), companyId: f.companyId, heartbeatRunId: f.sourceRunId, + provider: "daytona", providerLeaseId: "pending-workspace-export" }; + await db.insert(environmentLeases).values({ ...lease, status: "active", leasePolicy: "ephemeral" }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.sourceRunId)); + await db.update(heartbeatRuns).set({ runnerProfileJson: { ...run.runnerProfileJson, + nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v1", state: "prepared", + descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null, + workspaceId: randomUUID(), leaseId: lease.id, providerLeaseId: lease.providerLeaseId, + remoteCwd: "/work", resourceDisposition: "destroy" }, + } }).where(eq(heartbeatRuns.id, f.sourceRunId)); + for (let attempt = 0; attempt < 3; attempt++) { + await recordNativeFinalizationFailure({ db, runId: f.sourceRunId, + error: new Error("native_workspace_sync_out_failed"), failureScope: "workspace", projectRunStatus: true }); + } + const [retainedLease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)); + expect(retainedLease).toMatchObject({ status: "pending_cleanup", metadata: { + nativeWorkspaceExportResume: { runId: f.sourceRunId, leaseId: lease.id, resultId }, + } }); + await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success", + metadata: { ...retainedLease.metadata, + remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }) }, + }).where(eq(environmentLeases.id, lease.id)); + const exportState = () => Promise.all([ + db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.sourceRunId)), + db.select().from(nativeRunResults).where(eq(nativeRunResults.id, resultId)), + db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)), + db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)), + ]); + const before = await exportState(); + // Export repair is intentionally excluded before conversation stop checks. + // A new message must leave the accepted result, retention, and repair intact. + await db.update(issueComments).set({ createdAt: new Date(Date.now() + 1000) }).where(eq(issueComments.id, f.commentId)); + expect(await admit(f)).toBeNull(); + expect(await exportState()).toEqual(before); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.sourceRunId)); + expect(coordinator).toMatchObject({ phase: "terminal_failure", resultId, attempt: 1, + failureCode: "native_workspace_sync_out_retry_exhausted", failureDetail: { workspaceFinalizeAttempt: 3 } }); + const [action] = await db.select().from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.sourceIssueId, f.issueId), eq(issueRecoveryActions.cause, "native_workspace_sync_out_retry_exhausted"), + )); + expect(action).toMatchObject({ status: "active", cause: "native_workspace_sync_out_retry_exhausted" }); + }); it.each(["linked", "revoked", "unlinked", "wrong_author"])( "admits a fresh Slack message after failure only with current linked-user authority (%s)", async scenario => { const f = await seed(); diff --git a/server/src/services/explicit-native-continuation.ts b/server/src/services/explicit-native-continuation.ts index 5c6c0349d17..2eafaf4d3e3 100644 --- a/server/src/services/explicit-native-continuation.ts +++ b/server/src/services/explicit-native-continuation.ts @@ -212,9 +212,13 @@ export async function admitExplicitNativeContinuation(input: { sql`${nativeRunResults.resultJson}->'terminal'->>'runTerminalState' = 'failed'`, )).limit(1) : []; + // A terminal failure may retain a result accepted before checkpoint or + // cleanup failed. That immutable result is history, not an active commit. + // Keep it intact and require the same controller/process/lease stop proofs + // before admitting new user input; never apply or replay the old result. if (!cancelledStartup && coordinator && ( (coordinator.phase !== "terminal_failure" && !committedFailure) || coordinator.leaseOwner || - (coordinator.resultId && !committedFailure) || coordinator.failureDetail?.successorRunId)) return blocked("controller_settling", + coordinator.failureDetail?.successorRunId)) return blocked("controller_settling", run.status === "cancelled" && !coordinator.leaseOwner ? "The cancelled run still needs verified cleanup. Your message is saved. Inspect the run and its environment for details." : "Waiting for the previous run to finish recovery. Your message will start automatically."); diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 57f0c5fa5b3..14b8ed35ea4 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -28484,8 +28484,12 @@ export function heartbeatService( or(isNull(heartbeatRuns.nativeIssueId), eq(heartbeatRuns.nativeIssueId, issue.id)), )).then(rows => rows[0] ?? null) : null; + const canCoalesceComments = !isConversation(issue) && opts.allowRunCoalescing !== false; + // A resumed receipt already passed admission under this issue lock. + // Consume it with its successor even when chat keeps other messages + // in separate turns, or finalization will deliver it a second time. const pendingComments = - !isConversation(issue) && opts.allowRunCoalescing !== false && + (executionWaitRequestId || canCoalesceComments) && !(await getExecutionBlocker(tx as unknown as Db, issue.companyId, issue.id)) ? await tx .select() @@ -28496,11 +28500,13 @@ export function heartbeatService( inArray(agentWakeupRequests.agentId, handoffSource ? [agentId, handoffSource.agentId] : [agentId]), eq(agentWakeupRequests.status, "deferred_issue_execution"), sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`, + canCoalesceComments ? undefined : eq(agentWakeupRequests.id, executionWaitRequestId!), ), ) .orderBy(asc(agentWakeupRequests.requestedAt)) : []; const adoptedComments = pendingComments.filter((wake) => { + if (wake.id === executionWaitRequestId) return true; if (wake.id === opts.queuedCommentInterruptId || wake.id === opts.queuedCommentRequestId) return true; const deferredPayload = parseObject(wake.payload); const deferredContext = parseObject(