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 6057de9f613..829cbdbe6f2 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 @@ -14,8 +14,15 @@ import { instanceSettingsService } from "../instance-settings.js"; import { issueService } from "../issues.js"; import * as nativeResponseNotifications from "../native-response-presentation-notifications.js"; import { compactRunLogChunk } from "../heartbeat/run-log.js"; +import { CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON } from "../heartbeat-run-summary.js"; const runLogReads = vi.hoisted(() => [] as unknown[]); +const presentationAuthorization = vi.hoisted(() => ({ override: null as string | null })); +vi.mock("../chat-run-publications.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, resolveChatRunPresentationAuthorizationReason: (async (...args: Parameters) => + presentationAuthorization.override ?? actual.resolveChatRunPresentationAuthorizationReason(...args)) as typeof actual.resolveChatRunPresentationAuthorizationReason }; +}); vi.mock("../run-log-store.js", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, getRunLogStore: () => { @@ -703,6 +710,78 @@ describe.skipIf(!support.supported)("committed Agent Chat reply recovery", () => expect(await comments(f.runId)).toEqual([expect.objectContaining({ body: f.reply })]); expect((await issue(f.issueId)).conversationAgentId).toBeNull(); }); + it.each([ + ["done", { source: "chat:github" }], + ["needs_review", { source: "chat:github" }], + ["done", { source: "automation", externalChatContinuation: true }], + ] as const)("publishes an external-chat task's %s reply when copy-back failure skipped the live path (%j)", async (disposition, context) => { + // A run woken by an external chat message reaches its accepted final reply, + // then workspace copy-back fails, so the live completion path never posts + // it. Presentation recovery must still put that reply on the task. + const f = await fixture(false, { disposition }); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, ...context } }) + .where(eq(heartbeatRuns.id, f.runId)); + const work = nativeResponsePresentationWork(db), entries = await work.load(f.input); + expect(entries).toEqual([expect.objectContaining({ id: f.runId })]); + await expect(work.check(entries[0])).resolves.toBeNull(); + expect(await comments(f.runId)).toEqual([expect.objectContaining({ body: f.reply, createdByRunId: f.runId })]); + const [run] = await db.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.resultJson).toMatchObject({ presentationDecision: { reasonCodes: expect.arrayContaining(["committed_task_response_recovered"]) } }); + expect((run.resultJson as Record).responsePublication).not.toMatchObject({ state: "failed" }); + expect(await work.load(f.input)).toEqual([]); + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false); + expect(await comments(f.runId)).toHaveLength(1); + }); + it("posts a non-GitHub external-chat task reply once with the provider presentation authorization", async () => { + const f = await fixture(false); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, source: "chat:slack" } }) + .where(eq(heartbeatRuns.id, f.runId)); + presentationAuthorization.override = CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON; + try { + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(true); + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false); + } finally { presentationAuthorization.override = null; } + expect(await comments(f.runId)).toEqual([expect.objectContaining({ body: f.reply, + metadata: expect.objectContaining({ authorizationReason: CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON }) })]); + }); + it.each([false, true])("reuses an external-chat task reply the live path saved without recording it (deleted=%s)", async deleted => { + const f = await fixture(false); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, source: "chat:github" } }) + .where(eq(heartbeatRuns.id, f.runId)); + const [saved] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorAgentId: f.agentId, + createdByRunId: f.runId, body: f.reply, ...(deleted ? { deletedAt: new Date("2020-01-01T00:03:00Z") } : {}) }).returning(); + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false); + expect(await comments(f.runId)).toEqual([saved]); + const [run] = await db.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.resultJson).toMatchObject({ presentationDecision: { commentAction: "reuse", commentId: saved.id } }); + expect(await nativeResponsePresentationWork(db).load(f.input)).toEqual([]); + }); + it.each([false, true])("posts an external-chat task's final answer after an earlier progress comment (deleted=%s)", async deleted => { + const f = await fixture(false); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, source: "chat:github" } }) + .where(eq(heartbeatRuns.id, f.runId)); + const [progress] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorAgentId: f.agentId, + createdByRunId: f.runId, body: "Looking into the review comment now.", + ...(deleted ? { deletedAt: new Date("2020-01-01T00:03:00Z") } : {}) }).returning(); + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(true); + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false); + const saved = await comments(f.runId); + expect(saved).toHaveLength(2); + expect(saved).toEqual(expect.arrayContaining([progress, expect.objectContaining({ body: f.reply, deletedAt: null })])); + }); + it("reuses the summary the live path saved when the final message is a structured result", async () => { + const summary = "A completed hire, with its final message preserved separately."; + const reply = JSON.stringify({ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary }); + const f = await fixture(false, { reply }); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, source: "chat:github" } }) + .where(eq(heartbeatRuns.id, f.runId)); + const [saved] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorAgentId: f.agentId, + createdByRunId: f.runId, body: summary }).returning(); + await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false); + expect(await comments(f.runId)).toEqual([saved]); + const [run] = await db.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.resultJson).toMatchObject({ presentationDecision: { commentAction: "reuse", commentId: saved.id } }); + }); it("recovers a deferred review reply once without resolving the review or rerunning work", async () => { const f = await fixture(false, { disposition: "needs_review" }); const before = await issue(f.issueId); 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 d2cd9016ad0..1706720ca4e 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 @@ -137,6 +137,20 @@ describe.skipIf(!support.supported)("blocked task reply after a retried workspac expect(await comments(f.issueId)).toHaveLength(1); }); + it("reuses a channel task's blocked reply that the live path saved without recording it", async () => { + const f = await blockedRun({ source: "chat:slack", finalReply: true }); + await retryCopyBack(f.runId, { skipNativeResponsePresentation: true }); + const [saved] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorAgentId: f.agentId, + createdByRunId: f.runId, body: finalReply }).returning(); + const work = nativeResponsePresentationWork(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 comments(f.issueId)).toEqual([saved]); + expect(((await run(f.runId)).resultJson as Record).presentationDecision) + .toMatchObject({ commentAction: "reuse", commentId: saved.id }); + }); + it("does not present a stale blocker after a later status decision or once the task moved on", async () => { const f = await blockedRun(); await retryCopyBack(f.runId, { skipNativeResponsePresentation: true }); diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 90b200f63a1..dc7f0cca8cb 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -1210,8 +1210,12 @@ async function recoverCommittedNativeChatResponseInScope( && run.contextSnapshot.conversationSessionGeneration === issue.conversationSessionGeneration; // A deferred ordinary-task review still needs its recorded final reply. // Publishing that reply must not resolve the interaction or the task. - const ordinaryTaskReply = (!conversation || currentConversation) && - !isExternalChatPresentationContext(run.contextSnapshot) && + // A task woken by an external chat message (for example a GitHub review + // comment) gets the same final reply as on the live completion path, + // which a post-result failure such as copy-back can skip. + const externalChatContext = isExternalChatPresentationContext(run.contextSnapshot); + const externalChatTaskReply = !conversation && externalChatContext; + const ordinaryTaskReply = (!conversation || (currentConversation && !externalChatContext)) && ((result.reportedWorkDisposition === "done" && terminal.reportedWorkDisposition === "done") || (!conversation && result.reportedWorkDisposition === "needs_review" && terminal.reportedWorkDisposition === "needs_review") || // A conversation turn can yield while an approval, an execution @@ -1223,9 +1227,10 @@ async function recoverCommittedNativeChatResponseInScope( terminal.turnTerminalState === "completed" && (ordinaryTaskReply || blockedTaskReply); const replyAuthorization = taskReplyEligible ? await resolveChatRunPresentationAuthorizationReason(tx, input) : null; - const externalChatReply = blockedTaskReply && + const externalChatBlockedReply = blockedTaskReply && isExternalChatPresentationContext(run.contextSnapshot, replyAuthorization === CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON); - if (taskReplyEligible && replyAuthorization && (blockedTaskReply || replyAuthorization === "internal_agent_write")) { + if (taskReplyEligible && replyAuthorization && + (blockedTaskReply || externalChatTaskReply || replyAuthorization === "internal_agent_write")) { const rows = await tx.select({ seq: heartbeatRunEvents.seq, payload: heartbeatRunEvents.payload }) .from(heartbeatRunEvents).where(and( eq(heartbeatRunEvents.companyId, input.companyId), @@ -1259,7 +1264,8 @@ async function recoverCommittedNativeChatResponseInScope( eq(issueComments.issueId, input.issueId), eq(issueComments.createdByRunId, run.id), )).orderBy(desc(issueComments.createdAt), desc(issueComments.id)); - const resolved = resolveHeartbeatRunResponse({ + const existingComment = findHeartbeatRunCompletionComment(comments, run.resultJson); + const responseInput = { resultJson: { ...record(run.resultJson), nativeResult: result }, nativeConversationFinalResponse: conversation, // The same answered rule as live run completion. @@ -1267,9 +1273,20 @@ async function recoverCommittedNativeChatResponseInScope( db: tx, ...input, finalizationPhase: coordinator.phase, finalizationReasonCode: decision.reasonCode, }), interactionOwnsResponse: conversation && await hasChatRunOwnedProviderInteraction(tx, input), - existingComment: findHeartbeatRunCompletionComment(comments, run.resultJson), + existingComment, finalAgentMessage, - preferFinalResponseOverExistingComment: externalChatReply, + }; + // An external-chat reply presents its final answer, as on the live + // path, over an earlier run comment such as a progress note. A saved + // copy of the text that answer resolves to, including a deleted one, is + // reused instead, so recovery never posts the same reply twice. + const preferredText = externalChatTaskReply || externalChatBlockedReply + ? resolveHeartbeatRunResponse({ ...responseInput, existingComment: null, preferFinalResponseOverExistingComment: true }).text + : null; + const resolved = resolveHeartbeatRunResponse({ + ...responseInput, + preferFinalResponseOverExistingComment: Boolean(preferredText) && + existingComment?.body.trim() !== preferredText?.trim(), }); if (resolved.decision.commentAction === "reuse" && typeof resolved.decision.commentId === "string") { // The reply is already on the task (for example, the live path wrote