"use client"; import { useState, useCallback, useRef, useEffect } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { useGlobalKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts"; import { SessionSidebar } from "./SessionSidebar"; import { ChatWindow } from "./ChatWindow"; import { FileViewer } from "./FileViewer"; import { TabBar, type Tab } from "./TabBar"; import { ModelsConfig } from "./ModelsConfig"; import { SkillsConfig } from "./SkillsConfig"; import { PluginsConfig } from "./PluginsConfig"; import { ProjectTrustDialog } from "./ProjectTrustDialog"; import { BranchNavigator } from "./BranchNavigator"; import { useTheme } from "@/hooks/useTheme"; import { useI18n } from "@/hooks/useI18n"; import { useIsMobile } from "@/hooks/useIsMobile"; import { copyText } from "@/lib/clipboard"; import { getFileName } from "@/lib/file-paths"; import { buildAtMentionText, buildFileAtMentionsText, buildFileLineMentionText } from "@/lib/file-fuzzy"; import { getInitialNavigation } from "@/lib/initial-navigation"; import type { SessionInfo, SessionTreeNode } from "@/lib/types"; import type { ProjectTrustStatus } from "@/lib/api-types"; import type { ChatInputHandle } from "./ChatInput"; import type { SessionStatsInfo } from "@/lib/pi-types"; type SessionCopyField = "file" | "id"; type AutoNameStatus = | { kind: "idle" } | { kind: "naming" } | { kind: "success" } | { kind: "error"; message: string }; const TOP_BAR_ICON_BUTTON_SIZE = 36; const LANGUAGE_MENU_WIDTH = 176; export function AppShell() { const router = useRouter(); const searchParams = useSearchParams(); const [initialNavigation] = useState(() => getInitialNavigation(searchParams)); const { isDark, toggleTheme } = useTheme(); const { locale, setLocale, t: translate, supportedLocales } = useI18n(); const isMobile = useIsMobile(); const [selectedSession, setSelectedSession] = useState(null); // When user clicks +, we only store the cwd — no fake session id const [newSessionCwd, setNewSessionCwd] = useState(null); const [initialCwdStatus, setInitialCwdStatus] = useState<"idle" | "validating" | "ready" | "error">( () => initialNavigation.requestedCwd ? "validating" : "idle", ); const [initialCwdError, setInitialCwdError] = useState(null); const [refreshKey, setRefreshKey] = useState(0); const [sessionKey, setSessionKey] = useState(0); const [explorerRefreshKey, setExplorerRefreshKey] = useState(0); const [modelsConfigOpen, setModelsConfigOpen] = useState(false); const [modelsRefreshKey, setModelsRefreshKey] = useState(0); const [skillsConfigOpen, setSkillsConfigOpen] = useState(false); const [pluginsConfigOpen, setPluginsConfigOpen] = useState(false); const [projectTrust, setProjectTrust] = useState(null); const [projectTrustDialogOpen, setProjectTrustDialogOpen] = useState(false); const [projectTrustBusy, setProjectTrustBusy] = useState(false); const [projectTrustError, setProjectTrustError] = useState(null); const [sidebarOpen, setSidebarOpen] = useState(true); const [mobileSidebarReady, setMobileSidebarReady] = useState(false); // On mobile the sidebar is an overlay drawer; hide it by default so the chat // is visible on load. Runs once the breakpoint resolves after hydration. useEffect(() => { if (isMobile) setSidebarOpen(false); }, [isMobile]); useEffect(() => { setMobileSidebarReady(true); }, []); const chatInputRef = useRef(null); const topBarRef = useRef(null); const languageBtnRef = useRef(null); // Branch navigator state — populated by ChatWindow via onBranchDataChange const [branchTree, setBranchTree] = useState([]); const [branchActiveLeafId, setBranchActiveLeafId] = useState(null); const branchLeafChangeFnRef = useRef<((leafId: string | null) => void) | null>(null); const handleBranchDataChange = useCallback((tree: SessionTreeNode[], activeLeafId: string | null, onLeafChange: (leafId: string | null) => void) => { setBranchTree(tree); setBranchActiveLeafId(activeLeafId); branchLeafChangeFnRef.current = onLeafChange; }, []); const handleBranchLeafChange = useCallback((leafId: string | null) => { branchLeafChangeFnRef.current?.(leafId); }, []); const [systemPrompt, setSystemPrompt] = useState(null); const systemBtnRef = useRef(null); const handleSystemPromptChange = useCallback((prompt: string | null) => { setSystemPrompt(prompt); }, []); // Session stats (tokens + cost) — populated by ChatWindow, displayed in top bar const [sessionStats, setSessionStats] = useState(null); const [autoNameStatus, setAutoNameStatus] = useState({ kind: "idle" }); const autoNameTimerRef = useRef | null>(null); const activeSessionIdRef = useRef(selectedSession?.id ?? null); activeSessionIdRef.current = selectedSession?.id ?? null; const handleSessionStatsChange = useCallback((stats: SessionStatsInfo | null) => { setSessionStats(stats); }, []); const [copiedSessionField, setCopiedSessionField] = useState(null); const sessionCopyTimerRef = useRef | null>(null); const handleCopySessionField = useCallback((field: SessionCopyField, value: string) => { void copyText(value).then(() => { if (sessionCopyTimerRef.current) clearTimeout(sessionCopyTimerRef.current); setCopiedSessionField(field); sessionCopyTimerRef.current = setTimeout(() => setCopiedSessionField(null), 1400); }); }, []); useEffect(() => { return () => { if (sessionCopyTimerRef.current) clearTimeout(sessionCopyTimerRef.current); if (autoNameTimerRef.current) clearTimeout(autoNameTimerRef.current); }; }, []); // Context usage — populated by ChatWindow, displayed in top bar const [contextUsage, setContextUsage] = useState<{ percent: number | null; contextWindow: number; tokens: number | null } | null>(null); const handleContextUsageChange = useCallback((usage: { percent: number | null; contextWindow: number; tokens: number | null } | null) => { setContextUsage(usage); }, []); // Single active panel — only one dropdown open at a time const [activeTopPanel, setActiveTopPanel] = useState<"branches" | "system" | "session" | "language" | null>(null); const [topPanelPos, setTopPanelPos] = useState<{ top: number; left: number; width: number } | null>(null); const toggleTopPanel = useCallback((panel: "branches" | "system" | "session" | "language") => { if (isMobile) setSidebarOpen(false); setActiveTopPanel((cur) => cur === panel ? null : panel); }, [isMobile]); const openSessionStatsPanel = useCallback(() => { if (isMobile) setSidebarOpen(false); setActiveTopPanel("session"); }, [isMobile]); const handleSidebarToggle = useCallback(() => { if (isMobile) setActiveTopPanel(null); setSidebarOpen((open) => !open); }, [isMobile]); useEffect(() => { if (!activeTopPanel || !topBarRef.current) return; const update = () => { const topBarRect = topBarRef.current!.getBoundingClientRect(); if (activeTopPanel === "language" && !isMobile && languageBtnRef.current) { const buttonRect = languageBtnRef.current.getBoundingClientRect(); const width = Math.min(LANGUAGE_MENU_WIDTH, topBarRect.width); const left = Math.min( buttonRect.left - 1, Math.max(topBarRect.left, topBarRect.right - width), ); setTopPanelPos({ top: topBarRect.bottom, left, width }); return; } setTopPanelPos({ top: topBarRect.bottom, left: topBarRect.left, width: topBarRect.width }); }; update(); const ro = new ResizeObserver(update); ro.observe(topBarRef.current); if (languageBtnRef.current) ro.observe(languageBtnRef.current); return () => ro.disconnect(); }, [activeTopPanel, isMobile]); // Right panel — file tabs only const [fileTabs, setFileTabs] = useState([]); const [activeFileTabId, setActiveFileTabId] = useState(null); const [rightPanelOpen, setRightPanelOpen] = useState(false); // Same @mention format as the chat input's @ autocomplete, so the agent's // read tool resolves it the same way (it strips the @ prefix). const handleAtMention = useCallback((relativePath: string, isDir: boolean) => { chatInputRef.current?.insertText(buildAtMentionText(relativePath, isDir)); }, []); const handleAtMentions = useCallback((relativePaths: string[]) => { const mentions = buildFileAtMentionsText(relativePaths); if (mentions) chatInputRef.current?.insertText(mentions); }, []); const handleFileLineMention = useCallback((relativePath: string, startLine: number, endLine: number) => { chatInputRef.current?.insertText(buildFileLineMentionText(relativePath, startLine, endLine)); }, []); const initialSessionId = initialNavigation.sessionId; const [activeCwd, setActiveCwd] = useState(null); const activeProjectRootRef = useRef(null); // True once the initial ?session= URL param has been resolved (or confirmed absent) const [initialSessionRestored, setInitialSessionRestored] = useState(() => !initialSessionId); // Suppresses sessionKey bump in handleCwdChange during the initial URL restore const suppressCwdBumpRef = useRef(false); useEffect(() => { const requestedCwd = initialNavigation.requestedCwd; if (!requestedCwd) return; const controller = new AbortController(); setInitialCwdStatus("validating"); setInitialCwdError(null); void fetch("/api/cwd/validate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cwd: requestedCwd }), signal: controller.signal, }) .then(async (response) => { const data = await response.json().catch(() => ({})) as { cwd?: string; error?: string }; if (!response.ok || !data.cwd) { throw new Error(data.error ?? `HTTP ${response.status}`); } // The sidebar will notify us when it adopts this cwd. Avoid remounting // the just-created empty chat during that initial synchronization. suppressCwdBumpRef.current = true; setNewSessionCwd(data.cwd); setInitialCwdStatus("ready"); }) .catch((error: unknown) => { if (controller.signal.aborted) return; setInitialCwdError(error instanceof Error ? error.message : String(error)); setInitialCwdStatus("error"); }); return () => controller.abort(); }, [initialNavigation]); const handleCwdChange = useCallback((cwd: string | null, projectRoot?: string | null) => { setActiveCwd(cwd); // Skip if cwd is null (initial mount). if (!cwd) return; const newProject = projectRoot ?? cwd; const currentProject = activeProjectRootRef.current ?? (selectedSession ? (selectedSession.projectRoot ?? selectedSession.cwd) : null); activeProjectRootRef.current = newProject; // Keep the project identity in sync during the initial URL restore without // remounting the just-created or restored chat. if (suppressCwdBumpRef.current) { suppressCwdBumpRef.current = false; return; } // Worktrees of one repo share a project root. Moving the effective cwd // within the same project (e.g. switching worktree, or clicking a session // that lives in another worktree) must not close the open session. if (currentProject === newProject) { return; } // Close any session that belongs to a different project — it no longer // matches the selected project directory. setSelectedSession(null); setNewSessionCwd((prev) => { if (prev && prev !== cwd) return null; return prev; }); setSessionKey((k) => k + 1); setBranchTree([]); setBranchActiveLeafId(null); setSystemPrompt(null); setActiveTopPanel(null); // File tabs are keyed by absolute path, so tabs opened in the previous // project would otherwise linger after switching to a different project. // Reached only past the same-project early return above, so worktrees of // one repo keep their open tabs. Mirror handleCloseFileTab and close the // now-empty right panel. setFileTabs([]); setActiveFileTabId(null); setRightPanelOpen(false); router.replace("/", { scroll: false }); }, [router, selectedSession]); const handleSelectSession = useCallback((session: SessionInfo, isRestore = false) => { setNewSessionCwd(null); setSelectedSession(session); setSessionKey((k) => k + 1); setSystemPrompt(null); setInitialSessionRestored(true); // On mobile, collapse the overlay drawer so the chat is revealed after pick. if (isMobile && !isRestore) setSidebarOpen(false); if (isRestore) { // Suppress the redundant sessionKey bump that would come from the // onCwdChange effect firing after setSelectedCwd in the sidebar suppressCwdBumpRef.current = true; } // Skip router.replace when restoring from URL — the param is already correct // and calling replace in production Next.js triggers a Suspense remount loop if (!isRestore) { router.replace(`?session=${encodeURIComponent(session.id)}`, { scroll: false }); } }, [router, isMobile]); const handleNewSession = useCallback((_sessionId: string, cwd: string) => { setSelectedSession(null); setNewSessionCwd(cwd); setSessionKey((k) => k + 1); setBranchTree([]); setBranchActiveLeafId(null); setSystemPrompt(null); setActiveTopPanel(null); if (isMobile) setSidebarOpen(false); router.replace("/", { scroll: false }); }, [router, isMobile]); // Global keyboard shortcuts (handles Esc, Ctrl+Alt+N etc.) useGlobalKeyboardShortcuts({ onNewSession: (cwd: string) => handleNewSession(`kb-${Date.now()}`, cwd), activeCwd, }); // Client-built transient SessionInfo (new session / fork) lacks the // server-computed projectRoot, which the same-project check in // handleCwdChange relies on. Hydrate it from the session list so switching // worktrees right after creating a session doesn't close the chat. const hydrateSelectedSession = useCallback((sessionId: string) => { void fetch("/api/sessions") .then((r) => (r.ok ? (r.json() as Promise<{ sessions: SessionInfo[] }>) : null)) .then((d) => { const full = d?.sessions.find((s) => s.id === sessionId); if (!full) return; setSelectedSession((prev) => (prev && prev.id === sessionId && !prev.projectRoot ? full : prev)); }) .catch(() => {}); }, []); // Called by ChatWindow when a new session gets its real id from pi const handleSessionCreated = useCallback((session: SessionInfo) => { setNewSessionCwd(null); setSelectedSession(session); setRefreshKey((k) => k + 1); hydrateSelectedSession(session.id); router.replace(`?session=${encodeURIComponent(session.id)}`, { scroll: false }); }, [router, hydrateSelectedSession]); const handleAgentEnd = useCallback(() => { setRefreshKey((k) => k + 1); setExplorerRefreshKey((k) => k + 1); }, []); const handleAutoName = useCallback(async () => { const sessionId = selectedSession?.id; if (!sessionId || autoNameStatus.kind === "naming") return; if (autoNameTimerRef.current) clearTimeout(autoNameTimerRef.current); setActiveTopPanel(null); setAutoNameStatus({ kind: "naming" }); try { const response = await fetch(`/api/sessions/${encodeURIComponent(sessionId)}/auto-name`, { method: "POST", }); const body = (await response.json().catch(() => ({}))) as { title?: string; error?: string }; if (!response.ok || !body.title) { throw new Error(body.error || `HTTP ${response.status}`); } const title = body.title.trim(); setRefreshKey((key) => key + 1); if (activeSessionIdRef.current !== sessionId) return; setSelectedSession((current) => current?.id === sessionId ? { ...current, name: title } : current); setSessionStats((current) => current?.sessionId === sessionId ? { ...current, sessionName: title } : current); setAutoNameStatus({ kind: "success" }); autoNameTimerRef.current = setTimeout(() => setAutoNameStatus({ kind: "idle" }), 1800); } catch (error) { if (activeSessionIdRef.current !== sessionId) return; const message = error instanceof Error ? error.message : String(error); setAutoNameStatus({ kind: "error", message }); autoNameTimerRef.current = setTimeout(() => setAutoNameStatus({ kind: "idle" }), 5000); } }, [autoNameStatus.kind, selectedSession?.id]); useEffect(() => { if (autoNameTimerRef.current) clearTimeout(autoNameTimerRef.current); setAutoNameStatus({ kind: "idle" }); }, [selectedSession?.id]); const handleExplorerRefresh = useCallback(() => { setExplorerRefreshKey((k) => k + 1); }, []); const handleSessionForked = useCallback((newSessionId: string) => { setRefreshKey((k) => k + 1); setSessionKey((k) => k + 1); setNewSessionCwd(null); setSelectedSession((prev) => ({ ...(prev ?? { path: "", cwd: "", created: "", modified: "", messageCount: 0, firstMessage: "" }), id: newSessionId, })); hydrateSelectedSession(newSessionId); router.replace(`?session=${encodeURIComponent(newSessionId)}`, { scroll: false }); }, [router, hydrateSelectedSession]); const handleInitialRestoreDone = useCallback(() => { setInitialSessionRestored(true); }, []); const handleSessionDeleted = useCallback((sessionId: string) => { setRefreshKey((k) => k + 1); if (selectedSession?.id === sessionId) { const cwd = selectedSession.cwd; setSelectedSession(null); setNewSessionCwd(cwd ?? null); setSessionKey((k) => k + 1); setBranchTree([]); setBranchActiveLeafId(null); setSystemPrompt(null); setActiveTopPanel(null); router.replace("/", { scroll: false }); } }, [selectedSession, router]); const handleOpenFile = useCallback(( filePath: string, fileName: string, options?: { sourceSessionId?: string | null; modeHint?: "diff" }, ) => { const sourceSessionId = options?.sourceSessionId; const modeHint = options?.modeHint; const tabId = `file:${filePath}`; setFileTabs((prev) => { const existing = prev.find((t) => t.id === tabId); if (!existing) { return [...prev, { id: tabId, label: fileName, filePath, sourceSessionId, initialDisplayMode: modeHint, }]; } const sourceUnchanged = !sourceSessionId || existing.sourceSessionId === sourceSessionId; const modeUnchanged = !modeHint || existing.initialDisplayMode === modeHint; if (sourceUnchanged && modeUnchanged) return prev; return prev.map((t) => { if (t.id !== tabId) return t; const next: Tab = { ...t }; if (sourceSessionId) next.sourceSessionId = sourceSessionId; if (modeHint) next.initialDisplayMode = modeHint; return next; }); }); setActiveFileTabId(tabId); setRightPanelOpen(true); // On mobile the file panel is full-screen; close the drawer so it shows. if (isMobile) setSidebarOpen(false); }, [isMobile]); const handleOpenLinkedFile = useCallback((filePath: string) => { handleOpenFile(filePath, getFileName(filePath), { sourceSessionId: selectedSession?.id ?? null }); }, [handleOpenFile, selectedSession?.id]); const handleCloseFileTab = useCallback((tabId: string) => { setFileTabs((prev) => { const next = prev.filter((t) => t.id !== tabId); if (next.length === 0) setRightPanelOpen(false); return next; }); setActiveFileTabId((cur) => { if (cur !== tabId) return cur; const remaining = fileTabs.filter((t) => t.id !== tabId); return remaining.length > 0 ? remaining[remaining.length - 1].id : null; }); }, [fileTabs]); const handleViewFullHistory = useCallback(() => { if (!selectedSession) return; window.open( `/api/sessions/${encodeURIComponent(selectedSession.id)}/export?inline=1`, "_blank", "noopener,noreferrer", ); }, [selectedSession]); // Show chat area if a session is selected, or if we have a cwd to start a new session in const effectiveNewSessionCwd = newSessionCwd ?? (selectedSession === null && activeCwd ? activeCwd : null); const showChat = selectedSession !== null || effectiveNewSessionCwd !== null; const projectTrustCwd = selectedSession?.cwd ?? effectiveNewSessionCwd; // While restoring initial session from URL, don't show the placeholder const showPlaceholder = initialSessionRestored && !showChat; useEffect(() => { setProjectTrust(null); setProjectTrustDialogOpen(false); setProjectTrustError(null); if (!projectTrustCwd) return; const controller = new AbortController(); fetch(`/api/project-trust?cwd=${encodeURIComponent(projectTrustCwd)}`, { signal: controller.signal, }) .then(async (response) => { const data = await response.json() as ProjectTrustStatus & { error?: string }; if (!response.ok || data.error) throw new Error(data.error ?? `HTTP ${response.status}`); setProjectTrust(data); }) .catch((error) => { if (error instanceof DOMException && error.name === "AbortError") return; console.error("Failed to load project trust:", error); }); return () => controller.abort(); }, [projectTrustCwd]); const handleTrustProject = useCallback(async () => { if (!projectTrustCwd || projectTrustBusy) return; setProjectTrustBusy(true); setProjectTrustError(null); try { const response = await fetch("/api/project-trust", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cwd: projectTrustCwd }), }); const data = await response.json() as ProjectTrustStatus & { error?: string }; if (!response.ok || data.error) throw new Error(data.error ?? `HTTP ${response.status}`); setProjectTrust(data); setProjectTrustDialogOpen(false); setModelsRefreshKey((key) => key + 1); setSessionKey((key) => key + 1); } catch (error) { setProjectTrustError(error instanceof Error ? error.message : String(error)); } finally { setProjectTrustBusy(false); } }, [projectTrustBusy, projectTrustCwd]); const activeFileTab = fileTabs.find((t) => t.id === activeFileTabId) ?? null; const activeCwdName = activeCwd ? getFileName(activeCwd) || activeCwd : null; const windowTitle = activeCwdName ? `${activeCwdName} - Pi Web` : "Pi Web"; useEffect(() => { const syncWindowTitle = () => { if (document.title !== windowTitle) document.title = windowTitle; }; syncWindowTitle(); const observer = new MutationObserver(syncWindowTitle); observer.observe(document.head, { childList: true, subtree: true, characterData: true }); return () => observer.disconnect(); }, [windowTitle]); const sidebarContent = ( <>
{([ { label: translate("common.models"), onClick: () => setModelsConfigOpen(true), disabled: false, icon: ( ), }, { label: translate("common.skills"), onClick: () => setSkillsConfigOpen(true), disabled: !activeCwd && !selectedSession?.cwd && !newSessionCwd, icon: ( ), }, { label: translate("common.plugins"), onClick: () => setPluginsConfigOpen(true), disabled: !activeCwd && !selectedSession?.cwd && !newSessionCwd, icon: ( ), }, ] as { label: string; onClick: () => void; disabled: boolean; icon: React.ReactNode }[]).map(({ label, onClick, disabled, icon }) => ( ))}
); return ( <>
{/* Mobile overlay backdrop */}
setSidebarOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 199, background: "rgba(0,0,0,0.4)", opacity: sidebarOpen ? 1 : 0, pointerEvents: sidebarOpen ? "auto" : "none", transition: "opacity 0.25s ease", }} /> {/* Left sidebar */}
{sidebarContent}
{/* Center: chat */}
{/* Top bar with sidebar toggle */}
{showChat && projectTrust?.requiresTrust && !projectTrust.trusted && ( )} {showChat && (
{(() => { const hasMessages = Boolean( selectedSession && (sessionStats?.userMessages ?? selectedSession.messageCount) > 0, ); const disabled = !selectedSession || !hasMessages || autoNameStatus.kind === "naming"; const isSuccess = autoNameStatus.kind === "success"; const isError = autoNameStatus.kind === "error"; const label = autoNameStatus.kind === "naming" ? translate("title.generating") : isSuccess ? translate("title.updated") : isError ? translate("title.failed") : translate("title.generate"); const title = !selectedSession ? translate("title.unsaved") : !hasMessages ? translate("title.noMessages") : isError ? autoNameStatus.message : translate("title.generateSession"); return ( ); })()} toggleTopPanel("branches")} hasSession />
)} {/* Session stats — right-aligned in top bar */} {showChat && (sessionStats || contextUsage) && (() => { const tokens = sessionStats?.tokens; const c = sessionStats?.cost ?? 0; const fmt = (n: number) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(0)}k` : String(n); const costStr = c > 0 ? (c >= 0.01 ? `$${c.toFixed(2)}` : `<$0.01`) : null; let ctxColor = "var(--text-muted)"; let ctxStr: string | null = null; if (contextUsage?.contextWindow) { const pct = contextUsage.percent; if (pct !== null && pct > 90) ctxColor = "#ef4444"; else if (pct !== null && pct > 70) ctxColor = "rgba(234,179,8,0.95)"; ctxStr = pct !== null ? `${pct.toFixed(0)}% / ${fmt(contextUsage.contextWindow)}` : `? / ${fmt(contextUsage.contextWindow)}`; } const tooltipParts: string[] = []; if (tokens) { tooltipParts.push(`in: ${tokens.input.toLocaleString(locale)}`); tooltipParts.push(`out: ${tokens.output.toLocaleString(locale)}`); tooltipParts.push(`cache read: ${tokens.cacheRead.toLocaleString(locale)}`); tooltipParts.push(`cache write: ${tokens.cacheWrite.toLocaleString(locale)}`); if (c > 0) tooltipParts.push(`cost: $${c.toFixed(4)}`); } if (contextUsage?.contextWindow) { const pct = contextUsage.percent; tooltipParts.push(`context: ${pct !== null ? pct.toFixed(1) + "%" : "unknown"} of ${contextUsage.contextWindow.toLocaleString()} tokens`); } const tooltip = tooltipParts.join(" | "); return ( ); })()} {/* Top panel dropdown — shared, only one active at a time */} {activeTopPanel && topPanelPos && (
{activeTopPanel === "language" && (
{supportedLocales.map((plugin) => ( ))}
)} {activeTopPanel === "system" && (
{systemPrompt ? (
{systemPrompt}
) : systemPrompt === "" ? (
{translate("system.empty")}
) : (
{translate("system.load")}
)}
)} {activeTopPanel === "session" && (
{sessionStats ? (() => { const sessionRows = [ ...(sessionStats.sessionName ? [{ label: translate("session.name"), value: sessionStats.sessionName, copyField: null }] : []), { label: translate("session.file"), value: sessionStats.sessionFile ?? translate("session.inMemory"), copyField: "file" as const }, { label: translate("session.id"), value: sessionStats.sessionId, copyField: "id" as const }, ]; const messageRows = [ [translate("session.user"), sessionStats.userMessages.toLocaleString(locale)], [translate("session.assistant"), sessionStats.assistantMessages.toLocaleString(locale)], [translate("session.toolCalls"), sessionStats.toolCalls.toLocaleString(locale)], [translate("session.toolResults"), sessionStats.toolResults.toLocaleString(locale)], [translate("session.total"), sessionStats.totalMessages.toLocaleString(locale)], ]; const tokenRows = [ [translate("session.input"), sessionStats.tokens.input.toLocaleString(locale)], [translate("session.output"), sessionStats.tokens.output.toLocaleString(locale)], ...(sessionStats.tokens.cacheRead > 0 ? [[translate("session.cacheRead"), sessionStats.tokens.cacheRead.toLocaleString(locale)]] : []), ...(sessionStats.tokens.cacheWrite > 0 ? [[translate("session.cacheWrite"), sessionStats.tokens.cacheWrite.toLocaleString(locale)]] : []), [translate("session.total"), sessionStats.tokens.total.toLocaleString(locale)], ]; const ctx = contextUsage ?? sessionStats.contextUsage; const formatCompact = (n: number) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(0)}k` : String(n); const extraTokenRows = [ ...(sessionStats.cost > 0 ? [[translate("session.cost"), `$${sessionStats.cost.toFixed(4)}`]] : []), ...(ctx?.contextWindow ? [[translate("session.context"), `${ctx.percent !== null ? `${ctx.percent.toFixed(1)}%` : "?"} / ${formatCompact(ctx.contextWindow)}`]] : []), ]; const section = ( title: string, sectionRows: string[][], valueAlign: "left" | "right" = "left", compact = false, ) => (
{title}
{sectionRows.map(([label, value]) => (
{label}
{value}
))}
); const copyButton = (field: SessionCopyField, value: string) => { const copied = copiedSessionField === field; return ( ); }; const sessionInfoSection = (
{translate("session.infoSection")}
{sessionRows.map((row) => (
{row.label}
{row.value}
{row.copyField ? copyButton(row.copyField, row.value) : null}
))}
); return (
{sessionInfoSection} {section(translate("session.messages"), messageRows)} {section(translate("session.tokens"), [...tokenRows, ...extraTokenRows], "right", true)}
); })() : (
{translate("session.load")}
)}
)}
)}
{/* Chat content */}
{showChat ? ( ) : initialCwdStatus === "validating" ? (
{translate("workspace.opening")}
{initialNavigation.requestedCwd}
) : initialCwdStatus === "error" ? (
{translate("workspace.unable")}
{initialNavigation.requestedCwd}
{initialCwdError}
) : showPlaceholder ? ( activeCwd ? (
{translate("workspace.selectSession")}
) : (
{translate("workspace.getStarted")}
1.{translate("workspace.selectProject")}
2.{translate("workspace.addModels")}
) ) : null}
{/* Right panel: file viewer — always mounted, width animated via CSS */}
{/* Right panel tab bar */}
{/* File content */}
{activeFileTab?.filePath ? ( handleOpenFile( filePath, getFileName(filePath), { sourceSessionId: activeFileTab.sourceSessionId }, )} /> ) : (
{translate("files.noneOpen")}
)}
{/* File panel toggle — always visible at top-right */} {modelsConfigOpen && { setModelsConfigOpen(false); setModelsRefreshKey((k) => k + 1); }} />} {projectTrustDialogOpen && projectTrustCwd && ( { if (!projectTrustBusy) setProjectTrustDialogOpen(false); }} onConfirm={() => void handleTrustProject()} /> )} {skillsConfigOpen && projectTrustCwd && ( setSkillsConfigOpen(false)} /> )} {pluginsConfigOpen && projectTrustCwd && ( setPluginsConfigOpen(false)} onReloaded={() => setSessionKey((k) => k + 1)} /> )} ); }