import { useEffect, useState } from 'react'; import type { ReactNode } from 'react'; import { ChevronDown, ChevronRight, Copy, RefreshCw, Check, Share2, RotateCw, GitFork, Trash2, PanelRightOpen } from 'lucide-react'; import { toast } from 'sonner'; import type { Chat, ErrorReason, Message } from '@/api/types'; import { api, ApiError } from '@/api/client'; import { sessionEvents } from '@/hooks/sessionEvents'; import { sendToTerminal, terminalsRegistry, type TerminalRegistration } from '@/lib/events'; import { CapHitSentinel } from './CapHitSentinel'; import { DoomLoopSentinel } from './DoomLoopSentinel'; import { MarkdownRenderer } from './MarkdownRenderer'; import { Button } from '@/components/ui/button'; import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, } from '@/components/ui/context-menu'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; // v1.10 booterm: tiny subscription hook for the mounted-terminals registry. // Used by the right-click "Send to terminal" submenu so it always reflects // currently-open terminal panes without prop drilling from Workspace. function useTerminals(): TerminalRegistration[] { const [list, setList] = useState(() => terminalsRegistry.list()); useEffect(() => terminalsRegistry.subscribe(() => setList(terminalsRegistry.list())), []); return list; } // Wrap a message body with a right-click context menu offering Copy and // "Send to terminal → ". Send is disabled when nothing is // selected or no terminal panes are open; clicking a target emits a // sendToTerminal event that TerminalPane subscribes to (filtered by pane_id). function SendToTerminalMenu({ children }: { children: ReactNode }) { const [selection, setSelection] = useState(''); const terminals = useTerminals(); const hasSelection = selection.length > 0; const canSend = hasSelection && terminals.length > 0; return ( { if (open) { const sel = typeof window !== 'undefined' ? window.getSelection()?.toString() ?? '' : ''; setSelection(sel); } }} > {children} { void navigator.clipboard.writeText(selection).catch((err) => { toast.error(err instanceof Error ? err.message : 'copy failed'); }); }} > Copy Send to terminal {terminals.length === 0 ? ( No terminal panes open ) : ( terminals.map((t) => ( sendToTerminal.emit({ pane_id: t.paneId, text: selection })} > {t.label} )) )} ); } // v1.8.2: human labels for the machine-readable error reasons that ride on // failed assistant messages via metadata.kind === 'error'. Kept short so the // inline render under "message failed" stays a single muted line. const ERROR_REASON_LABELS: Record = { llm_provider_error: 'LLM provider error', tool_execution_failed: 'Tool execution failed', summary_after_cap_failed: 'Summary after tool budget hit failed', }; // v1.14.x-html-artifact-panes: MarkdownBody and its path-linkifier helpers // moved to apps/web/src/components/MarkdownRenderer.tsx so the new artifact // panes can render assistant content with the same Shiki + remark-gfm setup. // Pane-header title derivation for a markdown artifact. Order matches the // server slug logic in services/artifacts.ts: first `# ` heading → first 6 // words of the body → 'Markdown artifact'. Truncated to keep the pane header // readable. function deriveMarkdownTitle(content: string): string { const headingMatch = content.match(/^\s*#\s+(.+?)\s*$/m); if (headingMatch && headingMatch[1]) return headingMatch[1].slice(0, 80); const words = content.trim().split(/\s+/).slice(0, 6).join(' '); if (words) return words.slice(0, 80); return 'Markdown artifact'; } interface Props { message: Message; sessionChats?: Chat[]; // v1.8.2: passed by MessageList's render-item pass for cap-hit sentinels. // Only the most recent sentinel shows the Continue button. capHitInfo?: { position: number; isLatest: boolean }; } function StatsLine({ message }: { message: Message }) { const tokens = message.tokens_used; if (typeof tokens !== 'number' || tokens <= 0) return null; const started = message.started_at ? Date.parse(message.started_at) : NaN; const finished = message.finished_at ? Date.parse(message.finished_at) : NaN; let tps: number | null = null; if (!Number.isNaN(started) && !Number.isNaN(finished) && finished > started) { const seconds = (finished - started) / 1000; if (seconds > 0) tps = Math.round((tokens / seconds) * 10) / 10; } const ctxUsed = message.ctx_used; const ctxMax = message.ctx_max; const ctxPart = typeof ctxUsed === 'number' ? typeof ctxMax === 'number' && ctxMax > 0 ? `${ctxUsed} / ${ctxMax} ctx` : `${ctxUsed} ctx` : null; const parts: string[] = [`${tokens} tokens`]; if (tps !== null) parts.push(`${tps.toFixed(1)} tok/s`); if (ctxPart) parts.push(ctxPart); return (
{parts.join(' · ')}
); } function ActionRow({ message, }: { message: Message; }) { const [justCopied, setJustCopied] = useState(false); const [regenerating, setRegenerating] = useState(false); const [forking, setForking] = useState(false); const [deleteOpen, setDeleteOpen] = useState(false); const [deleting, setDeleting] = useState(false); async function copy() { try { await navigator.clipboard.writeText(message.content); setJustCopied(true); setTimeout(() => setJustCopied(false), 1200); } catch (err) { toast.error(err instanceof Error ? err.message : 'copy failed'); } } async function regenerate() { if (regenerating || message.status === 'streaming') return; setRegenerating(true); try { await api.messages.regenerate(message.chat_id, message.id); } catch (err) { toast.error(err instanceof Error ? err.message : 'regenerate failed'); } finally { setRegenerating(false); } } async function fork() { if (forking || message.status !== 'complete') return; setForking(true); try { const chat = await api.chats.fork(message.chat_id, { messageId: message.id }); sessionEvents.emit({ type: 'open_chat_in_active_pane', chat_id: chat.id }); } catch (err) { toast.error(err instanceof Error ? err.message : 'fork failed'); } finally { setForking(false); } } async function confirmDelete() { if (deleting) return; setDeleting(true); try { await api.messages.remove(message.chat_id, message.id); setDeleteOpen(false); } catch (err) { toast.error(err instanceof Error ? err.message : 'delete failed'); } finally { setDeleting(false); } } const isAssistant = message.role === 'assistant'; const canRegen = isAssistant && message.status !== 'streaming'; const canFork = message.status === 'complete'; const canDelete = message.status !== 'streaming'; const [openingPane, setOpeningPane] = useState(false); // v1.14.x-html-artifact-panes: probe for an html_artifact part. If present, // open the HTML pane variant; otherwise fall back to the markdown variant. // Title derivation for markdown: first `# ` heading → first 6 words of the // body → 'Markdown artifact' (mirrors the slug logic in // services/artifacts.ts). async function openInPane() { if (openingPane || message.status === 'streaming') return; setOpeningPane(true); try { try { const payload = await api.messages.getHtmlArtifact( message.chat_id, message.id, ); sessionEvents.emit({ type: 'open_html_artifact_pane', state: { chat_id: message.chat_id, message_id: message.id, title: payload.title, }, }); return; } catch (err) { // 404 (no html_artifact part) is the expected fall-through path — // markdown variant opens below. Any other error (network, 500) is // a real failure; toast and bail rather than masquerading as markdown. const status = err instanceof ApiError ? err.status : null; if (status !== 404) { toast.error(err instanceof Error ? err.message : 'open in pane failed'); return; } } const title = deriveMarkdownTitle(message.content); sessionEvents.emit({ type: 'open_markdown_artifact_pane', state: { chat_id: message.chat_id, message_id: message.id, title, }, }); } finally { setOpeningPane(false); } } return ( <>
{isAssistant && ( )} {isAssistant && ( )}
{ if (!deleting) setDeleteOpen(open); }} > Delete this message and all messages after it? This removes the selected message and every later message in this chat. This cannot be undone. ); } function CompactCard({ message, sessionChats }: { message: Message; sessionChats?: Chat[] }) { const [expanded, setExpanded] = useState(false); const [copied, setCopied] = useState(false); const [shareOpen, setShareOpen] = useState(false); const [rerunning, setRerunning] = useState(false); const headerMatch = message.content.match(/^\[Context compacted — (\d+) messages summarized\]/); const headerText = headerMatch ? headerMatch[0] : 'Context compacted'; const summaryText = headerMatch ? message.content.slice(headerMatch[0].length).trim() : message.content; async function handleCopy() { try { await navigator.clipboard.writeText(summaryText); setCopied(true); setTimeout(() => setCopied(false), 1200); toast.success('Summary copied to clipboard'); } catch { toast.error('Copy failed'); } } async function handleShareToChat(chat: Chat) { try { await api.messages.send(chat.id, summaryText); toast.success(`Summary sent to ${chat.name ?? 'New chat'}`); setShareOpen(false); } catch (err) { toast.error(err instanceof Error ? err.message : 'Failed to share'); } } async function handleRerun() { if (rerunning) return; setRerunning(true); try { await api.chats.compact(message.chat_id); } catch (err) { toast.error(err instanceof Error ? err.message : 'Re-run failed'); } finally { setRerunning(false); } } const otherChats = (sessionChats ?? []).filter( (c) => c.id !== message.chat_id && c.status === 'open' ); return (
{shareOpen && (
{otherChats.length === 0 ? (
No other chats in this session
) : ( otherChats.map((c) => ( )) )}
)}
{expanded && (
{summaryText}
)}
); } // v1.11 anchored rolling summary. Inserted by services/compaction.ts as a // role='assistant', summary=true row. Distinct from legacy CompactCard // (which renders the kind='compact' system rows produced by v1.10 /compact). // Collapsed by default; header shows the timestamp; body renders the // summary markdown when expanded. Copy button matches CompactCard's affordance. function SummaryCard({ message }: { message: Message }) { const [expanded, setExpanded] = useState(false); const [copied, setCopied] = useState(false); // Use finished_at when available (that's when the summary actually landed); // fall back to created_at for any row missing it. Both are ISO strings. const ts = message.finished_at ?? message.created_at; const headerTs = ts ? new Date(ts).toLocaleString() : ''; async function handleCopy() { try { await navigator.clipboard.writeText(message.content); setCopied(true); setTimeout(() => setCopied(false), 1200); toast.success('Summary copied to clipboard'); } catch { toast.error('Copy failed'); } } return (
{expanded && (
)}
); } export function MessageBubble({ message, sessionChats, capHitInfo }: Props) { // v1.11: anchored rolling summary row. Checked BEFORE the kind==='compact' // branch because summary=true never coexists with kind='compact' (new // compactions emit role='assistant' rows with kind='message'+summary=true). if (message.summary) { return ; } if (message.kind === 'compact') { return ; } // v1.8.2: cap-hit sentinels render as a distinct system bubble with a // Continue button. MessageList's pre-render pass tags each sentinel with // its position; only the latest gets the actionable button. if ( message.role === 'system' && message.metadata?.kind === 'cap_hit' && capHitInfo ) { return ( ); } // v1.11.6: doom-loop sentinel. No Continue affordance — retrying with the // same tools would just re-loop. The card explains what tripped and // suggests next steps (new message angle / switch agents). if (message.role === 'system' && message.metadata?.kind === 'doom_loop') { return ; } // v1.8.2: tool messages and assistant tool_calls are now rendered by // MessageList via ToolCallLine / ToolCallGroup. Tool-role messages reach // this point only if MessageList didn't consume them (shouldn't happen, // but guard against it by rendering nothing rather than a stale card). if (message.role === 'tool') return null; if (message.role === 'user') { return (
{message.content}
); } const isStreaming = message.status === 'streaming'; const failed = message.status === 'failed'; // v1.13.7: match the MessageList.flatten trim guard so a whitespace-only // assistant turn doesn't render an empty bubble + dangling ActionRow. const hasContent = message.content.trim().length > 0; // v1.8.2: if metadata stamps an error reason, surface it inline under the // generic "message failed" line. Keeps the user's eye where it already is // rather than introducing a separate banner. const errorMeta = message.metadata !== null && message.metadata.kind === 'error' ? message.metadata : null; return (
{(hasContent || isStreaming) && (
{hasContent ? : null} {isStreaming && ( )}
)} {failed && (
message failed {errorMeta && ( {ERROR_REASON_LABELS[errorMeta.error_reason]} {errorMeta.error_text ? ` — ${errorMeta.error_text}` : ''} )}
)} {!isStreaming && } {!isStreaming && hasContent && }
); }