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

QueuedRunsControl.tsx

627 lines25.2 KB

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