import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; import type { ChatAttachment as ContractChatAttachment, EnvironmentId, MessageId, RunId, ThreadId, } from "@t3tools/contracts"; import { ChevronDownIcon, Clock3Icon, CornerUpRightIcon, GripVerticalIcon, ListOrderedIcon, PencilIcon, XIcon, } from "lucide-react"; import { useId, useImperativeHandle, useRef, useState, type Ref } from "react"; import { useAssetUrls } from "../../assets/assetUrls"; import { threadEnvironment } from "../../state/threads"; import { useThreadProjection } from "../../state/entities"; import { useAtomCommand } from "../../state/use-atom-command"; import { isImageAttachment, type ChatMessage } from "../../types"; import { cn } from "~/lib/utils"; import { Button, InlineButton } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; export interface EditQueuedRunRequest { readonly runId: RunId; readonly messageId: MessageId; readonly text: string; readonly attachments: ReadonlyArray; } interface QueuedRowThumbnail { readonly key: string; readonly name: string; readonly url: string | null; } const QUEUED_RUN_DRAG_TYPE = "application/x-t3code-queued-run"; // A longer queue shows its first messages and a button that shows the rest. const QUEUE_VISIBLE_ROWS = 3; export interface QueuedRunsControlHandle { steerNext: (repeat: boolean) => boolean; editLatest: (repeat: boolean) => boolean; } type ThreadQueueProjection = Parameters[0]; function queuedImageResources(projection: ThreadQueueProjection | undefined) { if (!projection) return []; return deriveThreadQueueWorkflowState(projection).queuedRuns.flatMap(({ attachments }) => attachments.flatMap((attachment) => attachment.type === "image" ? [{ _tag: "attachment" as const, attachmentId: attachment.id }] : [], ), ); } export function QueuedRunsControl({ ref, ...props }: { readonly ref?: Ref; readonly steerShortcutLabel?: string | null; readonly editShortcutLabel?: string | null; readonly environmentId: EnvironmentId; readonly threadId: ThreadId; readonly optimisticMessages: ReadonlyArray< Pick >; readonly editingRunId: RunId | null; /** Set while something else holds the composer, such as an open question. */ readonly editBlockedReason: string | null; readonly onEditQueuedRun: (request: EditQueuedRunRequest) => void; readonly onCancelEdit: () => void; }) { const projection = useThreadProjection( scopeThreadRef(props.environmentId, props.threadId), )?.projection; const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun); const promote = useAtomCommand(threadEnvironment.promoteQueuedRun); const resume = useAtomCommand(threadEnvironment.resumeThreadQueue); const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun); const [showAll, setShowAll] = useState(false); const queueListId = useId(); const [busyRunId, setBusyRunId] = useState(null); const [dragState, setDragState] = useState<{ readonly runId: RunId; readonly insertIndex: number | null; } | null>(null); // Arm from the grip to prevent accidental text drags from reordering queued runs. const dragArmedRunIdRef = useRef(null); const steerInFlightRef = useRef(false); // Run-only acknowledgements can resurrect pending rows after cancellation or startup. const acknowledgedMessageIds = new Set((projection?.messages ?? []).map((message) => message.id)); const queuedImageAttachmentResources = queuedImageResources(projection); const queuedImageAttachmentUrls = useAssetUrls( props.environmentId, queuedImageAttachmentResources, ); const workflow = projection ? deriveThreadQueueWorkflowState(projection) : null; const queued = workflow?.queuedRuns ?? []; const activeRun = workflow?.activeRun ?? null; const canReorder = workflow?.canReorder === true; const canSend = workflow?.canSendNow === true || workflow?.canPromoteToSteer === true; const queuedImageUrlById = new Map( queuedImageAttachmentUrls.flatMap((url, index) => { const resource = queuedImageAttachmentResources[index]; return url && resource ? [[resource.attachmentId, url] as const] : []; }), ); const optimisticQueued = props.optimisticMessages.filter( (message) => message.inputIntent === "queued_turn" && !acknowledgedMessageIds.has(message.id), ); const items = [ ...queued.map(({ run, text, attachments, context }, serverIndex) => ({ key: run.id, runId: run.id, messageId: run.userMessageId, serverIndex, text, // A guest's message keeps the guest's words; the owner can cancel it, not rewrite it. editable: context?.guest === undefined, guestName: context?.guest?.name, attachments, thumbnails: attachments .filter((attachment) => attachment.type === "image") .map((attachment) => ({ key: attachment.id, name: attachment.name, url: queuedImageUrlById.get(attachment.id) ?? null, })), pending: false, })), ...optimisticQueued.map((message) => ({ key: message.id, runId: null, messageId: null, serverIndex: null, text: message.text, editable: true, guestName: undefined, attachments: [] as ReadonlyArray, thumbnails: (message.attachments ?? []) .filter(isImageAttachment) .map((attachment) => ({ key: attachment.id, name: attachment.name, url: attachment.previewUrl ?? null, })), pending: true, })), ]; const move = async (runId: RunId, beforeRunId: RunId | null) => { setBusyRunId(runId); await reorder({ environmentId: props.environmentId, input: { threadId: props.threadId, runId, beforeRunId }, }); setBusyRunId(null); }; const completeDrag = (runId: RunId, insertIndex: number | null) => { setDragState(null); dragArmedRunIdRef.current = null; if (insertIndex === null || busyRunId !== null) return; const draggedIndex = queued.findIndex(({ run }) => run.id === runId); if (draggedIndex === -1) return; if (insertIndex === draggedIndex || insertIndex === draggedIndex + 1) return; void move(runId, queued[insertIndex]?.run.id ?? null); }; const sendQueuedMessage = async (queuedRunId: RunId) => { if (!canSend || steerInFlightRef.current) return; steerInFlightRef.current = true; setBusyRunId(queuedRunId); if (workflow?.canSendNow) { await resume({ environmentId: props.environmentId, input: { threadId: props.threadId, runId: queuedRunId }, }); } else if (activeRun !== null) { await promote({ environmentId: props.environmentId, input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, }); } steerInFlightRef.current = false; setBusyRunId(null); }; useImperativeHandle(ref, () => ({ steerNext(repeat) { const next = queued[0]; if (!next || !canSend) return false; if (!repeat && busyRunId === null) void sendQueuedMessage(next.run.id); return true; }, // Leave the key to caret navigation while editing. editLatest(repeat) { const latest = queued.at(-1); if ( !latest || latest.context?.guest !== undefined || props.editingRunId !== null || props.editBlockedReason !== null || busyRunId !== null ) { return false; } if (!repeat) { setShowAll(true); props.onEditQueuedRun({ runId: latest.run.id, messageId: latest.run.userMessageId, text: latest.text, attachments: latest.attachments, }); } return true; }, })); if (items.length === 0) return null; const remove = async (runId: RunId) => { setBusyRunId(runId); await cancel({ environmentId: props.environmentId, input: { threadId: props.threadId, runId }, }); setBusyRunId(null); }; const collapsible = items.length > QUEUE_VISIBLE_ROWS; const visibleItems = collapsible && !showAll ? items.slice(0, QUEUE_VISIBLE_ROWS - 1) : items; return (

Up next ยท {items.length} queued

    {visibleItems.map((item, position) => { const previewText = assistantCitationsToPlainText( replaceComposerContextReferences(item.text, (reference) => reference.kind === "image" && item.thumbnails.length > 0 ? "" : reference.label, ), ).trim(); const rowRunId = item.runId; const rowServerIndex = item.serverIndex; const isEditing = rowRunId !== null && rowRunId === props.editingRunId; const rowDraggable = rowRunId !== null && rowServerIndex !== null && canReorder && busyRunId === null; return (
  1. { if (item.runId === null || dragArmedRunIdRef.current !== item.runId) { event.preventDefault(); return; } event.dataTransfer.setData(QUEUED_RUN_DRAG_TYPE, item.runId); event.dataTransfer.effectAllowed = "move"; setDragState({ runId: item.runId, insertIndex: null }); }} onDragEnd={() => { dragArmedRunIdRef.current = null; setDragState(null); }} onDragOver={(event) => { if (dragState === null || item.serverIndex === null) return; event.preventDefault(); event.dataTransfer.dropEffect = "move"; const rect = event.currentTarget.getBoundingClientRect(); const insertIndex = event.clientY < rect.top + rect.height / 2 ? item.serverIndex : item.serverIndex + 1; if (dragState.insertIndex !== insertIndex) { setDragState({ runId: dragState.runId, insertIndex }); } }} onDrop={(event) => { if (dragState === null) return; event.preventDefault(); completeDrag(dragState.runId, dragState.insertIndex); }} > {item.serverIndex !== null && dragState?.insertIndex === item.serverIndex ? ( ) : null} {item.serverIndex === queued.length - 1 && dragState?.insertIndex === queued.length ? ( ) : null} {/* Dashed and unfilled: a turn that has not been sent yet. */}
    {item.thumbnails.length > 0 ? ( {item.thumbnails.map((thumbnail) => ( {thumbnail.url ? ( {thumbnail.name} ) : ( )} ))} ) : null} {/* In full, like a sent turn: a queued message is read before it is sent. */} {previewText ? (

    {item.guestName === undefined ? null : ( {item.guestName} )} {previewText}

    ) : null}
    {items.length > 1 && canReorder && rowRunId !== null && rowServerIndex !== null ? ( ) : items.length > 1 ? ( {position + 1} ) : null} {item.pending ? ( Saving ) : null} {isEditing ? ( <> Editing in the composer ) : ( <> {/* The span keeps the tooltip, and its reason, on a disabled button. */} }> {props.editBlockedReason ?? `Edit in the composer${item.serverIndex === queued.length - 1 && props.editShortcutLabel ? ` (${props.editShortcutLabel})` : ""}`} }> {`${workflow?.canSendNow ? "Start a turn with this message" : "Send as a steer instead"}${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`} { if (item.runId !== null) void remove(item.runId); }} /> } > Remove from queue )}
  2. ); })}
{collapsible ? (
event.preventDefault()} onClick={() => setShowAll((value) => !value)} > {showAll ? "Show fewer" : `Show all ${items.length} queued`}
) : null}
); }