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

QueuedRunsControl.tsx

525 lines21.1 KB

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