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