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