"use client"; import { useCallback, useEffect, useState } from "react"; import type { ReactNode } from "react"; import { IconLayoutList, IconPlayerPlay, IconTrash, IconX } from "@tabler/icons-react"; import { toast } from "sonner"; import { Button } from "@kandev/ui"; import { Collapsible, CollapsibleContent } from "@kandev/ui/collapsible"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; import { cn } from "@/lib/utils"; import { stripSystemTags } from "@/lib/utils/system-tags"; import { useQueue } from "@/hooks/domains/session/use-queue"; import { isWorkflowQueuedMessage, QueuedGhostMessage } from "./queued-ghost-message"; import type { QueuedMessage } from "@/lib/state/slices/session/types"; const HEAD_PREVIEW_MAX = 80; /** Inter-task entries are dispatched with queued_by="agent" and stay read-only. */ function canUserEditEntry(entry: QueuedMessage): boolean { return entry.queued_by !== "agent" && !isWorkflowQueuedMessage(entry); } function headPreviewText(entries: QueuedMessage[]): string { const first = entries[0]; if (!first) return ""; const clean = stripSystemTags(first.content); if (clean.length <= HEAD_PREVIEW_MAX) return clean; return clean.slice(0, HEAD_PREVIEW_MAX).trimEnd() + "…"; } function isEditableTarget(el: EventTarget | null): boolean { if (!(el instanceof HTMLElement)) return false; const tag = el.tagName; if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return true; // contentEditable covers the TipTap chat editor and any rich-text surface. // `el.isContentEditable` walks up the contenteditable inheritance chain. return el.isContentEditable; } function useEscToClose(open: boolean, onClose: () => void): void { useEffect(() => { if (!open) return; const onKey = (e: KeyboardEvent) => { if (e.key !== "Escape") return; // Don't hijack Esc while the user is editing inside any input control on // the page (queue textarea, TipTap chat editor, native input/select, or // the clarification overlay). if (isEditableTarget(e.target)) return; e.preventDefault(); onClose(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [open, onClose]); } type QueueAffordanceProps = { sessionId: string | null; children: ReactNode; canDrain?: boolean; /** * Optional render slot for placing the chip inside an external row (e.g. the * chat status bar). The callback receives the chip node (or `null` when no * chip should be shown) and returns the row markup. When omitted, the chip * falls back to rendering inline above the input. */ renderStatusBar?: (queueChip: ReactNode) => ReactNode; }; type QueuePanelHandlerArgs = { clearAll: () => Promise; drainNext: () => Promise; editEntry: (entryId: string, content: string) => Promise; removeEntry: (entryId: string) => Promise; }; function useQueuePanelHandlers({ clearAll, drainNext, editEntry, removeEntry, }: QueuePanelHandlerArgs) { const handleSave = useCallback( async (entryId: string, content: string) => { await editEntry(entryId, content); }, [editEntry], ); const handleRemove = useCallback( async (entryId: string) => { try { await removeEntry(entryId); } catch (err) { console.error("Failed to remove queued entry:", err); toast.error("Failed to remove queued message."); } }, [removeEntry], ); const handleClear = useCallback(() => { clearAll().catch((err) => { console.error("Failed to clear queued messages:", err); toast.error("Failed to clear queued messages."); }); }, [clearAll]); const handleDrain = useCallback(() => { drainNext().catch((err) => { console.error("Failed to run queued message:", err); toast.error("Failed to run queued message."); }); }, [drainNext]); return { handleSave, handleRemove, handleClear, handleDrain }; } /** * Wraps the chat input with the per-session queue affordance: * - When there are no queued entries, just renders `children` (the input). * - Otherwise a small "n queued" chip is exposed (either inline above the * input, or via `renderStatusBar` into a caller-controlled row); clicking * it expands a panel above the input. Drained or session-switched queues * auto-collapse. */ export function QueueAffordance({ sessionId, children, canDrain = false, renderStatusBar, }: QueueAffordanceProps) { const { entries, count, max, isFull, isLoading, clearAll, drainNext, editEntry, removeEntry } = useQueue(sessionId); const [isOpen, setIsOpen] = useState(false); const { handleSave, handleRemove, handleClear, handleDrain } = useQueuePanelHandlers({ clearAll, drainNext, editEntry, removeEntry, }); // Reset disclosure on session switch or full drain using render-phase state // adjustment (React docs: "Adjusting some state when a prop changes"). This // avoids the cascading-render anti-pattern of doing it inside useEffect. const entryCount = entries.length; const [lastSession, setLastSession] = useState(sessionId); const [lastEntryCount, setLastEntryCount] = useState(entryCount); if (sessionId !== lastSession) { setLastSession(sessionId); setIsOpen(false); } if (entryCount !== lastEntryCount) { setLastEntryCount(entryCount); if (entryCount === 0) setIsOpen(false); } const close = useCallback(() => setIsOpen(false), []); useEscToClose(isOpen, close); const hasEntries = !!sessionId && entryCount > 0; const chipNode = hasEntries && !isOpen ? ( setIsOpen((v) => !v)} /> ) : null; if (!hasEntries) { return ( <> {/* Call renderStatusBar even with null so the status bar stays mounted when the queue is empty. */} {renderStatusBar?.(null)} {children} ); } return ( <> {renderStatusBar?.(chipNode)} {!renderStatusBar && chipNode && (
{chipNode}
)} {children} ); } type QueueChipProps = { count: number; isFull: boolean; previewText: string; onToggle: () => void; }; function chipPalette(isFull: boolean): string { if (isFull) { return "text-amber-600 dark:text-amber-400 border-amber-500/60 hover:bg-amber-500/10"; } return "text-muted-foreground border-muted-foreground/40 hover:text-foreground hover:border-muted-foreground/60"; } function QueueChip({ count, isFull, previewText, onToggle }: QueueChipProps) { // aria-expanded/aria-controls are intentionally omitted: the chip and the // expanded panel are mutually exclusive in the DOM (clicking the chip swaps // it for the panel header, which carries its own collapse controls). Pointing // aria-controls at an element that isn't currently mounted would be a worse // a11y signal than the descriptive aria-label below. const button = ( ); if (!previewText) return button; return ( {button} {previewText} ); } type QueuePanelProps = { entries: QueuedMessage[]; count: number; max: number; isFull: boolean; canDrain: boolean; isLoading: boolean; onClose: () => void; onClear: () => void; onDrain: () => void; onSave: (entryId: string, content: string) => Promise; onRemove: (entryId: string) => Promise; }; function QueuePanel({ entries, count, max, isFull, canDrain, isLoading, onClose, onClear, onDrain, onSave, onRemove, }: QueuePanelProps) { return (
{entries.map((entry, index) => ( onSave(entry.id, content)} onRemove={() => onRemove(entry.id)} /> ))}
); } type QueuePanelHeaderProps = { count: number; max: number; isFull: boolean; canDrain: boolean; isLoading: boolean; onClear: () => void; onDrain: () => void; onClose: () => void; }; function QueuePanelHeader({ count, max, isFull, canDrain, isLoading, onClear, onDrain, onClose, }: QueuePanelHeaderProps) { const capacityText = max > 0 ? `${count} of ${max}` : `${count}`; return (
Queued {capacityText} {isFull ? " · full" : ""}
{canDrain && ( )}
); }