fix(queue): send a message into a starting run without a cancel or recovery errors (#21661)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A user can queue a message while an agent works, then send it into
the running turn
> - A run that is still starting takes queued messages into its first
turn, and Interrupt hands off to them
> - Both rules only accepted a queue that a user started
> - A user's message can merge into an earlier automatic wake that waits
behind the task, and that wake keeps its system requester
> - Then the starting run did not take the message, Interrupt cancelled
the boot, and the task showed "Couldn't finish this attempt" with Retry
and "Waiting for execution recovery" under the composer until the
cancelled boot settled
> - This pull request makes both rules judge the messages and the
recorded Interrupt intent, not the wake's requester, and shows an
Interrupt hand-off as sent
> - The benefit is that sending a queued message feels immediate and
shows no error

## Linked Issues or Issue Description

**What happened?**
A run started from a resolved blocker. The user queued a message 20
seconds later, while the runner was still starting. The message merged
into an older automatic deferred wake. The queue offered Interrupt
instead of sending it. Interrupt cancelled the starting run. For about 7
seconds the task showed "Couldn't finish this attempt. Your message is
saved." with Retry, and the composer showed "Waiting for execution
recovery. Your message is saved." Then the message was delivered.

**Expected behavior**
The starting run takes the message into its first turn. When an
Interrupt does stop a run, the message shows as sent, with no error
banner, Retry, or recovery text.

**Steps to reproduce**
1. Have an automatic deferred wake for a task (for example from an
earlier blocked execution).
2. Start a run for the task with a Paperclip runner agent.
3. While the runner is still starting, queue a message and click the
send control.

## What Changed

- `deferredWakeJoinsFirstTurn`: a system or unattributed wake qualifies.
Each message must still be the responsible user's own
(`firstTurnEligibleComment`). A wake from another user or an agent keeps
its own delivery.
- Task interruption presentation: find the Interrupt queue by its
recorded `queuedCommentInterrupt` intent, not by `requestedByActorType =
user`. The hand-off now shows as working for a merged queue too.
- Queued-comment read: while a deferred queue carries an Interrupt
intent, report an `interrupt_handoff` wait instead of the recovery
message.
- UI (`TaskChatQueuedMessages`, `IssueDetail`): an `interrupt_handoff`
response counts as sent. The messages stay out of the queue and no
status or error line shows.

## Verification

Red/green tests. Each failed before the fix and passes after it:
- `server/src/__tests__/issue-queued-comments-routes.test.ts`: "gives a
booting run's first turn the user's message merged into an earlier
automatic wake"; the Interrupt fallback case now expects
`interrupt_handoff` on the response and on a poll. 144/144 pass.
- `server/src/__tests__/task-interruption-query.test.ts`: the hand-off
case runs for a user-started and a system-started queue. 32/32 pass.
- `ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx`: "shows
an Interrupt as sent while the stopped turn hands off". 43/43 pass.
- `first-turn-queued-input.test.ts` 8/8, `issue-queued-comment-queue`
7/7. Server and UI typecheck pass.

Root cause from the staging wake diagnostics: the run started at
20:26:54, the message was coalesced at 20:27:17 into a deferred
`issue_execution_deferred` automation wake from the previous day, the
Interrupt at 20:27:20 recorded `execution_recovery`, and the
false-positive hold resolved at 20:27:26.

Not run: local runner E2E steering cells. The OpenCode chat-features
cells require the trusted CI host. The Codex and Claude
`revise-while-running` chat cells failed before steering on a fixture
workspace path (`workspaces/` vs `isolated-workspaces/`), which this
change does not touch. Staging verification follows the deploy.

## Risks

- Low. A wider set of deferred wakes can join a starting run's first
turn. Message eligibility, the claim receipt, and exactly-once delivery
are unchanged.
- An Interrupt intent that never delivers shows "sent" in the composer.
The task notice still shows a failure with Retry after its existing
grace period.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and
code execution.

## 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:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-14 18:06:15 -06:00
1 parent ac114d9479
commit 97a167093d
10 files changed
+106 -12

No files matched your search

@@ -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<string, unknown>),
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");
@@ -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) => {
+9 -2
View File
@@ -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,
@@ -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 &&
@@ -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(
@@ -546,6 +546,20 @@ describe("TaskChatQueuedMessages", () => {
expect(container.textContent).toContain(saved.executionWait.message);
expect(container.querySelector<HTMLButtonElement>('[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<HTMLButtonElement>('[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) });
@@ -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." });
@@ -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,
+14
View File
@@ -12,6 +12,12 @@ export function startingQueuedCommentIds(
queue: IssueQueuedCommentQueue | null | undefined,
runs: readonly RunForIssue[],
): ReadonlySet<string> {
// 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<IssueQueuedCommentQueue, "state" | "executionWait"> | null | undefined) {
return queue?.state === "deferred" && queue.executionWait?.reason === "interrupt_handoff";
}
+2 -1
View File
@@ -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))));