import { ComposeDirectoryPicker } from './ComposeDirectoryPicker'; /** * Terminal Compose Bar * An immersive prompt bar below the terminal with a quick-snippet strip, * user-resizable height, and terminal-matched chrome. */ import { GripHorizontal, Pin, Plus, Radio, Search, X } from 'lucide-react'; import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { terminalReconnectRegistry } from '../../application/state/terminalReconnectRegistry'; import { useComposeBarHistory } from '../../application/state/useComposeBarHistory'; import { canNavigateComposeBarHistory } from '../../domain/composeBarHistory'; import { STORAGE_KEY_TERMINAL_BROADCAST_PASSWORD_BYPASS } from '../../infrastructure/config/storageKeys'; import { useStoredBoolean } from '../../application/state/useStoredBoolean'; import { useComposeBarHeight } from '../../application/state/useComposeBarHeight'; import { useComposeBarPinnedSnippets } from '../../application/state/useComposeBarPinnedSnippets'; import { useI18n } from '../../application/i18n/I18nProvider'; import { useClipboardBackend } from '../../application/state/useClipboardBackend'; import { resolveSnippetCommand } from '../SnippetExecutionProvider'; import { Snippet } from '../../types'; import { cn } from '../../lib/utils'; import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'; import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'; import { buildSnippetIdKey, filterComposeBarSnippets, mergeComposeBarSnippetMap, resolveComposeBarDefaultSeedIds, } from './composeBarHelpers'; const SNIPPET_STRIP_HEIGHT = 30; const RESIZE_HANDLE_HEIGHT = 6; export type ComposeBarTheme = { resolvedBg: string; resolvedFg: string; borderColor: string; mutedFg: string; hoverBg: string; chipBg: string; chipHoverBg: string; }; function buildTheme(themeColors?: { background: string; foreground: string }): ComposeBarTheme { const bg = themeColors?.background ?? '#0a0a0a'; const fg = themeColors?.foreground ?? '#d4d4d4'; const resolvedBg = 'var(--terminal-ui-bg, ' + bg + ')'; const resolvedFg = 'var(--terminal-ui-fg, ' + fg + ')'; return { resolvedBg, resolvedFg, borderColor: `color-mix(in srgb, ${resolvedFg} 8%, ${resolvedBg} 92%)`, mutedFg: `color-mix(in srgb, ${resolvedFg} 55%, ${resolvedBg} 45%)`, hoverBg: `color-mix(in srgb, ${resolvedFg} 10%, ${resolvedBg} 90%)`, chipBg: `color-mix(in srgb, ${resolvedFg} 6%, ${resolvedBg} 94%)`, chipHoverBg: `color-mix(in srgb, ${resolvedFg} 12%, ${resolvedBg} 88%)`, }; } interface ComposeBarSnippetChipProps { snippet: Snippet; theme: ComposeBarTheme; onActivate: (snippet: Snippet, sendImmediately: boolean) => void; onUnpin: (id: string) => void; unpinLabel: string; clickHint: string; } const ComposeBarSnippetChip = memo(function ComposeBarSnippetChip({ snippet, theme, onActivate, onUnpin, unpinLabel, clickHint, }: ComposeBarSnippetChipProps) { const commandPreview = snippet.command.split('\n')[0]; return (
{ e.currentTarget.style.backgroundColor = theme.chipHoverBg; }} onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = theme.chipBg; }} >

{snippet.label}

{commandPreview}

{clickHint}

); }); interface ComposeBarSnippetManagePopoverProps { snippets: Snippet[]; pinnedCount: number; theme: ComposeBarTheme; isPinned: (id: string) => boolean; onTogglePin: (id: string) => void; manageLabel: string; searchPlaceholder: string; noSnippetsLabel: string; noMatchingLabel: string; pinnedCountLabel: string; } const ComposeBarSnippetManagePopover = memo(function ComposeBarSnippetManagePopover({ snippets, pinnedCount, theme, isPinned, onTogglePin, manageLabel, searchPlaceholder, noSnippetsLabel, noMatchingLabel, pinnedCountLabel, }: ComposeBarSnippetManagePopoverProps) { const [open, setOpen] = useState(false); const [search, setSearch] = useState(''); const filteredSnippets = useMemo( () => filterComposeBarSnippets(snippets, search), [snippets, search], ); return ( { setOpen(next); if (!next) setSearch(''); }} >

{manageLabel}

setSearch(e.target.value)} placeholder={searchPlaceholder} className="flex-1 min-w-0 bg-transparent text-[11px] font-mono outline-none placeholder:opacity-60" style={{ color: theme.resolvedFg }} />
{snippets.length === 0 ? (

{noSnippetsLabel}

) : filteredSnippets.length === 0 ? (

{noMatchingLabel}

) : ( filteredSnippets.map((snippet) => { const pinned = isPinned(snippet.id); return ( ); }) )}
{pinnedCount > 0 && (
{pinnedCountLabel}
)}
); }); export interface TerminalComposeBarProps { contextChipsEnabled?: boolean; // Return false for rejected or sensitive input so it is not recalled. onSend: (text: string) => boolean | void | Promise; sessionId: string; onClose: () => void; onSnippetClick?: (snippet: Snippet) => void; snippets?: Snippet[]; isBroadcastEnabled?: boolean; /** Compose-bar send target. Undefined follows toolbar broadcast. */ composeSendToAll?: boolean; onToggleComposeSendTarget?: () => void; themeColors?: { background: string; foreground: string; }; } export const TerminalComposeBar: React.FC = ({ onSend, contextChipsEnabled = true, sessionId, onClose, onSnippetClick, snippets = [], isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, themeColors, }) => { const { t } = useI18n(); const { readClipboardText, writeClipboardText } = useClipboardBackend(); const textareaRef = useRef(null); const restoreDraft = useCallback((draft: string) => { if (textareaRef.current) textareaRef.current.value = draft; }, []); const { prepareRecord, navigate, reset } = useComposeBarHistory(sessionId, restoreDraft); const isComposingRef = useRef(false); const resizeCleanupRef = useRef<(() => void) | null>(null); const [barHeight, setBarHeight, persistBarHeight] = useComposeBarHeight(); const heightRef = useRef(barHeight); const snippetIdKey = useMemo( () => buildSnippetIdKey(snippets.map((snippet) => snippet.id)), [snippets], ); const defaultSeedIds = useMemo( () => resolveComposeBarDefaultSeedIds(snippets), [snippets], ); const { pinnedIds, unpin, toggle, isPinned } = useComposeBarPinnedSnippets( snippetIdKey, defaultSeedIds, ); heightRef.current = barHeight; const theme = useMemo(() => buildTheme(themeColors), [themeColors]); // Opt-in "broadcast without password protection" (#3488). Shared storage key // with the terminal runtime, which reads it to keep broadcasting during // password / interactive prompts while this switch is on. const [allowPasswordBroadcast, setAllowPasswordBroadcast] = useStoredBoolean( STORAGE_KEY_TERMINAL_BROADCAST_PASSWORD_BYPASS, false, ); const [broadcastMenuAnchor, setBroadcastMenuAnchor] = useState<{ x: number; y: number; inTextarea: boolean } | null>(null); useEffect(() => { if (!broadcastMenuAnchor) return; const handlePointerDown = (event: PointerEvent) => { if (event.target instanceof Element && event.target.closest('[data-compose-broadcast-menu]')) return; setBroadcastMenuAnchor(null); }; const handleKeyDown = (event: KeyboardEvent) => { if (event.key === 'Escape') setBroadcastMenuAnchor(null); }; window.addEventListener('pointerdown', handlePointerDown); window.addEventListener('keydown', handleKeyDown); return () => { window.removeEventListener('pointerdown', handlePointerDown); window.removeEventListener('keydown', handleKeyDown); }; }, [broadcastMenuAnchor]); const sendToAll = composeSendToAll ?? Boolean(isBroadcastEnabled); const handleBroadcastContextMenu = useCallback((event: React.MouseEvent) => { if (!isBroadcastEnabled && !sendToAll) return; event.preventDefault(); event.stopPropagation(); setBroadcastMenuAnchor({ x: event.clientX, y: event.clientY, inTextarea: event.target instanceof Element && Boolean(event.target.closest('textarea')), }); }, [isBroadcastEnabled, sendToAll]); const handleComposeMenuEdit = useCallback(async (action: 'cut' | 'copy' | 'paste' | 'selectAll') => { setBroadcastMenuAnchor(null); const textarea = textareaRef.current; if (!textarea) return; textarea.focus(); if (action === 'selectAll') { textarea.select(); return; } const start = textarea.selectionStart; const end = textarea.selectionEnd; try { if (action === 'paste') { let text: string | undefined; try { text = await readClipboardText(); } catch { /* Use browser clipboard. */ } if (typeof text !== 'string') text = await navigator.clipboard.readText(); if (!text) return; textarea.setSelectionRange(start, end); if (!document.execCommand('insertText', false, text)) { textarea.setRangeText(text, start, end, 'end'); textarea.dispatchEvent(new Event('input', { bubbles: true })); } reset(); return; } if (start === end) return; const selectedText = textarea.value.slice(start, end); let wroteToBridge = false; try { wroteToBridge = await writeClipboardText(selectedText); } catch { /* Use browser clipboard. */ } if (!wroteToBridge) { await navigator.clipboard.writeText(selectedText); } if (action === 'cut') { textarea.setSelectionRange(start, end); if (!document.execCommand('delete')) { textarea.setRangeText('', start, end, 'end'); textarea.dispatchEvent(new Event('input', { bubbles: true })); } reset(); } } catch (error) { console.error('Compose bar clipboard action failed', error); } }, [readClipboardText, reset, writeClipboardText]); const snippetsById = useMemo( () => mergeComposeBarSnippetMap(snippets), [snippets], ); const pinnedSnippets = useMemo( () => pinnedIds .map((id) => snippetsById.get(id)) .filter((snippet): snippet is Snippet => Boolean(snippet)), [pinnedIds, snippetsById], ); const clickHint = t('terminal.composeBar.snippetClickHint'); useEffect(() => { const timer = setTimeout(() => textareaRef.current?.focus(), 50); return () => clearTimeout(timer); }, []); useEffect(() => () => { resizeCleanupRef.current?.(); }, []); const handleSend = useCallback(() => { const el = textareaRef.current; if (!el) return; const text = el.value; if (!text) return; const recordSent = prepareRecord(); let result: ReturnType; try { result = onSend(text); } catch (error) { recordSent(); throw error; } void Promise.resolve(result).then((sent) => { recordSent(sent !== false ? text : undefined); }).catch((error: unknown) => { recordSent(); console.error('Compose bar send failed', error); }); reset(); el.value = ''; el.focus(); }, [onSend, prepareRecord, reset]); const insertCommand = useCallback((command: string) => { const el = textareaRef.current; if (!el) return; reset(); const prefix = el.value && !el.value.endsWith('\n') ? '\n' : ''; el.value = el.value ? `${el.value}${prefix}${command}` : command; el.focus(); }, [reset]); const handleSnippetActivate = useCallback(async (snippet: Snippet, sendImmediately: boolean) => { if (sendImmediately) { if (onSnippetClick) { onSnippetClick(snippet); } else { const command = await resolveSnippetCommand(snippet); if (command !== null) onSend(command); } return; } const command = await resolveSnippetCommand(snippet); if (command === null) return; insertCommand(command); }, [insertCommand, onSend, onSnippetClick]); const handleKeyDown = useCallback((e: React.KeyboardEvent) => { if (isComposingRef.current || e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229) return; if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) { const el = e.currentTarget; const direction = e.key === 'ArrowUp' ? 'up' : 'down'; if (canNavigateComposeBarHistory(el.value, el.selectionStart, direction, el.selectionEnd)) { const value = navigate(el.value, direction); if (value !== undefined) { e.preventDefault(); el.value = value; const position = direction === 'up' ? 0 : value.length; el.setSelectionRange(position, position); } } return; } if (e.key === 'Enter' && !e.shiftKey && !isComposingRef.current) { e.preventDefault(); // Plain Enter on an empty draft reconnects a disconnected session. // Modified Enter and a non-empty draft keep the existing send path (#3767). const plainEnter = !e.altKey && !e.ctrlKey && !e.metaKey; if ( plainEnter && !e.currentTarget.value && terminalReconnectRegistry.requestEnterReconnect(sessionId) ) { return; } handleSend(); } else if (e.key === 'Escape') { e.preventDefault(); onClose(); } }, [handleSend, navigate, onClose, sessionId]); const handleResizeStart = useCallback((e: React.MouseEvent) => { e.preventDefault(); resizeCleanupRef.current?.(); const startY = e.clientY; const startHeight = heightRef.current; document.body.style.cursor = 'ns-resize'; document.body.style.userSelect = 'none'; const onMove = (moveEvent: MouseEvent) => { const delta = moveEvent.clientY - startY; setBarHeight(startHeight - delta); }; const cleanup = () => { document.body.style.cursor = ''; document.body.style.userSelect = ''; window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); resizeCleanupRef.current = null; }; const onUp = () => { persistBarHeight(heightRef.current); cleanup(); }; resizeCleanupRef.current = cleanup; window.addEventListener('mousemove', onMove); window.addEventListener('mouseup', onUp); }, [persistBarHeight, setBarHeight]); return (
{pinnedSnippets.map((snippet) => ( ))}
{contextChipsEnabled && textareaRef.current?.focus({ preventScroll: true })} />}
{(onToggleComposeSendTarget || sendToAll) && ( {sendToAll ? t('terminal.composeBar.broadcasting') : t('terminal.composeBar.sendToActive')} )}