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

QueuedRunsControl.tsx

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