Skip to content

Open source CapCut alternative.

TypeScript

feat(site): chat message queue in a composer tray

David Le7808ea1e3d61
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index bba9307b..c0e3dee0 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -31,6 +31,8 @@ The Gemini path skips the engine entirely — the same carve-out as AI media gen
Two mechanisms keep a turn honest. A mutation ledger, computed in code from the tool results, rides every model call as an ephemeral context note: what ran, what failed, and what debris the edits left (a parked transition bar, an item stranded past the video's end) — the model must fix or plainly report each entry before its reply lands, and the note is never stored or rendered. And the round budget extends itself: a build that outgrows its 24 rounds gets fresh budget automatically (up to three extensions, then a hard stop that forces a status reply), so the user never types "keep going".
+The composer stays open while a turn runs. A message sent mid-turn waits in a small tray on the composer's top edge and goes out when the running turn settles — one turn at a time, each with a fresh editor snapshot, so a queued ask always sees the edits made before it. The tray is the review surface: waiting rows can be reordered, rewritten, or removed, and the queue pauses and resumes from its header. While a row is being rewritten the list holds still — the row under edit waits, the others keep draining and cross out in place as they finish. Stopping a turn or hitting an error pauses the queue automatically, so the remaining asks hold for review. Waiting rows are saved with the thread on the machine: a reload or a trip to another project brings them back paused, ready to resume.
+
Which path runs is chosen by the model id alone. The picker lives in the page so a site deploy updates it for everyone; the engine only reports which CLIs are installed and signed in (probed and cached for a minute), and the page overlays Gemini availability from its own sign-in probe.
## What the model knows
diff --git a/site/src/components/ui/scroll-area.tsx b/site/src/components/ui/scroll-area.tsx
index 97f56aaa..ef20a555 100644
--- a/site/src/components/ui/scroll-area.tsx
+++ b/site/src/components/ui/scroll-area.tsx
@@ -10,14 +10,24 @@ import { cn } from "@/lib/utils"
* content: it fades in while the pointer is inside or the view is scrolling,
* and it takes no width from the layout, so a narrow column keeps every pixel
* it has. `contentClassName` styles the scrolling content itself — padding and
- * layout belong there, sizing on the outer element.
+ * layout belong there, sizing on the outer element. The viewport props reach
+ * the element that actually scrolls, for callers that pin to the bottom or
+ * find the scroller by class.
*/
function ScrollArea({
className,
contentClassName,
+ viewportClassName,
+ viewportRef,
+ onViewportScroll,
children,
...props
-}: ScrollAreaPrimitive.Root.Props & { contentClassName?: string }) {
+}: ScrollAreaPrimitive.Root.Props & {
+ contentClassName?: string
+ viewportClassName?: string
+ viewportRef?: React.Ref<HTMLDivElement>
+ onViewportScroll?: React.UIEventHandler<HTMLDivElement>
+}) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
@@ -26,7 +36,12 @@ function ScrollArea({
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
- className="size-full rounded-[inherit] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"
+ ref={viewportRef}
+ onScroll={onViewportScroll}
+ className={cn(
+ "size-full rounded-[inherit] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
+ viewportClassName
+ )}
>
<ScrollAreaPrimitive.Content
data-slot="scroll-area-content"
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index c6a677f7..21566b03 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -32,6 +32,7 @@ import { LiveElapsed } from "./Elapsed";
import { SceneCard } from "./SceneCard";
import { useElapsed } from "@/cut/hooks/useElapsed";
import { Button } from "@/components/ui/button";
+import { ScrollArea } from "@/components/ui/scroll-area";
import {
DropdownMenu,
DropdownMenuContent,
@@ -100,6 +101,7 @@ import { useEditor } from "@/cut/lib/store";
import { cn } from "@/lib/utils";
import { cardIconButton } from "@/cut/components/iconButton";
import { MentionTextarea, RefChips, RefThumb, RefTokenChip } from "./AssetRefs";
+import { ComposerQueue, type QueuedMessage } from "./ComposerQueue";
import { DictationBody } from "./MicDictation";
import { RECORD_RUNNING_TTL_MS, ToolOutputAssets } from "./ChatAssets";
import { HostedErrorText } from "./hostedError";
@@ -246,6 +248,8 @@ function writeThreads(projectId: string, list: ChatThread[]) {
if (!keptIds.has(t.id)) {
useGenScene.getState().killThread(t.id);
deleteCloudThread(projectId, t.id);
+ if (typeof window !== "undefined")
+ localStorage.removeItem(queueKey(projectId, t.id));
}
}
writeRawThreads(projectId, slimForStorage(kept));
@@ -253,6 +257,35 @@ function writeThreads(projectId: string, list: ChatThread[]) {
const MODEL_KEY = "cut-ai-model";
const FAVS_KEY = "cut-ai-favs";
+
+// Waiting composer-queue rows, saved per thread so a reload or a project
+// switch brings them back. Running and done rows stay out — their turns die
+// with the page.
+const queueKey = (projectId: string, threadId: string) =>
+ `cut-ai-queue-${projectId}-${threadId}`;
+function readStoredQueue(
+ projectId: string,
+ threadId: string,
+): QueuedMessage[] {
+ if (typeof window === "undefined") return [];
+ try {
+ const raw = localStorage.getItem(queueKey(projectId, threadId));
+ if (!raw) return [];
+ return (JSON.parse(raw) as QueuedMessage[])
+ .filter(
+ (m) =>
+ m?.status === "queued" &&
+ typeof m.id === "string" &&
+ typeof m.text === "string",
+ )
+ .map((m) => ({
+ ...m,
+ attachments: Array.isArray(m.attachments) ? m.attachments : [],
+ }));
+ } catch {
+ return [];
+ }
+}
// A fresh user starts on Gemini — it runs on their signed-in Donkey account, so
// it works without a local CLI. Claude/Codex show up automatically once the
// engine probes them installed. The choice persists, so this is first-run only.
@@ -377,6 +410,7 @@ export function AiPanel({
// into Media/Library stays.
deleteChatAssets(id);
deleteCloudThread(projectId, id);
+ localStorage.removeItem(queueKey(projectId, id));
// Its work dies with it too: a scene run the thread owned aborts and its
// plan clears — nothing keeps running behind a conversation the user killed.
useGenScene.getState().killThread(id);
@@ -954,21 +988,74 @@ function ChatSession({
}, [messages, busy]);
const [sendError, setSendError] = useState<string | null>(null);
+ // Messages submitted while a turn runs wait here and dispatch one at a time
+ // as turns settle. Waiting rows persist per thread, so a reload or a trip
+ // to another project brings them back — paused, so nothing fires on its
+ // own until the user resumes.
+ const [initialQueue] = useState(() => readStoredQueue(projectId, threadId));
+ const [queue, setQueue] = useState<QueuedMessage[]>(initialQueue);
+ const [queuePaused, setQueuePaused] = useState(initialQueue.length > 0);
+ const [queueEditing, setQueueEditing] = useState<string | null>(null);
+ const drainedRef = useRef(false);
+ // Height of the floating stack above the composer (warning tabs + queue
+ // tray); the messages pad their bottom by it so the newest message can
+ // scroll out from behind the stack.
+ const overlayRef = useRef<HTMLDivElement>(null);
+ const [overlayH, setOverlayH] = useState(0);
+ useEffect(() => {
+ const el = overlayRef.current;
+ if (!el) return;
+ const ro = new ResizeObserver(() => setOverlayH(el.offsetHeight));
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [readOnly]);
+ const currentAvailable = info
+ ? info.providers[provider(model)]?.available !== false
+ : true;
+ const unavailableMessage = (): string => {
+ const p = provider(model);
+ if (p === "gemini") return "Sign in to your Donkey account to chat with Gemini.";
+ const note = info?.providers[p]?.note?.trim();
+ return note ? `${PROVIDER_LABEL[p]}: ${note}` : `${PROVIDER_LABEL[p]} isn't available.`;
+ };
const send = (text: string) => {
// Inline @mentions attach their assets alongside the dropped chips. The
// message keeps the raw tokens — they render as interactive chips and the
// model reads the handle↔asset mapping from <attached_assets>.
const body = text.trim();
const { refs: all } = collectRefs(body, attachments, candidates);
- if ((!body && all.length === 0) || busy) return;
+ if (!body && all.length === 0) return;
// An unavailable provider surfaces as an error in the thread at send time
// rather than a standing footer note: say why nothing sent, then stop.
if (!currentAvailable) {
setSendError(unavailableMessage());
return;
}
+ if (busy) {
+ // A paused queue stays paused: parked rows fire only from the tray's
+ // resume button, never as a side effect of submitting something new.
+ setQueue((q) => [
+ ...q,
+ { id: crypto.randomUUID(), text: body, attachments: all, status: "queued" },
+ ]);
+ setInput("");
+ setAttachments([]);
+ pinnedRef.current = true;
+ return;
+ }
clearError();
setSendError(null);
+ // A direct send starts a new turn; a row still marked running belongs to
+ // the settled one — sweep it, or cross it out under a frozen view.
+ setQueue((q) =>
+ q.flatMap((m) =>
+ m.status !== "running"
+ ? [m]
+ : queueEditing === null
+ ? []
+ : [{ ...m, status: "done" as const }],
+ ),
+ );
pinnedRef.current = true;
void sendMessage({
text: body,
@@ -978,15 +1065,78 @@ function ChatSession({
setAttachments([]);
};
- const currentAvailable = info
- ? info.providers[provider(model)]?.available !== false
- : true;
- const unavailableMessage = (): string => {
- const p = provider(model);
- if (p === "gemini") return "Sign in to your Donkey account to chat with Gemini.";
- const note = info?.providers[p]?.note?.trim();
- return note ? `${PROVIDER_LABEL[p]}: ${note}` : `${PROVIDER_LABEL[p]} isn't available.`;
- };
+ // Drain the queue as turns settle. drainedRef keeps it to one dispatch per
+ // ready period — the effect re-runs when the queue changes before useChat
+ // surfaces the new turn's status. A dispatched row stays in the queue as
+ // running until the next dispatch settles it: it leaves the tray, or stays
+ // crossed out in place while an open row edit has the view frozen. The edit
+ // skips only its own row — the rest keep draining. An unavailable provider
+ // holds the drain the same way it stops a direct send; the tray reads as
+ // paused until the user switches models or the provider comes back.
+ // Defined after the settle-flush effect above, so the finished transcript
+ // saves before the next turn starts mutating messages.
+ useEffect(() => {
+ if (status !== "ready") {
+ drainedRef.current = false;
+ return;
+ }
+ if (drainedRef.current || queuePaused || !currentAvailable) return;
+ const next = queue.find(
+ (m) => m.status === "queued" && m.id !== queueEditing,
+ );
+ if (!next) return;
+ drainedRef.current = true;
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- the drain reacts to the chat stream settling; drainedRef caps it at one guarded dispatch per ready period
+ setQueue((q) =>
+ q.flatMap((m) => {
+ if (m.id === next.id) return [{ ...m, status: "running" as const }];
+ if (m.status !== "running") return [m];
+ return queueEditing === null
+ ? []
+ : [{ ...m, status: "done" as const }];
+ }),
+ );
+ setSendError(null);
+ pinnedRef.current = true;
+ // A restored row's attachments may point at assets deleted since it was
+ // parked (or at file blobs that died with the last page); dropping the
+ // dead refs keeps the message from claiming media it can't deliver.
+ const live = next.attachments.filter(
+ (a) =>
+ !a.url?.startsWith("blob:") &&
+ (a.scope !== "project" ||
+ useEditor.getState().assets.some((x) => x.id === a.id)),
+ );
+ void sendMessage({
+ text: next.text,
+ ...(live.length > 0 && { metadata: { attachments: live } }),
+ });
+ }, [status, queue, queuePaused, queueEditing, currentAvailable, sendMessage]);
+
+ // Mirror the waiting rows to storage as they change; an empty queue clears
+ // its slot.
+ useEffect(() => {
+ if (readOnly) return;
+ const waiting = queue.filter((m) => m.status === "queued");
+ if (waiting.length === 0)
+ localStorage.removeItem(queueKey(projectId, threadId));
+ else
+ localStorage.setItem(
+ queueKey(projectId, threadId),
+ JSON.stringify(waiting),
+ );
+ }, [queue, projectId, threadId, readOnly]);
+
+ // An errored turn holds the queue for review — the drain only fires on
+ // 'ready', and the tray reads the error as paused. Resuming clears the
+ // error, which settles status back to ready and releases the drain. An
+ // unavailable provider holds it the same way.
+ const queueHeld = queuePaused || status === "error" || !currentAvailable;
+ // The tray shows only while a row is waiting; settled running rows linger
+ // in the array until the next dispatch sweeps them, and alone they are
+ // nothing to show.
+ const trayVisible = queue.some((m) => m.status === "queued");
+
// The saved model's provider may be uninstalled — its group is hidden from
// the picker, so fall back to the first installed provider rather than sit on
// a selection the user can no longer see or change.
@@ -1006,18 +1156,19 @@ function ChatSession({
{...targetProps}
className="relative flex min-h-0 flex-1 flex-col"
>
- <div
- ref={scrollRef}
- onScroll={onMessagesScroll}
- className={cn(
- "ai-messages min-h-0 flex-1 overflow-y-auto px-3.5 py-3",
- // The credits tab floats over the bottom of this area; the extra
- // padding lets the last message scroll out from behind it.
- outOfCredits && "pb-9",
- )}
+ <ScrollArea
+ className="min-h-0 flex-1"
+ // Scene cards and the pinning logic reach the scrolling element by
+ // class and ref, so both ride the viewport.
+ viewportClassName="ai-messages"
+ viewportRef={scrollRef}
+ onViewportScroll={onMessagesScroll}
+ contentClassName="px-3.5 py-3"
>
- {/* Single wrapper so the ResizeObserver sees all content growth. */}
- <div>
+ {/* Single wrapper so the ResizeObserver sees all content growth. The
+ bottom padding matches the floating stack over the composer, so
+ the newest message can scroll out from behind it. */}
+ <div style={{ paddingBottom: overlayH }}>
{messages.length === 0 && !hasSceneRun && (
<div className="flex flex-col gap-3 pt-6">
<p className="text-[12.5px] leading-relaxed text-muted-foreground">
@@ -1065,42 +1216,102 @@ function ChatSession({
</div>
)}
</div>
- </div>
+ </ScrollArea>
{!readOnly && (
<div className="shrink-0 px-2.5 pb-2.5">
<div className="relative">
- {outOfCredits && (
- // Folder tab behind the box: its bottom few pixels slide under the
- // box, which paints over it, so the tab meets the border even where
- // the box's corner radius curves away. Extra bottom padding keeps
- // the text above the overlap. It floats over the messages, which
- // scroll behind it.
- <a
- className="ai-credits-tab absolute inset-x-1.5 bottom-full -mb-1 flex items-center gap-1.5 rounded-t-lg border border-b-0 border-amber-500/30 bg-amber-50 px-3 pt-1.5 pb-2.5 text-[11px] text-amber-800"
- href={creditsUrl()}
- target="_blank"
- rel="noreferrer"
- >
- <TriangleAlert className="size-3 shrink-0" />
- <span>
- No credits left —{" "}
- <span className="font-medium underline">reload credits</span>
- </span>
- </a>
- )}
- {!outOfCredits && notice && (
- // The credits tab's folder shape, borrowed for transient
- // refusals; the credits warning outranks it when both apply.
- <div className="ai-notice-tab absolute inset-x-1.5 bottom-full -mb-1 flex items-center gap-1.5 rounded-t-lg border border-b-0 border-amber-500/30 bg-amber-50 px-3 pt-1.5 pb-2.5 text-[11px] text-amber-800">
- <TriangleAlert className="size-3 shrink-0" />
- <span>{notice}</span>
- </div>
- )}
+ {/* The stack above the composer — warning tabs first, then the
+ queue tray — floats over the messages, which scroll behind it;
+ the messages pad their bottom by its measured height so the
+ newest message still lands in view. Its bottom few pixels slide
+ under the composer box, which paints over them, so the bottom
+ piece meets the border even where the box's corner radius
+ curves away. */}
+ <div
+ ref={overlayRef}
+ className="pointer-events-none absolute inset-x-0 bottom-full z-10 -mb-1 flex flex-col"
+ >
+ {outOfCredits && (
+ <a
+ className={cn(
+ "ai-credits-tab pointer-events-auto mx-1.5 flex items-center gap-1.5 rounded-t-lg border border-b-0 border-amber-500/30 bg-amber-50 px-3 pt-1.5 pb-2.5 text-[11px] text-amber-800",
+ // With the tray below, the tab tucks under it the same way
+ // the stack tucks under the composer.
+ trayVisible && "-mb-1",
+ )}
+ href={creditsUrl()}
+ target="_blank"
+ rel="noreferrer"
+ >
+ <TriangleAlert className="size-3 shrink-0" />
+ <span>
+ No credits left —{" "}
+ <span className="font-medium underline">reload credits</span>
+ </span>
+ </a>
+ )}
+ {!outOfCredits && notice && (
+ // The credits tab's folder shape, borrowed for transient
+ // refusals; the credits warning outranks it when both apply.
+ <div
+ className={cn(
+ "ai-notice-tab pointer-events-auto mx-1.5 flex items-center gap-1.5 rounded-t-lg border border-b-0 border-amber-500/30 bg-amber-50 px-3 pt-1.5 pb-2.5 text-[11px] text-amber-800",
+ trayVisible && "-mb-1",
+ )}
+ >
+ <TriangleAlert className="size-3 shrink-0" />
+ <span>{notice}</span>
+ </div>
+ )}
+ {trayVisible && (
+ <div className="pointer-events-auto">
+ <ComposerQueue
+ items={queue}
+ paused={queueHeld}
+ busy={busy}
+ editingId={queueEditing}
+ onEditingChange={(id) => {
+ setQueueEditing(id);
+ // Closing the freeze sweeps out the crossed-out rows it kept
+ // around for display.
+ if (id === null)
+ setQueue((q) => q.filter((m) => m.status === "queued"));
+ }}
+ onCommitEdit={(id, text) =>
+ setQueue((q) =>
+ q.map((m) =>
+ m.id === id ? { ...m, text: text.trim() || m.text } : m,
+ ),
+ )
+ }
+ onRemove={(id) => setQueue((q) => q.filter((m) => m.id !== id))}
+ onReorder={(from, to) =>
+ setQueue((q) => {
+ const next = [...q];
+ const [grabbed] = next.splice(from, 1);
+ next.splice(to, 0, grabbed);
+ return next;
+ })
+ }
+ onTogglePaused={() => {
+ if (status === "error") {
+ clearError();
+ setQueuePaused(false);
+ } else {
+ setQueuePaused((p) => !p);
+ }
+ }}
+ />
+ </div>
+ )}
+ </div>
<div
ref={composerBoxRef}
className={cn(
- "relative rounded-xl border bg-background transition-colors",
+ // z above the floating stack so the box paints over its tucked
+ // bottom edge.
+ "relative z-10 rounded-xl border bg-background transition-colors",
dropActive
? "border-[#0a84ff] ring-2 ring-[#0a84ff]/30"
: fileDropHint
@@ -1175,7 +1386,15 @@ function ChatSession({
size="sm"
className="ai-stop"
title="Stop"
- onClick={() => void stop()}
+ onClick={() => {
+ // stop() settles to 'ready', which the drain reads as
+ // a clean finish — park the queue here so it stays put
+ // for review. An empty queue has nothing to park, and
+ // pausing it anyway would leave a stale flag.
+ if (queue.some((m) => m.status === "queued"))
+ setQueuePaused(true);
+ void stop();
+ }}
>
<Square className="size-3" />
</Button>
diff --git a/site/src/cut/components/ComposerQueue.tsx b/site/src/cut/components/ComposerQueue.tsx
new file mode 100644
index 00000000..a88407c8
--- /dev/null
+++ b/site/src/cut/components/ComposerQueue.tsx
@@ -0,0 +1,348 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import {
+ Check,
+ ChevronDown,
+ GripVertical,
+ Loader2,
+ Pause,
+ Pencil,
+ Play,
+ Trash2,
+} from "lucide-react";
+import { cn } from "@/lib/utils";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { RefThumb } from "./AssetRefs";
+import type { AssetRef } from "@/cut/lib/assetRef";
+
+/** Small icon control on a tray row or the tray header. */
+const queueIconButton =
+ "grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted-foreground/20 hover:text-foreground";
+
+/** A message waiting its turn while the assistant works. Attachments are
+ * captured at enqueue time, so mentions and chips ride exactly as typed.
+ * Running and done rows exist only while an open edit freezes the view —
+ * they render crossed out there; outside a freeze they leave the tray. */
+export interface QueuedMessage {
+ id: string;
+ text: string;
+ attachments: AssetRef[];
+ status: "queued" | "running" | "done";
+}
+
+/** The queue tray: a folder tab on top of the composer holding the messages
+ * waiting for the running turn to settle. Rows can be reordered by drag,
+ * rewritten in place, or removed; the header pauses and resumes dispatch and
+ * collapses the list. While a row is being edited the visible list freezes:
+ * the other rows keep draining, and each one that dispatches stays in place —
+ * a spinner while its turn runs, crossed out once it settles — so the editor
+ * never shifts under the cursor. Mounted only while the queue has items. */
+export function ComposerQueue({
+ items,
+ paused,
+ busy,
+ editingId,
+ onEditingChange,
+ onCommitEdit,
+ onRemove,
+ onReorder,
+ onTogglePaused,
+}: {
+ items: QueuedMessage[];
+ paused: boolean;
+ /** Whether a turn is streaming right now. A running row spins only while
+ * its turn is live; once the turn settles it reads as done, even before
+ * the next dispatch rewrites its stored status. */
+ busy: boolean;
+ editingId: string | null;
+ onEditingChange: (id: string | null) => void;
+ onCommitEdit: (id: string, text: string) => void;
+ onRemove: (id: string) => void;
+ onReorder: (from: number, to: number) => void;
+ onTogglePaused: () => void;
+}) {
+ const [open, setOpen] = useState(true);
+ const dragFrom = useRef<number | null>(null);
+ const [dragOver, setDragOver] = useState<number | null>(null);
+ const frozen = editingId !== null;
+ const waiting = items.filter((m) => m.status === "queued");
+ // Rows carry their index in the full queue so a reorder maps back to it.
+ const rows = items
+ .map((item, index) => ({ item, index }))
+ .filter(({ item }) => frozen || item.status === "queued");
+ // The wrapper owns the list height: the rows' measured height capped at
+ // 38vh, animated to zero on collapse, clipped while it moves. The scroll
+ // area fills the wrapper and floats the slim scrollbar over the rows once
+ // the cap bites.
+ const listRef = useRef<HTMLDivElement>(null);
+ const [listH, setListH] = useState(0);
+ useEffect(() => {
+ const el = listRef.current;
+ if (!el) return;
+ const measure = () =>
+ setListH(Math.min(el.offsetHeight, window.innerHeight * 0.38));
+ const ro = new ResizeObserver(measure);
+ ro.observe(el);
+ window.addEventListener("resize", measure);
+ return () => {
+ ro.disconnect();
+ window.removeEventListener("resize", measure);
+ };
+ }, []);
+
+ return (
+ // The floating stack in the panel tucks the tray's bottom few pixels
+ // under the composer box; the bottom padding keeps the rows above that
+ // overlap.
+ <div className="ai-queue-tray relative mx-1.5 rounded-t-lg border border-b-0 border-border bg-muted pb-1">
+ <div
+ className={cn(
+ "flex items-center gap-2 px-3 py-1",
+ open && "border-b border-border",
+ )}
+ >
+ <button
+ type="button"
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ onClick={() => setOpen(!open)}
+ >
+ <span className="shrink-0 text-[11px] font-medium text-muted-foreground">
+ {waiting.length === 1 ? "1 up next" : `${waiting.length} in queue`}
+ </span>
+ {paused && (
+ <span className="truncate text-[11px] text-muted-foreground/60">
+ Paused
+ </span>
+ )}
+ </button>
+ <div className="flex shrink-0 items-center gap-0.5">
+ <button
+ type="button"
+ className={queueIconButton}
+ title={paused ? "Resume the queue" : "Pause the queue"}
+ onClick={onTogglePaused}
+ >
+ {paused ? <Play className="size-3" /> : <Pause className="size-3" />}
+ </button>
+ <button
+ type="button"
+ className={queueIconButton}
+ title={open ? "Collapse" : "Expand"}
+ onClick={() => setOpen(!open)}
+ >
+ <ChevronDown
+ className={cn(
+ "size-3 transition-transform duration-200 motion-reduce:transition-none",
+ !open && "rotate-180",
+ )}
+ />
+ </button>
+ </div>
+ </div>
+
+ <div
+ className="overflow-hidden transition-[height,opacity] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none"
+ style={{ height: open ? listH : 0, opacity: open ? 1 : 0 }}
+ >
+ <ScrollArea className="h-full">
+ <div ref={listRef}>
+ {rows.map(({ item: it, index }) => {
+ const isEditing = editingId === it.id;
+ const shown =
+ it.status === "running" && !busy ? "done" : it.status;
+ const gone = shown !== "queued";
+ const locked = frozen && !isEditing;
+ return (
+ <div
+ key={it.id}
+ draggable={!frozen}
+ onDragStart={(e) => {
+ dragFrom.current = index;
+ e.dataTransfer.effectAllowed = "move";
+ // The browser snapshots the row on a flat backdrop, which
+ // squares off its corners; hand it a styled clone so the
+ // ghost keeps the rounded row shape.
+ const el = e.currentTarget;
+ const rect = el.getBoundingClientRect();
+ const ghost = el.cloneNode(true) as HTMLElement;
+ // The row hugs the tray edge-to-edge; the detached ghost
+ // gets its rounding back.
+ ghost.className = cn(
+ el.className,
+ "fixed overflow-hidden rounded-lg bg-muted shadow-md",
+ );
+ ghost.style.width = `${rect.width}px`;
+ ghost.style.top = "-1000px";
+ ghost.style.left = "-1000px";
+ document.body.appendChild(ghost);
+ e.dataTransfer.setDragImage(
+ ghost,
+ e.clientX - rect.left,
+ e.clientY - rect.top,
+ );
+ setTimeout(() => ghost.remove(), 0);
+ }}
+ onDragOver={(e) => {
+ e.preventDefault();
+ setDragOver(index);
+ }}
+ onDrop={(e) => {
+ e.preventDefault();
+ if (dragFrom.current !== null && dragFrom.current !== index)
+ onReorder(dragFrom.current, index);
+ dragFrom.current = null;
+ setDragOver(null);
+ }}
+ onDragEnd={() => {
+ dragFrom.current = null;
+ setDragOver(null);
+ }}
+ className={cn(
+ "group flex items-start gap-1.5 px-2.5 py-1.5 transition-colors duration-100 motion-reduce:transition-none",
+ dragOver === index
+ ? "bg-muted-foreground/20"
+ : !isEditing &&
+ !locked &&
+ !gone &&
+ "hover:bg-muted-foreground/10",
+ )}
+ >
+ {!isEditing && (
+ <span className="mt-0.5 -ml-0.5 shrink-0">
+ {shown === "running" ? (
+ <Loader2 className="size-3.5 animate-spin text-muted-foreground/60" />
+ ) : shown === "done" ? (
+ <Check className="size-3.5 text-muted-foreground/60" />
+ ) : (
+ <GripVertical className="size-3.5 cursor-grab text-muted-foreground/60" />
+ )}
+ </span>
+ )}
+ <div className="min-w-0 flex-1">
+ {isEditing ? (
+ <QueueEditBox
+ initial={it.text}
+ onCancel={() => onEditingChange(null)}
+ onSave={(v) => {
+ onCommitEdit(it.id, v);
+ onEditingChange(null);
+ }}
+ />
+ ) : (
+ <>
+ <div
+ className={cn(
+ "text-xs leading-snug break-words",
+ locked || gone
+ ? "text-muted-foreground/60"
+ : "text-foreground",
+ gone && "line-through decoration-muted-foreground/40",
+ )}
+ >
+ {it.text}
+ </div>
+ {it.attachments.length > 0 && (
+ <div
+ className={cn(
+ "mt-1 flex flex-wrap gap-1",
+ gone && "opacity-50",
+ )}
+ >
+ {it.attachments.map((a) => (
+ <RefThumb
+ key={`${a.scope}:${a.id}`}
+ item={a}
+ className={
+ a.kind === "audio" ? "h-8 w-14" : "size-8"
+ }
+ />
+ ))}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ {!isEditing && !locked && !gone && (
+ <div className="flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 motion-reduce:transition-none">
+ <button
+ type="button"
+ className={queueIconButton}
+ title="Edit this message"
+ onClick={() => onEditingChange(it.id)}
+ >
+ <Pencil className="size-3" />
+ </button>
+ <button
+ type="button"
+ className={queueIconButton}
+ title="Remove from the queue"
+ onClick={() => onRemove(it.id)}
+ >
+ <Trash2 className="size-3" />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </ScrollArea>
+ </div>
+ </div>
+ );
+}
+
+function QueueEditBox({
+ initial,
+ onCancel,
+ onSave,
+}: {
+ initial: string;
+ onCancel: () => void;
+ onSave: (text: string) => void;
+}) {
+ const [value, setValue] = useState(initial);
+ const ref = useRef<HTMLTextAreaElement>(null);
+ useEffect(() => {
+ const el = ref.current;
+ if (el) {
+ el.focus();
+ el.setSelectionRange(el.value.length, el.value.length);
+ }
+ }, []);
+ return (
+ <div className="py-0.5">
+ <textarea
+ ref={ref}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ onSave(value);
+ }
+ if (e.key === "Escape") onCancel();
+ }}
+ rows={2}
+ className="w-full resize-none rounded-lg border border-input bg-background px-2.5 py-2 text-xs leading-relaxed text-foreground outline-none focus:border-ring"
+ />
+ <div className="mt-1.5 flex items-center gap-1.5">
+ <button
+ type="button"
+ className="inline-flex h-6 items-center gap-1 rounded-md bg-primary px-2 text-[11px] font-medium text-primary-foreground transition-colors hover:bg-primary/85"
+ onClick={() => onSave(value)}
+ >
+ <Check className="size-3" /> Save
+ </button>
+ <button
+ type="button"
+ className="h-6 rounded-md px-2 text-[11px] text-muted-foreground transition-colors hover:bg-muted-foreground/10"
+ onClick={onCancel}
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}