Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
3import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
4import {
5 isAttachmentOnlyBootstrapPrompt,
6 replaceComposerContextReferences,
7} from "@t3tools/shared/composerContextReferences";
8import type {
9 ChatAttachment as ContractChatAttachment,
10 EnvironmentId,
11 MessageId,
12 RunId,
13 ThreadId,
14} from "@t3tools/contracts";
15import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
16import { Link } from "@tanstack/react-router";
17import {
18 ArrowUpIcon,
19 CalendarClockIcon,
20 ChevronDownIcon,
21 Clock3Icon,
22 MessagesSquareIcon,
23 PencilIcon,
24 XIcon,
25} from "lucide-react";
26import * as DateTime from "effect/DateTime";
27import { useId, useImperativeHandle, useRef, useState, type ReactNode, type Ref } from "react";
28
29import { useAssetUrls } from "../../assets/assetUrls";
30import { threadEnvironment } from "../../state/threads";
31import { useQuietThreadShell, useThreadProjection } from "../../state/entities";
32import { useAtomCommand } from "../../state/use-atom-command";
33import { isImageAttachment, type ChatMessage } from "../../types";
34import { cn } from "~/lib/utils";
35import { Button, InlineButton } from "../ui/button";
36import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
37import type { TimestampFormat } from "@t3tools/contracts/settings";
38import { GuestMessageName } from "./guestMessageStyle";
39import { TimelineRowTimestamp } from "./TimelineRowParts";
40import { FoldedMessageHeader, useScheduledTaskTitle } from "./TimelineUserMessageRow";
41
42export interface EditQueuedRunRequest {
43 readonly runId: RunId;
44 readonly messageId: MessageId;
45 readonly text: string;
46 readonly attachments: ReadonlyArray<ContractChatAttachment>;
47}
48
49interface QueuedRowThumbnail {
50 readonly key: string;
51 readonly name: string;
52 readonly url: string | null;
53}
54
55// A longer queue shows its first messages and a button that shows the rest.
56const QUEUE_VISIBLE_ROWS = 3;
57
58export interface QueuedRunsControlHandle {
59 steerNext: (repeat: boolean) => boolean;
60 editLatest: (repeat: boolean) => boolean;
61}
62
63type ThreadQueueProjection = Parameters<typeof deriveThreadQueueWorkflowState>[0];
64
65function queuedImageResources(projection: ThreadQueueProjection | undefined) {
66 if (!projection) return [];
67 return deriveThreadQueueWorkflowState(projection).queuedRuns.flatMap(({ attachments }) =>
68 attachments.flatMap((attachment) =>
69 attachment.type === "image"
70 ? [{ _tag: "attachment" as const, attachmentId: attachment.id }]
71 : [],
72 ),
73 );
74}
75
76export function QueuedRunsControl({
77 ref,
78 ...props
79}: {
80 readonly ref?: Ref<QueuedRunsControlHandle>;
81 readonly steerShortcutLabel?: string | null;
82 readonly editShortcutLabel?: string | null;
83 readonly environmentId: EnvironmentId;
84 readonly threadId: ThreadId;
85 readonly optimisticMessages: ReadonlyArray<
86 Pick<ChatMessage, "id" | "inputIntent" | "text" | "attachments">
87 >;
88 readonly editingRunId: RunId | null;
89 /** Set while something else holds the composer, such as an open question. */
90 readonly editBlockedReason: string | null;
91 readonly onEditQueuedRun: (request: EditQueuedRunRequest) => void;
92 readonly onCancelEdit: () => void;
93 readonly timestampFormat: TimestampFormat;
94 readonly onOpenThread: (threadId: ThreadId) => void;
95}) {
96 const projection = useThreadProjection(
97 scopeThreadRef(props.environmentId, props.threadId),
98 )?.projection;
99 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun);
100 const resume = useAtomCommand(threadEnvironment.resumeThreadQueue);
101 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun);
102 const [showAll, setShowAll] = useState(false);
103 const queueListId = useId();
104 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
105 const steerInFlightRef = useRef(false);
106 // Run-only acknowledgements can resurrect pending rows after cancellation or startup.
107 const acknowledgedMessageIds = new Set((projection?.messages ?? []).map((message) => message.id));
108 const queuedImageAttachmentResources = queuedImageResources(projection);
109 const queuedImageAttachmentUrls = useAssetUrls(
110 props.environmentId,
111 queuedImageAttachmentResources,
112 );
113 const workflow = projection ? deriveThreadQueueWorkflowState(projection) : null;
114 const queued = workflow?.queuedRuns ?? [];
115 const activeRun = workflow?.activeRun ?? null;
116 const canSend = workflow?.canSendNow === true || workflow?.canPromoteToSteer === true;
117 const queuedImageUrlById = new Map(
118 queuedImageAttachmentUrls.flatMap((url, index) => {
119 const resource = queuedImageAttachmentResources[index];
120 return url && resource ? [[resource.attachmentId, url] as const] : [];
121 }),
122 );
123 const optimisticQueued = props.optimisticMessages.filter(
124 (message) => message.inputIntent === "queued_turn" && !acknowledgedMessageIds.has(message.id),
125 );
126 const items = [
127 ...queued.map(({ run, text, attachments, context, message }, serverIndex) => ({
128 key: run.id,
129 message,
130 runId: run.id,
131 messageId: run.userMessageId,
132 serverIndex,
133 text,
134 // A guest's message keeps the guest's words; the owner can cancel it, not rewrite it.
135 editable: context?.guest === undefined,
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 message: undefined,
149 runId: null,
150 messageId: null,
151 serverIndex: null,
152 text: message.text,
153 editable: true,
154 attachments: [] as ReadonlyArray<ContractChatAttachment>,
155 thumbnails: (message.attachments ?? [])
156 .filter(isImageAttachment)
157 .map<QueuedRowThumbnail>((attachment) => ({
158 key: attachment.id,
159 name: attachment.name,
160 url: attachment.previewUrl ?? null,
161 })),
162 pending: true,
163 })),
164 ];
165
166 const sendQueuedMessage = async (queuedRunId: RunId) => {
167 if (!canSend || steerInFlightRef.current) return;
168 steerInFlightRef.current = true;
169 setBusyRunId(queuedRunId);
170 if (workflow?.canSendNow) {
171 await resume({
172 environmentId: props.environmentId,
173 input: { threadId: props.threadId, runId: queuedRunId },
174 });
175 } else if (activeRun !== null) {
176 await promote({
177 environmentId: props.environmentId,
178 input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
179 });
180 }
181 steerInFlightRef.current = false;
182 setBusyRunId(null);
183 };
184
185 useImperativeHandle(ref, () => ({
186 steerNext(repeat) {
187 const next = queued[0];
188 if (!next || !canSend) return false;
189 if (!repeat && busyRunId === null) void sendQueuedMessage(next.run.id);
190 return true;
191 },
192 // Leave the key to caret navigation while editing.
193 editLatest(repeat) {
194 const latest = queued.at(-1);
195 if (
196 !latest ||
197 latest.context?.guest !== undefined ||
198 props.editingRunId !== null ||
199 props.editBlockedReason !== null ||
200 busyRunId !== null
201 ) {
202 return false;
203 }
204 if (!repeat) {
205 setShowAll(true);
206 props.onEditQueuedRun({
207 runId: latest.run.id,
208 messageId: latest.run.userMessageId,
209 text: latest.text,
210 attachments: latest.attachments,
211 });
212 }
213 return true;
214 },
215 }));
216
217 if (items.length === 0) return null;
218
219 const remove = async (runId: RunId) => {
220 setBusyRunId(runId);
221 await cancel({
222 environmentId: props.environmentId,
223 input: { threadId: props.threadId, runId },
224 });
225 setBusyRunId(null);
226 };
227
228 const collapsible = items.length > QUEUE_VISIBLE_ROWS;
229 const visibleItems = collapsible && !showAll ? items.slice(0, QUEUE_VISIBLE_ROWS - 1) : items;
230
231 return (
232 <section
233 aria-label={`${items.length} queued message${items.length === 1 ? "" : "s"}`}
234 data-thread-queue="true"
235 // Anchors the sr-only live region; unanchored, it escapes the timeline scroller and makes the chat column scroll.
236 className="relative mx-auto flex w-full max-w-(--chat-content-max-width) flex-col gap-2 pb-4"
237 >
238 <span className="sr-only" aria-live="polite">
239 {items.length} queued
240 </span>
241 <ol className="flex flex-col items-end gap-3" id={queueListId}>
242 {visibleItems.map((item, position) => {
243 const previewText = isAttachmentOnlyBootstrapPrompt(item.text)
244 ? ""
245 : assistantCitationsToPlainText(
246 replaceComposerContextReferences(item.text, (reference) =>
247 reference.kind === "image" && item.thumbnails.length > 0 ? "" : reference.label,
248 ),
249 ).trim();
250 const isEditing = item.runId !== null && item.runId === props.editingRunId;
251 return (
252 <li
253 key={item.key}
254 aria-label={`Queued message ${position + 1} of ${items.length}, not sent`}
255 aria-posinset={position + 1}
256 aria-setsize={items.length}
257 aria-current={isEditing ? "true" : undefined}
258 className="group/queued flex w-full flex-col items-end gap-1 transition-opacity duration-150 ease-out starting:opacity-0 motion-reduce:transition-none"
259 >
260 <QueuedMessage
261 environmentId={props.environmentId}
262 message={item.message}
263 previewText={previewText}
264 thumbnails={item.thumbnails}
265 isEditing={isEditing}
266 timestampFormat={props.timestampFormat}
267 onOpenThread={props.onOpenThread}
268 >
269 {canSend && !isEditing ? (
270 <>
271 <Tooltip>
272 <TooltipTrigger render={<span className="flex shrink-0" />}>
273 <Button
274 size="xs"
275 variant="ghost-muted"
276 disabled={item.runId === null || busyRunId !== null}
277 onClick={() => {
278 if (item.runId !== null) {
279 void sendQueuedMessage(item.runId);
280 }
281 }}
282 >
283 <ArrowUpIcon />
284 Send now
285 </Button>
286 </TooltipTrigger>
287 <TooltipPopup>
288 {`${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})` : ""}`}
289 </TooltipPopup>
290 </Tooltip>
291 </>
292 ) : null}
293 {item.pending ? (
294 <span className="flex items-center gap-1 px-1">
295 <Clock3Icon aria-hidden className="size-3" />
296 Saving
297 </span>
298 ) : null}
299 {isEditing ? (
300 <>
301 <span className="px-1 text-foreground">Editing in the composer</span>
302 <Button
303 size="xs"
304 variant="ghost"
305 aria-label="Cancel editing queued message"
306 onClick={props.onCancelEdit}
307 >
308 Cancel
309 </Button>
310 </>
311 ) : (
312 <>
313 <Tooltip>
314 {/* The span keeps the tooltip, and its reason, on a disabled button. */}
315 <TooltipTrigger render={<span className="flex shrink-0" />}>
316 <Button
317 size="icon-xs"
318 variant="ghost-muted"
319 aria-label="Edit queued message"
320 disabled={
321 item.runId === null ||
322 !item.editable ||
323 busyRunId !== null ||
324 props.editBlockedReason !== null
325 }
326 onClick={() => {
327 if (item.runId !== null && item.messageId !== null) {
328 props.onEditQueuedRun({
329 runId: item.runId,
330 messageId: item.messageId,
331 text: item.text,
332 attachments: item.attachments,
333 });
334 }
335 }}
336 >
337 <PencilIcon />
338 </Button>
339 </TooltipTrigger>
340 <TooltipPopup>
341 {props.editBlockedReason ??
342 `Edit in the composer${item.serverIndex === queued.length - 1 && props.editShortcutLabel ? ` (${props.editShortcutLabel})` : ""}`}
343 </TooltipPopup>
344 </Tooltip>
345 <Tooltip>
346 <TooltipTrigger
347 render={
348 <Button
349 size="icon-xs"
350 variant="ghost-muted"
351 aria-label="Remove queued message"
352 disabled={item.runId === null || busyRunId !== null}
353 onClick={() => {
354 if (item.runId !== null) void remove(item.runId);
355 }}
356 />
357 }
358 >
359 <XIcon />
360 </TooltipTrigger>
361 <TooltipPopup>Remove from queue</TooltipPopup>
362 </Tooltip>
363 </>
364 )}
365 </QueuedMessage>
366 </li>
367 );
368 })}
369 </ol>
370 {collapsible ? (
371 <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">
372 <InlineButton
373 tone="muted"
374 aria-expanded={showAll}
375 aria-controls={queueListId}
376 // Keep the composer focused; keyboard activation still works.
377 onPointerDown={(event) => event.preventDefault()}
378 onClick={() => setShowAll((value) => !value)}
379 >
380 {showAll ? "Show fewer" : `Show all ${items.length} queued`}
381 <ChevronDownIcon
382 aria-hidden
383 className={cn(
384 "size-3.5 transition-transform duration-150 motion-reduce:transition-none",
385 showAll && "rotate-180",
386 )}
387 />
388 </InlineButton>
389 </div>
390 ) : null}
391 </section>
392 );
393}
394
395type QueuedRunMessage = NonNullable<ThreadQueueProjection["messages"][number]>;
396
397/** A queued turn wears its sent form's attribution; only the dashed edge and controls differ. */
398function QueuedMessage(props: {
399 readonly environmentId: EnvironmentId;
400 readonly message: QueuedRunMessage | undefined;
401 readonly previewText: string;
402 readonly thumbnails: ReadonlyArray<QueuedRowThumbnail>;
403 readonly isEditing: boolean;
404 readonly timestampFormat: TimestampFormat;
405 readonly onOpenThread: (threadId: ThreadId) => void;
406 readonly children: ReactNode;
407}) {
408 const presentation = props.message ? resolveUserMessagePresentation(props.message) : null;
409 const attribution = presentation?.attribution ?? null;
410 const scheduledTaskId = presentation?.scheduledTaskId;
411 const senderThreadId = props.message?.senderThreadId;
412 const [expanded, setExpanded] = useState(false);
413 const taskTitle = useScheduledTaskTitle(props.environmentId, scheduledTaskId);
414 const senderShell = useQuietThreadShell(
415 attribution === "agent" && senderThreadId
416 ? { environmentId: props.environmentId, threadId: senderThreadId }
417 : null,
418 );
419 const fold =
420 attribution === "automation"
421 ? {
422 icon: CalendarClockIcon,
423 label: "Automation",
424 summary: taskTitle ?? props.previewText.split(/\r?\n/, 1)[0] ?? "",
425 }
426 : attribution === "agent"
427 ? {
428 icon: MessagesSquareIcon,
429 label: senderShell?.title.trim() || "Agent",
430 summary: props.previewText.split(/\r?\n/).find((line) => line.trim()) ?? "",
431 }
432 : null;
433 const bodyVisible = fold === null || expanded;
434
435 return (
436 <>
437 {attribution === "t3code" ? (
438 <p className="me-1 text-2xs text-muted-foreground/70">Sent by T3 Code</p>
439 ) : null}
440 {presentation?.guestName === undefined ? null : (
441 <GuestMessageName name={presentation.guestName} />
442 )}
443 {/* Dashed and unfilled: a turn that has not been sent yet. */}
444 <div
445 className={cn(
446 "flex min-w-0 max-w-[80%] flex-col rounded-2xl border border-dashed text-sm",
447 props.isEditing
448 ? "border-primary/60 text-foreground"
449 : attribution === "guest"
450 ? "border-guest/50 text-muted-foreground"
451 : "border-muted-foreground/40 text-muted-foreground",
452 fold === null && "px-3 py-2",
453 fold !== null && expanded && "w-full",
454 )}
455 >
456 {fold ? (
457 <FoldedMessageHeader
458 icon={fold.icon}
459 label={fold.label}
460 summary={fold.summary}
461 expanded={expanded}
462 onToggle={() => setExpanded((value) => !value)}
463 />
464 ) : null}
465 {bodyVisible ? (
466 <div
467 className={cn(
468 "flex flex-col gap-2",
469 fold !== null && "max-h-96 overflow-auto px-3 pb-2",
470 )}
471 >
472 {props.thumbnails.length > 0 ? (
473 <span className="flex flex-wrap items-center gap-1">
474 {props.thumbnails.map((thumbnail) => (
475 <span
476 key={thumbnail.key}
477 className="size-8 overflow-hidden rounded-md border border-border/70 bg-background"
478 >
479 {thumbnail.url ? (
480 <img
481 src={thumbnail.url}
482 alt={thumbnail.name}
483 className="size-full object-cover"
484 />
485 ) : (
486 <span aria-label={thumbnail.name} className="block size-full bg-muted/60" />
487 )}
488 </span>
489 ))}
490 </span>
491 ) : null}
492 {/* In full, like a sent turn: a queued message is read before it is sent. */}
493 {props.previewText ? (
494 <p className="whitespace-pre-wrap wrap-anywhere">{props.previewText}</p>
495 ) : null}
496 </div>
497 ) : null}
498 </div>
499 <div className="flex items-center gap-0.5 pe-1 text-xs text-muted-foreground">
500 {props.message ? (
501 <span className="me-1 flex items-center gap-2 px-1 opacity-0 transition-opacity duration-200 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover/queued:opacity-100">
502 {attribution === "agent" && senderThreadId ? (
503 <InlineButton tone="muted" onClick={() => props.onOpenThread(senderThreadId)}>
504 Open thread
505 </InlineButton>
506 ) : null}
507 {scheduledTaskId ? (
508 <InlineButton
509 tone="muted"
510 render={
511 <Link
512 to="/settings/scheduled-tasks"
513 search={{ environmentId: props.environmentId, taskId: scheduledTaskId }}
514 />
515 }
516 >
517 Open automation
518 </InlineButton>
519 ) : null}
520 <TimelineRowTimestamp
521 createdAt={DateTime.formatIso(props.message.createdAt)}
522 timestampFormat={props.timestampFormat}
523 alwaysVisible
524 />
525 </span>
526 ) : null}
527 {props.children}
528 </div>
529 </>
530 );
531}