import type { ModelRef, SessionState, ThinkingLevel } from "@protocol/types"; import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; import { useTranslation } from "react-i18next"; import { Icon } from "@/components/icons"; import { Button } from "@/components/ui/button"; import { Modal } from "@/components/ui/dialog"; import { toast } from "@/components/ui/toast"; import { plural } from "@/lib/i18n"; import { cn } from "@/lib/utils"; import "@/styles/pages/chat-composer.css"; import { promptImage, type PromptImage, type PromptMode } from "./commands"; import type { ModelGroup } from "./data"; import { withCurrentModel } from "./data"; import { THINKING_LEVELS } from "./format"; import { historyScope, localPromptHistorySource, PromptHistoryNav, type PromptHistorySource } from "./prompt-history"; import type { Attachment } from "./store"; export interface ComposerProps { session: SessionState | null; models: ModelGroup[]; connected: boolean; paired?: boolean; /** * The optimistic first message of a send. The composer never renders its body * any more (CHG-2026-10-26-16): it only adds to the pending count while the * daemon has not projected the message into `session.queue` yet. */ sending?: { text: string } | null; /** `mode` is `follow_up` when the run is busy (queued) and `steer` for an interrupt. */ onSend: (text: string, images: PromptImage[], mode?: PromptMode) => void; onAbort: () => void; onRemoveQueue: (id: string) => void; /** * Kept for signature compatibility (`pages/chat.tsx` still passes it). Steering * is a session-wide mode (`queue.setSteer {mode}`), so the composer renders no * per-message toggle any more — the queued footer in the stream owns it. */ onSetSteer: (steer: boolean) => void; /** Session-level bulk clear for the status bar; falls back to `onRemoveQueue`. */ onClearQueue?: () => void; /** Authoritative pending count (e.g. including an in-stream queued entity). */ queuedCount?: number; onSetModel: (model: ModelRef) => void; onSetThinking: (level: ThinkingLevel) => void; /** * Where ↑/↓ recall reads from and where a send is recorded. `pages/chat.tsx` * passes the plugin-backed feed (`usePromptHistory`) so nvim and the browser * share one archive; without it the composer falls back to the browser-local * mirror for this session's workspace. */ history?: PromptHistorySource; disabled?: boolean; className?: string; } function attachmentId(file: File): string { return `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; } /** * Bottom composer: auto-growing textarea, a `role="status"` pending bar (no queue * bodies), model/thinking pickers and one circular send slot that turns into abort. */ export function Composer({ session, models, connected, paired = true, sending, onSend, onAbort, onRemoveQueue, onClearQueue, queuedCount, onSetModel, onSetThinking, history, disabled = false, className, }: ComposerProps) { const { t } = useTranslation(); const [text, setText] = useState(""); const [attachments, setAttachments] = useState([]); const [attachOpen, setAttachOpen] = useState(false); const [dragging, setDragging] = useState(false); const textareaRef = useRef(null); const fileRef = useRef(null); /** * Prompt recall (↑/↓) — see `prompt-history.ts`. The entries come from the * injected feed (the plugin relay, or the browser mirror as fallback); the * cursor is this composer's own, and is rebuilt when the source changes so a * session switch or a lost plugin never carries a stranger's position over. */ const fallbackSource = useMemo( () => localPromptHistorySource(historyScope(session?.workspaceId)), [session?.workspaceId], ); const source = history ?? fallbackSource; const navRef = useRef<{ source: PromptHistorySource; nav: PromptHistoryNav } | null>(null); /** Set by a recall so the layout effect can park the caret after the entry. */ const caretToEnd = useRef(false); const enabled = Boolean(session) && connected && !disabled; const busy = session ? session.status === "busy" || session.status === "compacting" : false; const queue = session?.queue ?? []; const model = session?.model ?? null; const thinking = session?.thinking ?? "off"; const groups = withCurrentModel(models, model); const hint = !paired ? t("chat.unpairedHint") : !connected ? t("chat.offlineHint") : null; // The stream owns the single queued entity; the composer only counts. `sending` // counts once and only until `queue_update` projects the same message. const pending = Math.max(queuedCount ?? (queue.length || (sending ? 1 : 0)), 0); const inline = queue.filter((item) => item.steer).length; const pendingLabel = plural("chat.queueCount", pending, { defaultValue: pending === 1 ? "{n} pending message" : "{n} pending messages", }); const hintLabel = inline > 0 ? t("chat.queueCountInline", { n: inline, defaultValue: "{n} inserting now" }) : t("chat.queueAfterTurn", { defaultValue: "Sends after this turn" }); useLayoutEffect(() => { const element = textareaRef.current; if (!element) return; element.style.height = "auto"; const max = 5 * 24; element.style.height = `${Math.min(element.scrollHeight, max)}px`; element.style.overflowY = element.scrollHeight > max ? "auto" : "hidden"; if (caretToEnd.current) { // A recall replaced the whole value: keep typing after the entry // instead of wherever the caret happened to be in the old draft. caretToEnd.current = false; const end = element.value.length; element.setSelectionRange(end, end); } }, [text]); useEffect(() => { if (!enabled) return; textareaRef.current?.focus({ preventScroll: true }); }, [enabled]); /** This composer's recall cursor, rebuilt when the source changes identity. */ function historyNav(): PromptHistoryNav { if (navRef.current === null || navRef.current.source !== source) { navRef.current = { source, nav: new PromptHistoryNav(source) }; } return navRef.current.nav; } /** Replace the draft with an archived prompt (or the stashed draft). */ function recall(direction: "prev" | "next"): boolean { const nav = historyNav(); const entry = direction === "prev" ? nav.prev(text) : nav.next(); if (entry === null) return false; caretToEnd.current = true; setText(entry); return true; } /** * Enter sends. ↑/↓ recall once there is nowhere left to move the caret, the * way pi2.nvim's prompt buffer does it; ``/`` are the readline * aliases and always recall. Anything else stays a plain textarea key. */ function handleKeyDown(event: KeyboardEvent) { // A composing IME owns ↑/↓ (candidate list) and Enter (commit). if (event.nativeEvent.isComposing) return; if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); submit(); return; } const modifier = event.ctrlKey || event.metaKey; if (modifier && !event.altKey && !event.shiftKey) { const direction = event.key === "p" ? "prev" : event.key === "n" ? "next" : null; if (direction === null) return; event.preventDefault(); recall(direction); return; } if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return; if (modifier || event.altKey || event.shiftKey) return; // A selection means the user is editing a fragment, not recalling. const element = event.currentTarget; const { selectionStart, selectionEnd } = element; if (selectionStart === null || selectionEnd === null) return; if (selectionStart !== selectionEnd) return; if (event.key === "ArrowUp") { // Only from the first logical line: inside a multi-line entry ↑ still // moves the caret (nvim's `` rule). if (text.slice(0, selectionStart).includes("\n")) return; if (recall("prev")) event.preventDefault(); return; } // ↓ recalls from the last logical line, and always while browsing, so the // first ↓ out of a recalled prompt is never swallowed by a caret move. const atLastLine = !text.slice(selectionEnd).includes("\n"); if (!atLastLine && !historyNav().navigating()) return; if (recall("next")) event.preventDefault(); } function submit(mode?: PromptMode) { const trimmed = text.trim(); if (!trimmed || !enabled) return; const images = attachments.map(({ mimeType, data }) => ({ mimeType, data })); setText(""); setAttachments([]); // Record the send and leave recall, exactly like pi2.nvim's prompt buffer. source.remember(trimmed); historyNav().reset(); // A busy session queues the message as a follow-up; idle sends a plain prompt. onSend(trimmed, images, mode ?? (busy ? "follow_up" : undefined)); } /** * The protocol has no bulk `queue.clear`: `onClearQueue` (one session-level * command) wins; the fallback removes the projected items one by one. */ function clearQueue() { if (onClearQueue) { onClearQueue(); return; } for (const item of queue) onRemoveQueue(item.id); } async function addFiles(files: FileList | File[] | null) { if (!files) return; for (const file of Array.from(files)) { if (!file.type.startsWith("image/")) continue; try { const image = await promptImage(file); setAttachments((current) => [ ...current, { id: attachmentId(file), name: file.name, mimeType: image.mimeType, data: image.data, preview: `data:${image.mimeType};base64,${image.data}`, }, ]); toast(t("chat.attachmentAdded", { name: file.name })); } catch { toast.error(t("chat.attachmentFailed", { name: file.name })); } } } return (
{pendingLabel} {hintLabel}
{attachments.length ? (
{attachments.map((attachment) => ( {attachment.name} ))}
) : null}