The best way to control Claude Code, Codex and more from any computer or phone

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