mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 08:22:20 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Task conversations save messages that arrive during an active turn. > - Legacy adapters deliver these messages in a later turn. > - A run can stop before the saved queue is delivered. > - The Interrupt button previously required an active run, so it could not release this queue. > - This pull request lets a board operator send the saved queue after the run stops and retries queues missed during finalization. > - Manual dispatch must use the clicking operator and must not require permission to create agents. > - The task can continue without a duplicate message or a second execution owner. ## Linked Issues or Issue Description **What happened?** A legacy task retained a queued message after its run stopped. Interrupt was disabled because the queue had no active target. Finalization and deferred message admission can also leave a queue without a successor. **Expected behavior** Interrupt sends the saved messages when no runner is active. Messages that arrive during normal completion are delivered automatically. An uncertain previous execution still requires proof that its process or sandbox stopped. **Steps to reproduce** 1. Queue a user message during a legacy conversation turn. 2. Let the turn stop or simulate a server restart before queue promotion. 3. Open the task with a deferred queue and no active run. 4. Try Interrupt. Before this change, the button is disabled. **Paperclip version or commit** Reproduced against `8f40b4ad4`. **Deployment mode** Legacy conversation adapter. The same persisted queue state is covered with an isolated PostgreSQL fixture. Related public work: #13275 adds active legacy interruption. #13291 addresses automatic sandbox conversation recovery. This change handles explicit saved-queue delivery and late queue promotion. ## What Changed - Accept a null Interrupt target while retaining queue identity, revision, company, and assignee checks. - Save the operator's request on the existing queue. Reuse normal admission after verified stop, including older messages, different authors, and queues whose original wake came from the system. - Strip interruption authority from caller-supplied wake payloads. Only the board queue route can persist that authority. - Retry durable interruption requests after restart and deferred queues after legacy cleanup. - Let an explicit Interrupt retry cleanup for its stopped run, including old ephemeral leases that recorded success without a provider stop receipt. Preserve retained resources, other lease owners, and the automatic retry limit. - Preserve the server's waiting explanation when normalizing and combining queue entries. - Revalidate the consumed board queue receipt at dispatch so a different message author does not cause setup failure. - Use the Interrupt user's execution identity for the new run. Preserve original message authors. Validate the receipt independently at startup and inherit the resulting identity on retry. - Persist authenticated board authority for ordinary manual wakes too. Adopting someone else's queued messages cannot switch a manual run to that author's permissions. Strip caller-supplied authority markers and retain private conversation ownership checks. - Keep the clicking user when a manual wake is merged into an older deferred receipt. Update its requester and payload in the same transaction. - Use the same current-queue/revision API on task details and pipeline conversations; show Interrupt after a legacy target stops. - Keep manual wakes out of active runs, including unscoped agent wakes. They receive their own execution identity; a matching receipt requester is not sufficient because an exact retry can retain a different originating identity. - Authorize both existing-agent wake endpoints with `agent:wake`, available to active non-viewer company members. Keep `agents:create` for hiring. Validate the stored task and current assignee before an exact task retry. - Reject viewer Interrupt requests before saving intent or stopping execution. Keep external chat retry authorization and per-action agent/user permission checks. - Preserve edits and discards until dispatch. Prevent another queue promotion when the same agent already has a successor. Keep independent reviewer recovery available. - Suppress cancelled/failed run toasts for intentional operator interruption. Keep ordinary runtime error notices. - Add UI, route, admission, restart, successor ownership, and toast regression tests. Document the behavior. - Reuse the existing socket reservation helper for both credential-quorum test cases after CI exposed an ambient-port collision. This changes test preparation only; production credential staging is still called exactly once. ## Verification - Failing regression tests reproduced the message-author identity bug and an operator's `agents:create` rejection before the fixes. - All 316 focused tests pass across eight route, queue, identity, authorization, continuation, and responsible-user suites, including the 44-test rerun of queue admission and actual startup after the final manual-wake restriction. Regressions reproduce cross-user merging both with and without a task, and same-requester receipt ambiguity. The cross-company existence guard also passes both tests. - Startup integration tests reach adapter execution under the clicking operator and retain that identity through follow-up. Coverage includes mixed authors, adopted queues, system-origin queues, restarts, forged or stale receipts, viewers, suspended memberships, changed assignees, private conversations, and caller-supplied authority markers. - The earlier queue/cleanup/UI regression suite passed 402 tests. The final review corrections pass another 180 tests across queue admission/persistence, real heartbeat startup, UI API, conversation rendering, and pipeline suites. Regression tests reproduced both review findings before correction. The final head has a 5/5 review with no unresolved threads. Full CI passes on `c2002979c`, including every general and serialized server shard, all browser shards, Paperclip Runner verification, typecheck, build, canary dry run, and the aggregate gates. - Full `pnpm -r typecheck`, `pnpm build`, and UI token gates pass after the final application changes. CI identified an outdated task-page API mock after the shared helper extraction; the fixture now exercises the real helper, and all 131 task-page/API tests pass. The final application build passes with the additional manual-wake restriction. - CI exposed a pre-existing port collision in the Codex credential-quorum fixture. It reproduced locally; both listener cases now use the existing bounded reservation helper. All 41 credential tests pass on rerun. One intervening local run hit a separate ambient bind collision in the two-occupied-port case. - The full local `pnpm test:run` attempt was stopped after host contention caused focused-suite timeouts. The affected focused tests passed on rerun. An expiring trace fixture and a missing private-conversation state were corrected. The successful full CI run is the complete-suite verification. - Hosted Interrupt previously cleared the original queue and produced exactly one successor with neutral interruption feedback. It exposed the dispatch authorization defect. Retry on that earlier build was rejected for missing `agents:create` before creating another run. - Deployed the final application build (`38257f391`) to the scoped hosted instance and verified readiness. The latest PR commit changes only the credential test fixture; application code matches that deployment. A live Retry by the same operator without `agents:create` created one successor attributed to that operator, passing the former dispatch permission gate. Startup then stopped at `configuration_incomplete` because that operator has not configured their required personal Claude Code OAuth secret; the post-deployment run page confirms the operator identity and no provider work started, and the My secrets UI still shows the token as not set. Provider execution remains unverified pending that credential. No permission grants or credentials were changed. ## Risks Queue admission and finalization can race. The task lock, durable queue receipt, current comment IDs, and successor guard prevent duplicate dispatch. Process and lease stop checks, task pauses, approvals, ownership, and budgets remain in force. The API change only allows null on legacy Interrupt; native steering still requires an active run. No schema migration is required. Active non-viewer board members can now invoke existing agents without agent-creation permission. Agent self-invocation rules, raw provider-trace admin access, task retry scope, external chat authorization, and action-specific user/agent permissions remain enforced. ## Model Used OpenAI GPT-6 through Codex. The session does not expose an exact backend model ID or context-window size. Used reasoning, repository search, code execution, tests, and browser tools. ## 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 #` 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
422 lines
14 KiB
TypeScript
422 lines
14 KiB
TypeScript
import { useEffect, useMemo, useState } from "react";
|
||
import {
|
||
DndContext,
|
||
KeyboardSensor,
|
||
PointerSensor,
|
||
closestCenter,
|
||
useSensor,
|
||
useSensors,
|
||
type DragEndEvent,
|
||
} from "@dnd-kit/core";
|
||
import {
|
||
SortableContext,
|
||
arrayMove,
|
||
sortableKeyboardCoordinates,
|
||
useSortable,
|
||
verticalListSortingStrategy,
|
||
} from "@dnd-kit/sortable";
|
||
import { CSS } from "@dnd-kit/utilities";
|
||
import {
|
||
CornerDownRight,
|
||
GripVertical,
|
||
Loader2,
|
||
MoreHorizontal,
|
||
Pencil,
|
||
Trash2,
|
||
} from "lucide-react";
|
||
import type {
|
||
IssueQueuedCommentEntry,
|
||
IssueQueuedCommentQueue,
|
||
} from "@paperclipai/shared";
|
||
import { cn } from "@/lib/utils";
|
||
import {
|
||
DropdownMenu,
|
||
DropdownMenuContent,
|
||
DropdownMenuItem,
|
||
DropdownMenuTrigger,
|
||
} from "@/components/ui/dropdown-menu";
|
||
|
||
type QueueAction = "steer" | "interrupt" | "discard" | null;
|
||
|
||
export function reorderQueuedMessageEntries(
|
||
entries: IssueQueuedCommentEntry[],
|
||
activeId: string,
|
||
overId: string,
|
||
) {
|
||
const from = entries.findIndex((entry) => entry.comment.id === activeId);
|
||
const to = entries.findIndex((entry) => entry.comment.id === overId);
|
||
if (from < 0 || to < 0 || from === to) return null;
|
||
return arrayMove(entries, from, to).map((entry, position) => ({
|
||
...entry,
|
||
position,
|
||
}));
|
||
}
|
||
|
||
function queueActionErrorCode(error: unknown): string | null {
|
||
if (typeof error !== "object" || error === null) return null;
|
||
const body = (error as { body?: unknown }).body;
|
||
if (typeof body !== "object" || body === null) return null;
|
||
const directCode = (body as { code?: unknown }).code;
|
||
if (typeof directCode === "string") return directCode;
|
||
const details = (body as { details?: unknown }).details;
|
||
if (typeof details !== "object" || details === null) return null;
|
||
const detailCode = (details as { code?: unknown }).code;
|
||
return typeof detailCode === "string" ? detailCode : null;
|
||
}
|
||
|
||
export interface TaskChatQueuedMessagesProps {
|
||
queue: IssueQueuedCommentQueue;
|
||
onEdit: (commentId: string) => void;
|
||
onReorder: (orderedCommentIds: string[], revision: string) => Promise<void>;
|
||
onSteer: (commentId: string, revision: string) => Promise<void>;
|
||
onInterrupt?: () => Promise<void>;
|
||
onDiscard: (commentId: string, revision: string) => Promise<void>;
|
||
}
|
||
|
||
function SortableQueuedMessage({
|
||
entry,
|
||
queue,
|
||
busy,
|
||
queueMutationDisabled,
|
||
action,
|
||
onEdit,
|
||
onSteer,
|
||
onInterrupt,
|
||
onDiscard,
|
||
}: {
|
||
entry: IssueQueuedCommentEntry;
|
||
queue: IssueQueuedCommentQueue;
|
||
busy: boolean;
|
||
queueMutationDisabled: boolean;
|
||
action: QueueAction;
|
||
onEdit: () => void;
|
||
onSteer: () => void;
|
||
onInterrupt?: () => void;
|
||
onDiscard: () => void;
|
||
}) {
|
||
const sortable = useSortable({
|
||
id: entry.comment.id,
|
||
disabled: queueMutationDisabled,
|
||
});
|
||
const style = {
|
||
transform: CSS.Transform.toString(sortable.transform),
|
||
transition: sortable.transition,
|
||
};
|
||
const steerDisabled =
|
||
queueMutationDisabled || queue.steeringDisposition !== "available";
|
||
const steerTitle =
|
||
queue.steeringDisposition === "unsupported"
|
||
? "This runner does not support steering"
|
||
: queue.steeringDisposition === "temporarily_unavailable"
|
||
? "Steering is temporarily unavailable"
|
||
: "Steer this message into the active turn";
|
||
|
||
return (
|
||
<div
|
||
ref={sortable.setNodeRef}
|
||
style={style}
|
||
className={cn(
|
||
"group flex h-11 min-w-0 items-center gap-1 border-b border-border/55 bg-card/95 px-2.5 text-sm last:border-b-0",
|
||
sortable.isDragging &&
|
||
"relative z-20 rounded-lg border border-border shadow-lg",
|
||
)}
|
||
data-testid={`task-chat-queued-message-${entry.comment.id}`}
|
||
>
|
||
<button
|
||
type="button"
|
||
ref={sortable.setActivatorNodeRef}
|
||
{...sortable.attributes}
|
||
{...sortable.listeners}
|
||
disabled={queueMutationDisabled}
|
||
aria-label={`Reorder queued message: ${entry.comment.body}`}
|
||
className="flex h-7 w-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground/70 transition-colors hover:bg-accent hover:text-foreground active:cursor-grabbing disabled:cursor-default disabled:opacity-40"
|
||
>
|
||
<GripVertical className="h-3.5 w-3.5" aria-hidden />
|
||
</button>
|
||
|
||
<CornerDownRight
|
||
className="h-3.5 w-3.5 shrink-0 text-muted-foreground"
|
||
aria-hidden
|
||
/>
|
||
<span className="min-w-0 flex-1 truncate px-1" title={entry.comment.body}>
|
||
{entry.comment.body}
|
||
</span>
|
||
|
||
{queue.protocol === "legacy" ? (
|
||
<button
|
||
type="button"
|
||
onClick={onInterrupt}
|
||
disabled={busy || !queue.queueId || !onInterrupt}
|
||
title={queue.targetRunId ? "Interrupt the active turn and send queued messages" : "Send queued messages now"}
|
||
className="flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
|
||
data-testid={`task-chat-queued-interrupt-${entry.comment.id}`}
|
||
>
|
||
{action === "interrupt" ? (
|
||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||
) : (
|
||
<CornerDownRight className="h-3.5 w-3.5" aria-hidden />
|
||
)}
|
||
Interrupt
|
||
</button>
|
||
) : (
|
||
<button
|
||
type="button"
|
||
onClick={onSteer}
|
||
disabled={steerDisabled}
|
||
title={steerTitle}
|
||
className="flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
|
||
data-testid={`task-chat-queued-steer-${entry.comment.id}`}
|
||
>
|
||
{action === "steer" ? (
|
||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||
) : (
|
||
<CornerDownRight className="h-3.5 w-3.5" aria-hidden />
|
||
)}
|
||
Steer
|
||
</button>
|
||
)}
|
||
|
||
<button
|
||
type="button"
|
||
onClick={onDiscard}
|
||
disabled={
|
||
busy ||
|
||
(!queue.queueId && !entry.comment.id.startsWith("optimistic-")) ||
|
||
!entry.canDiscard
|
||
}
|
||
title="Discard queued message"
|
||
aria-label={`Discard queued message: ${entry.comment.body}`}
|
||
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-40"
|
||
data-testid={`task-chat-queued-discard-${entry.comment.id}`}
|
||
>
|
||
{action === "discard" ? (
|
||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||
) : (
|
||
<Trash2 className="h-3.5 w-3.5" aria-hidden />
|
||
)}
|
||
</button>
|
||
|
||
<DropdownMenu>
|
||
<DropdownMenuTrigger asChild>
|
||
<button
|
||
type="button"
|
||
disabled={queueMutationDisabled}
|
||
title="Queued message actions"
|
||
aria-label={`Queued message actions: ${entry.comment.body}`}
|
||
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
|
||
>
|
||
<MoreHorizontal className="h-4 w-4" aria-hidden />
|
||
</button>
|
||
</DropdownMenuTrigger>
|
||
<DropdownMenuContent align="end" className="w-44">
|
||
<DropdownMenuItem disabled={!entry.canEdit} onSelect={onEdit}>
|
||
<Pencil className="h-4 w-4" aria-hidden />
|
||
Edit message
|
||
</DropdownMenuItem>
|
||
</DropdownMenuContent>
|
||
</DropdownMenu>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Compact production queue shown immediately above the default task composer. */
|
||
export function TaskChatQueuedMessages({
|
||
queue,
|
||
onEdit,
|
||
onReorder,
|
||
onSteer,
|
||
onInterrupt,
|
||
onDiscard,
|
||
}: TaskChatQueuedMessagesProps) {
|
||
const [entries, setEntries] = useState(queue.entries);
|
||
const [pending, setPending] = useState<{
|
||
commentId: string;
|
||
action: Exclude<QueueAction, null>;
|
||
} | null>(null);
|
||
const [reordering, setReordering] = useState(false);
|
||
const [announcement, setAnnouncement] = useState("");
|
||
const [visibleError, setVisibleError] = useState<string | null>(null);
|
||
const sensors = useSensors(
|
||
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
|
||
useSensor(KeyboardSensor, {
|
||
coordinateGetter: sortableKeyboardCoordinates,
|
||
}),
|
||
);
|
||
|
||
useEffect(() => {
|
||
setEntries(queue.entries);
|
||
}, [queue.entries, queue.revision]);
|
||
|
||
const ids = useMemo(
|
||
() => entries.map((entry) => entry.comment.id),
|
||
[entries],
|
||
);
|
||
|
||
async function handleDragEnd(event: DragEndEvent) {
|
||
const { active, over } = event;
|
||
if (
|
||
!queue.queueId ||
|
||
!over ||
|
||
active.id === over.id ||
|
||
reordering ||
|
||
pending
|
||
)
|
||
return;
|
||
const previous = entries;
|
||
const next = reorderQueuedMessageEntries(
|
||
entries,
|
||
String(active.id),
|
||
String(over.id),
|
||
);
|
||
if (!next) return;
|
||
const orderedIds = next.map((entry) => entry.comment.id);
|
||
const activeCommentId = String(active.id);
|
||
const to = next.findIndex((entry) => entry.comment.id === activeCommentId);
|
||
setEntries(next);
|
||
setReordering(true);
|
||
setVisibleError(null);
|
||
setAnnouncement(
|
||
`Moved queued message to position ${to + 1} of ${next.length}.`,
|
||
);
|
||
try {
|
||
await onReorder(orderedIds, queue.revision);
|
||
} catch (error) {
|
||
setEntries(previous);
|
||
setAnnouncement("");
|
||
setVisibleError(
|
||
queueActionErrorCode(error) === "queued_comment_revision_conflict"
|
||
? "The queue changed in another session. Its latest order has been restored."
|
||
: "Couldn’t reorder. Previous order restored.",
|
||
);
|
||
} finally {
|
||
setReordering(false);
|
||
}
|
||
}
|
||
|
||
async function runRowAction(
|
||
commentId: string,
|
||
action: Exclude<QueueAction, null>,
|
||
) {
|
||
const locallyDiscardable =
|
||
action === "discard" && commentId.startsWith("optimistic-");
|
||
if (
|
||
pending ||
|
||
reordering ||
|
||
(!queue.queueId && action !== "interrupt" && !locallyDiscardable)
|
||
) {
|
||
return;
|
||
}
|
||
const previous = entries;
|
||
setPending({ commentId, action });
|
||
setVisibleError(null);
|
||
setAnnouncement(
|
||
action === "steer"
|
||
? "Steering queued message."
|
||
: action === "interrupt"
|
||
? "Sending queued messages."
|
||
: "Discarding queued message.",
|
||
);
|
||
if (action === "steer") {
|
||
setEntries((current) =>
|
||
current.filter((entry) => entry.comment.id !== commentId),
|
||
);
|
||
}
|
||
try {
|
||
if (action === "steer") await onSteer(commentId, queue.revision);
|
||
else if (action === "interrupt") await onInterrupt?.();
|
||
else await onDiscard(commentId, queue.revision);
|
||
if (action === "discard") {
|
||
setEntries((current) =>
|
||
current.filter((entry) => entry.comment.id !== commentId),
|
||
);
|
||
}
|
||
setAnnouncement(
|
||
action === "steer"
|
||
? "Message steered into the active turn."
|
||
: action === "interrupt"
|
||
? "Queued messages will be sent when the previous run has stopped."
|
||
: "Queued message discarded.",
|
||
);
|
||
} catch (error) {
|
||
if (action === "steer") setEntries(previous);
|
||
setAnnouncement("");
|
||
const code = queueActionErrorCode(error);
|
||
setVisibleError(
|
||
code === "queued_comment_already_dispatching"
|
||
? "Too late to discard: this message is already being sent."
|
||
: action === "steer"
|
||
? "Couldn’t steer. Message is still queued."
|
||
: action === "interrupt"
|
||
? "Couldn’t interrupt. Message is still queued."
|
||
: code === "queued_comment_revision_conflict"
|
||
? "The queue changed in another session. Review it and try again."
|
||
: "Couldn’t discard. Message is still queued.",
|
||
);
|
||
} finally {
|
||
setPending(null);
|
||
}
|
||
}
|
||
|
||
if (entries.length === 0) return null;
|
||
|
||
return (
|
||
<div
|
||
className="relative z-0 mx-3 -mb-px overflow-hidden rounded-t-xl rounded-b-none border border-b-0 border-border/75 bg-card shadow-sm"
|
||
data-testid="task-chat-queued-messages"
|
||
aria-label="Queued messages"
|
||
>
|
||
{queue.executionWait && (
|
||
<div role="status" aria-live="polite" className="px-3 py-1.5 text-xs text-muted-foreground">
|
||
{queue.executionWait.message}
|
||
</div>
|
||
)}
|
||
<DndContext
|
||
sensors={sensors}
|
||
collisionDetection={closestCenter}
|
||
onDragEnd={(event) => void handleDragEnd(event)}
|
||
>
|
||
<SortableContext items={ids} strategy={verticalListSortingStrategy}>
|
||
{entries.map((entry) => {
|
||
const action =
|
||
pending?.commentId === entry.comment.id ? pending.action : null;
|
||
const busy = Boolean(pending || reordering);
|
||
const queueMutationDisabled = Boolean(
|
||
!queue.queueId || pending || reordering,
|
||
);
|
||
return (
|
||
<SortableQueuedMessage
|
||
key={entry.comment.id}
|
||
entry={entry}
|
||
queue={queue}
|
||
busy={busy}
|
||
queueMutationDisabled={queueMutationDisabled}
|
||
action={action}
|
||
onEdit={() => onEdit(entry.comment.id)}
|
||
onSteer={() => void runRowAction(entry.comment.id, "steer")}
|
||
onInterrupt={
|
||
onInterrupt
|
||
? () => void runRowAction(entry.comment.id, "interrupt")
|
||
: undefined
|
||
}
|
||
onDiscard={() => void runRowAction(entry.comment.id, "discard")}
|
||
/>
|
||
);
|
||
})}
|
||
</SortableContext>
|
||
</DndContext>
|
||
{visibleError ? (
|
||
<div
|
||
role="status"
|
||
aria-live="polite"
|
||
className="border-t border-destructive/20 bg-destructive/5 px-3 py-1.5 text-xs text-destructive"
|
||
>
|
||
{visibleError}
|
||
</div>
|
||
) : null}
|
||
<div className="sr-only" aria-live="polite" aria-atomic="true">
|
||
{announcement}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|