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

QueuedRunsControl.tsx

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