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