Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

QueuedRunsControl.tsx

501 lines20.0 KB

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