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

QueuedRunsControl.tsx

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