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