diff --git a/server/src/__tests__/issue-queued-comments-routes.test.ts b/server/src/__tests__/issue-queued-comments-routes.test.ts index dc527c5c8a9..dd1f9b10719 100644 --- a/server/src/__tests__/issue-queued-comments-routes.test.ts +++ b/server/src/__tests__/issue-queued-comments-routes.test.ts @@ -993,13 +993,18 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { }, ); - async function seedFirstTurnQueue(runtime: "preparing" | "native") { + async function seedFirstTurnQueue(runtime: "preparing" | "native", queueStartedBy: "user" | "system" = "user") { const seeded = await seedQueue(); // A user's follow-ups, as the comment route saves them behind that user's run. const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId)); await db.update(agentWakeupRequests).set({ payload: { ...wake!.payload, _paperclipWakeContext: { ...(wake!.payload?._paperclipWakeContext as Record), - issueId: seeded.issueId, wakeReason: "issue_commented" } } }).where(eq(agentWakeupRequests.id, seeded.wakeId)); + issueId: seeded.issueId, wakeReason: "issue_commented" } }, + // An earlier automatic wake that waited behind the task's execution: the + // comment route merges the user's message into it and keeps its requester. + ...(queueStartedBy === "system" ? { source: "automation", reason: "issue_execution_deferred", + requestedByActorType: "system", requestedByActorId: null } : {}), + }).where(eq(agentWakeupRequests.id, seeded.wakeId)); await db.update(heartbeatRuns).set(runtime === "preparing" ? { responsibleUserId: "queue-owner", runtimeMode: "legacy", runtimeModeResolvedAt: null, executionStage: "preparing", runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } } @@ -1051,6 +1056,29 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { }, ); + it("gives a booting run's first turn the user's message merged into an earlier automatic wake", async () => { + const seeded = await seedFirstTurnQueue("preparing", "system"); + const client = app(seeded.companyId); + // Shown as sent: Steer cannot reach a provider that has not started yet. + const queue = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200); + expect(queue.body.firstTurnCommentIds).toEqual(seeded.commentIds); + // Interrupt must not cancel the boot and leave the message behind a recovery wait. + const response = await request(client).post(`/api/issues/${seeded.issueId}/queued-comments/interrupt`).send({ + queueId: seeded.wakeId, targetRunId: seeded.runId, revision: queue.body.revision, + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + expect(response.body.executionWait).toMatchObject({ reason: "first_turn_pending" }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId)); + expect(run!.status).toBe("running"); + expect(run!.errorCode).toBeNull(); + await db.update(heartbeatRuns).set({ runtimeMode: "native", runtimeModeResolvedAt: new Date(), + nativeIssueId: seeded.issueId }).where(eq(heartbeatRuns.id, seeded.runId)); + const firstTurn = await claimFirstTurnQueuedInput(db, { companyId: seeded.companyId, runId: seeded.runId, + issueId: seeded.issueId, agentId: seeded.agentId }); + expect(firstTurn).toContain("First queued message"); + expect(firstTurn).toContain("Second queued message"); + }); + it.each(["preparing", "native"] as const)( "reports the messages a %s run's first turn takes, before and after it seals them", async (runtime) => { @@ -1093,7 +1121,11 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { queueId: seeded.wakeId, targetRunId: seeded.runId, revision: queue.body.revision, }); expect(response.status, JSON.stringify(response.body)).toBe(200); - expect(response.body.executionWait?.reason).not.toBe("first_turn_pending"); + // The stop is the user's own click: the messages are on their way, not + // waiting on a recovery the user should read about. + expect(response.body.executionWait?.reason).toBe("interrupt_handoff"); + const polled = await request(client).get(`/api/issues/${seeded.issueId}/queued-comments`).expect(200); + expect(polled.body.executionWait?.reason).toBe("interrupt_handoff"); const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId)); expect(run!.status).toBe("cancelled"); expect(run!.errorCode).toBe("operator_interrupted"); diff --git a/server/src/__tests__/task-interruption-query.test.ts b/server/src/__tests__/task-interruption-query.test.ts index 3b0f4b45121..afb8763b56a 100644 --- a/server/src/__tests__/task-interruption-query.test.ts +++ b/server/src/__tests__/task-interruption-query.test.ts @@ -235,7 +235,8 @@ describe.skipIf(!support.supported)("task interruption latest run query", () => observedRunId: otherRunId }); }); - it("shows a queued-message Interrupt as handing off, not as a failed attempt", async () => { + // A user's message can join an earlier automatic wake that keeps its system requester. + it.each(["user", "system"] as const)("shows a queued-message Interrupt as handing off, not as a failed attempt (queue started by %s)", async (queueStartedBy) => { const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), userId = "board-user"; await db.insert(companies).values({ id: companyId, name: "Interrupted task", issuePrefix: `Q${companyId.slice(0, 7)}` }); await db.insert(agents).values({ id: agentId, companyId, name: "Researcher", adapterType: "paperclip_runner" }); @@ -243,7 +244,7 @@ describe.skipIf(!support.supported)("task interruption latest run query", () => status: "todo", assigneeAgentId: agentId }).returning(); // The message was queued well before the user clicked Interrupt. const [wake] = await db.insert(agentWakeupRequests).values({ - companyId, agentId, source: "on_demand", status: "deferred_issue_execution", requestedByActorType: "user", + companyId, agentId, source: "on_demand", status: "deferred_issue_execution", requestedByActorType: queueStartedBy, requestedAt: new Date(Date.now() - 60_000), payload: { issueId: issue.id }, }).returning(); const interrupt = async (requestedAt: Date) => { diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index f3c6df91389..5d105bef1a3 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -7714,6 +7714,8 @@ export function issueRoutes( response?: QueuedInteractionResponse | null; }; + const QUEUED_INTERRUPT_HANDOFF_WAIT = { reason: "interrupt_handoff", message: "Sending your messages." } as const; + async function findQueuedCommentWake( executor: IssueQueueDb, issue: { id: string; companyId: string; assigneeAgentId: string | null }, @@ -7896,10 +7898,15 @@ export function issueRoutes( .then((state) => state.disposition) .catch(() => "temporarily_unavailable" as const)); const wait = queueState?.state === "deferred" ? readObject(readObject(wake?.payload).executionWait) : {}; + // The user's Interrupt click is delivering these messages. Its stopped run + // settling is not something to read about under the composer; the task + // notice owns any wait that needs the user. + const interruptHandoff = queueState?.state === "deferred" && readObject(wake?.payload).queuedCommentInterrupt != null; const queue = buildQueuedCommentQueueSnapshot({ issueId: input.issue.id, - executionWait: typeof wait.reason === "string" && typeof wait.message === "string" - ? { reason: wait.reason, message: wait.message } : null, + executionWait: interruptHandoff ? QUEUED_INTERRUPT_HANDOFF_WAIT + : typeof wait.reason === "string" && typeof wait.message === "string" + ? { reason: wait.reason, message: wait.message } : null, queueId: wake?.id ?? null, state: queueState?.state ?? null, activeRunId: input.activeRun?.id ?? null, diff --git a/server/src/services/native-runtime/first-turn-queued-input.ts b/server/src/services/native-runtime/first-turn-queued-input.ts index 5f494b4c5b3..e8476e2295c 100644 --- a/server/src/services/native-runtime/first-turn-queued-input.ts +++ b/server/src/services/native-runtime/first-turn-queued-input.ts @@ -86,6 +86,12 @@ export function firstTurnClaimedCommentIds(run: { id: string; status?: string | * chat-conversation wakes keep their own delivery contracts. Only the run's * responsible user's own messages qualify, so taking them cannot change the * run's execution authority. + * + * A user's message can join an earlier automatic wake that was already waiting + * behind the task, which keeps that wake's system requester. The messages, not + * the wake's origin, carry the authority: every caller also requires each one + * to be the responsible user's own (`firstTurnEligibleComment`). Another + * user's or an agent's wake keeps its own delivery. */ export function deferredWakeJoinsFirstTurn( wake: { agentId: string; status: string; requestedByActorType: string | null; requestedByActorId: string | null; reason: string | null; payload: unknown }, @@ -94,10 +100,12 @@ export function deferredWakeJoinsFirstTurn( const payload = record(wake.payload); const context = record(payload[DEFERRED_WAKE_CONTEXT_KEY]); const reason = nonEmptyString(context.wakeReason) ?? nonEmptyString(wake.reason); + const requester = wake.requestedByActorType === "user" + ? wake.requestedByActorId === run.responsibleUserId + : wake.requestedByActorType === "system" || wake.requestedByActorType === null; return wake.status === DEFERRED_WAKE_STATUS && wake.agentId === run.agentId && - wake.requestedByActorType === "user" && - Boolean(run.responsibleUserId) && wake.requestedByActorId === run.responsibleUserId && + Boolean(run.responsibleUserId) && requester && reason !== null && COMMENT_WAKE_REASONS.has(reason) && !payload.interactionId && !context.interactionId && !context.interactionStatus && !payload.queuedCommentInterrupt && context.resumeIntent !== true && diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index c7d8d85fb40..db76c8976e3 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -605,6 +605,8 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i } // A queued-message Interrupt records its queue on the stopped run. Newer // input can hide that wake from the latest-wait read, so load it by id. + // The click's recorded intent is the authority, not the wake's requester: + // a user's message can join an earlier automatic wake. const interruptQueueId = (run: typeof runs[number]) => { const id = run.status === "cancelled" ? run.resultJson?.queuedCommentInterruptQueueId : null; return typeof id === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id) ? id : null; @@ -614,7 +616,8 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i requestedAt: agentWakeupRequests.requestedAt, queuedInterruptRequestedAt: boundedJsonString(sql`${agentWakeupRequests.payload}#>'{queuedCommentInterrupt,requestedAt}'`, 40) }) .from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId), inArray(agentWakeupRequests.id, interruptQueueIds), - eq(agentWakeupRequests.status, "deferred_issue_execution"), eq(agentWakeupRequests.requestedByActorType, "user"))) : []; + eq(agentWakeupRequests.status, "deferred_issue_execution"), + sql`${agentWakeupRequests.payload}#>>'{queuedCommentInterrupt,actorId}' is not null`)) : []; const interruptWaitById = new Map(interruptWaits.map(wait => [wait.id, wait])); const runIds = runs.map(run => run.id); const actions = runIds.length ? await db.selectDistinctOn([issueRecoveryActions.sourceIssueId]).from(issueRecoveryActions).where(and( diff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx index a1a03831c32..0f72986da4f 100644 --- a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx +++ b/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx @@ -546,6 +546,20 @@ describe("TaskChatQueuedMessages", () => { expect(container.textContent).toContain(saved.executionWait.message); expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')?.disabled).toBe(false); }); + it("shows an Interrupt as sent while the stopped turn hands off, with no wait or error text", async () => { + const handoff = { ...queue, targetRunId: null, + executionWait: { reason: "interrupt_handoff", message: "Sending your messages." } }; + const onInterrupt = vi.fn().mockResolvedValue(handoff); + render({ queue: { ...queue, steeringDisposition: "temporarily_unavailable" }, onInterrupt }); + await act(async () => { container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); }); + // A poll during the hand-off still lists the saved messages. + render({ queue: handoff, onInterrupt }); + await act(async () => {}); + expect(container.textContent).not.toContain("First queued message"); + expect(container.textContent).not.toContain("Sending your messages."); + expect(container.textContent).not.toContain("Couldn’t"); + expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); + }); it("clears a deferred wait message when a refreshed queue finishes sending", async () => { const saved = { ...queue, targetRunId: null, executionWait: { reason: "decision_pending", message: "Resolve the pending approval before sending." } }; render({ queue: saved, onInterrupt: vi.fn().mockResolvedValue(saved) }); diff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.tsx index 8772e7e274e..5bee5ec9b56 100644 --- a/ui/src/components/task-chat/TaskChatQueuedMessages.tsx +++ b/ui/src/components/task-chat/TaskChatQueuedMessages.tsx @@ -37,6 +37,7 @@ import { queuedMessageAutoSteerEligible, queuedMessageAutoSteerKey, } from "./queued-message-auto-steer"; +import { isQueuedInterruptHandoff } from "@/lib/issue-queued-comment-queue"; import { DropdownMenu, DropdownMenuContent, @@ -474,7 +475,8 @@ export function TaskChatQueuedMessages({ if (action === "steer") await onSteer(commentId, queue.revision); else if (action === "interrupt") { const updatedQueue = await onInterrupt?.(); - if (updatedQueue?.state === "deferred") { + // The stopped turn is handing off to these messages: they are sent. + if (updatedQueue?.state === "deferred" && !isQueuedInterruptHandoff(updatedQueue)) { for (const entry of updatedQueue.entries) optimisticDeliveryIds.current.delete(entry.comment.id); setEntries(updatedQueue.entries.filter(entry => !optimisticDeliveryIds.current.has(entry.comment.id))); setDeferredStatus({ queueId: updatedQueue.queueId, message: updatedQueue.executionWait?.message ?? "Messages are still queued. They will send when the task is ready." }); diff --git a/ui/src/lib/issue-queued-comment-queue.test.ts b/ui/src/lib/issue-queued-comment-queue.test.ts index 663edc4305f..1b9d91aeabe 100644 --- a/ui/src/lib/issue-queued-comment-queue.test.ts +++ b/ui/src/lib/issue-queued-comment-queue.test.ts @@ -39,6 +39,18 @@ describe("normalizeIssueQueuedCommentQueue", () => { expect(ids([run], { ...queue, targetRunId: "previous", state: "deferred" })).toEqual([]); expect(ids([run], { ...queue, entries: [{ ...queue.entries[0]!, source: { kind: "interaction", interactionId: "decision", interactionKind: "request_confirmation", requiresFreshSession: false } }] })).toEqual([]); }); + it("shows an Interrupt hand-off's messages as sent, including on a fresh page load", () => { + const first = comment("first", "Wait, are the daily tests passing?"); + const second = { ...comment("second", "And which ones fail?"), createdAt: new Date("2026-09-04T12:00:02Z") }; + // No successor run exists yet: the stopped run is still settling. + const handoff = normalizeIssueQueuedCommentQueue({ queueId: "wake", state: "deferred", targetRunId: null, + executionWait: { reason: "interrupt_handoff", message: "Sending your messages." }, + entries: [first, second].map(comment => ({ comment })) }, "issue-1"); + expect([...startingQueuedCommentIds(handoff, [])]).toEqual(["first", "second"]); + // A real wait keeps the messages queued and editable. + expect([...startingQueuedCommentIds({ ...handoff, + executionWait: { reason: "remote_cleanup", message: "Waiting for the previous environment to stop." } }, [])]).toEqual([]); + }); it("retains the immutable response and fresh-turn requirement", () => { const source = { kind: "interaction", interactionId: "approval-1", interactionKind: "request_confirmation", requiresFreshSession: true }; const normalized = normalizeIssueQueuedCommentQueue({ entries: [{ comment: comment("approval-1", "Accepted: Plan"), source, diff --git a/ui/src/lib/issue-queued-comment-queue.ts b/ui/src/lib/issue-queued-comment-queue.ts index bfbf93b73b0..fcb11b1468c 100644 --- a/ui/src/lib/issue-queued-comment-queue.ts +++ b/ui/src/lib/issue-queued-comment-queue.ts @@ -12,6 +12,12 @@ export function startingQueuedCommentIds( queue: IssueQueuedCommentQueue | null | undefined, runs: readonly RunForIssue[], ): ReadonlySet { + // The user's Interrupt is delivering this queue. Every page load, not only + // the tab that clicked, shows its messages as sent. + if (queue?.queueId && isQueuedInterruptHandoff(queue)) { + return new Set(queue.entries.flatMap(entry => + !entry.source && !entry.comment.authorAgentId && !entry.comment.deletedAt ? [entry.comment.id] : [])); + } if (!queue?.queueId || queue.state !== "queued" || queue.targetRunId) return new Set(); const owners = runs.filter(run => run.contextIssueId === queue.issueId && run.wakeupRequestId === queue.queueId && run.status === "queued" && @@ -188,3 +194,11 @@ export function mergePendingIssueQueuedComments(params: { ...(params.authoritativeQueue?.firstTurnCommentIds ? { firstTurnCommentIds: params.authoritativeQueue.firstTurnCommentIds } : {}), }; } + +/** + * The user's Interrupt is delivering this deferred queue while the turn it + * stopped settles. Its messages count as sent, not as waiting. + */ +export function isQueuedInterruptHandoff(queue: Pick | null | undefined) { + return queue?.state === "deferred" && queue.executionWait?.reason === "interrupt_handoff"; +} diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 8180a7f285b..d1d77565620 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -135,6 +135,7 @@ import { queryKeys } from "../lib/queryKeys"; import { keepPreviousDataForSameQueryTail } from "../lib/query-placeholder-data"; import { useIssueWorkProducts } from "../hooks/useIssueWorkProducts"; import { + isQueuedInterruptHandoff, mergePendingIssueQueuedComments, normalizeIssueQueuedCommentQueue, startingQueuedCommentIds, @@ -2492,7 +2493,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ }); try { const updatedQueue = await onInterruptQueued(runId); - if (updatedQueue?.state === "deferred") { + if (updatedQueue?.state === "deferred" && !isQueuedInterruptHandoff(updatedQueue)) { const remaining = new Set(updatedQueue.entries.map(entry => entry.comment.id)); setConsumedQueuedCommentIds(current => new Set([...current].filter(id => !remaining.has(id)))); setLocalInterruptPlacements(current => new Map([...current].filter(([id]) => !remaining.has(id))));