"use client" import { useEffect, useMemo, useRef, useState } from "react" import { Archive, ArrowRightLeft, Brain, Check, ChevronRight, Cpu, Download, ExternalLink, FileText, FlaskConical, FolderRoot, GitBranch, KeyRound, LifeBuoy, LoaderCircle, LogIn, LogOut, PencilLine, Radio, RefreshCw, Search, ShieldCheck, SlidersHorizontal, SquareTerminal, X, } from "lucide-react" import { toast } from "sonner" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { ScrollArea } from "@/components/ui/scroll-area" import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, } from "@/components/ui/sheet" import { Switch } from "@/components/ui/switch" import { Textarea } from "@/components/ui/textarea" import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip" import { COMMAND_SURFACE_THINKING_LEVELS, type CommandSurfaceSection, type CommandSurfaceTarget, } from "@/lib/command-surface-contract" import { cn } from "@/lib/utils" import { DEV_OVERRIDE_REGISTRY, useDevOverrides, } from "@/lib/dev-overrides" import { DoctorPanel, ForensicsPanel, SkillHealthPanel } from "./diagnostics-panels" import { KnowledgeCapturesPanel } from "./knowledge-captures-panel" import { PrefsPanel, ModelRoutingPanel, BudgetPanel, RemoteQuestionsPanel, GeneralPanel, ExperimentalPanel } from "./settings-panels" import { DevRootSettingsSection } from "./projects-view" import { QuickPanel, HistoryPanel, UndoPanel, SteerPanel, HooksPanel, InspectPanel, ExportPanel, CleanupPanel, QueuePanel, StatusPanel, } from "./remaining-command-panels" import { formatCost, formatTokens, getModelLabel, getSessionLabelFromBridge, shortenPath, useSFWorkspaceActions, useSFWorkspaceState, } from "@/lib/sf-workspace-store" // ─── Section metadata ──────────────────────────────────────────────── const SETTINGS_SURFACE_SECTIONS = ["general", "model", "session-behavior", "recovery", "auth", "integrations", "workspace", "experimental"] as const const ADMIN_SECTION: CommandSurfaceSection = "admin" const GIT_SURFACE_SECTIONS = ["git"] as const const SESSION_SURFACE_SECTIONS = ["resume", "name", "fork", "session", "compact"] as const function availableSectionsForSurface(surface: string | null, includeAdmin: boolean = false): CommandSurfaceSection[] { switch (surface) { case "git": return [...GIT_SURFACE_SECTIONS] case "resume": case "name": case "fork": case "session": case "export": case "compact": return [...SESSION_SURFACE_SECTIONS] default: return includeAdmin ? [...SETTINGS_SURFACE_SECTIONS, ADMIN_SECTION] : [...SETTINGS_SURFACE_SECTIONS] } } function sectionLabel(section: CommandSurfaceSection): string { const labels: Partial> = { general: "General", model: "Model", thinking: "Thinking", queue: "Queue", compaction: "Compaction", retry: "Retry", "session-behavior": "Session", recovery: "Recovery", auth: "Auth", admin: "Admin", git: "Git", resume: "Resume", name: "Name", fork: "Fork", session: "Session", compact: "Compact", workspace: "Workspace", integrations: "Integrations", experimental: "Experimental", } return labels[section] ?? section } function sectionIcon(section: CommandSurfaceSection) { const icons: Partial> = { general: , model: , thinking: , queue: , compaction: , retry: , "session-behavior": , recovery: , auth: , admin: , git: , resume: , name: , fork: , session: , compact: , workspace: , integrations: , experimental: , } return icons[section] ?? null } function surfaceTitle(surface: string | null): string { const titles: Record = { model: "Model", thinking: "Thinking", git: "Git", login: "Login", logout: "Logout", settings: "Settings", resume: "Resume", name: "Name", fork: "Fork", session: "Session", export: "Export", compact: "Compact", } return titles[surface ?? ""] ?? "Settings" } function currentAuthIntent(activeSurface: string | null, selectedTarget: CommandSurfaceTarget | null): "login" | "logout" | "manage" { if (selectedTarget?.kind === "auth") return selectedTarget.intent if (activeSurface === "login") return "login" if (activeSurface === "logout") return "logout" return "manage" } function formatRelativeTime(isoDate: string): string { const now = Date.now() const then = new Date(isoDate).getTime() const diffMs = now - then if (diffMs < 60_000) return "just now" const minutes = Math.floor(diffMs / 60_000) if (minutes < 60) return `${minutes}m ago` const hours = Math.floor(minutes / 60) if (hours < 24) return `${hours}h ago` const days = Math.floor(hours / 24) return `${days}d ago` } // ─── Inline status dot ────────────────────────────────────────────── function StatusDot({ status }: { status: "ok" | "warning" | "error" | "idle" }) { return ( ) } // ─── Inline section header ────────────────────────────────────────── function SectionHeader({ title, action, status, }: { title: string action?: React.ReactNode status?: React.ReactNode }) { return (

{title}

{status}
{action}
) } // ─── Inline key-value row ─────────────────────────────────────────── function KV({ label, children, mono }: { label: string; children: React.ReactNode; mono?: boolean }) { return (
{label} {children}
) } // ─── Toggle row: label + switch ───────────────────────────────────── function ToggleRow({ label, description, checked, onCheckedChange, disabled, busy, testId, }: { label: string description?: string checked: boolean onCheckedChange: (checked: boolean) => void disabled?: boolean busy?: boolean testId?: string }) { return (
{label} {busy && }
{description &&

{description}

}
) } // ─── Segmented control ────────────────────────────────────────────── function SegmentedControl({ options, value, onChange, disabled, }: { options: { value: T; label: string }[] value: T | null onChange: (value: T) => void disabled?: boolean }) { return (
{options.map((opt) => ( ))}
) } // ═════════════════════════════════════════════════════════════════════ // MAIN COMPONENT // ═════════════════════════════════════════════════════════════════════ export function CommandSurface() { const workspace = useSFWorkspaceState() const { closeCommandSurface, openCommandSurface, refreshBoot, setCommandSurfaceSection, selectCommandSurfaceTarget, loadGitSummary, loadRecoveryDiagnostics, loadForensicsDiagnostics, loadDoctorDiagnostics, loadSkillHealthDiagnostics, loadKnowledgeData, loadCapturesData, loadSettingsData, updateSessionBrowserState, loadSessionBrowser, renameSessionFromSurface, loadAvailableModels, applyModelSelection, applyThinkingLevel, setSteeringModeFromSurface, setFollowUpModeFromSurface, setAutoCompactionFromSurface, setAutoRetryFromSurface, abortRetryFromSurface, switchSessionFromSurface, loadSessionStats, exportSessionFromSurface, loadForkMessages, forkSessionFromSurface, compactSessionFromSurface, saveApiKeyFromSurface, startProviderFlowFromSurface, submitProviderFlowInputFromSurface, cancelProviderFlowFromSurface, logoutProviderFromSurface, loadHistoryData, loadInspectData, loadHooksData, loadUndoInfo, loadCleanupData, loadSteerData, } = useSFWorkspaceActions() const { commandSurface } = workspace const onboarding = workspace.boot?.onboarding ?? null const activeFlow = onboarding?.activeFlow ?? null const gitSummary = commandSurface.gitSummary const recovery = commandSurface.recovery const sessionBrowser = commandSurface.sessionBrowser const liveSessionState = workspace.boot?.bridge.sessionState ?? null const settingsRequests = commandSurface.settingsRequests const currentModelLabel = getModelLabel(workspace.boot?.bridge) const currentSessionLabel = getSessionLabelFromBridge(workspace.boot?.bridge) const [apiKeys, setApiKeys] = useState>({}) const [flowInput, setFlowInput] = useState("") const commandSurfaceViewportRef = useRef(null) // ─── Auto-loaders ────────────────────────────────────────────────── useEffect(() => { if (!commandSurface.open || commandSurface.section !== "model") return if (commandSurface.availableModels.length > 0) return if (commandSurface.pendingAction === "loading_models") return void loadAvailableModels() }, [commandSurface.open, commandSurface.section, commandSurface.availableModels.length, commandSurface.pendingAction, loadAvailableModels]) useEffect(() => { if (!commandSurface.open || commandSurface.section !== "git") return if (commandSurface.pendingAction === "load_git_summary") return if (commandSurface.gitSummary.loaded || commandSurface.gitSummary.error) return void loadGitSummary() }, [commandSurface.open, commandSurface.section, commandSurface.pendingAction, commandSurface.gitSummary.loaded, commandSurface.gitSummary.error, loadGitSummary]) useEffect(() => { if (!commandSurface.open || commandSurface.section !== "recovery") return if (commandSurface.pendingAction === "load_recovery_diagnostics") return if (commandSurface.recovery.pending) return if (commandSurface.recovery.loaded && !commandSurface.recovery.stale && !commandSurface.recovery.error) return void loadRecoveryDiagnostics() }, [ commandSurface.open, commandSurface.section, commandSurface.pendingAction, commandSurface.recovery.pending, commandSurface.recovery.loaded, commandSurface.recovery.stale, commandSurface.recovery.error, loadRecoveryDiagnostics, ]) // Auto-fetch diagnostics panels when their sections open const diagnostics = commandSurface.diagnostics const knowledgeCaptures = commandSurface.knowledgeCaptures const settingsData = commandSurface.settingsData const remainingCommands = commandSurface.remainingCommands useEffect(() => { if (!commandSurface.open) return if (commandSurface.section === "sf-forensics" && diagnostics.forensics.phase === "idle") { void loadForensicsDiagnostics() } else if (commandSurface.section === "sf-doctor" && diagnostics.doctor.phase === "idle") { void loadDoctorDiagnostics() } else if (commandSurface.section === "sf-skill-health" && diagnostics.skillHealth.phase === "idle") { void loadSkillHealthDiagnostics() } else if ( commandSurface.section === "sf-knowledge" && knowledgeCaptures.knowledge.phase === "idle" ) { void loadKnowledgeData() void loadCapturesData() } else if ( (commandSurface.section === "sf-capture" || commandSurface.section === "sf-triage") && knowledgeCaptures.captures.phase === "idle" ) { void loadCapturesData() void loadKnowledgeData() } else if ( (commandSurface.section === "sf-prefs" || commandSurface.section === "sf-mode" || commandSurface.section === "sf-config" || commandSurface.section === "experimental") && settingsData.phase === "idle" ) { void loadSettingsData() } else if (commandSurface.section === "sf-history" && remainingCommands.history.phase === "idle") { void loadHistoryData() } else if (commandSurface.section === "sf-inspect" && remainingCommands.inspect.phase === "idle") { void loadInspectData() } else if (commandSurface.section === "sf-hooks" && remainingCommands.hooks.phase === "idle") { void loadHooksData() } else if (commandSurface.section === "sf-undo" && remainingCommands.undo.phase === "idle") { void loadUndoInfo() } else if (commandSurface.section === "sf-cleanup" && remainingCommands.cleanup.phase === "idle") { void loadCleanupData() } else if (commandSurface.section === "sf-steer" && remainingCommands.steer.phase === "idle") { void loadSteerData() } }, [ commandSurface.open, commandSurface.section, diagnostics.forensics.phase, diagnostics.doctor.phase, diagnostics.skillHealth.phase, knowledgeCaptures.knowledge.phase, knowledgeCaptures.captures.phase, settingsData.phase, remainingCommands.history.phase, remainingCommands.inspect.phase, remainingCommands.hooks.phase, remainingCommands.undo.phase, remainingCommands.cleanup.phase, remainingCommands.steer.phase, loadForensicsDiagnostics, loadDoctorDiagnostics, loadSkillHealthDiagnostics, loadKnowledgeData, loadCapturesData, loadSettingsData, loadHistoryData, loadInspectData, loadHooksData, loadUndoInfo, loadCleanupData, loadSteerData, ]) useEffect(() => { if (!commandSurface.open || (commandSurface.section !== "resume" && commandSurface.section !== "name")) return if (commandSurface.pendingAction === "load_session_browser") return if (commandSurface.sessionBrowser.loaded) return void loadSessionBrowser() }, [commandSurface.open, commandSurface.section, commandSurface.pendingAction, commandSurface.sessionBrowser.loaded, loadSessionBrowser]) useEffect(() => { if (!commandSurface.open) return const viewport = commandSurfaceViewportRef.current if (!viewport) return viewport.scrollTop = 0 }, [commandSurface.open, commandSurface.activeSurface, commandSurface.section]) useEffect(() => { if (!commandSurface.open || commandSurface.section !== "session") return if (commandSurface.sessionStats) return if (commandSurface.pendingAction === "load_session_stats") return void loadSessionStats() }, [commandSurface.open, commandSurface.section, commandSurface.sessionStats, commandSurface.pendingAction, loadSessionStats]) useEffect(() => { if (!commandSurface.open || commandSurface.section !== "fork") return if (commandSurface.forkMessages.length > 0) return if (commandSurface.pendingAction === "load_fork_messages") return void loadForkMessages() }, [commandSurface.open, commandSurface.section, commandSurface.forkMessages.length, commandSurface.pendingAction, loadForkMessages]) useEffect(() => { if (!commandSurface.open || commandSurface.section !== "resume") return const selectedResumeTarget = commandSurface.selectedTarget?.kind === "resume" ? commandSurface.selectedTarget : null if (selectedResumeTarget?.sessionPath) return const defaultSession = sessionBrowser.sessions.find((session) => !session.isActive) ?? sessionBrowser.sessions[0] if (!defaultSession) return selectCommandSurfaceTarget({ kind: "resume", sessionPath: defaultSession.path }) }, [commandSurface.open, commandSurface.section, commandSurface.selectedTarget, sessionBrowser.sessions, selectCommandSurfaceTarget]) useEffect(() => { if (!commandSurface.open || commandSurface.section !== "name") return const selectedNameTarget = commandSurface.selectedTarget?.kind === "name" ? commandSurface.selectedTarget : null if (selectedNameTarget?.sessionPath) return const defaultSession = sessionBrowser.sessions.find((session) => session.isActive) ?? sessionBrowser.sessions[0] if (!defaultSession) return selectCommandSurfaceTarget({ kind: "name", sessionPath: defaultSession.path, name: defaultSession.name ?? "" }) }, [commandSurface.open, commandSurface.section, commandSurface.selectedTarget, sessionBrowser.sessions, selectCommandSurfaceTarget]) useEffect(() => { const resetTimer = window.setTimeout(() => { setFlowInput("") }, 0) return () => window.clearTimeout(resetTimer) }, [activeFlow?.flowId]) // ─── Toast on action results ─────────────────────────────────────── useEffect(() => { if (commandSurface.lastError) { toast.error(commandSurface.lastError) } }, [commandSurface.lastError]) useEffect(() => { if (commandSurface.lastResult) { toast.success(commandSurface.lastResult) } }, [commandSurface.lastResult]) // ─── Derived state ───────────────────────────────────────────────── const selectedModelTarget = commandSurface.selectedTarget?.kind === "model" ? commandSurface.selectedTarget : null const selectedThinkingTarget = commandSurface.selectedTarget?.kind === "thinking" ? commandSurface.selectedTarget : null const selectedAuthTarget = commandSurface.selectedTarget?.kind === "auth" ? commandSurface.selectedTarget : null const selectedResumeTarget = commandSurface.selectedTarget?.kind === "resume" ? commandSurface.selectedTarget : null const selectedNameTarget = commandSurface.selectedTarget?.kind === "name" ? commandSurface.selectedTarget : null const selectedForkTarget = commandSurface.selectedTarget?.kind === "fork" ? commandSurface.selectedTarget : null const selectedSessionTarget = commandSurface.selectedTarget?.kind === "session" ? commandSurface.selectedTarget : null const selectedCompactTarget = commandSurface.selectedTarget?.kind === "compact" ? commandSurface.selectedTarget : null const selectedAuthIntent = currentAuthIntent(commandSurface.activeSurface, commandSurface.selectedTarget) const selectedAuthProvider = onboarding?.required.providers.find((provider) => provider.id === selectedAuthTarget?.providerId) ?? null const modelQuery = (selectedModelTarget?.query ?? commandSurface.args).trim().toLowerCase() const filteredModels = useMemo(() => { if (!modelQuery) return commandSurface.availableModels return commandSurface.availableModels.filter((model) => `${model.provider} ${model.modelId} ${model.name ?? ""}`.toLowerCase().includes(modelQuery), ) }, [commandSurface.availableModels, modelQuery]) // Group filtered models by provider for display const groupedModels = useMemo(() => { const groups = new Map() for (const model of filteredModels) { const key = model.provider const existing = groups.get(key) if (existing) existing.push(model) else groups.set(key, [model]) } return groups }, [filteredModels]) const authBusy = workspace.onboardingRequestState !== "idle" const modelBusy = commandSurface.pendingAction === "loading_models" || workspace.commandInFlight === "get_available_models" const gitSummaryBusy = commandSurface.pendingAction === "load_git_summary" const recoveryBusy = commandSurface.pendingAction === "load_recovery_diagnostics" || recovery.pending const recoveryDiagnostics = recovery.diagnostics const sessionBrowserBusy = commandSurface.pendingAction === "load_session_browser" const forkBusy = commandSurface.pendingAction === "load_fork_messages" || commandSurface.pendingAction === "fork_session" const sessionBusy = commandSurface.pendingAction === "load_session_stats" || commandSurface.pendingAction === "export_html" const resumeBusy = commandSurface.pendingAction === "switch_session" const renameBusy = commandSurface.pendingAction === "rename_session" const compactBusy = commandSurface.pendingAction === "compact_session" || liveSessionState?.isCompacting === true const queueBusy = settingsRequests.steeringMode.pending || settingsRequests.followUpMode.pending const autoCompactionBusy = settingsRequests.autoCompaction.pending const autoRetryBusy = settingsRequests.autoRetry.pending const abortRetryBusy = settingsRequests.abortRetry.pending const selectedProviderApiKey = selectedAuthProvider ? apiKeys[selectedAuthProvider.id] ?? "" : "" const devOverrides = useDevOverrides() const surfaceSections = availableSectionsForSurface(commandSurface.activeSurface, devOverrides.isDevMode) const surfaceKindLabel = `/${commandSurface.activeSurface ?? "settings"}` const triggerRecoveryBrowserAction = (actionId: string) => { switch (actionId) { case "refresh_diagnostics": void loadRecoveryDiagnostics() return case "refresh_workspace": void refreshBoot({ soft: true }) return case "open_retry_controls": setCommandSurfaceSection("retry") return case "open_resume_controls": openCommandSurface("resume", { source: "surface" }) return case "open_auth_controls": setCommandSurfaceSection("auth") return default: return } } // ═══════════════════════════════════════════════════════════════════ // SECTION RENDERERS // ═══════════════════════════════════════════════════════════════════ const renderModelSection = () => (
{currentModelLabel} } action={ } /> {/* Search filter */}
selectCommandSurfaceTarget({ kind: "model", provider: selectedModelTarget?.provider, modelId: selectedModelTarget?.modelId, query: e.target.value, }) } placeholder="Filter models…" className="h-8 pl-9 text-xs" />
{/* Model list */} {modelBusy && commandSurface.availableModels.length === 0 ? (
Loading models…
) : filteredModels.length > 0 ? (
{Array.from(groupedModels.entries()).map(([provider, models]) => (
{provider}
{models.map((model) => { const selected = selectedModelTarget?.provider === model.provider && selectedModelTarget?.modelId === model.modelId return ( ) })}
))}
) : (

No models matched.

)} {/* Apply */}
) const renderThinkingSection = () => (
{workspace.boot?.bridge.sessionState?.thinkingLevel ?? "off"} } />
{COMMAND_SURFACE_THINKING_LEVELS.map((level) => { const selected = selectedThinkingTarget?.level === level const isCurrent = workspace.boot?.bridge.sessionState?.thinkingLevel === level const description = level === "off" ? "No reasoning overhead" : level === "minimal" ? "Light reasoning" : level === "low" ? "Basic analysis" : level === "medium" ? "Balanced reasoning" : level === "high" ? "Deep analysis" : "Maximum deliberation" return ( ) })}
) const renderQueueSection = () => (
{/* Steering mode */}
Steering mode

How steering messages queue during streaming

{settingsRequests.steeringMode.pending && }
void setSteeringModeFromSurface(v)} disabled={!liveSessionState || queueBusy} /> {settingsRequests.steeringMode.error && (

{settingsRequests.steeringMode.error}

)}
{/* Follow-up mode */}
Follow-up mode

How follow-up prompts sequence during a live turn

{settingsRequests.followUpMode.pending && }
void setFollowUpModeFromSurface(v)} disabled={!liveSessionState || queueBusy} /> {settingsRequests.followUpMode.error && (

{settingsRequests.followUpMode.error}

)}
) const renderCompactionSection = () => (
Compacting ) : null } /> void setAutoCompactionFromSurface(checked)} disabled={!liveSessionState || autoCompactionBusy} busy={autoCompactionBusy} testId="command-surface-toggle-auto-compaction" /> {settingsRequests.autoCompaction.error && (

{settingsRequests.autoCompaction.error}

)} {settingsRequests.autoCompaction.result && (

{settingsRequests.autoCompaction.result}

)}
) const renderRetrySection = () => (
Attempt {Math.max(1, liveSessionState.retryAttempt)} ) : null } /> void setAutoRetryFromSurface(checked)} disabled={!liveSessionState || autoRetryBusy} busy={autoRetryBusy} testId="command-surface-toggle-auto-retry" />

{autoRetryBusy ? "Updating auto-retry…" : settingsRequests.autoRetry.error ? settingsRequests.autoRetry.error : settingsRequests.autoRetry.result ? settingsRequests.autoRetry.result : liveSessionState?.autoRetryEnabled ? "Auto-retry enabled" : "Auto-retry disabled"}

{liveSessionState?.retryInProgress && (
Retry in progress

Attempt {Math.max(1, liveSessionState.retryAttempt)} is active

)} {settingsRequests.autoRetry.error &&

{settingsRequests.autoRetry.error}

}

{abortRetryBusy ? "Aborting retry…" : settingsRequests.abortRetry.error ? settingsRequests.abortRetry.error : settingsRequests.abortRetry.result ? settingsRequests.abortRetry.result : liveSessionState?.retryInProgress ? "Retry can be aborted" : "No retry in progress"}

{settingsRequests.abortRetry.error &&

{settingsRequests.abortRetry.error}

}
) const renderRecoverySection = () => { const diag = recoveryDiagnostics return (
{recoveryBusy ? "Loading recovery diagnostics…" : recovery.error ? "Recovery diagnostics failed" : recovery.stale ? "Recovery diagnostics stale" : recovery.loaded ? "Recovery diagnostics loaded" : "Recovery diagnostics idle"}
) : null } action={ } /> {recovery.error && (
{recovery.error}
)} {recoveryBusy && !diag && ( <>
Loading diagnostics…
)} {diag?.status === "unavailable" && !recovery.error && ( <>
{diag.summary.label}

{diag.summary.detail}

)} {diag && diag.status !== "unavailable" && ( <>
{diag.summary.label}

{diag.summary.detail}

{/* Summary stats */}
Validation
{diag.summary.validationCount}
Doctor
{diag.summary.doctorIssueCount}
{/* Status badges */}
{diag.summary.retryInProgress && Retry {Math.max(1, diag.summary.retryAttempt)}} {diag.summary.compactionActive && Compacting} {diag.summary.lastFailurePhase && Phase {diag.summary.lastFailurePhase}} {recovery.stale && Stale}
{/* Last failure */} {diag.bridge.lastFailure && (
Last failure

{diag.bridge.lastFailure.message}

Phase: {diag.bridge.lastFailure.phase} {formatRelativeTime(diag.bridge.lastFailure.at)}
)} {/* Validation issues */} {diag.validation.topIssues.length > 0 && (
Validation issues
{diag.validation.topIssues.map((issue) => (
{issue.code}

{issue.message}

{issue.suggestion &&

→ {issue.suggestion}

}
))}
)} {/* Doctor issues */} {diag.doctor.topIssues.length > 0 && (
Doctor issues
{diag.doctor.topIssues.map((issue) => (
{issue.code}

{issue.message}

))}
)} {/* Interrupted run */} {diag.interruptedRun.detected && (
Interrupted run detected

Available: yes

Detected: yes

{diag.interruptedRun.detail}

Tool calls: {diag.interruptedRun.counts.toolCalls} Files written: {diag.interruptedRun.counts.filesWritten} Commands: {diag.interruptedRun.counts.commandsRun} Errors: {diag.interruptedRun.counts.errors} Last forensic error: {diag.interruptedRun.lastError ?? "[redacted]"}
)} {/* Actions */}
{diag.actions.browser.length > 0 ? ( diag.actions.browser.map((action) => ( )) ) : ( {recoveryBusy ? "Loading recovery actions…" : "No browser recovery actions available."} )}
{diag.actions.commands.length > 0 && (
Suggested commands
{diag.actions.commands.map((command) => (
{command.command}

{command.label}

))}
)} )}
) } const gitFileStatusColor = (status: string) => { switch (status) { case "M": return "text-warning bg-warning/10" case "A": return "text-success bg-success/10" case "D": return "text-destructive bg-destructive/10" case "R": return "text-info bg-info/10" case "C": return "text-info bg-info/10" case "U": return "text-destructive bg-destructive/10" case "?": return "text-muted-foreground bg-foreground/5" default: return "text-muted-foreground bg-foreground/5" } } const renderGitSection = () => { const result = gitSummary.result return (
{gitSummaryBusy ? "Loading git summary…" : gitSummary.error ? "Git summary failed" : result?.kind === "not_repo" ? "No git repository" : result?.kind === "repo" ? `Repo ready${result.hasChanges ? " — changes detected" : " — clean"}` : "Git summary idle"}
{gitSummaryBusy && !result && (
Loading repo state…
)} {gitSummary.error && (
{gitSummary.error}
)} {!gitSummary.error && result?.kind === "not_repo" && (
No Git repository

{result.message}

)} {!gitSummary.error && result?.kind === "repo" && ( <> {/* Repo info bar */}
{shortenPath(result.project.repoRoot, 3)} {result.project.repoRelativePath && ( <> {result.project.repoRelativePath} )}
{/* Counts row */}
{[ { label: "Staged", count: result.counts.staged, active: result.counts.staged > 0, color: "text-success" }, { label: "Modified", count: result.counts.dirty, active: result.counts.dirty > 0, color: "text-warning" }, { label: "Untracked", count: result.counts.untracked, active: result.counts.untracked > 0, color: "text-muted-foreground" }, { label: "Conflicts", count: result.counts.conflicts, active: result.counts.conflicts > 0, color: "text-destructive" }, ].map(({ label, count, active, color }) => (
{count}
{label}
))}
{/* Changed files */} {result.changedFiles.length > 0 && (
Changes {result.changedFiles.length}{result.truncatedFileCount > 0 ? `+${result.truncatedFileCount}` : ""} files
{result.changedFiles.map((file) => (
{file.status} {file.path} {file.conflict && ( conflict )}
))}
{result.truncatedFileCount > 0 && (

+{result.truncatedFileCount} more files not shown

)}
)} {result.changedFiles.length === 0 && (
Working tree clean
)} )}
) } const renderSessionBrowserSection = (mode: "resume" | "name") => { const renameMode = mode === "name" const selectedSessionPath = renameMode ? selectedNameTarget?.sessionPath : selectedResumeTarget?.sessionPath return (
{currentSessionLabel ?? "pending"} ) : null } /> {/* Search bar */}
updateSessionBrowserState({ query: e.target.value })} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void loadSessionBrowser() } }} placeholder="Search sessions…" className="h-8 pl-9 text-xs" disabled={sessionBrowserBusy} data-testid="command-surface-session-browser-query" />
{/* Sort/filter controls */}
{ updateSessionBrowserState({ sortMode: v }); void loadSessionBrowser({ sortMode: v }) }} disabled={sessionBrowserBusy} />
{sessionBrowser.error && (
{sessionBrowser.error}
)} {/* Session list */} {sessionBrowserBusy && sessionBrowser.sessions.length === 0 ? (
Loading sessions…
) : sessionBrowser.sessions.length > 0 ? (
{sessionBrowser.sessions.map((session) => { const selected = session.path === selectedSessionPath return ( ) })}
) : (

No sessions matched.

)} {sessionBrowser.loaded && (

Current-project sessions · {sessionBrowser.returnedSessions} of {sessionBrowser.totalSessions} · {sessionBrowser.sortMode} · {sessionBrowser.nameFilter}

)} {/* Rename controls */} {renameMode && (
selectCommandSurfaceTarget({ kind: "name", sessionPath: selectedNameTarget?.sessionPath, name: e.target.value }) } placeholder="Session name" className="h-8 flex-1 text-xs" disabled={!selectedNameTarget?.sessionPath || renameBusy} data-testid="command-surface-rename-input" />
{commandSurface.renameRequest.error &&

{commandSurface.renameRequest.error}

} {commandSurface.renameRequest.result &&

{commandSurface.renameRequest.result}

}
)} {/* Resume controls */} {!renameMode && (
{resumeBusy ? "Switching…" : commandSurface.resumeRequest.error ?? commandSurface.resumeRequest.result ?? "Select a session"}
)}
) } const renderForkSection = () => (
void loadForkMessages()} disabled={forkBusy} className="h-7 gap-1.5 text-xs"> Refresh } /> {forkBusy && commandSurface.forkMessages.length === 0 ? (
Loading fork points…
) : commandSurface.forkMessages.length > 0 ? (
{commandSurface.forkMessages.map((message) => { const selected = selectedForkTarget?.entryId === message.entryId return ( ) })}
) : (

No fork points available yet.

)}
) const renderSessionSection = () => (
{currentSessionLabel ?? "pending"} } action={ } /> {commandSurface.sessionStats ? ( <> {/* Token & cost grid */}
{[ { label: "Input", value: formatTokens(commandSurface.sessionStats.tokens.input) }, { label: "Output", value: formatTokens(commandSurface.sessionStats.tokens.output) }, { label: "Total", value: formatTokens(commandSurface.sessionStats.tokens.total) }, ].map(({ label, value }) => (
{label}
{value}
))}
{/* Message breakdown */}
{commandSurface.sessionStats.userMessages} {commandSurface.sessionStats.assistantMessages} {commandSurface.sessionStats.toolCalls} {commandSurface.sessionStats.toolResults}
{commandSurface.sessionStats.totalMessages} {formatCost(commandSurface.sessionStats.cost)} {commandSurface.sessionStats.tokens.cacheRead > 0 && ( {formatTokens(commandSurface.sessionStats.tokens.cacheRead)} )}
) : (

Refresh to load session stats.

)} {/* Export */}
Export
selectCommandSurfaceTarget({ kind: "session", outputPath: e.target.value })} placeholder="Output path (optional)" className="h-8 flex-1 text-xs" disabled={commandSurface.pendingAction === "export_html"} data-testid="command-surface-export-path" />
) const renderCompactSection = () => (
Working ) : null } />