/** * Step 1 主面板 —— 任务意图理解人机问答区。 * * 主页面把所有 Step 1 状态(`useStep1Intent` 的返回值)+ 输入框 + 按钮处理函数 * 透传过来,这里只关心:对话列表渲染、INTENT_READY 摘要卡、澄清卡片嵌入气泡、 * 输入框 + 发送 / 暂停 / 跳过 / 继续追问 / 进入研讨 等底部按钮。 * * 气泡通用渲染部分(头像 / header / loading 占位 / 流式 cursor / markdown 渲染) * 复用 `MessageBubble.tsx` 暴露的原子件,与 Step 2 保持一致。 * * **不要**在这里再 fetch / 建 thread / 跑 SSE —— 这些逻辑都在 `useStep1Intent`, * 本组件保持纯展示 + 透传事件。 */ import { useCallback, useEffect, useRef, useState } from "react"; import { CheckCircle, FileText, Loader2, MessageSquare, Paperclip, Pause, Repeat, Save, Send, Smile, Sparkles, X, } from "lucide-react"; /** 人类可读的文件大小(B / KB / MB)。 */ function formatFileSize(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / 1024 / 1024).toFixed(1)} MB`; } import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea"; import { Button } from "@/components/ui/button"; import { useLocalSettings } from "@/core/settings"; import type { MessageMetric } from "@/components/workspace/messages/use-message-metrics"; import { Man1Avatar, RobotAvatar } from "@/roundtable-planning/components/Avatars"; import { DialogueSpeedMeter } from "@/roundtable-planning/components/DialogueSpeedMeter"; import { clarificationKey, IntentClarificationCard, type IntentClarificationSelection, } from "@/roundtable-planning/components/IntentClarificationCard"; import { MarkdownContent, MessageBubble, MessageLoadingPlaceholder, ReasoningBlock, StreamingCursor, } from "@/roundtable-planning/components/MessageBubble"; import { MessageStepsCard } from "@/roundtable-planning/components/MessageStepsCard"; import { ScrollToBottomButton } from "@/roundtable-planning/components/ScrollToBottomButton"; import { useAutoScroll } from "@/roundtable-planning/hooks/useAutoScroll"; import { useDialogueSpeedMetrics } from "@/roundtable-planning/hooks/useDialogueSpeedMetrics"; import type { InteractiveMessage } from "@/roundtable-planning/hooks/useStep1Intent"; import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree"; import { splitInlineReasoning } from "@/roundtable-planning/lib/reasoning"; import { splitIntentReadyBlock } from "@/roundtable-planning/lib/roundtable-constants"; import type { ClarificationPayload, } from "@/roundtable-planning/api/multi-agent"; import type { IntentSummary } from "@/roundtable-planning/api/intent"; /** * Step 1 输入区的受控数据与行为契约。 * * 默认输入区继续由 Step1Panel 渲染;嵌入式页面可通过 `inputArea` 复用相同的 * 发送、附件和阶段按钮行为,同时拥有完全独立的 DOM 与视觉样式。 */ export interface Step1InputAreaProps { value: string; onValueChange: (value: string) => void; attachedFiles: File[]; onAddFiles: (files: File[]) => void; onRemoveFile: (index: number) => void; charactersLeft: number; isSending: boolean; canSend: boolean; pendingClarification: boolean; /** 发送当前输入框内容;传 `overrideText` 时直接发送该文本(常用问题一键发送)。 */ onSend: (overrideText?: string) => void; onStop: () => void; onFollowUp: () => void; onSkip: () => void; onEnterRoundtable: () => void; enterButtonLabel: string; intentReady: object | null; footerAction?: React.ReactNode; hideEnterRoundtable: boolean; onManualSave: () => void; onTriggerToast: (message: string) => void; } export interface Step1PanelProps { rootClassName?: string; // ─── State ──────────────────────────────────────────────────── /** * 头部左侧自定义内容(深链 taskId 模式:用「策划流程」小图取代默认标题)。 * 不传 → 显示默认「任务意图理解 (人机问答)」标题。右侧「问答轮次」始终保留。 */ headerLeftSlot?: React.ReactNode; headerRightSlot?: React.ReactNode; /** Optional side content rendered below the shared header, beside the dialogue area. */ rightSidebar?: React.ReactNode; /** Hide the shared question-count badge when a workspace supplies its own header actions. */ hideQuestionCount?: boolean; /** Optional empty state rendered in the centre of an otherwise blank dialogue list. */ emptyState?: React.ReactNode; interactiveMessages: InteractiveMessage[]; intentThreadId: string | null; intentReady: object | null; isIntentSending: boolean; pendingIntentClarificationMsgId: number | null; intentClarificationSelections: Map; // ─── Setters / Handlers ────────────────────────────────────── setIntentClarificationSelections: React.Dispatch< React.SetStateAction> >; onSendMessage: (text: string, files?: File[]) => void; onStopIntent: () => void; onSkipQuestion: () => void; onFollowUp: () => void; onEnterRoundtable: () => void; /** 保持旧文案默认不变;嵌入式新工作流可覆写确认动作名称。 */ enterButtonLabel?: string; /** 用于在意图确认后承接同一工作流的下一步动作。 */ footerAction?: React.ReactNode; /** 已进入后续工作流时,隐藏默认的「进入研讨」动作。 */ hideEnterRoundtable?: boolean; /** * 隐藏「继续追问」「跳过此项」两个快捷动作(多智能体会商页不需要; * 岗位会商 / 8BF 不传保持原样)。 */ hideFollowupActions?: boolean; /** * 仅替换输入区的渲染插槽。消息列表、意图状态及附件状态仍由 Step1Panel * 统一管理,因此岗位会商定制样式时不会分叉或复制 Step 1 的业务逻辑。 */ inputArea?: (props: Step1InputAreaProps) => React.ReactNode; /** Optional database-backed composer state used by the position workspace. */ inputDraftKey?: string; initialInputText?: string; onInputTextChange?: (value: string) => void; onManualSave: () => void; onTriggerToast: (msg: string) => void; submitIntentClarifications: ( msgId: number, clarifications: ClarificationPayload[], overrideByKey?: Record, ) => void; } export function Step1Panel(props: Step1PanelProps) { const { headerLeftSlot, headerRightSlot, rightSidebar, hideQuestionCount = false, emptyState, rootClassName, interactiveMessages, intentThreadId, intentReady, isIntentSending, pendingIntentClarificationMsgId, intentClarificationSelections, setIntentClarificationSelections, onSendMessage, onStopIntent, onSkipQuestion, onFollowUp, onEnterRoundtable, enterButtonLabel = "进入多智能体研讨 >", footerAction, hideEnterRoundtable = false, hideFollowupActions = false, inputArea, inputDraftKey, initialInputText = "", onInputTextChange, onManualSave, onTriggerToast, submitIntentClarifications, } = props; const step1ScrollRef = useRef(null); const step1ContentRef = useRef(null); const { atBottom: step1AtBottom, scrollToBottom: scrollStep1ToBottom } = useAutoScroll(step1ScrollRef, [interactiveMessages], { contentRef: step1ContentRef, }); // 「回答速度指示器」—— 与主页面共用全局开关 streamSpeedMeterEnabled。 const [localSettings] = useLocalSettings(); const speedMeterEnabled = localSettings.display.streamSpeedMeterEnabled; const messageMetrics = useDialogueSpeedMetrics(interactiveMessages); // 输入框完全是本地状态 —— 提到 Page 层会导致每次打字都重渲整页。 const [inputText, setInputText] = useState(""); useEffect(() => { setInputText(initialInputText); }, [inputDraftKey, initialInputText]); const handleInputTextChange = useCallback( (value: string) => { setInputText(value); onInputTextChange?.(value); }, [onInputTextChange], ); // 待发送的本地附件(点发送时连同文本一起上传)。 const [attachedFiles, setAttachedFiles] = useState([]); const fileInputRef = useRef(null); const charactersLeft = inputText.length; const addAttachedFiles = (picked: File[]) => { if (picked.length > 0) { // 去重(按 名称+大小),追加到已选列表。 setAttachedFiles((prev) => { const seen = new Set(prev.map((f) => `${f.name}:${f.size}`)); return [...prev, ...picked.filter((f) => !seen.has(`${f.name}:${f.size}`))]; }); } }; const handlePickFiles = (e: React.ChangeEvent) => { addAttachedFiles(Array.from(e.target.files ?? [])); // 清空 input 值,允许再次选同名文件。 e.target.value = ""; }; const removeAttachedFile = (idx: number) => { setAttachedFiles((prev) => prev.filter((_, i) => i !== idx)); }; const handleSend = (overrideText?: string) => { // overrideText:常用问题 chip 一键发送——绕过异步的输入框 state, // 直接以问题全文作为本回合消息(仍共享附件与发送后的清空逻辑)。 const textToSend = overrideText ?? inputText; if (!textToSend.trim() && attachedFiles.length === 0) return; onSendMessage(textToSend, attachedFiles.length > 0 ? attachedFiles : undefined); handleInputTextChange(""); setAttachedFiles([]); }; // 顶部标题栏整片脱敏(消息列表正文在下方,不在此容器内,保持原文)。 const headerDzRef = useDesensitizeSubtree(); const showEmptyState = interactiveMessages.length === 0 && Boolean(emptyState); return (
{/* Dialogue Header */}
{headerLeftSlot ?? (

任务意图理解 (人机问答)

)}
{!hideQuestionCount && ( 问答轮次:{interactiveMessages.filter((m) => m.sender === "user").length} 轮 )} {headerRightSlot}
{/* Chat list */}
{showEmptyState ? (
{emptyState}
) : ( interactiveMessages.map((msg) => ( )) )}
{!step1AtBottom && }
{/* Bottom input area */} {inputArea ? ( inputArea({ value: inputText, onValueChange: handleInputTextChange, attachedFiles, onAddFiles: addAttachedFiles, onRemoveFile: removeAttachedFile, charactersLeft, isSending: isIntentSending, canSend: !isIntentSending && Boolean(intentThreadId), pendingClarification: Boolean(pendingIntentClarificationMsgId), onSend: handleSend, onStop: onStopIntent, onFollowUp, onSkip: onSkipQuestion, onEnterRoundtable, enterButtonLabel, intentReady, footerAction, hideEnterRoundtable, onManualSave, onTriggerToast, }) ) : (
{/* 已选附件预览(点发送时随消息上传) */} {attachedFiles.length > 0 && (
{attachedFiles.map((file, idx) => ( {file.name} {formatFileSize(file.size)} ))}
)} setInputText(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend(); } }} placeholder={ pendingIntentClarificationMsgId ? "也可在此输入自定义回答 (Enter 发送 / Shift+Enter 换行)" : "请输入补充信息 / 回答问题 / 继续澄清 (Enter 发送 / Shift+Enter 换行)" } className="w-full text-xs text-slate-700 placeholder:text-slate-400 min-h-[48px] max-h-80 focus:outline-none leading-relaxed font-normal" maxHeight={320} maxLength={500} />
{charactersLeft}/500
{isIntentSending && ( )} {!hideFollowupActions && ( )} {!hideFollowupActions && ( )} {footerAction ?? (!hideEnterRoundtable && ( ))}
)}
{rightSidebar}
); } /** * 单条 Step 1 消息。 * * 拆成独立函数避免主 panel 里大量嵌套 JSX。三种正文形态: * - 流式中、还没首字节 → MessageLoadingPlaceholder * - agent 消息 → splitIntentReadyBlock 拆出前 / 摘要 / 后,分别渲染 * + IntentClarificationCard(若待澄清) * - user 消息 → 纯文本 */ interface Step1MessageProps { msg: InteractiveMessage; /** * 本条气泡的「回答速度」度量(tok/s + 时长)。仅对流式过的智能体发言有值; * 由调用方按全局开关 streamSpeedMeterEnabled 决定是否传入(关则传 undefined)。 */ metric?: MessageMetric; intentReady: object | null; pendingIntentClarificationMsgId: number | null; intentClarificationSelections: Map; setIntentClarificationSelections: React.Dispatch< React.SetStateAction> >; isIntentSending: boolean; submitIntentClarifications: ( msgId: number, clarifications: ClarificationPayload[], overrideByKey?: Record, ) => void; } function Step1Message({ msg, metric, intentReady, pendingIntentClarificationMsgId, intentClarificationSelections, setIntentClarificationSelections, isIntentSending, submitIntentClarifications, }: Step1MessageProps) { const isStreaming = msg.streaming === true; const isAgent = msg.sender !== "user"; // 先把 `...` 抽出来作 reasoning,剩下的正文再走 INTENT_READY 解析。 // 顺序很关键:若先 split INTENT_READY 再抽 think,think 块如果横跨 INTENT_READY // 标记会导致 JSON 解析失败。 const rawContent = msg.content ?? ""; const { content: thoughtFreeContent, reasoning } = isAgent ? splitInlineReasoning(rawContent) : { content: rawContent, reasoning: null }; const hasContent = thoughtFreeContent.length > 0; // 一轮可能有多条澄清问题(任务理解智能体一次问多个)。流式期就逐个灌进来, // 实时展示「协助过程」;终态再以权威集合覆盖。 const clarifications = msg.clarifications ?? []; const parts = isAgent ? splitIntentReadyBlock(thoughtFreeContent) : { before: thoughtFreeContent, summary: null as IntentSummary | null, after: "" }; // 是否展示澄清卡(还没出 summary / 还没整体就绪时)。流式中也展示(只读), // 终态且该消息为当前待澄清条目时才可交互。 const showClarifications = isAgent && clarifications.length > 0 && !intentReady && !parts.summary; // 一轮多个问题才进入「逐题作答 + 合并发送」模式;单问题沿用「点击即发送」。 const multiQuestion = clarifications.length > 1; const isPending = pendingIntentClarificationMsgId === msg.id; const clarificationsInteractive = isPending && !isStreaming; const introText = clarifications.length === 1 && parts.before.trim() === (clarifications[0].question || "").trim() ? "" : parts.before; // 主聊天里步骤卡放在「正文之上」(气泡内,header 之下),Step 2 也是这样。 // 流式中默认显示 last tool call + 折叠 "查看其他 N 个步骤";完成后保留卡。 const stepsCard = isAgent && Array.isArray(msg.steps) && msg.steps.length > 0 ? ( ) : null; // 「思考过程」折叠卡 —— 流式中默认展开,完成后自动延迟收起。 const reasoningBlock = isAgent && reasoning ? ( {reasoning} ) : null; return ( ) : ( ) } senderName={msg.senderName} senderNameClassName={msg.sender === "user" ? "text-primary" : undefined} badge={isStreaming ? msg.phase : undefined} time={msg.time} > {stepsCard} {reasoningBlock} {isStreaming && !hasContent ? ( ) : isAgent ? (
{introText && {introText}} {parts.summary && } {/* parts.after 是模型违反 SOUL §0「硬规则 3」在 [INTENT_READY] 块后 继续输出的内容(典型:"那么我先帮你列一下大纲……")。后端 intent.py 的终态帧已经把 content 截断到 marker 结尾,但流式期间 LangGraph messages-tuple 还是会把那段废话逐 token 推过来——故意在 UI 层 把它丢弃,让用户看到的就是"复述 + 摘要卡",干净结束。 */} {isStreaming && } {showClarifications && (
{clarifications.map((clar, index) => { const key = clarificationKey(msg.id, clar.id, index); const selection = intentClarificationSelections.get(key) ?? { selectedIds: [], custom: "", }; return ( { setIntentClarificationSelections((prev) => { const map = new Map(prev); map.set(key, next); return map; }); }} disabled={!clarificationsInteractive} submitting={isIntentSending && isPending} onSubmit={(override) => submitIntentClarifications( msg.id, clarifications, // 单题单选「点击即发送」时选择还没进 state map,把即时值 // 按 key 传进去直接用。 override ? { [key]: override } : undefined, ) } /> ); })} {/* 合并提交按钮仅多问题时出现;单问题点选项即发送,无需此按钮。 */} {multiQuestion && clarificationsInteractive && (
共 {clarifications.length} 个问题,可逐个作答后一并发送
)}
)}
) : (
{msg.files && msg.files.length > 0 && (
{msg.files.map((file, i) => ( {file.filename} {formatFileSize(file.size)} ))}
)} {msg.content && (
{msg.content}
)}
)} {metric && }
); } /** [INTENT_READY] 标记块解析出 IntentSummary 后的绿色摘要卡。 */ function IntentReadySummaryCard({ summary }: { summary: IntentSummary }) { const positionSections = summary.coreGoals && summary.riskWarnings && summary.keyPoints && summary.strategicSignificance ? ([ ["核心目标", summary.coreGoals], ["风险提示", summary.riskWarnings], ["关键要点", summary.keyPoints], ["战略意义", summary.strategicSignificance], ] as const) : null; return (
任务意图已明确
{positionSections ? positionSections.map(([label, values]) => (
{label} {values.length > 0 ?
    {values.map((value, index) =>
  • {value}
  • )}
:

暂无{label}

}
)) : <>
核心目标

{summary.objective}

{summary.constraints?.length > 0 && (
约束条件
    {summary.constraints.map((c, i) =>
  • {c}
  • )}
)} {summary.assumptions && summary.assumptions.length > 0 && (
关键假设
    {summary.assumptions.map((a, i) =>
  • {a}
  • )}
)} }
); }