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

QueuedRunsControl.tsx

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