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