/** * 圆桌规划主页面(三步合一)。 * * 重构后的主文件只负责"组合 + 编排": * - 顶栏(步骤切换 + 草稿菜单 + 新建任务 + 设置) * - 左侧栏:Step1/2 为任务概览 + 角色 + 人工参与;Step2 侧栏可整体收起为图标条,含可收起的意图理解 * - 中间视区:Step1Panel / Step2Panel / Step3Panel(`currentStep` 切换);Step2 顶栏含推理模型下拉 * - 右侧栏:仅 Step1(推理模型 / 当前意图摘要 / 澄清记录);Step2/3 隐藏以让中间区自适应 * - 推荐弹窗 + Toast * * 业务状态全部下沉到 hook: * - useStep1Intent —— 任务理解、INTENT_READY、澄清卡 * - useStep2Orchestration —— 编排循环、对话流、Persona 覆盖、澄清回复 * - useDraftPersistence —— 本地草稿(自动保存 / 手动 / 加载 / 重命名 / 删除) * * 历史踩坑请保留(细节见各 hook 的文件头注释): * 1) special 顺序派活,**不要**改回 `Promise.all`(详见 §5.4) * 2) step1InitGenRef / step2InitRef 闸门用于规避 StrictMode 双 mount 副作用 * 3) 离开 Step 2 不销毁 threadIds,允许返回继续看 * 4) 草稿自动保存仅在前进切换(1→2、2→3)触发,后退不保存 * 5) Persona 抽屉改的 model 不会立即重启编排,下一轮才生效 * 6) 模型选择全局默认 `availableModels[0].name`,Persona 覆盖更高优先级 */ import { useCallback, useEffect, useRef, useState } from "react"; import { Activity, Check, CheckCircle, ChevronRight, ChevronDown, ChevronUp, PanelLeftClose, PanelLeftOpen, Clipboard, Clock, Cpu, History, Loader2, Pencil, Save, Settings, Sparkles, Trash2, Upload, Users, } from "lucide-react"; import { useTheme } from "@/contexts/ThemeContext"; import { useArtifacts } from "@/components/workspace/artifacts"; import { cn } from "@/lib/utils"; import { useModels } from "@/core/models/hooks"; import { getAvatar, Man1Avatar, RobotAvatar } from "@/roundtable-planning/components/Avatars"; import { RecommendAgentsDialog } from "@/roundtable-planning/components/RecommendAgentsDialog"; import { Step1Panel } from "@/roundtable-planning/components/Step1Panel"; import { Step2Panel } from "@/roundtable-planning/components/Step2Panel"; import { Step3Panel } from "@/roundtable-planning/components/Step3Panel"; import { useStep1Intent, type InteractiveMessage, } from "@/roundtable-planning/hooks/useStep1Intent"; import { useStep2Orchestration } from "@/roundtable-planning/hooks/useStep2Orchestration"; import { useDraftPersistence } from "@/roundtable-planning/hooks/useDraftPersistence"; import { BUILTIN_AGENT_META, makeRolesFromTemplates, nowTime, type RoleEntry, type SelectedAgent, } from "@/roundtable-planning/lib/roundtable-constants"; export default function RoundtablePlanningPage() { const { theme } = useTheme(); const isDark = theme === "dark"; const { models: availableModels, isLoading: modelsLoading } = useModels(); // ─── 顶层导航 / 跨步状态 ───────────────────────────────────── const [currentStep, setCurrentStep] = useState(1); const [showToast, setShowToast] = useState(null); const [isRecommendDialogOpen, setIsRecommendDialogOpen] = useState(false); const [selectedModel, setSelectedModel] = useState(""); const [step2SidebarExpanded, setStep2SidebarExpanded] = useState(true); // 角色面板(LeftSidebar)。原页面把它当成两步共用的展示数据,这里继续放在 // 主页 —— Step 1 / Step 2 / Step 3 都会读 / 写它,任何 hook 单独持有都不合适。 const [roles, setRoles] = useState([]); const triggerToast = useCallback((msg: string) => { setShowToast(msg); }, []); useEffect(() => { if (!showToast) return; const timer = setTimeout(() => setShowToast(null), 3500); return () => clearTimeout(timer); }, [showToast]); // 首次 /api/models 返回后初始化 selectedModel;后端配置变化导致当前选中 // 不在列表里时也回退到首项。与 /page/canvas/ai-writing 行为对齐。 useEffect(() => { if (availableModels.length === 0) return; const stillExists = availableModels.some((m) => m.name === selectedModel); if (!selectedModel || !stillExists) { setSelectedModel(availableModels[0].name); } }, [availableModels, selectedModel]); // ─── 业务 hook ──────────────────────────────────────────── // 草稿 hook 提供 loadedFromDraftRef,Step 2 init 与左侧角色面板都会读它。 // 先用一个临时 ref,等 draft hook 初始化后再共享。注意:hook 之间不能循环依赖, // 这里通过把 ref 作为参数传给 step2 hook 来打破。 const loadedFromDraftRefHolder = useRef(false); // Step 2 hook 拿到 selectedAgents 等;但 buildInitialIntent 需要 Step 1 状态, // 这是循环依赖。解法:用 ref 把 step1 的最新值暴露给 buildInitialIntent。 const step1StateRef = useRef<{ intentReady: ReturnType["intentReady"]; interactiveMessages: InteractiveMessage[]; }>({ intentReady: null, interactiveMessages: [] }); const buildInitialIntent = useCallback((): string => { const { intentReady, interactiveMessages } = step1StateRef.current; if (intentReady) { const parts: string[] = [intentReady.objective]; if (intentReady.constraints?.length) { parts.push(""); parts.push("约束条件:"); for (const c of intentReady.constraints) parts.push(`- ${c}`); } if (intentReady.assumptions?.length) { parts.push(""); parts.push("关键假设:"); for (const a of intentReady.assumptions) parts.push(`- ${a}`); } parts.push(""); parts.push( "用户已经过任务理解智能体澄清,以上信息可以直接作为研讨依据。请基于上述目标与约束,在圆桌内调度合适的子智能体完成研讨,不要再反问用户。", ); return parts.join("\n"); } const userTurns = interactiveMessages .filter((m) => m.sender === "user") .map((m) => m.content?.trim()) .filter((s): s is string => !!s); if (userTurns.length === 0) { return "用户尚未在第一步明确任务意图。请先调用 ask_clarification,简要询问目标、范围与硬性约束,再进入研讨。"; } const conversation = userTurns.map((t, i) => `用户#${i + 1}: ${t}`).join("\n"); return `${conversation}\n\n注意:用户尚未完成结构化的任务理解流程,以上是原始输入。若信息不足以开展研讨,请先调用 ask_clarification 询问关键约束,再开始派活。`; }, []); const step2 = useStep2Orchestration({ currentStep, selectedModel, buildInitialIntent, triggerToast, setRoles, loadedFromDraftRef: loadedFromDraftRefHolder, }); const step1 = useStep1Intent({ currentStep, selectedModel, triggerToast, }); // 同步 step1StateRef,让 buildInitialIntent / Persona / Step 3 都能读到最新值。 useEffect(() => { step1StateRef.current = { intentReady: step1.intentReady, interactiveMessages: step1.interactiveMessages, }; }, [step1.intentReady, step1.interactiveMessages]); // 草稿 hook —— 同时依赖 step1 + step2 的 snapshot / hydrate。 const drafts = useDraftPersistence({ currentStep, setCurrentStep, triggerToast, getStep1Snapshot: () => ({ intentThreadId: step1.intentThreadId, intentReady: step1.intentReady, interactiveMessages: step1.interactiveMessages, timelineEntries: step1.timelineEntries, }), getStep2Snapshot: () => ({ selectedAgents: step2.selectedAgents, threadIds: step2.threadIds, coordinatorName: step2.coordinatorName, step2RoundtableDialogues: step2.step2RoundtableDialogues, lastLeaderContent: step2.lastLeaderContent, hasConsensus: step2.hasConsensus, consensusPercentage: step2.consensusPercentage, budgetLimit: step2.budgetLimit, seatStubMessages: step2.seatStubMessages, }), hydrateStep1: step1.hydrateFromDraft, hydrateStep2: step2.hydrateFromDraft, cancelAllStreams: () => { step2.abortAllInFlight(); step1.stopIntentStream(); // resetStep2State 内部也会 abortAllInFlight + setIsOrchestrating(false), // 这里**不**调用 resetStep2State —— 加载草稿要保留 dialogues 内容, // 只中断 in-flight 即可。 }, setStep2InitGate: (initialized) => { if (initialized) { // 已经走过 Step 2 的草稿:直接复用 threadIds,跳过自动 init。 // step2 hook 的 hydrateFromDraft 已经把 step2InitRef.current 置为 true, // 这里无需再做事。但用一个空闭包避免后续重构忘记这种语义。 } else { step2.resetInitGate(); } }, }); // 共享 ref:把 draft hook 的 latch 同步给 step2 hook 用的占位 ref。 useEffect(() => { loadedFromDraftRefHolder.current = drafts.loadedFromDraftRef.current; }); // ─── 角色面板转场 ──────────────────────────────────────── // Step 1: 仅指挥员 + 任务理解智能体两行(状态跟随 intent init)。 // Step 2: 完整席位(loadedFromDraft 时直接 "在线",否则 "正在上线")。 // Step 3: 全部 "已完成"。 useEffect(() => { if (currentStep === 1) { setRoles([ { id: 1, name: "指挥员 / 主持人", type: "human", status: "在线" }, { id: 100, name: "任务理解", agentId: "roundtable-intent", type: "agent", status: step1.intentInitError ? "异常" : step1.intentThreadId ? "在线" : "正在上线", }, ]); } else if (currentStep === 2) { const baseStatus = drafts.loadedFromDraftRef.current ? "在线" : "正在上线"; setRoles(makeRolesFromTemplates(step2.roleTemplates, baseStatus, { 1: "在线" })); } else { setRoles(makeRolesFromTemplates(step2.roleTemplates, "已完成")); } }, [ currentStep, step1.intentThreadId, step1.intentInitError, step2.roleTemplates, drafts.loadedFromDraftRef, ]); // ─── 步骤间转场 handler ─────────────────────────────────── const handleConfirmAgents = useCallback( (agents: Array<{ agent_id: string; name: string }>) => { const normalized: SelectedAgent[] = agents.map(({ agent_id, name }) => ({ agent_id, // 内置 agent 走 BUILTIN_AGENT_META;非内置用候选池传过来的 name。 name: BUILTIN_AGENT_META[agent_id]?.displayName ?? name ?? agent_id, })); step2.setSelectedAgents(normalized); step2.resetInitGate(); setIsRecommendDialogOpen(false); setCurrentStep(2); triggerToast("成功确认!已切换至第二阶段圆桌研讨系统"); }, [step2, triggerToast], ); const handleStartNewTask = useCallback(() => { step2.resetStep2State(); step1.stopIntentStream(); drafts.loadedFromDraftRef.current = false; drafts.setCurrentDraftId(null); setCurrentStep(1); // 同步触发 Step 1 init,而不是依赖 useEffect —— 已经在 Step 1 时 // currentStep 不变,useEffect 不会 re-fire。 step1.runStep1Init(); triggerToast("✨ 已开始新任务,请在第一步与任务理解智能体澄清需求"); }, [drafts, step1, step2, triggerToast]); // 本地 demo handler:继续追问 / 跳过此项 —— 不发请求,只本地 push 一条气泡。 const handleSkipQuestion = useCallback(() => { step1.appendLocalMessage({ id: Date.now() + Math.random(), sender: "agent", senderName: "系统提示", content: "⚠️ 您跳过了当前追问,系统已使用深度预测模型填充默认最稳健配置。", time: nowTime(), }); triggerToast("已跳过,自动填充最优配置"); }, [step1, triggerToast]); const handleAgentFollowUp = useCallback(() => { step1.appendLocalMessage({ id: Date.now() + Math.random(), sender: "agent", senderName: "任务理解智能体", content: "🔎 为了使方案时间边界更加安全:请问72小时内是否允许团队进行全仿真机房集成演练?这需要额外调拨3% of 预算冗余,但安全系数能提升12%。", time: nowTime(), }); triggerToast("追问生成就绪!"); }, [step1, triggerToast]); // ─── Render ────────────────────────────────────────────── return (
setIsRecommendDialogOpen(false)} onConfirm={handleConfirmAgents} /> {showToast && (
{showToast}
)} {/* HEADER */}
setCurrentStep(s)} triggerToast={triggerToast} />
{currentStep !== 2 && ( <> )}
{/* MAIN */}
{/* LEFT SIDEBAR */} {/* MIDDLE VIEWPORT */}
{currentStep === 1 && ( void step1.sendIntentMessage(text)} onStopIntent={step1.stopIntentStream} onSkipQuestion={handleSkipQuestion} onFollowUp={handleAgentFollowUp} onEnterRoundtable={() => { if (!step1.intentReady) { triggerToast("⚠️ 请先与任务理解智能体完成澄清,生成任务摘要后再进入"); return; } // 先把草稿落地拿到 draft_id,推荐历史才有归属;失败也照常打开弹窗 // (弹窗在无 draftId 时退化为「直接推荐、不存历史」)。 void drafts.ensureDraft(1).finally(() => setIsRecommendDialogOpen(true)); }} onManualSave={drafts.handleManualSave} onTriggerToast={triggerToast} submitIntentClarifications={step1.submitIntentClarifications} /> )} {currentStep === 2 && ( { if (!step2.hasConsensus) { triggerToast("⚠️ 圆桌尚未自然收敛,请等待总控派活全部完成"); return; } setCurrentStep(3); triggerToast( "🎉 多角色智能体博弈共识达成,最终交付全套路线成果文档及方案图!", ); }} onTriggerToast={triggerToast} /> )} {currentStep === 3 && ( )}
{/* RIGHT SIDEBAR */}
); } // ──────────────────────────────────────────────────────────── // 子组件 —— 这些 JSX 只在主页面里出现一次,没有跨文件复用价值, // 留在本文件里阅读起来比抽到 components/ 更直观。 // ──────────────────────────────────────────────────────────── interface StepNavigationProps { currentStep: number; intentReady: object | null; hasConsensus: boolean; onStepClick: (step: number) => void; triggerToast: (msg: string) => void; } function StepNavigation({ currentStep, intentReady, hasConsensus, onStepClick, triggerToast, }: StepNavigationProps) { const step2Locked = !intentReady; const step3Locked = !hasConsensus; return (
onStepClick(1)} /> { if (step2Locked) { triggerToast("⚠️ 请先在第一步完成任务理解,确认[INTENT_READY]信号后再进入"); return; } onStepClick(2); }} /> { if (step3Locked) { triggerToast( intentReady ? "⚠️ 请先在第二步达成共识(总控自然收敛)再进入" : "⚠️ 请先依次完成第一步和第二步", ); return; } onStepClick(3); }} />
); } function StepButton({ index, label, active, locked, onClick, }: { index: number; label: string; active: boolean; locked: boolean; onClick: () => void; }) { return ( ); } interface HistoryDropdownProps { innerRef: React.MutableRefObject; isOpen: boolean; setIsOpen: React.Dispatch>; drafts: ReturnType["drafts"]; currentDraftId: string | null; renamingDraftId: string | null; renameDraftValue: string; setRenameDraftValue: React.Dispatch>; onLoad: (id: string) => void; onDelete: (id: string) => void; onStartRename: (d: ReturnType["drafts"][number]) => void; onCommitRename: (id: string) => void; onCancelRename: () => void; } function HistoryDropdown(props: HistoryDropdownProps) { const { innerRef, isOpen, setIsOpen, drafts, currentDraftId, renamingDraftId, renameDraftValue, setRenameDraftValue, onLoad, onDelete, onStartRename, onCommitRename, onCancelRename, } = props; return (
{isOpen && (
历史草稿 {drafts.length} 条
{drafts.length === 0 ? (
暂无历史。点击「保存草稿」或走完一步会自动保存到这里。
) : (
    {drafts.map((d) => { const isCurrent = d.id === currentDraftId; const isRenaming = d.id === renamingDraftId; return (
  • {isRenaming ? ( setRenameDraftValue(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") onCommitRename(d.id); if (e.key === "Escape") onCancelRename(); }} onBlur={() => onCommitRename(d.id)} className="w-full text-[11.5px] font-semibold text-slate-800 border border-slate-300 rounded px-2 py-1 outline-none focus:border-primary dark:bg-background dark:text-foreground" /> ) : ( )}
    {!isRenaming && ( <> )}
  • ); })}
)}
)}
); } interface LeftSidebarProps { currentStep: number; roles: RoleEntry[]; agentNameToRole: Record< string, { speakerId: number; avatarType: string; displayName: string } >; budgetLimit: number; intentReady: ReturnType["intentReady"]; sidebarExpanded: boolean; setSidebarExpanded: React.Dispatch>; } function Step2SandboxSidebarSync({ currentStep, sidebarExpanded, setSidebarExpanded, }: { currentStep: number; sidebarExpanded: boolean; setSidebarExpanded: React.Dispatch>; }) { const { open } = useArtifacts(); const prevOpenRef = useRef(open); useEffect(() => { if (currentStep !== 2) { prevOpenRef.current = open; return; } if (open && !prevOpenRef.current && sidebarExpanded) { setSidebarExpanded(false); } prevOpenRef.current = open; }, [currentStep, open, setSidebarExpanded, sidebarExpanded]); return null; } function LeftSidebar({ currentStep, roles, agentNameToRole, budgetLimit: _budgetLimit, intentReady, sidebarExpanded, setSidebarExpanded, }: LeftSidebarProps) { const isStep2 = currentStep === 2; // Step 3 隐藏左侧栏(原「参与与结论贡献」列),让中间「最终方案展示」自适应 // 撑满整行宽度(右侧栏在 Step !==1 时也已 return null)。 if (currentStep === 3) return null; return ( ); } function TaskOverviewCard({ currentStep }: { currentStep: number }) { return (

任务概览

当前节点
初始任务 {currentStep === 1 ? "待澄清" : currentStep === 2 ? "研讨中" : "已规划交付"}

围绕某复杂任务制定规划方案

); } function HumanParticipationCard() { return (

人工参与

用户
在线
); } interface ModelSelectorCardProps { selectedModel: string; setSelectedModel: React.Dispatch>; availableModels: ReadonlyArray<{ name: string; display_name?: string }>; modelsLoading: boolean; } function ModelSelectorCard({ selectedModel, setSelectedModel, availableModels, modelsLoading, }: ModelSelectorCardProps) { return (

推理模型

); } interface IntentSummaryCardProps { intentReady: ReturnType["intentReady"]; title?: string; /** Step 2 侧栏: 收起时仅展示目标,展开后显示约束与假设。 */ collapsible?: boolean; /** 侧栏整体收起按钮,放在标题栏右侧。 */ sidebarToggle?: { expanded: boolean; onToggle: () => void; }; } function IntentSummaryCard({ intentReady, title = "当前意图摘要", collapsible = false, sidebarToggle, }: IntentSummaryCardProps) { const [expanded, setExpanded] = useState(!collapsible); const showFullDetail = !collapsible || expanded; return (

{title}

{sidebarToggle && ( )}
{intentReady ? ( <>
  • • 目标: {intentReady.objective}
{collapsible && ( )} {showFullDetail && (
    {intentReady.constraints.map((c, i) => (
  • • 约束: {c}
  • ))} {(intentReady.assumptions ?? []).map((a, i) => (
  • • 假设: {a}
  • ))}
)} ) : (

等待任务理解智能体澄清完成...

)}
); } function IntentSectionIcon({ className }: { className?: string }) { return ( ); } function CollapsedSidebarSection({ title, children, className, }: { title: string; children: React.ReactNode; className?: string; }) { return (
{children}
); } function renderRoleAvatar( role: RoleEntry, agentNameToRole: Record< string, { speakerId: number; avatarType: string; displayName: string } >, size: string, ) { if (role.type === "human") { return ; } return getAvatar( role.agentId ? agentNameToRole[role.agentId]?.avatarType ?? "blue" : "blue", size, ); } function RoleAvatarBadge({ role, agentNameToRole, size = "h-7 w-7", showSpeakingAnimation = false, }: { role: RoleEntry; agentNameToRole: Record< string, { speakerId: number; avatarType: string; displayName: string } >; size?: string; showSpeakingAnimation?: boolean; }) { const isOngoing = role.status === "研讨中"; const animate = showSpeakingAnimation && isOngoing; return (
{animate && ( )}
{renderRoleAvatar(role, agentNameToRole, size)}
); } function RoleRow({ role, agentNameToRole, }: { role: RoleEntry; agentNameToRole: Record< string, { speakerId: number; avatarType: string; displayName: string } >; }) { const isActive = role.status === "在线" || role.status === "研讨中" || role.status === "已完成"; const isOngoing = role.status === "研讨中"; const isBootingUp = role.status === "正在上线"; return (
{role.name} {role.type === "agent" && ( AI 智能体 )}
{isOngoing ? ( ) : role.status === "在线" ? ( ) : role.status === "已完成" ? ( ) : isBootingUp ? ( ) : ( )} {role.status}
); } interface RightSidebarProps { currentStep: number; selectedModel: string; setSelectedModel: React.Dispatch>; availableModels: ReadonlyArray<{ name: string; display_name?: string }>; modelsLoading: boolean; intentReady: ReturnType["intentReady"]; timelineEntries: ReturnType["timelineEntries"]; triggerToast: (msg: string) => void; } function RightSidebar({ currentStep, selectedModel, setSelectedModel, availableModels, modelsLoading, intentReady, timelineEntries, triggerToast, }: RightSidebarProps) { // Step 2 侧栏内容已迁至左侧;Step 3 沿用原逻辑不展示右侧栏。 if (currentStep !== 1) return null; return ( ); }