/** * ============================================================ * src/ui/Root.tsx —— TUI 顶层 phase 切换器 * ------------------------------------------------------------ * 作为 Ink 渲染树的根节点,根据"有没有 Provider 配置"决定渲染: * - 没有 → :菜单式分段配置,完成基座 * 模型配置(可选顺带配其它项)后切到 App * - 有 → :常规对话界面 * * 为什么需要这一层而不是直接在 main.tsx 二选一渲染? * 菜单里选"完成退出"后必须直接进 App,不能让用户手动重跑命令。在 React * 树里用 state 切换是最自然的方式,无需 ink unmount/remount 的额外开销。 * * initialHistory 的构造(buildBaseSystemPrompt + 历史持久化加载)在菜单退出 * 后才跑,因为: * - 系统提示词本身不依赖 provider,但流程上推迟到"确定要进 App"那一刻 * 最干净。 * - 第一次启动时常常没历史可加载,buildInitialHistory 行为是只返 system * prompt,开销可忽略。 * ============================================================ */ import React, { useEffect, useLayoutEffect, useState } from 'react'; import { Box, Text, useApp, useInput, useStdin } from 'ink'; import { getWorkingDir } from '../bootstrap/workingDir.js'; import { QuickModelSetup } from '../cli/quickModelSetup.js'; import { loadContext } from '../context/persistContext.js'; import { getActiveSession } from '../context/sessionRegistry.js'; import { resolveSessionFile } from '../context/sessionPath.js'; import { workspaceIndexService } from '../context/workspaceIndex.js'; import { buildBaseSystemPrompt } from '../prompts/system.js'; import { ALL_TOOLS } from '../tools/index.js'; import type { Message, Provider } from '../types.js'; import { App } from './App.js'; import { theme } from './theme.js'; import { terminalText } from './terminalText.js'; type Phase = | { kind: 'wizard' } | { kind: 'loading-history'; provider: Provider; error?: string } | { kind: 'app'; provider: Provider; initialHistory: Message[]; initialSessionId: string }; interface Props { /** 启动时已加载到的 provider;null 表示要先走向导 */ initialProvider: Provider | null; } export function Root({ initialProvider }: Props): JSX.Element { useTerminalInputLifetime(); const [phase, setPhase] = useState( initialProvider ? { kind: 'loading-history', provider: initialProvider } : { kind: 'wizard' }, ); const { exit } = useApp(); useInput((input, key) => { if (key.ctrl && input === 'c') exit(); if (key.return && phase.kind === 'loading-history' && phase.error) setPhase({ kind: 'loading-history', provider: phase.provider }); }, { isActive: phase.kind !== 'app' }); useEffect(() => { if (phase.kind !== 'loading-history' || phase.error) return; let cancelled = false; void (async () => { const history = await buildInitialHistory(); if (cancelled) return; setPhase({ kind: 'app', provider: phase.provider, ...history }); })().catch(error => { if (!cancelled) setPhase({ ...phase, error: error instanceof Error ? error.message : String(error) }); }); return () => { cancelled = true; }; }, [phase]); if (phase.kind === 'wizard') { return ( setPhase({ kind: 'loading-history', provider })} /> ); } if (phase.kind === 'loading-history') { return {phase.error ? <> 加载会话失败:{terminalText(phase.error)} Enter 重试 · Ctrl+C 退出 : 正在加载历史上下文…} ; } return ; } /** Keep Ink's raw input lease across editor, menu and question transitions. * Only the visible component handles keys; this lease adds no key listener. */ export function useTerminalInputLifetime(): void { const { isRawModeSupported, setRawMode } = useStdin(); useLayoutEffect(() => { if (!isRawModeSupported) return; setRawMode(true); return () => setRawMode(false); }, [isRawModeSupported, setRawMode]); } /** * 复用 main.tsx 的逻辑:fresh system prompt + 上次未关闭的对话。 * 这里独立一份是为了让 Root 内部能在向导成功后即时构造,不必返工 main.tsx。 */ async function buildInitialHistory(): Promise<{initialHistory: Message[]; initialSessionId: string}> { const cwd = getWorkingDir(); await workspaceIndexService.register(cwd).catch(() => {}); // 只放稳定层(同 main.tsx::buildInitialHistory);易变层每回合经 transientContext 注入尾部。 const content = await buildBaseSystemPrompt(cwd, ALL_TOOLS); const fresh: Message = { role: 'system', content }; const initialSessionId = await getActiveSession(cwd); const persisted = await loadContext(await resolveSessionFile(cwd, initialSessionId)); const rest = persisted?.[0]?.role === 'system' ? persisted.slice(1) : persisted ?? []; return { initialHistory: [fresh, ...rest], initialSessionId }; }