/** * ============================================================ * src/ui/AskQuestion.tsx —— AskUserQuestion 工具的 TUI 问答界面 * ------------------------------------------------------------ * 这是 AskUserQuestion 工具向用户提问时弹出的选择题界面。由 askBridge 的 * AskHandler(在 useChat mount 时通过 setAskHandler 注册)触发:handler 把 * 问题数组存进 pendingAsk state,App 看到 pendingAsk 存在便渲染本组件, * 并让它**独占输入焦点**(屏蔽 InputBox),用户答完后 handler 的 Promise * 以 AskAnswer[] resolve、继续工具回路;ESC/Ctrl+C 取消则 reject。 * * 逐题进行:从第 0 题问到最后一题,每题答完推进,末题答完一次性回调 onAnswer。 * 每题选项列表末尾自动追加一个「✏️ 其他(自由输入)」伪选项,命中即切到文本 * 输入子模式,让用户填选项之外的答案(自由输入按单值处理,覆盖多选集合)。 * * Ink 用法与风格对齐 cli/wizards/providerWizard.tsx:useInput 手写键位、↑↓ 取模移动 * 高亮、`> ` 前缀 + cyan 高亮、gray 操作提示、文本输入用累积 draft + backspace。 * ============================================================ */ import React, { useEffect, useMemo, useState } from 'react'; import { Box, Text, useInput } from 'ink'; import type { AskAnswer, AskOption, AskQuestionSpec, AskSource } from '../askBridge.js'; import { theme } from './theme.js'; import { terminalText } from './terminalText.js'; interface AskQuestionProps { questions: AskQuestionSpec[]; /** 提问来源;kind:'subagent' 时在问题上方显示「子任务:X」徽标。缺省=主循环提问,不显徽标。 */ source?: AskSource | null; queuedCount?: number; /** 全部问题答完后调用一次 */ onAnswer: (answers: AskAnswer[]) => void; /** ESC / Ctrl+C 取消当前来源;子任务问题不会中断其他并行任务 */ onCancel: () => void; } /** description 过长截断到此长度,防止 live 区被超长文本撑爆。 */ const DESC_MAX = 80; /** * 提问上限——与 system prompt 里的"最多 4 题"硬性对齐。超出会: * - UI 截断到 4 题(仅前 4 题可答,后面的被静默丢弃) * - stderr 注记,提示上游(callers 应在调 AskUserQuestion 工具前自检) * 这是防御层——理想情况是 tool 上游 Zod 校验就拦住。 */ const MAX_QUESTIONS = 4; function clampDesc(s: string): string { return s.length > DESC_MAX ? `${s.slice(0, DESC_MAX - 1)}…` : s; } export function AskQuestion({ questions, source, queuedCount = 0, onAnswer, onCancel, }: AskQuestionProps): JSX.Element { // 硬限 4 题;超量截断。注记走 useEffect(只发一次):渲染期写 stderr 会随 // 每次按键重渲重复打行,且 Ink 渲染期间写 stdout/stderr 会撕裂终端画面。 const effectiveQuestions = useMemo( () => questions.slice(0, MAX_QUESTIONS), [questions], ); useEffect(() => { if (questions.length <= MAX_QUESTIONS) return; try { process.stderr.write( `[AskUserQuestion] 收到 ${questions.length} 题超过上限 ${MAX_QUESTIONS},已截断\n`, ); } catch { /* ignore */ } }, [questions]); // 当前进行到第几题 const [questionIndex, setQuestionIndex] = useState(0); // 当前题高亮的选项下标(含末尾「其他」伪选项) const [idx, setIdx] = useState(0); // 多选时已选中的真实 option 下标集合 const [picked, setPicked] = useState>(new Set()); // 已累积的答案 const [answers, setAnswers] = useState([]); // 是否处于「其他(自由输入)」文本子模式 const [textMode, setTextMode] = useState(false); // 文本子模式的累积草稿 const [draft, setDraft] = useState(''); const current: AskQuestionSpec | undefined = effectiveQuestions[questionIndex]; const multi = current?.multiSelect === true; const options: AskOption[] = current?.options ?? []; // 末尾「其他」伪选项占据下标 options.length,故列表总长 = options.length + 1 const otherIndex = options.length; const listLength = options.length + 1; /** 切到下一题,重置所有逐题状态;若已是末题则一次性回调 onAnswer。 */ function advance(answer: AskAnswer) { const nextAnswers = [...answers, answer]; const nextQ = questionIndex + 1; if (nextQ >= effectiveQuestions.length) { onAnswer(nextAnswers); return; } setAnswers(nextAnswers); setQuestionIndex(nextQ); setIdx(0); setPicked(new Set()); setTextMode(false); setDraft(''); } useInput((input, key) => { // 没有当前题(理论不会发生)→ 直接当作取消 if (!current) { onCancel(); return; } // ---- 文本子模式:自由输入 ---- if (textMode) { if (key.escape) { // 退回选项列表(不取消整轮) setTextMode(false); setDraft(''); return; } if (key.return) { const text = draft.trim(); if (text.length === 0) return; // 自由输入按单值处理,覆盖多选集合 advance({ header: current.header, question: current.question, selected: [text], }); return; } if (key.backspace || key.delete) { setDraft((s) => s.slice(0, -1)); return; } if (input && !key.meta && !key.ctrl) { setDraft((s) => s + input); } return; } // ---- 选项列表模式 ---- if (key.escape || (key.ctrl && input === 'c')) { onCancel(); return; } if (key.upArrow) { setIdx((i) => (i - 1 + listLength) % listLength); return; } if (key.downArrow) { setIdx((i) => (i + 1) % listLength); return; } // 高亮落在「其他」伪选项:Enter(单选/多选都)进入文本子模式 const onOther = idx === otherIndex; if (multi) { // 多选:空格 toggle;Enter 确认本题 if (input === ' ') { if (onOther) { // 「其他」上按空格 → 进入自由输入 setTextMode(true); setDraft(''); return; } setPicked((prev) => { const next = new Set(prev); if (next.has(idx)) next.delete(idx); else next.add(idx); return next; }); return; } if (key.return) { if (onOther) { setTextMode(true); setDraft(''); return; } const selected = options .map((o, i) => (picked.has(i) ? o.label : null)) .filter((l): l is string => l !== null); advance({ header: current.header, question: current.question, selected, }); return; } return; } // 单选:Enter 选中当前高亮项 if (key.return) { if (onOther) { setTextMode(true); setDraft(''); return; } const opt = options[idx]; if (!opt) return; advance({ header: current.header, question: current.question, selected: [opt.label], }); } }); // 无题可问(空数组)→ 渲染占位(useInput 已处理取消,这里只防御渲染崩) if (!current) { return ( (无问题) ); } const progress = `需要你决定 · ${questionIndex + 1}/${effectiveQuestions.length} · ${terminalText(current.header)}`; return ( {source?.kind === 'subagent' && ( {`来自子任务:${terminalText(source.description ?? '执行任务')}`} )} {queuedCount > 0 && ( {`另有 ${queuedCount} 个问题排队`} )} {progress} {terminalText(current.question)} {textMode ? ( ✏️ 自由输入: {draft || ' '} 输入后 Enter 提交 · ESC 返回 ) : ( {options.map((opt, i) => { const active = i === idx; const box = multi ? (picked.has(i) ? '[x] ' : '[ ] ') : ''; return ( {active ? '> ' : ' '} {box} {terminalText(opt.label)} {opt.description ? ( {' '} {clampDesc(terminalText(opt.description))} ) : null} ); })} {/* 末尾「其他(自由输入)」伪选项 */} {idx === otherIndex ? '> ' : ' '} {multi ? ' ' : ''} ✏️ 其他(自由输入) {multi ? '↑↓ 移动 · 空格 多选 · Enter 确认本题 · ESC 取消' : '↑↓ 选择 · Enter 确认 · ESC 取消'} )} ); }