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

QueuedRunsControl.tsx

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