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