mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 13:01:05 +01:00
fix(runtime): post the agent's blocker reply when a retried finalization blocks the task (#21169)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native runtime finalizes an agent's run, applies the agent's status decision to the task, and posts the agent's reply as a task comment > - When the first workspace copy-back fails, or the run reconnects, a background retry commits the result instead of the live heartbeat > - That retry path applies the "blocked" status but never posts the agent's reply, so the task turns blocked with no visible reason > - The retry path already shares one recovery step for replies, but that step accepted only "done", "needs review" and conversation replies > - This pull request lets the shared recovery step present a blocked task's reply, so the retry path and the normal path converge on one presentation step > - The benefit is that a blocked task always tells the user why, exactly once ## Linked Issues or Issue Description **What happened?** An agent reports that it is blocked. The task moves to "blocked". No comment from the agent explains why. This happens when the run finishes through a retried workspace copy-back or a reconnect loop instead of the live heartbeat. The run succeeds and its result has the agent's blocker summary, but the run has no presentation decision and the task has no reply. On a staging company, 58 of the 150 most recent agent-blocked tasks for one agent had no agent comment. **Expected behavior** Every finalization path that applies an agent's status decision also presents the agent's reply. A blocked task always shows the agent's explanation once. The status decision does not post a second copy. **Steps to reproduce** 1. Run a native agent on a task. The agent reports `blocked` with a summary and a task-wide blocker. 2. Make the first workspace copy-back fail (`native_workspace_sync_out_failed`), so the heartbeat leaves finalization to the retry. 3. Let the retry finish the copy-back and commit the result. 4. The task is blocked and the run succeeded, but the task has no agent comment. **Paperclip version or commit** `master` atb8207c4ea9**Deployment mode** Hosted (staging cloud). The defect is in server finalization, so it applies to all deployment modes that use the native runtime. **Agent adapter(s) involved** Native runtime (`paperclip_runner`), seen with the Codex-based agent. The defect is adapter-independent. ## What Changed - The response presentation recovery step (`recoverCommittedNativeChatResponse`) now presents a non-conversation task's reply when the agent reported `blocked` and the task is still blocked. - For a blocked reply, recovery uses the agent's final message when one exists. Otherwise it uses the accepted result summary, the same as the live completion path. - A blocked reply on a channel task (an external chat run) uses the same rule as live run completion. Recovery resolves the chat publication authorization, prefers the final response, and posts with that authorization. The worker does not refuse these runs, so it does not record a false publication failure. - The presentation work query now finds these runs, so the background worker also presents them and the bounded publication retry applies to them. - A blocker reply is not presented when the task is no longer blocked or when a later status decision was applied. This keeps old blockers from posting stale comments. - Presentation stays idempotent: the step records `presentationDecision`, reuses a reply that the run already posted, and never posts twice. - Existing affected tasks need no separate backfill. The presentation worker loads all pending candidates at startup, so each task that is still blocked gets its saved reply once after deploy. ## Verification - Red/green test: `server/src/services/native-runtime/native-blocked-reply-recovery.test.ts`. It completes a blocked native run, fails the first copy-back with `native_workspace_sync_out_failed`, then commits the retry with `finalizeNativeRun`. - Red on `master`: the retry-path tests fail (no comment is posted, and the worker finds no candidate). The channel task test also fails on the first PR revision (5eb8cdab95). - Green with this change: 4/4 pass. The tests check that the blocker summary is posted once, that the final reply is preferred, that a repeated retry and a repeated worker check do not double-post, and that a stale blocker is not posted. - `cd server && npx vitest run src/services/native-runtime/native-blocked-reply-recovery.test.ts src/services/native-runtime/native-response-publication-retry.test.ts src/services/native-runtime/agent-chat-response-recovery.test.ts src/__tests__/idle-native-finalization.test.ts src/services/presentation-ownership-read.test.ts src/services/chat-monitor-continuation.test.ts` passes (172 tests). - `cd server && npx tsc --noEmit -p .` passes. ## Risks - After deploy, tasks that are still blocked from earlier affected runs get the agent's saved reply once. This is the intended backfill. Tasks that moved on are skipped. - The candidate query has one more branch with a `NOT EXISTS` on `status_decisions`, keyed by the existing `(company_id, issue_id, decision_version)` unique index. The cost is low. - No schema change and no migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, file edits, browser reads of 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
f1d25aca14
commit
82c6810107
3 files changed
+184
-14
No files matched your search
@@ -0,0 +1,142 @@
|
||||
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";
|
||||
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";
|
||||
|
||||
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_NATIVE_BLOCKED_REPLY_TEST_DATABASE_URL");
|
||||
const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
describe.skipIf(!support.supported)("blocked task reply after a retried workspace copy-back", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
||||
let db: Db;
|
||||
beforeAll(async () => {
|
||||
if (!external) database = await startEmbeddedPostgresTestDatabase("native-blocked-reply-");
|
||||
db = createDb(external ?? database!.connectionString);
|
||||
}, 60_000);
|
||||
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
|
||||
|
||||
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 } = {}) {
|
||||
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) });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Uploader", adapterType: "paperclip_runner" });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Upload the build", status: "in_progress", assigneeAgentId: agentId });
|
||||
const [contract] = await db.insert(completionContracts).values({ companyId, issueId, revision: 1,
|
||||
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", risk: "standard", completionAuthority: "server_arbiter",
|
||||
incompleteCriteriaPolicy: "preserve_non_terminal", contractJson: { revision: "test", objective: "Upload the build", criteria: [] },
|
||||
canonicalSha256: `blocked-${runId}`, createdByActorType: "system", createdByActorId: "test" }).returning();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId, nativeSessionId: sessionId,
|
||||
runnerInstanceId: runnerId, completionContractId: contract.id, completionContractSha256: contract.canonicalSha256,
|
||||
status: "running", runtimeMode: "native", contextSnapshot: { issueId, source: options.source ?? "assignment" } });
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
||||
const port = new NativeRunCoordinatorStore(db, { companyId, issueId, runId, agentId, normalizedSessionId: sessionId,
|
||||
runnerSourceInstanceId: runnerId, completionContractId: contract.id, completionContractSha256: contract.canonicalSha256,
|
||||
completionContractRevision: "test", completionContractCriterionIds: [] });
|
||||
await port.completeRun({ result: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "blocked", summary,
|
||||
blocker: { reasonCode: "access", owner: { kind: "user", name: "Board operator" }, unblockAction: "Re-issue the deploy key",
|
||||
scope: "task_wide" },
|
||||
completionClaim: { contractRevision: "test", objectiveSatisfied: false, criteria: [], remainingWork: [] },
|
||||
evidence: [], verification: [], attentionRequests: [], artifacts: [] },
|
||||
terminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded", turnTerminalState: "completed",
|
||||
reportedWorkDisposition: "blocked" },
|
||||
turnId: "upload-turn" });
|
||||
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 } } } });
|
||||
await recordNativeFinalizationFailure({ db, runId, error: new Error("native_workspace_sync_out_failed"),
|
||||
failureScope: "workspace", projectRunStatus: true });
|
||||
return { companyId, agentId, issueId, runId };
|
||||
}
|
||||
const retryCopyBack = (runId: string, options: { skipNativeResponsePresentation?: boolean } = {}) =>
|
||||
finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true, preserveProviderAttempt: true,
|
||||
...options });
|
||||
const comments = (issueId: string) => db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
|
||||
const run = async (runId: string) => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0];
|
||||
const issue = async (issueId: string) => (await db.select().from(issues).where(eq(issues.id, issueId)))[0];
|
||||
|
||||
it("posts the blocker summary once when the retried copy-back commits the blocked status", async () => {
|
||||
const f = await blockedRun();
|
||||
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0].phase)
|
||||
.toBe("retryable_failure");
|
||||
await retryCopyBack(f.runId);
|
||||
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0].phase)
|
||||
.toBe("committed");
|
||||
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: summary, authorAgentId: f.agentId,
|
||||
createdByRunId: f.runId })]);
|
||||
expect(((await run(f.runId)).resultJson as Record<string, any>).presentationDecision).toMatchObject({
|
||||
commentAction: "create", chosenSource: "semantic_result_summary", commentId: expect.any(String) });
|
||||
|
||||
expect(await nativeResponsePresentationWork(db).load({ companyId: f.companyId, issueId: f.issueId })).toEqual([]);
|
||||
await retryCopyBack(f.runId);
|
||||
expect(await comments(f.issueId)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("presents the agent's final reply from the background worker exactly once", async () => {
|
||||
const f = await blockedRun({ finalReply: true });
|
||||
await retryCopyBack(f.runId, { skipNativeResponsePresentation: true });
|
||||
expect((await issue(f.issueId)).status).toBe("blocked");
|
||||
expect(await comments(f.issueId)).toEqual([]);
|
||||
|
||||
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([expect.objectContaining({ body: finalReply, createdByRunId: f.runId })]);
|
||||
expect(await work.load({ companyId: f.companyId, issueId: f.issueId })).toEqual([]);
|
||||
await expect(work.check(entry)).resolves.toBeNull();
|
||||
expect(await comments(f.issueId)).toHaveLength(1);
|
||||
});
|
||||
|
||||
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 });
|
||||
expect((await issue(f.issueId)).status).toBe("blocked");
|
||||
|
||||
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([expect.objectContaining({ body: summary, createdByRunId: f.runId })]);
|
||||
const result = (await run(f.runId)).resultJson as Record<string, any>;
|
||||
expect(result.presentationDecision).toMatchObject({ commentId: expect.any(String) });
|
||||
expect(result.responsePublication?.state).not.toBe("failed");
|
||||
expect(await work.load({ companyId: f.companyId, issueId: f.issueId })).toEqual([]);
|
||||
await retryCopyBack(f.runId);
|
||||
expect(await comments(f.issueId)).toHaveLength(1);
|
||||
});
|
||||
|
||||
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 });
|
||||
const work = nativeResponsePresentationWork(db);
|
||||
expect(await work.load({ companyId: f.companyId, issueId: f.issueId })).toHaveLength(1);
|
||||
|
||||
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId));
|
||||
const [assessment] = await db.select().from(workAssessments).where(eq(workAssessments.id, decision.assessmentId));
|
||||
const [laterAssessment] = await db.insert(workAssessments).values({ ...assessment, id: randomUUID(),
|
||||
inputDigest: `${assessment.inputDigest}-later` }).returning();
|
||||
const [later] = await db.insert(statusDecisions).values({ ...decision, id: randomUUID(), assessmentId: laterAssessment.id,
|
||||
decisionVersion: decision.decisionVersion + 1, decisionDigest: `${decision.decisionDigest}-later` }).returning();
|
||||
expect(await work.load({ companyId: f.companyId, issueId: f.issueId })).toEqual([]);
|
||||
await retryCopyBack(f.runId);
|
||||
expect(await comments(f.issueId)).toEqual([]);
|
||||
|
||||
await db.delete(statusDecisions).where(eq(statusDecisions.id, later.id));
|
||||
await db.delete(workAssessments).where(eq(workAssessments.id, laterAssessment.id));
|
||||
await db.update(issues).set({ status: "todo" }).where(eq(issues.id, f.issueId));
|
||||
expect(await work.load({ companyId: f.companyId, issueId: f.issueId })).toEqual([]);
|
||||
await retryCopyBack(f.runId);
|
||||
expect(await comments(f.issueId)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { QueryBuilder } from "drizzle-orm/pg-core";
|
||||
import { alias, QueryBuilder } from "drizzle-orm/pg-core";
|
||||
import { and, asc, eq, exists, gt, inArray, isNotNull, isNull, ne, notExists, or, 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 function nativeResponsePresentationCandidates(scope?: NativeResponsePresentationScope, after?: string, runId?: string) {
|
||||
const db = new QueryBuilder();
|
||||
return db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId,
|
||||
@@ -11,7 +13,7 @@ export function nativeResponsePresentationCandidates(scope?: NativeResponsePrese
|
||||
// Durable publication retry schedule for an ordinary final task reply.
|
||||
publicationNextAttemptAt: sql<string | null>`${heartbeatRuns.resultJson} #>> '{responsePublication,nextAttemptAt}'`.as("publication_next_attempt_at"),
|
||||
// Agent Chat conversations keep their completion outbox as the bounded owner.
|
||||
taskReply: sql<boolean>`coalesce(${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' in ('done', 'needs_review')
|
||||
taskReply: sql<boolean>`coalesce(${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' in ('done', 'needs_review', 'blocked')
|
||||
and (coalesce(${issues.conversationAgentId}::text, '') = '' or coalesce(${issues.conversationUserId}, '') = ''), false)`.as("task_reply"),
|
||||
}).from(nativeRunFinalizations)
|
||||
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, nativeRunFinalizations.runId),
|
||||
@@ -67,6 +69,14 @@ export function nativeResponsePresentationCandidates(scope?: NativeResponsePrese
|
||||
and(sql`(coalesce(${issues.conversationAgentId}::text, '') = '' or coalesce(${issues.conversationUserId}, '') = '')`,
|
||||
sql`${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' = 'needs_review'`,
|
||||
sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'needs_review'`),
|
||||
and(sql`(coalesce(${issues.conversationAgentId}::text, '') = '' or coalesce(${issues.conversationUserId}, '') = '')`,
|
||||
sql`${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' = 'blocked'`,
|
||||
sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'blocked'`,
|
||||
eq(issues.status, "blocked"),
|
||||
notExists(db.select({ id: laterDecisions.id }).from(laterDecisions).where(and(
|
||||
eq(laterDecisions.companyId, statusDecisions.companyId), eq(laterDecisions.issueId, statusDecisions.issueId),
|
||||
eq(laterDecisions.applicationState, "applied"),
|
||||
gt(laterDecisions.decisionVersion, statusDecisions.decisionVersion))))),
|
||||
and(sql`(coalesce(${issues.conversationAgentId}::text, '') <> '' and coalesce(${issues.conversationUserId}, '') <> '')`,
|
||||
sql`${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' = 'yielded'`,
|
||||
sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'yielded'`),
|
||||
|
||||
@@ -41,7 +41,7 @@ import { issueTreeControlService } from "../issue-tree-control.js";
|
||||
import { COMPLETION_REVIEW_STAGE_REASON, completionReviewStageEntry } from "../issue-execution-policy.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { preserveNativeWorkspaceExportLease } from "./native-workspace-export-resume.js";
|
||||
import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agentWakeupRequests,
|
||||
@@ -973,6 +973,18 @@ async function acceptedResponseDigestMatches(
|
||||
);
|
||||
}
|
||||
|
||||
async function hasLaterAppliedStatusDecision(db: Db, input: {
|
||||
companyId: string; issueId: string; decision: { decisionVersion: number };
|
||||
}) {
|
||||
const [later] = await db.select({ id: statusDecisions.id }).from(statusDecisions).where(and(
|
||||
eq(statusDecisions.companyId, input.companyId),
|
||||
eq(statusDecisions.issueId, input.issueId),
|
||||
eq(statusDecisions.applicationState, "applied"),
|
||||
gt(statusDecisions.decisionVersion, input.decision.decisionVersion),
|
||||
)).limit(1);
|
||||
return Boolean(later);
|
||||
}
|
||||
|
||||
/** 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(
|
||||
@@ -1171,6 +1183,9 @@ async function recoverCommittedNativeChatResponseInScope(
|
||||
return true;
|
||||
}
|
||||
const conversation = isConversation(issue);
|
||||
const blockedTaskReply = !conversation && result.reportedWorkDisposition === "blocked"
|
||||
&& terminal.reportedWorkDisposition === "blocked" && issue.status === "blocked"
|
||||
&& !(await hasLaterAppliedStatusDecision(tx, { ...input, decision }));
|
||||
// The turn is still the conversation's unsettled current turn. A held
|
||||
// turn keeps whatever status its gate committed; a finished turn
|
||||
// preserves in_progress.
|
||||
@@ -1184,20 +1199,22 @@ 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.
|
||||
if (
|
||||
(!conversation || currentConversation) &&
|
||||
run.status === "succeeded" &&
|
||||
record(run.contextSnapshot).skipIssueComment !== true &&
|
||||
const ordinaryTaskReply = (!conversation || currentConversation) &&
|
||||
!isExternalChatPresentationContext(run.contextSnapshot) &&
|
||||
terminal.runTerminalState === "succeeded" &&
|
||||
terminal.turnTerminalState === "completed" &&
|
||||
((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
|
||||
// stage or a blocker holds its task; it still answered the person.
|
||||
(currentConversation && result.reportedWorkDisposition === "yielded" && terminal.reportedWorkDisposition === "yielded")) &&
|
||||
(await resolveChatRunPresentationAuthorizationReason(tx, input)) === "internal_agent_write"
|
||||
) {
|
||||
(currentConversation && result.reportedWorkDisposition === "yielded" && terminal.reportedWorkDisposition === "yielded"));
|
||||
const taskReplyEligible = run.status === "succeeded" &&
|
||||
record(run.contextSnapshot).skipIssueComment !== true &&
|
||||
terminal.runTerminalState === "succeeded" &&
|
||||
terminal.turnTerminalState === "completed" &&
|
||||
(ordinaryTaskReply || blockedTaskReply);
|
||||
const replyAuthorization = taskReplyEligible ? await resolveChatRunPresentationAuthorizationReason(tx, input) : null;
|
||||
const externalChatReply = blockedTaskReply &&
|
||||
isExternalChatPresentationContext(run.contextSnapshot, replyAuthorization === CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON);
|
||||
if (taskReplyEligible && replyAuthorization && (blockedTaskReply || replyAuthorization === "internal_agent_write")) {
|
||||
const rows = await tx.select({ seq: heartbeatRunEvents.seq, payload: heartbeatRunEvents.payload })
|
||||
.from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, input.companyId),
|
||||
@@ -1224,7 +1241,7 @@ async function recoverCommittedNativeChatResponseInScope(
|
||||
return candidate ? [candidate] : [];
|
||||
}),
|
||||
});
|
||||
if (!finalAgentMessage) return false;
|
||||
if (!finalAgentMessage && !blockedTaskReply) return false;
|
||||
const comments = await tx.select({ id: issueComments.id, body: issueComments.body, presentation: issueComments.presentation })
|
||||
.from(issueComments).where(and(
|
||||
eq(issueComments.companyId, input.companyId),
|
||||
@@ -1241,6 +1258,7 @@ async function recoverCommittedNativeChatResponseInScope(
|
||||
interactionOwnsResponse: conversation && await hasChatRunOwnedProviderInteraction(tx, input),
|
||||
existingComment: findHeartbeatRunCompletionComment(comments, run.resultJson),
|
||||
finalAgentMessage,
|
||||
preferFinalResponseOverExistingComment: externalChatReply,
|
||||
});
|
||||
if (resolved.decision.commentAction === "reuse" && typeof resolved.decision.commentId === "string") {
|
||||
// The reply is already on the task (for example, the live path wrote
|
||||
@@ -1270,7 +1288,7 @@ async function recoverCommittedNativeChatResponseInScope(
|
||||
await notifyChatRunMilestones(tx, input);
|
||||
const comment = await issueService(db).addComment(input.issueId, resolved.text,
|
||||
{ agentId: run.agentId, runId: run.id },
|
||||
{ authorizationReason: "internal_agent_write", completionReply: true }, tx);
|
||||
{ authorizationReason: replyAuthorization, completionReply: true }, tx);
|
||||
await tx.update(heartbeatRuns).set({
|
||||
resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || ${JSON.stringify({
|
||||
presentationDecision: { ...resolved.decision, commentId: comment.id,
|
||||
|
||||
Reference in new issue
Block a user