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

QueuedRunsControl.tsx

489 lines20.1 KB

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