Files
PaperClipAI/ui/src/lib/issue-queued-comment-queue.ts
T
DottaandClaude Opus 5.5 97a167093d 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>
2026-11-14 18:06:15 -06:00

205 lines
8.2 KiB
TypeScript

import type {
IssueComment,
IssueQueuedCommentProtocol,
IssueQueuedCommentQueue,
IssueQueuedCommentQueueState,
IssueQueuedCommentSteeringDisposition,
} from "@paperclipai/shared";
import type { RunForIssue } from "../api/activity";
/** Presentation only. Admission has accepted these inputs, but has not consumed them. */
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" &&
!run.startedAt && !run.retryOfRunId);
if (owners.length !== 1 || runs.some(run => run.contextIssueId === queue.issueId &&
run.runId !== owners[0]!.runId && run.status === "running")) return new Set();
const run = owners[0]!;
const inputs = new Set(run.wakeCommentIds?.length ? run.wakeCommentIds
: [run.wakeCommentId ?? run.contextCommentId]);
const createdAt = new Date(run.createdAt).getTime();
return new Set(queue.entries.flatMap(entry =>
!entry.source && !entry.comment.authorAgentId && !entry.comment.deletedAt &&
inputs.has(entry.comment.id) && new Date(entry.comment.createdAt).getTime() <= createdAt
? [entry.comment.id] : []));
}
function record(value: unknown): Record<string, unknown> | null {
return typeof value === "object" && value !== null && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
const STEERING_DISPOSITIONS = new Set<IssueQueuedCommentSteeringDisposition>([
"available",
"unsupported",
"temporarily_unavailable",
]);
const QUEUE_STATES = new Set<IssueQueuedCommentQueueState>([
"deferred",
"queued",
]);
/** Defensive boundary shared by IssueDetail and Storybook queue fixtures. */
export function normalizeIssueQueuedCommentQueue(
value: unknown,
fallbackIssueId: string,
): IssueQueuedCommentQueue {
const source = record(value);
const seen = new Set<string>();
const entries = (Array.isArray(source?.entries) ? source.entries : [])
.flatMap((candidate, sourcePosition) => {
const entry = record(candidate);
const comment = record(entry?.comment);
const id = typeof comment?.id === "string" ? comment.id : "";
const body = typeof comment?.body === "string" ? comment.body : null;
if (!id || body === null || seen.has(id)) return [];
seen.add(id);
const position =
typeof entry?.position === "number" && Number.isFinite(entry.position)
? entry.position
: sourcePosition;
const response = record(entry?.source);
return [
{
comment: comment as unknown as IssueComment,
position,
...(response?.kind === "interaction" && typeof response.interactionId === "string"
&& typeof response.interactionKind === "string" ? { source: {
kind: "interaction" as const, interactionId: response.interactionId,
interactionKind: response.interactionKind,
requiresFreshSession: response.requiresFreshSession === true,
} } : {}),
canEdit: entry?.canEdit === true,
canDiscard: entry?.canDiscard === true,
},
];
})
.sort((left, right) => left.position - right.position)
.map((entry, position) => ({ ...entry, position }));
const disposition = source?.steeringDisposition;
const state = source?.state;
const wait = record(source?.executionWait);
return {
issueId:
typeof source?.issueId === "string" ? source.issueId : fallbackIssueId,
queueId: typeof source?.queueId === "string" ? source.queueId : null,
state:
typeof state === "string" &&
QUEUE_STATES.has(state as IssueQueuedCommentQueueState)
? (state as IssueQueuedCommentQueueState)
: null,
targetRunId:
typeof source?.targetRunId === "string" ? source.targetRunId : null,
revision:
typeof source?.revision === "string" ? source.revision : "unavailable",
protocol:
source?.protocol === "paperclip_runner_v1"
? "paperclip_runner_v1"
: "legacy",
steeringDisposition:
typeof disposition === "string" &&
STEERING_DISPOSITIONS.has(
disposition as IssueQueuedCommentSteeringDisposition,
)
? (disposition as IssueQueuedCommentSteeringDisposition)
: "unsupported",
entries,
executionWait: typeof wait?.reason === "string" && typeof wait?.message === "string"
? { reason: wait.reason, message: wait.message }
: null,
...(Array.isArray(source?.firstTurnCommentIds) ? {
firstTurnCommentIds: source.firstTurnCommentIds.filter((id): id is string => typeof id === "string" && id.length > 0),
} : {}),
};
}
export interface PendingIssueQueuedComment {
comment: IssueComment;
targetRunId: string | null;
}
/**
* Keeps a just-submitted follow-up in the composer queue while the comment and
* queue endpoints acknowledge it independently. If the server has not yet
* included every local entry, queue mutations are withheld by clearing the
* queue id; local discard remains available through the optimistic comment
* cancellation path.
*/
export function mergePendingIssueQueuedComments(params: {
issueId: string;
authoritativeQueue: IssueQueuedCommentQueue | null | undefined;
pendingComments: PendingIssueQueuedComment[];
fallbackProtocol: IssueQueuedCommentProtocol;
}): IssueQueuedCommentQueue | null {
const authoritativeEntries = params.authoritativeQueue?.entries ?? [];
const authoritativeIds = new Set(
authoritativeEntries.map((entry) => entry.comment.id),
);
const pendingEntries = params.pendingComments
.filter(({ comment }) => !authoritativeIds.has(comment.id))
.map(({ comment }, position) => ({
comment,
position: authoritativeEntries.length + position,
canEdit: false,
canDiscard: true,
}));
const entries = [...authoritativeEntries, ...pendingEntries].map(
(entry, position) => ({ ...entry, position }),
);
if (entries.length === 0) return null;
const queueAcknowledged = pendingEntries.length === 0;
const authoritativeOwnsQueue = Boolean(params.authoritativeQueue?.queueId);
const fallbackTargetRunId =
params.pendingComments.find((entry) => entry.targetRunId)?.targetRunId ??
null;
// An empty snapshot predating this submission does not own its runtime.
// Use the active run until the server acknowledges an actual queue.
const protocol = authoritativeOwnsQueue
? params.authoritativeQueue!.protocol
: params.fallbackProtocol;
const targetRunId = authoritativeOwnsQueue
? (params.authoritativeQueue?.targetRunId ?? null)
: fallbackTargetRunId;
return {
issueId: params.authoritativeQueue?.issueId ?? params.issueId,
queueId: queueAcknowledged
? (params.authoritativeQueue?.queueId ?? null)
: null,
state:
params.authoritativeQueue?.state ?? (targetRunId ? "deferred" : null),
targetRunId,
revision: params.authoritativeQueue?.revision ?? "awaiting-server",
protocol,
steeringDisposition:
(authoritativeOwnsQueue ? params.authoritativeQueue?.steeringDisposition : undefined) ??
(protocol === "paperclip_runner_v1" && targetRunId
? "temporarily_unavailable"
: "unsupported"),
entries,
executionWait: params.authoritativeQueue?.executionWait ?? null,
...(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";
}