diff --git a/server/src/services/fresh-continuation-fallback.test.ts b/server/src/services/fresh-continuation-fallback.test.ts index b7c82ae21d5..289fbd58d60 100644 --- a/server/src/services/fresh-continuation-fallback.test.ts +++ b/server/src/services/fresh-continuation-fallback.test.ts @@ -3,7 +3,7 @@ import { and, eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { activityLog, agentWakeupRequests, agents, approvals, authUsers, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueApprovals, issueRecoveryActions, issueThreadInteractions, - issues, nativeRunFinalizations, toolInvocations, + issueComments, issues, nativeRunFinalizations, toolInvocations, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { deliverReconciledExecutions, settleUnrecoverableExecutions } from "./execution-recovery-resolution.js"; @@ -789,6 +789,22 @@ suite("fresh-continuation fallback", () => { expect(decision.outcomeEvidence).not.toMatch(adminText); }, 60_000); + it.each([true, false])("relies on saved input only while it still holds an undelivered message (already taken by the cut-off run: %s)", async taken => { + // R2 cell t003: the cut-off run had taken the follow-up into its turn; the fallback chose saved_input, + // promotion settled the message as delivered, and no run followed. + const f = await unfinishedRun({ runtime: "native", errorCode: "native_restart_recovery_blocked" }); + const [comment] = await db.insert(issueComments).values({ companyId, issueId: f.issueId, authorType: "user", + authorUserId: userId, body: "Additional requirement: include FOLLOWUP-1" } as typeof issueComments.$inferInsert).returning(); + if (taken) await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentIds: [comment!.id] } }) + .where(eq(heartbeatRuns.id, f.runId)); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", triggerDetail: "system", + reason: "issue_execution_deferred", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: userId, + payload: { issueId: f.issueId, _paperclipWakeContext: { issueId: f.issueId, wakeReason: "issue_commented", wakeCommentIds: [comment!.id] } }, + } as typeof agentWakeupRequests.$inferInsert); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", delivery: taken ? "recorded" : "saved_input" }); + }, 60_000); + it.each([ { title: "a pending approval", setup: "approval" as const, errorCode: "native_continuation_requires_reconciliation" }, { title: "a credential the person has not shared", setup: "none" as const, errorCode: "configuration_incomplete" }, diff --git a/server/src/services/fresh-continuation-fallback.ts b/server/src/services/fresh-continuation-fallback.ts index 99d0e234af0..68f035fb35f 100644 --- a/server/src/services/fresh-continuation-fallback.ts +++ b/server/src/services/fresh-continuation-fallback.ts @@ -8,6 +8,8 @@ import { } from "@paperclipai/shared"; import { logger } from "../middleware/logger.js"; import { logActivity } from "./activity-log.js"; +import { undeliveredLegacyUserCommentIds } from "./explicit-native-continuation.js"; +import { queuedCommentIdsFromWakePayload } from "./issue-queued-comment-queue.js"; import { FRESH_CONTINUATION_SUPERSEDED_KEY } from "../agent-run-cancellation.js"; import { isAcknowledgedNativeReassignmentStop, isAcknowledgedNativeStop } from "./acknowledged-native-stop.js"; import { adapterExecutionControls } from "./adapter-execution-control.js"; @@ -487,9 +489,20 @@ export async function continueFreshInTransaction(tx: Db, input: Input): Promise< // Saved user input (a message or a Retry the person pressed) continues the // task through normal admission once nothing blocks it; a second, automatic // continuation would run after it. - const [savedInput] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + const savedWakes = await tx.select({ id: agentWakeupRequests.id, payload: agentWakeupRequests.payload }).from(agentWakeupRequests).where(and( eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.status, "deferred_issue_execution"), - eq(agentWakeupRequests.requestedByActorType, "user"), sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`)).limit(1); + eq(agentWakeupRequests.requestedByActorType, "user"), sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`)).limit(5); + // Saved input continues the task only while it still holds something the + // agent has not received: a message the cut-off run already took into its + // turn is settled as delivered when promoted, and then nothing would run. + let savedInput: { id: string } | undefined; + for (const wake of savedWakes) { + const commentIds = queuedCommentIdsFromWakePayload(wake.payload); + if (!commentIds.length || (await undeliveredLegacyUserCommentIds(tx, companyId, issue.id, run.agentId, commentIds)).length) { + savedInput = wake; + break; + } + } let delivery: "recorded" | "caller_owns" | "saved_input" = input.delivery === "caller_owns" ? "caller_owns" : savedInput ? "saved_input" : "recorded";