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