Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
3import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
4import type {
5 ChatAttachment as ContractChatAttachment,
6 EnvironmentId,
7 MessageId,
8 RunId,
9 ThreadId,
10} from "@t3tools/contracts";
11import {
12 Clock3Icon,
13 CornerUpRightIcon,
14 GripVerticalIcon,
15 ListOrderedIcon,
16 PencilIcon,
17 PauseIcon,
18} from "lucide-react";
19import { useId, useImperativeHandle, useMemo, useRef, useState, type Ref } from "react";
20
21import { useAssetUrls } from "../../assets/assetUrls";
22import { threadEnvironment } from "../../state/threads";
23import { useThreadProjection } from "../../state/entities";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { isImageAttachment, type ChatMessage } from "../../types";
26import { cn } from "~/lib/utils";
27import { ComposerBanner } from "./ComposerBanner";
28import { Button } from "../ui/button";
29import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30
31export interface EditQueuedRunRequest {
32 readonly runId: RunId;
33 readonly messageId: MessageId;
34 readonly text: string;
35 readonly attachments: ReadonlyArray<ContractChatAttachment>;
36}
37
38interface QueuedRowThumbnail {
39 readonly key: string;
40 readonly name: string;
41 readonly url: string | null;
42}
43
44const QUEUED_RUN_DRAG_TYPE = "application/x-t3code-queued-run";
45
46export interface QueuedRunsControlHandle {
47 steerNext: (repeat: boolean) => boolean;
48}
49
50export function QueuedRunsControl({
51 ref,
52 ...props
53}: {
54 readonly ref?: Ref<QueuedRunsControlHandle>;
55 readonly steerShortcutLabel?: string | null;
56 readonly environmentId: EnvironmentId;
57 readonly threadId: ThreadId;
58 readonly optimisticMessages: ReadonlyArray<
59 Pick<ChatMessage, "id" | "inputIntent" | "text" | "attachments">
60 >;
61 /** The saved queue entry stays visible while its draft is edited in the composer. */
62 readonly editingRunId: RunId | null;
63 readonly onEditQueuedRun: (request: EditQueuedRunRequest) => void;
64 readonly onCancelEdit: () => void;
65}) {
66 const projection = useThreadProjection(
67 scopeThreadRef(props.environmentId, props.threadId),
68 )?.projection;
69 const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun);
70 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun);
71 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun);
72 const resume = useAtomCommand(threadEnvironment.resumeThreadQueue);
73 const [resuming, setResuming] = useState(false);
74 const [expanded, setExpanded] = useState(true);
75 const queueListId = useId();
76 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
77 // Live drag-reorder state: the dragged run and the queue index the row
78 // would be inserted at (0..queued.length) as of the latest dragover.
79 const [dragState, setDragState] = useState<{
80 readonly runId: RunId;
81 readonly insertIndex: number | null;
82 } | null>(null);
83 // Drags must start from the grip, not from an accidental text-drag on the
84 // row. The grip arms its run id on pointerdown; dragstart verifies it.
85 const dragArmedRunIdRef = useRef<RunId | null>(null);
86 const workflow = useMemo(
87 () => (projection ? deriveThreadQueueWorkflowState(projection) : null),
88 [projection],
89 );
90 const queued = workflow?.queuedRuns ?? [];
91 const activeRun = workflow?.activeRun ?? null;
92 const canReorder = workflow?.canReorder === true;
93 const queuedImageAttachmentIds = useMemo(() => {
94 const ids: string[] = [];
95 for (const { attachments } of workflow?.queuedRuns ?? []) {
96 for (const attachment of attachments) {
97 if (attachment.type === "image") ids.push(attachment.id);
98 }
99 }
100 return ids;
101 }, [workflow]);
102 const queuedImageAttachmentResources = useMemo(
103 () =>
104 queuedImageAttachmentIds.map((attachmentId) => ({
105 _tag: "attachment" as const,
106 attachmentId,
107 })),
108 [queuedImageAttachmentIds],
109 );
110 const queuedImageAttachmentUrls = useAssetUrls(
111 props.environmentId,
112 queuedImageAttachmentResources,
113 );
114 const queuedImageUrlById = useMemo(
115 () =>
116 new Map(
117 queuedImageAttachmentIds.flatMap((attachmentId, index) => {
118 const url = queuedImageAttachmentUrls[index];
119 return url ? [[attachmentId, url] as const] : [];
120 }),
121 ),
122 [queuedImageAttachmentIds, queuedImageAttachmentUrls],
123 );
124 // Once the projection holds the message the optimistic copy is stale no
125 // matter what happened to its run — keying on still-queued runs alone would
126 // resurrect a phantom "pending" row after the run is cancelled or started.
127 const acknowledgedMessageIds = useMemo(
128 () => new Set((projection?.messages ?? []).map((message) => message.id)),
129 [projection],
130 );
131 const optimisticQueued = props.optimisticMessages.filter(
132 (message) => message.inputIntent === "queued_turn" && !acknowledgedMessageIds.has(message.id),
133 );
134 const items = [
135 ...queued.map(({ run, text, attachments }, serverIndex) => ({
136 key: run.id,
137 runId: run.id,
138 messageId: run.userMessageId,
139 serverIndex,
140 text,
141 attachments,
142 thumbnails: attachments
143 .filter((attachment) => attachment.type === "image")
144 .map<QueuedRowThumbnail>((attachment) => ({
145 key: attachment.id,
146 name: attachment.name,
147 url: queuedImageUrlById.get(attachment.id) ?? null,
148 })),
149 pending: false,
150 })),
151 ...optimisticQueued.map((message) => ({
152 key: message.id,
153 runId: null,
154 messageId: null,
155 serverIndex: null,
156 text: message.text,
157 attachments: [] as ReadonlyArray<ContractChatAttachment>,
158 thumbnails: (message.attachments ?? [])
159 .filter(isImageAttachment)
160 .map<QueuedRowThumbnail>((attachment) => ({
161 key: attachment.id,
162 name: attachment.name,
163 url: attachment.previewUrl ?? null,
164 })),
165 pending: true,
166 })),
167 ];
168
169 const move = async (runId: RunId, beforeRunId: RunId | null) => {
170 setBusyRunId(runId);
171 try {
172 await reorder({
173 environmentId: props.environmentId,
174 input: { threadId: props.threadId, runId, beforeRunId },
175 });
176 } finally {
177 setBusyRunId(null);
178 }
179 };
180
181 const completeDrag = (runId: RunId, insertIndex: number | null) => {
182 setDragState(null);
183 dragArmedRunIdRef.current = null;
184 if (insertIndex === null || busyRunId !== null) return;
185 const draggedIndex = queued.findIndex(({ run }) => run.id === runId);
186 if (draggedIndex === -1) return;
187 // Inserting immediately before or after itself is a no-op.
188 if (insertIndex === draggedIndex || insertIndex === draggedIndex + 1) return;
189 void move(runId, queued[insertIndex]?.run.id ?? null);
190 };
191
192 const steerInFlightRef = useRef(false);
193 const steer = async (queuedRunId: RunId) => {
194 if (activeRun === null || !workflow?.canPromoteToSteer || steerInFlightRef.current) return;
195 steerInFlightRef.current = true;
196 setBusyRunId(queuedRunId);
197 try {
198 await promote({
199 environmentId: props.environmentId,
200 input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
201 });
202 } finally {
203 steerInFlightRef.current = false;
204 setBusyRunId(null);
205 }
206 };
207
208 useImperativeHandle(ref, () => ({
209 steerNext(repeat) {
210 const next = queued[0];
211 if (!next || !workflow?.canPromoteToSteer) return false;
212 if (!repeat && busyRunId === null) void steer(next.run.id);
213 return true;
214 },
215 }));
216
217 if (items.length === 0) return null;
218
219 const remove = async (runId: RunId) => {
220 setBusyRunId(runId);
221 try {
222 await cancel({
223 environmentId: props.environmentId,
224 input: { threadId: props.threadId, runId },
225 });
226 } finally {
227 setBusyRunId(null);
228 }
229 };
230
231 return (
232 <ComposerBanner.Attachment>
233 <ComposerBanner.Root
234 role="region"
235 aria-label={`${items.length} queued message${items.length === 1 ? "" : "s"}`}
236 aria-live="polite"
237 data-chat-composer-collapsed-controls="true"
238 className="relative z-0"
239 >
240 <ComposerBanner.Row
241 render={<button type="button" />}
242 aria-label={expanded ? "Collapse queued messages" : "Expand queued messages"}
243 aria-expanded={expanded}
244 aria-controls={queueListId}
245 onPointerDown={(event) => event.preventDefault()}
246 onClick={() => setExpanded((value) => !value)}
247 >
248 <ComposerBanner.Icon>
249 <ListOrderedIcon />
250 </ComposerBanner.Icon>
251 <ComposerBanner.Content className="text-muted-foreground">
252 {workflow?.isHeld ? "Queue held after restart" : "Queued"}
253 </ComposerBanner.Content>
254 <ComposerBanner.Actions>
255 <ComposerBanner.Count>{items.length}</ComposerBanner.Count>
256 <ComposerBanner.ToggleIcon expanded={expanded} />
257 </ComposerBanner.Actions>
258 </ComposerBanner.Row>
259 {workflow?.isHeld && (
260 <ComposerBanner.Row layout="wrap-actions">
261 <ComposerBanner.Icon>
262 <PauseIcon />
263 </ComposerBanner.Icon>
264 <ComposerBanner.Content>Messages stay saved until you resume.</ComposerBanner.Content>
265 <ComposerBanner.Actions>
266 <Button
267 variant="ghost"
268 size="sm"
269 disabled={resuming || busyRunId !== null}
270 onClick={() => {
271 setResuming(true);
272 void resume({
273 environmentId: props.environmentId,
274 input: { threadId: props.threadId },
275 }).finally(() => setResuming(false));
276 }}
277 >
278 Resume queue
279 </Button>
280 </ComposerBanner.Actions>
281 </ComposerBanner.Row>
282 )}
283 <ComposerBanner.Scroll className={cn("max-h-32", !expanded && "hidden")}>
284 <ComposerBanner.Children render={<ol />} id={queueListId}>
285 {items.map((item) => {
286 const previewText = replaceComposerContextReferences(item.text, (reference) =>
287 reference.kind === "image" && item.thumbnails.length > 0 ? "" : reference.label,
288 ).trim();
289 const rowRunId = item.runId;
290 const rowServerIndex = item.serverIndex;
291 const isEditing = rowRunId !== null && rowRunId === props.editingRunId;
292 const rowDraggable =
293 rowRunId !== null && rowServerIndex !== null && canReorder && busyRunId === null;
294 return (
295 <ComposerBanner.Row
296 render={<li />}
297 key={item.key}
298 aria-current={isEditing ? "true" : undefined}
299 className={cn(
300 "relative rounded-sm",
301 isEditing && "bg-accent text-accent-foreground",
302 dragState !== null && dragState.runId === item.runId && "opacity-50",
303 )}
304 draggable={rowDraggable}
305 onDragStart={(event) => {
306 if (item.runId === null || dragArmedRunIdRef.current !== item.runId) {
307 event.preventDefault();
308 return;
309 }
310 event.dataTransfer.setData(QUEUED_RUN_DRAG_TYPE, item.runId);
311 event.dataTransfer.effectAllowed = "move";
312 setDragState({ runId: item.runId, insertIndex: null });
313 }}
314 onDragEnd={() => {
315 dragArmedRunIdRef.current = null;
316 setDragState(null);
317 }}
318 onDragOver={(event) => {
319 if (dragState === null || item.serverIndex === null) return;
320 event.preventDefault();
321 event.dataTransfer.dropEffect = "move";
322 const rect = event.currentTarget.getBoundingClientRect();
323 const insertIndex =
324 event.clientY < rect.top + rect.height / 2
325 ? item.serverIndex
326 : item.serverIndex + 1;
327 if (dragState.insertIndex !== insertIndex) {
328 setDragState({ runId: dragState.runId, insertIndex });
329 }
330 }}
331 onDrop={(event) => {
332 if (dragState === null) return;
333 event.preventDefault();
334 completeDrag(dragState.runId, dragState.insertIndex);
335 }}
336 >
337 {item.serverIndex !== null && dragState?.insertIndex === item.serverIndex ? (
338 <span
339 aria-hidden
340 className="pointer-events-none absolute inset-x-0 top-0 h-0.5 rounded bg-primary/70"
341 />
342 ) : null}
343 {item.serverIndex === queued.length - 1 &&
344 dragState?.insertIndex === queued.length ? (
345 <span
346 aria-hidden
347 className="pointer-events-none absolute inset-x-0 bottom-0 h-0.5 rounded bg-primary/70"
348 />
349 ) : null}
350 <ComposerBanner.Icon aria-hidden={false}>
351 {canReorder && rowRunId !== null && rowServerIndex !== null ? (
352 <Button
353 size="icon-xs"
354 variant="ghost-muted"
355 aria-label="Reorder queued message (drag, or press the arrow keys)"
356 className="cursor-grab active:cursor-grabbing disabled:cursor-default"
357 disabled={busyRunId !== null}
358 onPointerDown={() => {
359 dragArmedRunIdRef.current = rowRunId;
360 }}
361 onKeyDown={(event) => {
362 if (busyRunId !== null) return;
363 if (event.key === "ArrowUp" && rowServerIndex > 0) {
364 event.preventDefault();
365 void move(rowRunId, queued[rowServerIndex - 1]?.run.id ?? null);
366 }
367 if (event.key === "ArrowDown" && rowServerIndex < queued.length - 1) {
368 event.preventDefault();
369 void move(rowRunId, queued[rowServerIndex + 2]?.run.id ?? null);
370 }
371 }}
372 >
373 <GripVerticalIcon />
374 </Button>
375 ) : null}
376 </ComposerBanner.Icon>
377 <ComposerBanner.Content className="text-foreground/80">
378 {isEditing ? <span className="sr-only">Editing queued message: </span> : null}
379 {item.pending ? (
380 <Clock3Icon
381 aria-label="Saving queued message"
382 className="size-3 shrink-0 text-muted-foreground/60"
383 />
384 ) : null}
385 {item.thumbnails.length > 0 ? (
386 <span className="flex shrink-0 items-center gap-0.5">
387 {item.thumbnails.map((thumbnail) => (
388 <span
389 key={thumbnail.key}
390 className="size-4 overflow-hidden rounded border border-border/70 bg-background"
391 >
392 {thumbnail.url ? (
393 <img
394 src={thumbnail.url}
395 alt={thumbnail.name}
396 className="size-full object-cover"
397 />
398 ) : (
399 <span
400 aria-label={thumbnail.name}
401 className="block size-full bg-muted/60"
402 />
403 )}
404 </span>
405 ))}
406 </span>
407 ) : null}
408 <Tooltip>
409 <TooltipTrigger render={<span className="min-w-0 flex-1 truncate" />}>
410 {previewText}
411 </TooltipTrigger>
412 <TooltipPopup side="top" className="max-w-96 break-words">
413 {previewText}
414 </TooltipPopup>
415 </Tooltip>
416 </ComposerBanner.Content>
417 <ComposerBanner.Actions>
418 {isEditing ? (
419 <Button
420 size="xs"
421 variant="ghost"
422 aria-label="Cancel editing queued message"
423 onClick={props.onCancelEdit}
424 >
425 Cancel
426 </Button>
427 ) : (
428 <>
429 <Tooltip>
430 <TooltipTrigger
431 render={
432 <Button
433 size="icon-xs"
434 variant="ghost-muted"
435 aria-label="Edit queued message"
436 disabled={item.runId === null || busyRunId !== null}
437 onClick={() => {
438 if (item.runId !== null && item.messageId !== null) {
439 props.onEditQueuedRun({
440 runId: item.runId,
441 messageId: item.messageId,
442 text: item.text,
443 attachments: item.attachments,
444 });
445 }
446 }}
447 />
448 }
449 >
450 <PencilIcon />
451 </TooltipTrigger>
452 <TooltipPopup>Edit in the composer</TooltipPopup>
453 </Tooltip>
454 <Tooltip>
455 <TooltipTrigger render={<span className="flex shrink-0" />}>
456 <Button
457 size="xs"
458 variant="ghost-muted"
459 disabled={
460 item.runId === null ||
461 busyRunId !== null ||
462 !workflow?.canPromoteToSteer
463 }
464 onClick={() => {
465 if (item.runId !== null) {
466 void steer(item.runId);
467 }
468 }}
469 >
470 <CornerUpRightIcon />
471 Steer
472 </Button>
473 </TooltipTrigger>
474 <TooltipPopup>
475 {activeRun === null
476 ? "There is no active run to steer"
477 : `Send as a steer instead${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`}
478 </TooltipPopup>
479 </Tooltip>
480 <Tooltip>
481 <TooltipTrigger
482 render={
483 <ComposerBanner.Dismiss
484 aria-label="Remove queued message"
485 disabled={item.runId === null || busyRunId !== null}
486 onClick={() => {
487 if (item.runId !== null) void remove(item.runId);
488 }}
489 />
490 }
491 />
492 <TooltipPopup>Remove from queue</TooltipPopup>
493 </Tooltip>
494 </>
495 )}
496 </ComposerBanner.Actions>
497 </ComposerBanner.Row>
498 );
499 })}
500 </ComposerBanner.Children>
501 </ComposerBanner.Scroll>
502 </ComposerBanner.Root>
503 </ComposerBanner.Attachment>
504 );
505}