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

QueuedRunsControl.tsx

551 lines21.4 KB

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