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

QueuedRunsControl.tsx

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