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

QueuedRunsControl.tsx

406 lines16.0 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 { ChevronDownIcon, Clock3Icon, ArrowUpIcon, PencilIcon, XIcon } from "lucide-react";
13import { useId, useImperativeHandle, useRef, useState, type Ref } from "react";
14​
15import { useAssetUrls } from "../../assets/assetUrls";
16import { threadEnvironment } from "../../state/threads";
17import { useThreadProjection } from "../../state/entities";
18import { useAtomCommand } from "../../state/use-atom-command";
19import { isImageAttachment, type ChatMessage } from "../../types";
20import { cn } from "~/lib/utils";
21import { Button, InlineButton } from "../ui/button";
22import { Separator } from "../ui/separator";
23import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
24​
25export interface EditQueuedRunRequest {
26 readonly runId: RunId;
27 readonly messageId: MessageId;
28 readonly text: string;
29 readonly attachments: ReadonlyArray<ContractChatAttachment>;
31​
32interface QueuedRowThumbnail {
33 readonly key: string;
34 readonly name: string;
35 readonly url: string | null;
37​
38// A longer queue shows its first messages and a button that shows the rest.
39const QUEUE_VISIBLE_ROWS = 3;
40​
41export interface QueuedRunsControlHandle {
42 steerNext: (repeat: boolean) => boolean;
43 editLatest: (repeat: boolean) => boolean;
45​
46type ThreadQueueProjection = Parameters<typeof deriveThreadQueueWorkflowState>[0];
47​
48function queuedImageResources(projection: ThreadQueueProjection | undefined) {
49 if (!projection) return [];
50 return deriveThreadQueueWorkflowState(projection).queuedRuns.flatMap(({ attachments }) =>
51 attachments.flatMap((attachment) =>
52 attachment.type === "image"
53 ? [{ _tag: "attachment" as const, attachmentId: attachment.id }]
54 : [],
55 ),
56 );
58​
59export function QueuedRunsControl({
60 ref,
61 ...props
62}: {
63 readonly ref?: Ref<QueuedRunsControlHandle>;
64 readonly steerShortcutLabel?: string | null;
65 readonly editShortcutLabel?: string | null;
66 readonly environmentId: EnvironmentId;
67 readonly threadId: ThreadId;
68 readonly optimisticMessages: ReadonlyArray<
69 Pick<ChatMessage, "id" | "inputIntent" | "text" | "attachments">
70 >;
71 readonly editingRunId: RunId | null;
72 /** Set while something else holds the composer, such as an open question. */
73 readonly editBlockedReason: string | null;
74 readonly onEditQueuedRun: (request: EditQueuedRunRequest) => void;
75 readonly onCancelEdit: () => void;
76}) {
77 const projection = useThreadProjection(
78 scopeThreadRef(props.environmentId, props.threadId),
79 )?.projection;
80 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun);
81 const resume = useAtomCommand(threadEnvironment.resumeThreadQueue);
82 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun);
83 const [showAll, setShowAll] = useState(false);
84 const queueListId = useId();
85 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
86 const steerInFlightRef = useRef(false);
87 // Run-only acknowledgements can resurrect pending rows after cancellation or startup.
88 const acknowledgedMessageIds = new Set((projection?.messages ?? []).map((message) => message.id));
89 const queuedImageAttachmentResources = queuedImageResources(projection);
90 const queuedImageAttachmentUrls = useAssetUrls(
91 props.environmentId,
92 queuedImageAttachmentResources,
93 );
94 const workflow = projection ? deriveThreadQueueWorkflowState(projection) : null;
95 const queued = workflow?.queuedRuns ?? [];
96 const activeRun = workflow?.activeRun ?? null;
97 const canSend = workflow?.canSendNow === true || workflow?.canPromoteToSteer === true;
98 const queuedImageUrlById = new Map(
99 queuedImageAttachmentUrls.flatMap((url, index) => {
100 const resource = queuedImageAttachmentResources[index];
101 return url && resource ? [[resource.attachmentId, url] as const] : [];
102 }),
103 );
104 const optimisticQueued = props.optimisticMessages.filter(
105 (message) => message.inputIntent === "queued_turn" && !acknowledgedMessageIds.has(message.id),
106 );
107 const items = [
108 ...queued.map(({ run, text, attachments, context }, serverIndex) => ({
109 key: run.id,
110 runId: run.id,
111 messageId: run.userMessageId,
112 serverIndex,
113 text,
114 // A guest's message keeps the guest's words; the owner can cancel it, not rewrite it.
115 editable: context?.guest === undefined,
116 guestName: context?.guest?.name,
117 attachments,
118 thumbnails: attachments
119 .filter((attachment) => attachment.type === "image")
120 .map<QueuedRowThumbnail>((attachment) => ({
121 key: attachment.id,
122 name: attachment.name,
123 url: queuedImageUrlById.get(attachment.id) ?? null,
124 })),
125 pending: false,
126 })),
127 ...optimisticQueued.map((message) => ({
128 key: message.id,
129 runId: null,
130 messageId: null,
131 serverIndex: null,
132 text: message.text,
133 editable: true,
134 guestName: undefined,
135 attachments: [] as ReadonlyArray<ContractChatAttachment>,
136 thumbnails: (message.attachments ?? [])
137 .filter(isImageAttachment)
138 .map<QueuedRowThumbnail>((attachment) => ({
139 key: attachment.id,
140 name: attachment.name,
141 url: attachment.previewUrl ?? null,
142 })),
143 pending: true,
144 })),
145 ];
146​
147 const sendQueuedMessage = async (queuedRunId: RunId) => {
148 if (!canSend || steerInFlightRef.current) return;
149 steerInFlightRef.current = true;
150 setBusyRunId(queuedRunId);
151 if (workflow?.canSendNow) {
152 await resume({
153 environmentId: props.environmentId,
154 input: { threadId: props.threadId, runId: queuedRunId },
155 });
156 } else if (activeRun !== null) {
157 await promote({
158 environmentId: props.environmentId,
159 input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
160 });
161 }
162 steerInFlightRef.current = false;
163 setBusyRunId(null);
164 };
165​
166 useImperativeHandle(ref, () => ({
167 steerNext(repeat) {
168 const next = queued[0];
169 if (!next || !canSend) return false;
170 if (!repeat && busyRunId === null) void sendQueuedMessage(next.run.id);
171 return true;
172 },
173 // Leave the key to caret navigation while editing.
174 editLatest(repeat) {
175 const latest = queued.at(-1);
176 if (
177 !latest ||
178 latest.context?.guest !== undefined ||
179 props.editingRunId !== null ||
180 props.editBlockedReason !== null ||
181 busyRunId !== null
182 ) {
183 return false;
184 }
185 if (!repeat) {
186 setShowAll(true);
187 props.onEditQueuedRun({
188 runId: latest.run.id,
189 messageId: latest.run.userMessageId,
190 text: latest.text,
191 attachments: latest.attachments,
192 });
193 }
194 return true;
195 },
196 }));
197​
198 if (items.length === 0) return null;
199​
200 const remove = async (runId: RunId) => {
201 setBusyRunId(runId);
202 await cancel({
203 environmentId: props.environmentId,
204 input: { threadId: props.threadId, runId },
205 });
206 setBusyRunId(null);
207 };
208​
209 const collapsible = items.length > QUEUE_VISIBLE_ROWS;
210 const visibleItems = collapsible && !showAll ? items.slice(0, QUEUE_VISIBLE_ROWS - 1) : items;
211​
212 return (
213 <section
214 aria-label={`${items.length} queued message${items.length === 1 ? "" : "s"}`}
215 data-thread-queue="true"
216 className="mx-auto flex w-full max-w-(--chat-content-max-width) flex-col gap-2 pb-4"
217 >
218 <span className="sr-only" aria-live="polite">
219 {items.length} queued
220 </span>
221 <ol className="flex flex-col items-end gap-3" id={queueListId}>
222 {visibleItems.map((item, position) => {
223 const previewText = assistantCitationsToPlainText(
224 replaceComposerContextReferences(item.text, (reference) =>
225 reference.kind === "image" && item.thumbnails.length > 0 ? "" : reference.label,
226 ),
227 ).trim();
228 const isEditing = item.runId !== null && item.runId === props.editingRunId;
229 return (
230 <li
231 key={item.key}
232 aria-label={`Queued message ${position + 1} of ${items.length}, not sent`}
233 aria-posinset={position + 1}
234 aria-setsize={items.length}
235 aria-current={isEditing ? "true" : undefined}
236 className="flex w-full flex-col items-end gap-1 transition-opacity duration-150 ease-out starting:opacity-0 motion-reduce:transition-none"
237 >
238 {/* Dashed and unfilled: a turn that has not been sent yet. */}
239 <div
240 className={cn(
241 "flex min-w-0 max-w-[80%] flex-col gap-2 rounded-2xl border border-dashed px-3 py-2 text-sm",
242 isEditing
243 ? "border-primary/60 text-foreground"
244 : "border-muted-foreground/40 text-muted-foreground",
245 )}
246 >
247 {item.thumbnails.length > 0 ? (
248 <span className="flex flex-wrap items-center gap-1">
249 {item.thumbnails.map((thumbnail) => (
250 <span
251 key={thumbnail.key}
252 className="size-8 overflow-hidden rounded-md border border-border/70 bg-background"
253 >
254 {thumbnail.url ? (
255 <img
256 src={thumbnail.url}
257 alt={thumbnail.name}
258 className="size-full object-cover"
259 />
260 ) : (
261 <span
262 aria-label={thumbnail.name}
263 className="block size-full bg-muted/60"
264 />
265 )}
266 </span>
267 ))}
268 </span>
269 ) : null}
270 {/* In full, like a sent turn: a queued message is read before it is sent. */}
271 {previewText ? (
272 <p className="whitespace-pre-wrap wrap-anywhere">
273 {item.guestName === undefined ? null : (
274 <span className="text-guest-foreground">{item.guestName} </span>
275 )}
276 {previewText}
277 </p>
278 ) : null}
279 </div>
280 <div className="flex items-center gap-0.5 pe-1 text-xs text-muted-foreground">
281 {canSend && !isEditing ? (
282 <>
283 <Tooltip>
284 <TooltipTrigger render={<span className="flex shrink-0" />}>
285 <Button
286 size="xs"
287 variant="ghost-muted"
288 disabled={item.runId === null || busyRunId !== null}
289 onClick={() => {
290 if (item.runId !== null) {
291 void sendQueuedMessage(item.runId);
292 }
293 }}
294 >
295 <ArrowUpIcon />
296 Send now
297 </Button>
298 </TooltipTrigger>
299 <TooltipPopup>
300 {`${workflow?.canSendNow ? "Start a turn with this message" : workflow?.promoteSkipsCompaction ? "Skip compaction and send this message" : "Send into the current turn"}${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`}
301 </TooltipPopup>
302 </Tooltip>
303 <Separator orientation="vertical" className="mx-2 h-4" />
304 </>
305 ) : null}
306 {item.pending ? (
307 <span className="flex items-center gap-1 px-1">
308 <Clock3Icon aria-hidden className="size-3" />
309 Saving
310 </span>
311 ) : null}
312 {isEditing ? (
313 <>
314 <span className="px-1 text-foreground">Editing in the composer</span>
315 <Button
316 size="xs"
317 variant="ghost"
318 aria-label="Cancel editing queued message"
319 onClick={props.onCancelEdit}
320 >
321 Cancel
322 </Button>
323 </>
324 ) : (
325 <>
326 <Tooltip>
327 {/* The span keeps the tooltip, and its reason, on a disabled button. */}
328 <TooltipTrigger render={<span className="flex shrink-0" />}>
329 <Button
330 size="icon-xs"
331 variant="ghost-muted"
332 aria-label="Edit queued message"
333 disabled={
334 item.runId === null ||
335 !item.editable ||
336 busyRunId !== null ||
337 props.editBlockedReason !== null
338 }
339 onClick={() => {
340 if (item.runId !== null && item.messageId !== null) {
341 props.onEditQueuedRun({
342 runId: item.runId,
343 messageId: item.messageId,
344 text: item.text,
345 attachments: item.attachments,
346 });
347 }
348 }}
349 >
350 <PencilIcon />
351 </Button>
352 </TooltipTrigger>
353 <TooltipPopup>
354 {props.editBlockedReason ??
355 `Edit in the composer${item.serverIndex === queued.length - 1 && props.editShortcutLabel ? ` (${props.editShortcutLabel})` : ""}`}
356 </TooltipPopup>
357 </Tooltip>
358 <Tooltip>
359 <TooltipTrigger
360 render={
361 <Button
362 size="icon-xs"
363 variant="ghost-muted"
364 aria-label="Remove queued message"
365 disabled={item.runId === null || busyRunId !== null}
366 onClick={() => {
367 if (item.runId !== null) void remove(item.runId);
368 }}
369 />
370 }
371 >
372 <XIcon />
373 </TooltipTrigger>
374 <TooltipPopup>Remove from queue</TooltipPopup>
375 </Tooltip>
376 </>
377 )}
378 </div>
379 </li>
380 );
381 })}
382 </ol>
383 {collapsible ? (
384 <div className="self-end pe-1 text-xs pointer-coarse:[&_[data-slot=inline-button]]:relative pointer-coarse:[&_[data-slot=inline-button]]:after:absolute pointer-coarse:[&_[data-slot=inline-button]]:after:-inset-x-1.5 pointer-coarse:[&_[data-slot=inline-button]]:after:-inset-y-3.5">
385 <InlineButton
386 tone="muted"
387 aria-expanded={showAll}
388 aria-controls={queueListId}
389 // Keep the composer focused; keyboard activation still works.
390 onPointerDown={(event) => event.preventDefault()}
391 onClick={() => setShowAll((value) => !value)}
392 >
393 {showAll ? "Show fewer" : `Show all ${items.length} queued`}
394 <ChevronDownIcon
395 aria-hidden
396 className={cn(
397 "size-3.5 transition-transform duration-150 motion-reduce:transition-none",
398 showAll && "rotate-180",
399 )}
400 />
401 </InlineButton>
402 </div>
403 ) : null}
404 </section>
405 );