mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
fix(native-runtime): recover external-chat task replies skipped by copy-back failure (#22807)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A native agent run ends with an accepted final reply. Paperclip posts that reply on the task. > - The live completion path posts the reply. If a post-result step fails (for example, workspace copy-back), a background presentation worker recovers and posts the accepted reply later. > - The recovery path did not accept a task whose run was woken by an external chat message, such as a GitHub review comment. The worker found the run, recovery refused it, and after 6 attempts the reply was marked failed and lost. > - The live path posts these replies normally, so the recovery rule was stricter than the live rule for no reason. > - This pull request lets recovery post a `done` or `needs_review` reply for a non-conversation task that an external chat woke, with the same authorization and source rules as the live path. > - The benefit is that the agent's real answer reaches the task even when copy-back fails after the result is accepted. ## Linked Issues or Issue Description Refs #22798 **What happened?** On a hosted instance, some native runs finished `succeeded` with a committed result, but their final reply never appeared on the task. The run's `responsePublication` ended with `state: "failed"` and `lastReason: "publication_refused"` after 6 attempts. Every affected run had `source: "chat:github"`, a `done` result, and a `native.post_result_failure` event with `retryReasonCode: "workspace_sync_out_failed"`. Runs on the same task that did not hit the copy-back failure posted their reply on the live path. **Expected behavior** When the live path is skipped after the result is accepted, recovery posts the accepted final reply once, as the live path would. **Steps to reproduce** 1. Wake a native agent on an ordinary (non-conversation) task from an external chat message, so the run context has `source: "chat:..."`. 2. Let the agent report `done` with a final agent message. 3. Make workspace copy-back fail after the result is accepted, so the live completion path does not post the reply. 4. The presentation worker finds the run, but `recoverCommittedNativeChatResponse` returns `false`. The worker records `publication_refused` until it gives up. **Additional context** In `recoverCommittedNativeChatResponseInScope`, `ordinaryTaskReply` required `!isExternalChatPresentationContext(...)`. An external-chat `done` reply then fell through to the `response_wake` branch, which returns `false` for anything other than `yielded`. The candidate query in `native-response-presentation-query.ts` has no such exclusion, so the worker kept selecting a run that recovery always refused. ## What Changed - `native-run-finalizer.ts`: recovery now treats a `done` or `needs_review` reply on a non-conversation task that an external chat woke as an ordinary task reply. - That reply uses the authorization that `resolveChatRunPresentationAuthorizationReason` resolves, as the live path does. GitHub-origin replies resolve to `internal_agent_write`, so they stay a local task comment. Other chat providers keep their normal provider-visible reply. - That reply prefers the final agent message over an existing run comment, as the live path does for external chat (`preferFinalResponseOverExistingComment`). - Conversation tasks keep their current rules. Blocked replies, governed review replies, and `response_wake` replies are unchanged. - `agent-chat-response-recovery.test.ts`: new red/green regression cases for `chat:github` + `done`, `chat:github` + `needs_review`, and `externalChatContinuation: true` + `done`. Each case checks that the reply posts once, the run records `committed_task_response_recovered`, and a second recovery does not post again. ## Verification - Red: before the fix, all 3 new cases failed. `work.check` returned a retry entry (the `publication_refused` path), the same outcome as on the hosted instance. - Green: `npx vitest run src/services/native-runtime/agent-chat-response-recovery.test.ts` passes 67/67. - `npx tsc --noEmit -p server` is clean. - `pnpm verify` selected 2374 of 2737 test files (the finalizer is widely imported) and did not finish in 25 minutes locally. The 2 failures it reached are unrelated load-timing tests. Required CI supplies the broad coverage. - After deploy: confirm on staging that a new external-chat task run with a copy-back failure posts its reply, and that no new `issue.response_publication_failed` activity appears for this pattern. ## Risks - Low risk. The change only widens recovery for non-conversation tasks woken by external chat, and only for `done` and `needs_review` replies that the candidate query already selects. - For a non-GitHub chat provider, the recovered reply goes to the provider, as it does on the live path. Recovery runs only when the run has no recorded presentation decision or comment, so it does not post a second reply. - Runs that already ended as `responsePublication.state: "failed"` before this change stay failed. This change does not backfill them. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, file edits, browser reads of the staging API). ## 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: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9502a12252
commit
496efd201f
3 files changed
+117
-7
No files matched your search
@@ -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<typeof import("../chat-run-publications.js")>();
|
||||
return { ...actual, resolveChatRunPresentationAuthorizationReason: (async (...args: Parameters<typeof actual.resolveChatRunPresentationAuthorizationReason>) =>
|
||||
presentationAuthorization.override ?? actual.resolveChatRunPresentationAuthorizationReason(...args)) as typeof actual.resolveChatRunPresentationAuthorizationReason };
|
||||
});
|
||||
vi.mock("../run-log-store.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../run-log-store.js")>();
|
||||
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<string, unknown>).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);
|
||||
|
||||
@@ -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<string, any>).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 });
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user