Files
deerflow-code/frontend-web/src/roundtable-planning/pages/RoundtablePlanningPage.tsx
T
2026-09-07 17:30:53 +08:00

4800 lines
211 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 圆桌规划主页面(三步合一)。
*
* 重构后的主文件只负责"组合 + 编排":
* - 顶栏(步骤切换 + 草稿菜单 + 新建任务 + 设置)
* - 左侧栏: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)推进 furthestStep;此外每轮模型回答完
* (Step 1 一轮任务理解结束 / Step 2 每个气泡收尾)也增量回写一次,后者不动 furthestStep
* 5) Persona 抽屉改的 model 不会立即重启编排,下一轮才生效
* 6) 模型选择全局默认 `availableModels[0].name`,Persona 覆盖更高优先级
*/
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { getStoredAuth } from "@/core/auth";
import { setRoundtableErrorContext } from "@/roundtable-planning/api/diagnostics-report";
import {
Activity,
BookOpen,
Check,
CheckCircle,
ChevronRight,
ChevronDown,
ChevronUp,
PanelLeftClose,
PanelLeftOpen,
Clipboard,
Clock,
Cpu,
Download,
Filter,
History,
Layers,
ListOrdered,
Loader2,
Pencil,
Plus,
RotateCw,
Save,
Settings,
Sparkles,
Target,
Trash2,
Upload,
Users,
X,
Zap,
} from "lucide-react";
import { useTheme } from "@/contexts/ThemeContext";
import { useArtifacts } from "@/components/workspace/artifacts";
import {
LayoutModeSwitcher,
ThemeSwitcher,
} from "@/components/workspace/appearance-controls";
import { useSidebarSafe } from "@/components/ui/sidebar";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Switch } from "@/components/ui/switch";
import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
import { useModels } from "@/core/models/hooks";
import { getAvatar, Man1Avatar, RobotAvatar } from "@/roundtable-planning/components/Avatars";
import { ImportRoundtableDraftDialog } from "@/components/workspace/roundtable-draft-share-dialogs";
import { TaskPurposeDialog } from "@/strategy-components/components/task-components/TaskPurposeDialog";
import { TaskJumpBar } from "@/strategy-components/components/task-components/TaskJumpBar";
import { RwfxSqReportGate } from "@/strategy-components/components/task-components/RwfxSqReportGate";
import type { TaskBusiness } from "@/core/auth/task-buttons";
import {
derivePurposeLevels,
fetchTaskPurposeDetail,
type PurposeLevel,
} from "@/core/auth/task-purpose";
import { flowNodeMeta, type FlowNodeType } from "@/roundtable-planning/lib/flow-graph";
import { RecommendAgentsDialog } from "@/roundtable-planning/components/RecommendAgentsDialog";
import { BusinessChainListDialog } from "@/roundtable-planning/components/BusinessChainListDialog";
import { DispatchChainJobModal } from "@/roundtable-planning/components/DispatchChainJobModal";
import { Step1Panel, type Step1PanelProps } from "@/roundtable-planning/components/Step1Panel";
import { readActionDetail, readCopTaskDetail } from "@/core/auth/task-deeplink";
import { Step2Panel } from "@/roundtable-planning/components/Step2Panel";
import { Step3Panel } from "@/roundtable-planning/components/Step3Panel";
import type {
DraftStep2RunSnapshot,
DraftStep2Snapshot,
DraftStep3Snapshot,
DraftStep3SummarySnapshot,
} from "@/roundtable-planning/api/drafts";
import type { ThreadIdMap } from "@/roundtable-planning/api/multi-agent";
import {
useStep1Intent,
type InteractiveMessage,
} from "@/roundtable-planning/hooks/useStep1Intent";
import {
useStep2Orchestration,
type Step2Snapshot,
} from "@/roundtable-planning/hooks/useStep2Orchestration";
import { useDraftPersistence } from "@/roundtable-planning/hooks/useDraftPersistence";
import { useStep3Summary } from "@/roundtable-planning/hooks/useStep3Summary";
import { useStep3Report } from "@/roundtable-planning/hooks/useStep3Report";
import { useStep3Dashboard } from "@/roundtable-planning/hooks/useStep3Dashboard";
import { isDashboardHtml } from "@/roundtable-planning/lib/report-template";
import { checkIngestEligibility } from "@/roundtable-planning/api/ingest";
import { stripReasoning } from "@/roundtable-planning/lib/reasoning";
import {
BUILTIN_AGENT_META,
makeRolesFromTemplates,
nowTime,
type RoleEntry,
type SelectedAgent,
} from "@/roundtable-planning/lib/roundtable-constants";
import {
seatFilterForRole,
USER_SEAT_FILTER,
type SeatFilter,
} from "@/roundtable-planning/lib/seat-filter";
import {
buildChainSeatSelection,
isChainEnabled,
type BusinessChain,
type ChainSeat,
type SeatSelectionResult,
} from "@/roundtable-planning/lib/business-chain";
import { DEFAULT_SEAT_MODE, type SeatMode } from "@/roundtable-planning/lib/seat-mode";
import type { OrchestrationPlan } from "@/roundtable-planning/lib/dag-types";
import type { IntentSummary } from "@/roundtable-planning/api/intent";
import {
cancelJob,
getJobByDraft,
startJob,
startJobKeepalive,
} from "@/roundtable-planning/api/roundtable-jobs";
import { useRoundtableJobNotifier } from "@/roundtable-planning/components/RoundtableJobNotifier";
import { getChain, listChains } from "@/roundtable-planning/api/chains";
import { useRoundtableDrafts } from "@/roundtable-planning/hooks/useRoundtableDrafts";
import { filterRecommendCandidates } from "@/roundtable-planning/api/recommend";
import { listAgents } from "@/core/agents";
import { listBusinessMappings } from "@/strategy-components/api/business-mapping";
import { emitWujieEvent, isWujieEnv, onWujieEvent, readWujieProps } from "@/core/embed/wujie";
import { collectRoundtableDeliverables } from "@/roundtable-planning/lib/roundtable-deliverables";
import { useTaskArtifactSubmission } from "@/roundtable-planning/hooks/useTaskArtifactSubmission";
import type { TaskArtifactSubmissionConfig } from "@/roundtable-planning/lib/task-artifact-submission";
import {
findSeatSubmission,
submittedSeatKeysFor,
} from "@/roundtable-planning/lib/match-seat-submission";
import {
AnalysisResultDetailDialog,
type AnalysisResultCardItem,
} from "@/components/analysis-results";
/**
* 业务码 → 任务工作区业务码(``TaskBusiness``),用于深链 taskId 模式底部「快捷跳转」栏
* (与单智能体问答共用 ``TaskJumpBar``)。与 task-deeplink.ts 的 GOPATH_BUSINESS_CODE 反向一致。
*/
const BUSINESS_CODE_TO_TASK_BUSINESS: Record<string, TaskBusiness> = {
"3Q": "3qfx",
"6BF": "rwfx",
"7BF": "xdfx",
};
/**
* 入库仅 rwfx-A(任务分析,businessCode `6BF`)这一深链会商模式才提供——该业务较特殊,
* 其它业务(3qfx-A / xdfx-A 等)即便深链进会商生成了流程图也不出现入库按钮 / 入库询问。
*/
const INGEST_BUSINESS_CODE = "6BF";
/** 从任务页带进来的预填(经 navigation state 传递)。见会商自动化串联(模块 C)。 */
interface RoundtablePrefill {
/** 任务名称(注入 Step 1 首条用户消息)。 */
taskTitle?: string;
/** 任务描述(注入 Step 1 首条用户消息)。 */
taskGoal?: string;
/** 指定业务链条 id(wujie 抽屉直传,优先于 businessCode;据此自动选链)。 */
chainId?: string;
/** 来源业务码(如 "6BF"):据此查业务映射拿到要自动选用的业务链。 */
businessCode?: string;
/** 外部任务 id(无界抽屉):聊天记录按此存取、打开时回显最新一条。 */
taskId?: string;
/** xdfx 深链:原始行动 id(URL ?taskId= 传入的就是它)。供会商取行动详情用。 */
actionId?: string;
/** xdfx 深链:行动名称(注入 Step 1 首条用户消息——任务名称+任务描述+行动名称)。 */
actionName?: string;
/** 是否进入即自动开跑 Step 1 意图分析。 */
autoStart?: boolean;
}
/**
* 会商「聊天记录」存储键:草稿(useDraftPersistence / useRoundtableDrafts)与后台作业
* (startJob / getJobByDraft / cancelJob)统一按此键隔离与回显。
*
* - **xdfx-A(行动分析会商)**:同一任务下可派生多个「行动」,各行动的会商需互相独立,
* 故按「行动id」(`actionId`,即深链 URL `?taskId=` 原始传入值) 隔离,而非解析出的真实任务id。
* - 其它业务:无 `actionId`,回退真实 `taskId`。
*
* ⚠️ 仅用于聊天记录/作业存储。目的树、入库技能、任务详情、底部快捷跳转栏仍用真实
* `prefill.taskId`(见各调用点),不受此键影响。
*/
function recordTaskIdOf(prefill: RoundtablePrefill | null): string | null {
return prefill?.actionId ?? prefill?.taskId ?? null;
}
/**
* 无界(wujie)抽屉场景:父页面通过 `window.$wujie.props` 注入「任务名称/描述/业务链条」。
* iframe 降级时 props 可能晚于首帧,故再读 hash 路由 query 作兜底(宿主 `appendEmbedQueryToUrl` 写入)。
*/
function readWujiePrefill(): RoundtablePrefill | null {
if (!isWujieEnv()) return null;
const p = readWujieProps();
const taskTitle = typeof p.taskTitle === "string" ? p.taskTitle : undefined;
const taskGoal = typeof p.taskGoal === "string" ? p.taskGoal : undefined;
const chainId = typeof p.chainId === "string" ? p.chainId : undefined;
const businessCode = typeof p.businessCode === "string" ? p.businessCode : undefined;
const taskId = typeof p.taskId === "string" ? p.taskId : undefined;
if (!taskTitle && !taskGoal && !chainId && !businessCode && !taskId) {
return readEmbedHashQueryPrefill();
}
return { taskTitle, taskGoal, chainId, businessCode, taskId, autoStart: true };
}
/**
* 深链会商「刷新仍保持该模式」的持久化 key。
*
* 背景:深链 `?taskId=…&goPath=rwfx-A` 登录后,prefill 只经 react-router navigation state
* 传进来(URL 是 `…/roundtable`,不带 taskId),且首帧消费后会 `replaceState` 清掉 history
* state。刷新一次 navigation state 就没了 → taskId 绑定 / 业务链自动选用 / 底部快捷跳转栏 /
* 目的树全部丢失,退化成普通个人圆桌。
*
* 解法:首帧消费 prefill 时,按**路由 path** 把它存进 sessionStorage(同标签页存活、刷新保持,
* 关标签/新标签自然失效——与 `login.copTaskDetail` 同策略)。刷新挂载时若无 navigation state,
* 就按当前 path 取回,重新建立深链模式。taskId 模式刷新会先走 C1.5 `loadLatestByTask` 回显最新
* 草稿并抑制 autoStart,故恢复 prefill 不会重复发首条消息。按 path 区分,保证同一标签页内不同业务/
* 不同任务的深链互不串台,也不会污染个人圆桌路由(其 path 下永远取不到)。
*/
const ROUNDTABLE_DEEPLINK_PREFILL_KEY = "roundtable:deeplink-prefill";
// 进第三步三流「错峰起跑」的基准间隔(毫秒)。结果绘制延迟 1×、大屏延迟 2×,把三个
// start_run 的写尖峰摊开,避免单 worker + 单 sqlite 锁瞬时被打满导致回环 502(削峰,
// 不影响并行展示进度)。取值偏小,用户基本无感。
const STEP3_STAGGER_MS = 300;
/** 按路由 path 持久化深链 prefill,供刷新后恢复。隐私模式/quota 异常静默失败。 */
function persistDeeplinkPrefill(path: string, prefill: RoundtablePrefill): void {
try {
sessionStorage.setItem(
ROUNDTABLE_DEEPLINK_PREFILL_KEY,
JSON.stringify({ path, prefill }),
);
} catch {
/* noop */
}
}
/** 取回当前路由 path 对应的持久化深链 prefill;path 不匹配 / 无数据 → null。 */
function readPersistedDeeplinkPrefill(path: string): RoundtablePrefill | null {
try {
const raw = sessionStorage.getItem(ROUNDTABLE_DEEPLINK_PREFILL_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as { path?: string; prefill?: RoundtablePrefill };
if (!parsed?.prefill || parsed.path !== path) return null;
return parsed.prefill;
} catch {
return null;
}
}
/** 从 `#/embed/roundtable?…` 的 hash query 读取预填(iframe 降级兜底)。 */
function readEmbedHashQueryPrefill(): RoundtablePrefill | null {
if (typeof window === "undefined") return null;
const hash = window.location.hash || "";
if (!hash.includes("/embed/roundtable")) return null;
const qIndex = hash.indexOf("?");
if (qIndex < 0) return null;
const params = new URLSearchParams(hash.slice(qIndex + 1));
const taskTitle = params.get("taskTitle") ?? undefined;
const taskGoal = params.get("taskGoal") ?? undefined;
const chainId = params.get("chainId") ?? undefined;
const businessCode = params.get("businessCode") ?? undefined;
const taskId = params.get("taskId") ?? undefined;
if (!taskTitle && !taskGoal && !chainId && !businessCode && !taskId) return null;
return { taskTitle, taskGoal, chainId, businessCode, taskId, autoStart: true };
}
export default function RoundtablePlanningPage({
compactChrome = false,
/** 仅供独立业务页临时锁定深色视觉;不修改全局主题状态。 */
forceDarkAppearance = false,
/** 独立业务页锁定的公共业务链;不影响原多智能体会商入口。 */
lockedChainId = null,
/** 即使尚未配置业务链,也禁止用户改为推荐/手选链路。 */
lockBusinessChain = false,
/** 独立业务页的草稿/后台作业存储键。 */
storageTaskId,
/**
* 独立业务页要求「每次进入都是全新会话」(8BF 无 taskId 模式):挂载时跳过按存储键
* 回显最新草稿,直接展示空白新会话;历史会话仍留在历史下拉/分析记录里,可手动打开。
*/
skipInitialDraftRestore = false,
/** 供独立业务页在原页头部插入自己的操作入口。 */
toolbarSlot,
/** 独立业务页在第一步左上角替换默认业务链选择区的内容。 */
entryRailBusinessChainSlot,
/** 独立业务页在第一步左上角提供自己的任务卡片;不触发原深链任务接口。 */
entryRailTaskCardSlot,
/** 独立业务页传给意图智能体的隐藏任务上下文。 */
taskContext,
/** 第一步绑定的内置意图智能体 id(如 8BF 的 eightbf-roundtable-intent)。
* 缺省沿用通用会商的 roundtable-intent,原多智能体会商入口行为不变。 */
intentAgentId,
/**
* 8BF 页头「人工干预」开关(受控):开启后第二步每走一步暂停等待用户输入,
* 关闭自动推进。提供 onStep2InterventionChange 时才渲染开关,通用会商页不受影响。
*/
step2InterventionEnabled,
onStep2InterventionChange,
/** 独立业务页的任务作用域,仅用于左栏记录筛选,不改变原深链逻辑。 */
entryRailTaskId,
/** 独立业务页的根节点样式类,避免修改原会商样式。 */
rootClassName,
/** 独立业务页替换第一步消息工作区的纯展示组件;状态和行为仍由本页统一拥有。 */
renderStep1,
/** 独立业务页替换第一步左侧入口栏。 */
renderStep1LeftSidebar,
/** 独立业务页在第二步左栏顶部复用自己的任务/意图展示。 */
renderStep2LeftSidebarHeader,
/** 第一阶段使用内嵌右栏时,隐藏通用的模型/摘要/澄清记录栏。 */
hideDefaultStep1RightSidebar = false,
step2HeaderTitle,
step2HeaderRightSlot,
step3HeaderTitle,
/** 独立业务页的工作区品牌区,取代通用步骤导航。 */
headerLeftSlot,
/** 放在历史记录后面的独立业务操作或状态。 */
headerActionAfterHistory,
/** 独立业务页可隐藏通用的“保存草稿”按钮。 */
hideHeaderSaveDraft = false,
/** 独立业务页可调整新建动作的展示文案,行为不变。 */
newTaskLabel,
/** 独立业务页可隐藏通用的设置入口。 */
hideHeaderSettings = false,
/** 可选的外部任务过程产物提交适配器(8BF 使用,通用圆桌保持不显示)。 */
taskArtifactSubmissionConfig,
/**
* 第三步的交付范围。普通会商保留报告后的流程图、最终方案/席位列表与可视化大屏;
* 8BF 只交付 Markdown 总结报告,避免两个入口互相改变行为。
*/
step3Mode = "full",
}: {
compactChrome?: boolean;
forceDarkAppearance?: boolean;
lockedChainId?: string | null;
lockBusinessChain?: boolean;
storageTaskId?: string | null;
skipInitialDraftRestore?: boolean;
toolbarSlot?: ReactNode;
entryRailBusinessChainSlot?: ReactNode;
entryRailTaskCardSlot?: ReactNode;
taskContext?: Record<string, unknown> | null;
/** 第一步绑定的内置意图智能体 id;缺省走通用 roundtable-intent。 */
intentAgentId?: string;
/** 第二步「人工干预」开关(8BF 页头,新建任务按钮左侧)。 */
step2InterventionEnabled?: boolean;
onStep2InterventionChange?: (enabled: boolean) => void;
entryRailTaskId?: string | null;
rootClassName?: string;
renderStep1?: (props: Step1PanelProps & {
selectedModel: string;
modelOptions: Array<{ label: string; value: string }>;
onSelectedModelChange: (model: string) => void;
step2Dialogues: unknown[];
step2ThreadIds: ThreadIdMap | null;
step2CoordinatorName: string | null;
step2SeatStubMessages: Record<string, unknown[]>;
step3Summary: DraftStep3SummarySnapshot | null;
}) => ReactNode;
renderStep1LeftSidebar?: (context: {
intentReady: object | null;
onCollapse?: () => void;
submittedSeatKeys?: string[];
onSeatClick?: (seat: ChainSeat) => void;
}) => ReactNode;
renderStep2LeftSidebarHeader?: (context: {
intentReady: object | null;
onCollapse: () => void;
}) => ReactNode;
hideDefaultStep1RightSidebar?: boolean;
/** 8BF 第二步对话区标题,与第一步顶栏同一套样式。 */
step2HeaderTitle?: string;
/** 8BF 第二步顶栏右侧附加操作(如返回)。 */
step2HeaderRightSlot?: ReactNode;
/** 8BF 第三步对话区标题,与第一、二步顶栏同一套样式。 */
step3HeaderTitle?: string;
headerLeftSlot?: ReactNode;
headerActionAfterHistory?: ReactNode;
hideHeaderSaveDraft?: boolean;
newTaskLabel?: string;
hideHeaderSettings?: boolean;
taskArtifactSubmissionConfig?: TaskArtifactSubmissionConfig;
step3Mode?: "full" | "report-only";
}) {
const { theme } = useTheme();
// 全工作区跨页的后台作业完成通知器(Provider 挂在 PageLayout 常驻层)。
const { watchJob } = useRoundtableJobNotifier();
// 保留 ThemeContext 的主题切换能力;独立业务页可只覆盖自身的视觉模式,
// 不触碰全局 html 主题,后续移除该 prop 即可恢复随系统主题切换。
const isDark = forceDarkAppearance || theme === "dark";
const hasFullStep3Outputs = step3Mode === "full";
const navigate = useNavigate();
const location = useLocation();
const taskContextRef = useRef<Record<string, unknown> | null>(taskContext ?? null);
useEffect(() => {
taskContextRef.current = taskContext ?? null;
}, [taskContext]);
/** 无界(wujie)嵌入抽屉:隐藏业务链条入口,设置按钮改作手动回传交付。 */
const inWujieEmbed = isWujieEnv();
// ─── 会商自动化串联(模块 C):任务页带进来的预填 ─────────────────
// 只在首次渲染读一次 navigation state;随后清掉 history state,避免刷新/后退重放。
// 优先级:navigation state(站内跳转)> window.$wujie.props(无界抽屉)>
// sessionStorage(深链刷新恢复,按路由 path 取回;见 ROUNDTABLE_DEEPLINK_PREFILL_KEY)。
const prefillRef = useRef<RoundtablePrefill | null>(
((location.state as { roundtablePrefill?: RoundtablePrefill } | null)?.roundtablePrefill) ??
readWujiePrefill() ??
readPersistedDeeplinkPrefill(location.pathname),
);
// 8BF 等独立页面可提供专属存储键;原会商仍沿用深链 taskId / 个人草稿语义。
const draftStorageTaskId = storageTaskId ?? recordTaskIdOf(prefillRef.current);
// 由 prefill.businessCode 解析出的「自动选用业务链」结果;有值时「进入研讨」跳过选链弹窗直接进 Step 2。
const [autoChainResult, setAutoChainResult] = useState<SeatSelectionResult | null>(null);
// 固定业务链(8BF 等独立页面)的解析状态。不能只以 autoChainResult 是否为空判断:
// 它为空既可能是「还在拉取」,也可能是「业务链已配置但可用席位不足」。
// 若混为一谈,用户刚保存配置后立刻点击进入研讨时会被错误提示为「未配置业务链」。
const [lockedChainResolution, setLockedChainResolution] = useState<
"idle" | "loading" | "ready" | "unavailable"
>("idle");
const [lockedChainUnavailableReason, setLockedChainUnavailableReason] = useState<string | null>(null);
/** 无界直传 chainId 时,链条解析完成前禁止弹选链窗(避免 modal 布局抖动)。 */
const [autoChainLoading, setAutoChainLoading] = useState(
() =>
inWujieEmbed &&
!!(prefillRef.current?.chainId || prefillRef.current?.businessCode),
);
// 独立业务页使用管理员配置的固定业务链。它只负责预选,不触发深链的自动开跑逻辑。
useEffect(() => {
if (!lockedChainId) {
setAutoChainResult(null);
setLockedChainResolution("idle");
setLockedChainUnavailableReason(null);
return;
}
let cancelled = false;
// 映射切换时先清掉旧链结果,避免异步请求尚未返回时误用上一条业务链进入研讨。
setAutoChainResult(null);
setLockedChainResolution("loading");
setLockedChainUnavailableReason(null);
setAutoChainLoading(true);
void Promise.all([getChain(lockedChainId), listAgents()])
.then(([chain, agents]) => {
if (cancelled) return;
if (!chain) {
setAutoChainResult(null);
setLockedChainResolution("unavailable");
setLockedChainUnavailableReason("已配置的业务链不存在或未发布,请重新选择一条已发布的业务链");
return;
}
const candidates = filterRecommendCandidates(agents);
const result = buildChainSeatSelection(chain, candidates);
if (!cancelled) {
setAutoChainResult(result);
setLockedChainResolution(result ? "ready" : "unavailable");
if (!result) {
const availableAgentIds = new Set(candidates.map((agent) => agent.agent_id));
const unavailableSeats = chain.seats
.filter((seat) => !availableAgentIds.has(seat.agent_id))
.map((seat) => seat.name || seat.agent_id);
setLockedChainUnavailableReason(
unavailableSeats.length > 0
? `业务链中的智能体「${unavailableSeats.join("、")}」尚未发布、已删除或当前账号无访问权限;请先将它们发布,并保证至少有 2 个可用智能体`
: "业务链至少需要 2 个可用智能体,请检查业务链席位配置",
);
}
}
})
.catch(() => {
if (!cancelled) {
setAutoChainResult(null);
setLockedChainResolution("unavailable");
setLockedChainUnavailableReason("读取已配置业务链或智能体失败,请刷新后重试");
}
})
.finally(() => {
if (!cancelled) {
setAutoChainLoading(false);
// getChain 返回 null 时不会进入 then 内的 result 分支,同样标记为不可用。
setLockedChainResolution((current) => current === "loading" ? "unavailable" : current);
setLockedChainUnavailableReason((current) => current ?? "已配置的业务链暂不可用,请重新选择后重试");
}
});
return () => {
cancelled = true;
};
}, [lockedChainId]);
const autoStartedRef = useRef(false);
const prefillClearedRef = useRef(false);
// 共识达成后只向父页面(无界)回传一次交付结果。
const consensusEmittedRef = useRef(false);
/** 上一帧 hasConsensus,用于识别 false→true 的 live 过渡(回显不算)。 */
const prevHasConsensusRef = useRef(false);
const markRestoredConsensusAsEmitted = useCallback((hasConsensus: boolean) => {
prevHasConsensusRef.current = hasConsensus;
if (hasConsensus && inWujieEmbed) {
consensusEmittedRef.current = true;
}
}, [inWujieEmbed]);
// 带存储键 / 深链 taskId 时,先回显最新草稿再决定是否 autoStart。用 state 而非 ref:
// 解析完成需触发重渲染让 C2 effect 重跑(否则 intentThreadId 先就绪会错过 autoStart)。
// 无存储键时初始即「已解析」,autoStart 照常。8BF 走 storageTaskId,不依赖 prefill.taskId。
const [taskRestoreResolved, setTaskRestoreResolved] = useState<boolean>(
!draftStorageTaskId,
);
// 深链/预填自动会话:进入页面后要先建意图线程、(带 taskId 时)回显历史草稿,这段时间
// 页面只有一句欢迎语、问答还没真正开始,线程创建慢时像卡住。下面这个标志用来在超时后
// 强制撤掉「启动加载遮罩」,避免万一初始化卡死把界面永久锁住。
const [bootLoadingExpired, setBootLoadingExpired] = useState<boolean>(false);
const { models: availableModels, isLoading: modelsLoading } = useModels();
// ─── 顶层导航 / 跨步状态 ─────────────────────────────────────
const [currentStep, setCurrentStep] = useState<number>(1);
const [showToast, setShowToast] = useState<string | null>(null);
const [isRecommendDialogOpen, setIsRecommendDialogOpen] = useState<boolean>(false);
// 「业务链条」按钮 → 打开链条列表弹窗(弹窗里再决定进配置页 / 切到某条链条)。
const [isChainListOpen, setIsChainListOpen] = useState<boolean>(false);
// 历史下拉点击「进行中」任务 → 打开派活链路流程图弹窗(订阅该作业 SSE)。
const [chainModalJobId, setChainModalJobId] = useState<string | null>(null);
// 「导入会商」弹窗(输入分享码把别人分享的会商复制到本账号)。
const [isImportOpen, setIsImportOpen] = useState<boolean>(false);
// 任务目的弹窗(多智能体会商深链 taskId 模式:查看线上当前策划进度/目的树)。
const [isTaskPurposeOpen, setIsTaskPurposeOpen] = useState<boolean>(false);
// 深链 taskId 模式:消息列表上方的「策划流程示例图」——按目的树层级画彩色小图标
// (任务→目的→…→叙事),点击打开任务目的流程图弹窗。空 = 无数据/未取到,不显示。
const [purposeLevels, setPurposeLevels] = useState<PurposeLevel[]>([]);
const [selectedModel, setSelectedModel] = useState<string>("");
// Step 2 席位执行模式(快速/思考/专业问答/多智能体问答)——决定每个子智能体席位的
// 推理深度。由「选择参会智能体」弹窗确认时的 SeatSelectionResult.seatMode 决定。
const [seatMode, setSeatMode] = useState<SeatMode>(DEFAULT_SEAT_MODE);
// Step 2 每席位「技能识别强化」开关映射 {agentId: bool}:由所选业务链条里**每个席位**的同名
// 配置决定(recommend 无链条 → 空 {})。透传给每个席位 run,与各席位智能体自身的开关取 OR。
const [seatSkillDirectives, setSeatSkillDirectives] = useState<Record<string, boolean>>({});
// Per-seat human-validation checkpoints from the selected business chain.
// A checkpoint pauses Step 2 after the configured seat/stage completes and
// reuses the existing resume button plus bottom intervention composer.
const [humanValidations, setHumanValidations] = useState<Record<string, boolean>>({});
// Step 2 每席位「推理深度覆盖」映射 {agentId: SeatMode|null}:由所选业务链条里**每个席位**单独配
// 的推理深度决定(null/未配 → 跟随链条级 seatMode)。透传给席位 run(覆盖优先、否则跟随 seatMode)。
// 「卡顿提速」用:把次要席位降到 flash 即可大幅缩短第二步耗时。
const [seatModes, setSeatModes] = useState<Record<string, SeatMode | null>>({});
// Step 2「研讨前并行取数」开关:由所选业务链条的 gatherFirst 决定(recommend / 无链条 → false)。
// true = 研讨前先并行跑一轮全席位『取数』,产出作为共享资料注入研讨轮,给(尤其 chain 串行)研讨段提速。
const [gatherFirst, setGatherFirst] = useState<boolean>(false);
// Step 2 编排模式:recommend = 总控自由派活;chain = 总控按业务链条顺序派活;
// dag = 分层 DAG(stage 内并行、stage 间串行,配合 orchestrationPlan)。
// 由推荐弹窗确认时的 SeatSelectionResult.mode 决定(见 handleConfirmAgents)。
const [orchestrationMode, setOrchestrationMode] = useState<"recommend" | "chain" | "dag">(
"recommend",
);
// chain 模式来源链条(仅展示/持久化用)。
const [chainMeta, setChainMeta] = useState<{ id: string; title: string } | null>(null);
// dag 模式的分层编排计划(Phase 2 编辑器产出;持久化进 step2.orchestrationPlan)。
const [orchestrationPlan, setOrchestrationPlan] = useState<OrchestrationPlan | null>(null);
// dag 执行子模式:fast(并行双列禁写)/ sandbox(并行单列可写、沙箱跟随)。
// 由推荐弹窗的「执行方式」选择决定(仅 dag 有意义)。
const [dagExecMode, setDagExecMode] = useState<"fast" | "sandbox">("sandbox");
const [step2SidebarExpanded, setStep2SidebarExpanded] = useState(true);
const [step2Runs, setStep2Runs] = useState<DraftStep2RunSnapshot[]>([]);
const [activeStep2RunId, setActiveStep2RunId] = useState<string | null>(null);
// 第二步「按席位筛选会商记录」—— 左侧角色卡片与中间消息头像共用的筛选标识。
const [seatFilter, setSeatFilter] = useState<SeatFilter | null>(null);
// Step 3「结果绘制」结果 —— 持久化进草稿 step3。绘制完成由 onReportSaved 写入;
// 加载草稿时 hydrateStep3 恢复;新建任务清空。step3SavedTick 递增触发一次草稿自动保存。
const [step3Report, setStep3Report] = useState<DraftStep3Snapshot | null>(null);
const [step3SavedTick, setStep3SavedTick] = useState<number>(0);
// 入库是否可用 + 选中的入库技能:不再前端硬编码关键字,而是让**结构化输出智能体**读它
// 挂载的入库技能 + 当前业务场景**自行判断**是否有适合本场景的入库技能(决定第三步是否询问
// 入库 + 显示手动入库按钮)。入库仅深链(taskId)模式才有意义,故仅在该模式下判定。
const [ingestAvailable, setIngestAvailable] = useState<boolean>(false);
const [ingestSkill, setIngestSkill] = useState<string>("");
const ingestTaskIdForCheck = prefillRef.current?.taskId ?? null;
const ingestBusinessCode = prefillRef.current?.businessCode ?? null;
useEffect(() => {
// 入库仅 rwfx-A(businessCode 6BF)深链会商模式提供;其它业务一律不判定、不显示入库。
if (!ingestTaskIdForCheck || ingestBusinessCode !== INGEST_BUSINESS_CODE) {
setIngestAvailable(false);
setIngestSkill("");
return;
}
let cancelled = false;
void checkIngestEligibility({
taskId: ingestTaskIdForCheck,
businessCode: ingestBusinessCode,
chainName: chainMeta?.title ?? null,
coordinatorPrompt: orchestrationPlan?.coordinatorPrompt ?? null,
})
.then((r) => {
if (cancelled) return;
setIngestAvailable(r.canIngest);
setIngestSkill(r.skill);
})
.catch(() => {
if (cancelled) return;
setIngestAvailable(false);
setIngestSkill("");
});
return () => {
cancelled = true;
};
}, [
ingestTaskIdForCheck,
ingestBusinessCode,
chainMeta?.title,
orchestrationPlan?.coordinatorPrompt,
]);
const step2RunsRef = useRef<DraftStep2RunSnapshot[]>([]);
const activeStep2RunIdRef = useRef<string | null>(null);
// 并行执行时收起左侧栏 —— 全局工作区侧栏(最左)走 useSidebarSafe(与「打开沙箱」同一路径,
// 见 artifacts/context.tsx 的 sidebar.setOpen(false)),圆桌「参与角色」栏走 step2SidebarExpanded。
const sidebar = useSidebarSafe();
// ─── 沙箱默认关闭策略(2026-06-12)────────────────────────────
// 步骤切换(1↔2↔3 任意方向)时**默认关闭**沙箱预览:
// - 进第三步不再自动弹出旧产物预览(只有 live write_file 开始写文件时才自动打开);
// - 第三步回第二步不再遗留一个「没有文件的空沙箱」(步骤切换前选中的产物在新步骤
// 的 stub 映射里多半不存在 → 表现为空白沙箱)。
// 用 deselect(raw 关闭)而**不是** wrapped setOpen(false) —— 后者会把 autoOpen 置
// false,导致新步骤里 live 写文件时自动打开被守卫拦掉(见 useStep2Orchestration 注释)。
const { deselect: deselectArtifactOnStepChange } = useArtifacts();
const prevStepRef = useRef(currentStep);
useEffect(() => {
if (prevStepRef.current === currentStep) return;
prevStepRef.current = currentStep;
deselectArtifactOnStepChange();
}, [currentStep, deselectArtifactOnStepChange]);
// 角色面板(LeftSidebar)。原页面把它当成两步共用的展示数据,这里继续放在
// 主页 —— Step 1 / Step 2 / Step 3 都会读 / 写它,任何 hook 单独持有都不合适。
const [roles, setRoles] = useState<RoleEntry[]>([]);
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<boolean>(false);
// Step 2 hook 拿到 selectedAgents 等;但 buildInitialIntent 需要 Step 1 状态,
// 这是循环依赖。解法:用 ref 把 step1 的最新值暴露给 buildInitialIntent。
const step1StateRef = useRef<{
intentReady: ReturnType<typeof useStep1Intent>["intentReady"];
interactiveMessages: InteractiveMessage[];
}>({ intentReady: null, interactiveMessages: [] });
const buildInitialIntent = useCallback((): string => {
const task = taskContextRef.current?.task as Record<string, unknown> | null | undefined;
const taskTags = taskContextRef.current?.task_tags as
| Record<string, unknown>
| undefined;
const taskValue = (value: unknown) =>
value === undefined || value === null ? "" : String(value).trim();
const taskLines = task
? [
["任务 ID", taskValue(task.id ?? taskContextRef.current?.task_id)],
["任务名称", taskValue(task.title)],
["任务描述", taskValue(task.description)],
["任务概览", taskValue(task.overview)],
["任务方向", taskValue(task.direction ?? task.target_direction)],
["优先级", taskValue(task.task_priority ?? task.priority)],
["任务状态", taskValue(task.task_status)],
["优先级标签", taskValue(taskTags?.priority)],
["方向标签", taskValue(taskTags?.direction)],
["状态标签", taskValue(taskTags?.status)],
]
.filter(([, value]) => value)
.map(([label, value]) => `${label}: ${value}`)
: [];
const taskCardContext = taskLines.length
? [
"【8BF 任务卡片上下文】",
...taskLines,
"请把以上任务卡片信息作为本轮研讨的既有背景,不要让用户重复提供。",
"",
].join("\n")
: "";
const withTaskCardContext = (value: string) =>
taskCardContext ? `${taskCardContext}${value}` : value;
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 withTaskCardContext(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 withTaskCardContext("用户尚未在第一步明确任务意图。请先调用 ask_clarification,简要询问目标、范围与硬性约束,再进入研讨。");
}
const conversation = userTurns.map((t, i) => `用户#${i + 1}: ${t}`).join("\n");
return withTaskCardContext(`${conversation}\n\n注意:用户尚未完成结构化的任务理解流程,以上是原始输入。若信息不足以开展研讨,请先调用 ask_clarification 询问关键约束,再开始派活。`);
}, []);
const step2 = useStep2Orchestration({
currentStep,
selectedModel,
selectedMode: seatMode,
seatSkillDirectives,
humanValidations,
manualIntervention: step2InterventionEnabled ?? false,
seatModes,
gatherFirst,
orchestrationMode,
orchestrationPlan,
dagExecMode,
buildInitialIntent,
triggerToast,
setRoles,
loadedFromDraftRef: loadedFromDraftRefHolder,
});
const step1 = useStep1Intent({
currentStep,
selectedModel,
triggerToast,
taskContext,
intentAgentId,
});
const taskArtifactSubmission = useTaskArtifactSubmission(
taskArtifactSubmissionConfig,
step2.threadIds,
step2.agentNameToRole,
);
const [seatDeliverable, setSeatDeliverable] = useState<AnalysisResultCardItem | null>(null);
const submittedRecords = taskArtifactSubmission?.submittedRecords;
const submittedSeatKeys = useMemo(
() => submittedSeatKeysFor(
step2.selectedAgents.map((agent) => ({ agent_id: agent.agent_id, name: agent.name })),
submittedRecords ?? [],
step2.selectedAgents,
step2.threadIds,
),
[submittedRecords, step2.selectedAgents, step2.threadIds],
);
const handleChainSeatClick = useCallback((seat: ChainSeat) => {
const record = findSeatSubmission(
seat,
submittedRecords ?? [],
step2.selectedAgents,
step2.threadIds,
);
if (!record) {
triggerToast("该节点暂无可预览产物");
return;
}
setSeatDeliverable({
id: record.id,
agentName: seat.name || record.artifact.sourceKey,
productName: record.artifact.name,
positionName: seat.description?.trim() || autoChainResult?.chain?.title || "业务链席位",
delivered: true,
artifactPath: record.artifact.path,
artifactMimeType: record.artifact.mimeType,
artifactThreadId: record.artifact.threadId,
updatedAt: record.submittedAt ?? undefined,
});
}, [
autoChainResult?.chain?.title,
step2.selectedAgents,
step2.threadIds,
submittedRecords,
triggerToast,
]);
const renderStep1LeftSidebarWithDeliveries = useMemo(
() => (renderStep1LeftSidebar
? (context: { intentReady: object | null; onCollapse?: () => void }) =>
renderStep1LeftSidebar({
...context,
submittedSeatKeys,
onSeatClick: taskArtifactSubmission ? handleChainSeatClick : undefined,
})
: undefined),
[handleChainSeatClick, renderStep1LeftSidebar, submittedSeatKeys, taskArtifactSubmission],
);
// 同步 step1StateRef,让 buildInitialIntent / Persona / Step 3 都能读到最新值。
useEffect(() => {
step1StateRef.current = {
intentReady: step1.intentReady,
interactiveMessages: step1.interactiveMessages,
};
}, [step1.intentReady, step1.interactiveMessages]);
// Step 2 已收尾(非 streaming)的气泡数量 —— 递增即「某轮模型刚交付完」,
// 作为草稿自动保存的触发信号(详见 useDraftPersistence)。流式增量不计入,
// 所以不会在 token 级别刷屏式保存。
const step2FinalizedCount = useMemo(
() => step2.step2RoundtableDialogues.filter((d) => !d.streaming).length,
[step2.step2RoundtableDialogues],
);
useEffect(() => {
step2RunsRef.current = step2Runs;
}, [step2Runs]);
useEffect(() => {
activeStep2RunIdRef.current = activeStep2RunId;
}, [activeStep2RunId]);
const buildCurrentStep2Snapshot = useCallback(
(): DraftStep2Snapshot => ({
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,
orchestrationMode,
chain: chainMeta,
orchestrationPlan,
dagExecMode,
}),
[
chainMeta,
orchestrationMode,
orchestrationPlan,
dagExecMode,
step2.budgetLimit,
step2.consensusPercentage,
step2.coordinatorName,
step2.hasConsensus,
step2.lastLeaderContent,
step2.seatStubMessages,
step2.selectedAgents,
step2.step2RoundtableDialogues,
step2.threadIds,
],
);
const snapshotToRun = useCallback(
(
snapshot: DraftStep2Snapshot,
fallback: Partial<Pick<DraftStep2RunSnapshot, "id" | "title" | "createdAt" | "source">> = {},
): DraftStep2RunSnapshot => ({
id: fallback.id ?? `step2-run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
title: fallback.title ?? "第一次生成结果",
createdAt: fallback.createdAt ?? new Date().toISOString(),
source: fallback.source ?? snapshot.orchestrationMode ?? "initial",
selectedAgents: snapshot.selectedAgents,
threadIds: snapshot.threadIds,
coordinatorName: snapshot.coordinatorName,
step2RoundtableDialogues: snapshot.step2RoundtableDialogues ?? [],
lastLeaderContent: snapshot.lastLeaderContent ?? "",
hasConsensus: Boolean(snapshot.hasConsensus),
consensusPercentage: snapshot.consensusPercentage ?? 0,
budgetLimit: snapshot.budgetLimit ?? 0,
seatStubMessages: snapshot.seatStubMessages ?? {},
orchestrationMode: snapshot.orchestrationMode,
chain: snapshot.chain ?? null,
orchestrationPlan: snapshot.orchestrationPlan ?? null,
dagExecMode: snapshot.dagExecMode,
step3: step3Report,
}),
[step3Report],
);
const mergeActiveRun = useCallback(
(
runs: DraftStep2RunSnapshot[],
activeRunId: string | null,
snapshot: DraftStep2Snapshot,
report: DraftStep3Snapshot | null,
): DraftStep2RunSnapshot[] => {
if (!activeRunId) return runs;
const idx = runs.findIndex((run) => run.id === activeRunId);
if (idx === -1) return runs;
const current = runs[idx];
const next = snapshotToRun(snapshot, {
id: current.id,
title: current.title,
createdAt: current.createdAt,
source: current.source,
});
next.step3 = report;
return runs.map((run, i) => (i === idx ? next : run));
},
[snapshotToRun],
);
const getStep2SnapshotWithRuns = useCallback((): DraftStep2Snapshot => {
const snapshot = buildCurrentStep2Snapshot();
const runs = mergeActiveRun(
step2RunsRef.current,
activeStep2RunIdRef.current,
snapshot,
step3Report,
);
return {
...snapshot,
runs,
activeRunId: activeStep2RunIdRef.current,
};
}, [buildCurrentStep2Snapshot, mergeActiveRun, step3Report]);
const normalizeStep2Runs = useCallback(
(
snapshot: DraftStep2Snapshot,
fallbackStep3: DraftStep3Snapshot | null,
): { runs: DraftStep2RunSnapshot[]; activeRunId: string | null } => {
if (snapshot.runs?.length) {
const activeRunId = snapshot.activeRunId ?? snapshot.runs[0]?.id ?? null;
const runs = snapshot.runs.map((run) =>
run.id === activeRunId && !run.step3 && fallbackStep3
? { ...run, step3: fallbackStep3 }
: run,
);
return {
runs,
activeRunId,
};
}
const hasLegacyContent =
(snapshot.step2RoundtableDialogues?.length ?? 0) > 0 ||
Boolean(snapshot.threadIds) ||
Boolean(snapshot.lastLeaderContent);
if (!hasLegacyContent) return { runs: [], activeRunId: null };
const legacy = snapshotToRun(snapshot, {
id: "legacy-run",
title: "第一次生成结果",
source: snapshot.orchestrationMode ?? "initial",
});
legacy.step3 = fallbackStep3;
return { runs: [legacy], activeRunId: legacy.id };
},
[snapshotToRun],
);
const hydrateStep2Run = useCallback(
(run: DraftStep2RunSnapshot) => {
setOrchestrationMode(run.orchestrationMode ?? "recommend");
setChainMeta(run.chain ?? null);
setOrchestrationPlan(run.orchestrationPlan ?? null);
setDagExecMode(run.dagExecMode ?? "sandbox");
setStep3Report(run.step3 ?? null);
step2.hydrateFromDraft(run as unknown as Step2Snapshot);
markRestoredConsensusAsEmitted(Boolean(run.hasConsensus));
},
[markRestoredConsensusAsEmitted, step2],
);
const handleSelectStep2Run = useCallback(
(runId: string) => {
if (runId === activeStep2RunIdRef.current) return;
step2.stopOrchestration();
const currentSnapshot = buildCurrentStep2Snapshot();
const syncedRuns = mergeActiveRun(
step2RunsRef.current,
activeStep2RunIdRef.current,
currentSnapshot,
step3Report,
);
const target = syncedRuns.find((run) => run.id === runId);
if (!target) return;
setStep2Runs(syncedRuns);
setActiveStep2RunId(runId);
hydrateStep2Run(target);
setCurrentStep(2);
},
[buildCurrentStep2Snapshot, hydrateStep2Run, mergeActiveRun, step2, step3Report],
);
// 第三步三条生成流(总结报告 / 经典看板 / 大屏)各自生成过程的实时对话(中间文字 + 步骤条)。
// 在 render 阶段镜像进 ref(这些 flow 在本 hook 之后才定义,故用 ref 跨过 TDZ;render 期赋值,
// 保证 autoSave effect 读到的是本次提交已 flush 的最终对话,规避 effect 执行顺序问题)。
type Step3Convo = {
dialogues: unknown[];
seatStubMessages: Record<string, unknown[]>;
/** 仅总结流用:入库状态,随快照落库。 */
ingestStatus?: string;
};
const step3SummaryConvoRef = useRef<Step3Convo>({ dialogues: [], seatStubMessages: {} });
const step3ReportConvoRef = useRef<Step3Convo>({ dialogues: [], seatStubMessages: {} });
const step3DashConvoRef = useRef<Step3Convo>({ dialogues: [], seatStubMessages: {} });
// 草稿 hook —— 同时依赖 step1 + step2 的 snapshot / hydrate。
const drafts = useDraftPersistence({
currentStep,
setCurrentStep,
triggerToast,
// 聊天记录存储键:xdfx-A 按行动id 隔离,其它业务按真实 taskId(见 recordTaskIdOf)。
taskId: draftStorageTaskId,
intentSending: step1.isIntentSending,
step2FinalizedCount,
step3SavedTick,
// 存草稿时把第三步三条流(总结报告 / 经典看板 / 大屏)生成过程的完整对话(文字 + 步骤条)
// 一并落库,使加载后能像第二步一样回显整段研讨/绘制过程,而非只有最终 md/流程图/HTML。
// 仅在有实时对话时覆盖(避免对应 flow 尚未 hydrate 时用空对话抹掉已存的)。
getStep3Snapshot: () => {
const rep = step3Report;
if (!rep) return null;
const enriched: DraftStep3Snapshot = { ...rep };
const sr = rep.summaryReport;
const sumLive = step3SummaryConvoRef.current;
if (sr) {
enriched.summaryReport = {
...sr,
dialogues: sumLive.dialogues.length ? sumLive.dialogues : sr.dialogues,
seatStubMessages: Object.keys(sumLive.seatStubMessages).length
? sumLive.seatStubMessages
: sr.seatStubMessages,
ingestStatus: sumLive.ingestStatus ?? sr.ingestStatus,
};
}
const repLive = step3ReportConvoRef.current;
if (repLive.dialogues.length) {
enriched.reportDialogues = repLive.dialogues;
enriched.reportSeatStubMessages = repLive.seatStubMessages;
}
const dashLive = step3DashConvoRef.current;
if (dashLive.dialogues.length) {
enriched.dashboardDialogues = dashLive.dialogues;
enriched.dashboardSeatStubMessages = dashLive.seatStubMessages;
}
return enriched;
},
hydrateStep3: (snapshot) => setStep3Report(snapshot),
getStep1Snapshot: () => ({
intentThreadId: step1.intentThreadId,
intentReady: step1.intentReady,
interactiveMessages: step1.interactiveMessages,
timelineEntries: step1.timelineEntries,
}),
getStep2Snapshot: getStep2SnapshotWithRuns,
hydrateStep1: step1.hydrateFromDraft,
// 包一层:先把页面持有的编排模式 / 链条恢复出来(老草稿无字段 → recommend),
// 再交给 step2 hook 恢复其余 Step 2 状态。
hydrateStep2: (snapshot, savedStep3) => {
const normalized = normalizeStep2Runs(snapshot, savedStep3);
setStep2Runs(normalized.runs);
setActiveStep2RunId(normalized.activeRunId);
const active =
normalized.runs.find((run) => run.id === normalized.activeRunId) ?? null;
if (active) {
hydrateStep2Run(active);
return;
}
setOrchestrationMode(snapshot.orchestrationMode ?? "recommend");
setChainMeta(snapshot.chain ?? null);
setOrchestrationPlan(snapshot.orchestrationPlan ?? null);
setDagExecMode(snapshot.dagExecMode ?? "sandbox");
step2.hydrateFromDraft(snapshot as unknown as Step2Snapshot);
markRestoredConsensusAsEmitted(Boolean(snapshot.hasConsensus));
},
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;
});
// ─── 用户手动编辑「当前意图摘要」并保存 ───────────────────────
// 先 updateIntentReady 覆盖意图,再 bump 计数触发一次草稿保存。**必须用计数 + effect**
// 而非直接调 handleManualSave:enqueueSave 闭包捕获的 getStep1Snapshot 读的是本次渲染的
// step1.intentReady,同步调用会在 setState flush 前存进旧意图(踩坑);放到 effect 里,等
// 重渲染后再保存,getStep1Snapshot 才读到新值(与 step2/step3 的计数触发器同构)。
const [intentEditTick, setIntentEditTick] = useState(0);
const handleSaveIntent = useCallback(
(next: IntentSummary) => {
step1.updateIntentReady(next);
setIntentEditTick((t) => t + 1);
},
[step1],
);
useEffect(() => {
if (intentEditTick === 0) return;
drafts.handleManualSave();
// 仅在 tick 递增时保存;handleManualSave 取最新闭包(effect 跑在重渲染之后)。
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [intentEditTick]);
// ─── 从侧边栏「多智能体会商」记录进入 ───────────────────────
// 侧边栏点击某条草稿时:不在本页 → 把 id 存进 sessionStorage 再跳转,挂载时消费;
// 已在本页 → 直接派 `roundtable:open-draft` 事件。两条路径都走 handleLoadDraft。
// 用 ref 持有最新 handleLoadDraft,让下面的 effect 保持「挂载只跑一次」,避免
// handleLoadDraft 身份变化导致重复消费 / 重复加载。
const handleLoadDraftRef = useRef(drafts.handleLoadDraft);
useEffect(() => {
handleLoadDraftRef.current = drafts.handleLoadDraft;
}, [drafts.handleLoadDraft]);
useEffect(() => {
const pending = sessionStorage.getItem("roundtable:pending-draft");
if (pending) {
sessionStorage.removeItem("roundtable:pending-draft");
handleLoadDraftRef.current(pending);
}
const onOpenDraft = (e: Event) => {
const id = (e as CustomEvent<string>).detail;
if (id) handleLoadDraftRef.current(id);
};
window.addEventListener("roundtable:open-draft", onOpenDraft);
return () => window.removeEventListener("roundtable:open-draft", onOpenDraft);
}, []);
// ─── 角色面板转场 ────────────────────────────────────────
// 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,
]);
// 并行执行 → 收起左侧栏腾出横向空间放两列(和「打开沙箱」一样的收起体验):
// - 全局工作区侧栏(最左):sidebar.setOpen(false)(与 artifacts 打开沙箱同一路径);
// - 圆桌「参与角色」栏:setStep2SidebarExpanded(false)。
// **不自动复原**:并行结束后再进入单智能体回答时保持收起(用户需要时手动展开),
// 与沙箱收起后不自动回弹一致。
useEffect(() => {
if (step2.isParallelRunning) {
sidebar?.setOpen(false);
setStep2SidebarExpanded(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [step2.isParallelRunning]);
// ─── 步骤间转场 handler ───────────────────────────────────
const handleConfirmAgents = useCallback(
(result: SeatSelectionResult) => {
const normalized: SelectedAgent[] = result.agents.map(({ agent_id, name }) => ({
agent_id,
// 内置 agent 走 BUILTIN_AGENT_META;非内置用候选池传过来的 name。
name: BUILTIN_AGENT_META[agent_id]?.displayName ?? name ?? agent_id,
}));
step2.stopOrchestration();
const currentSnapshot = buildCurrentStep2Snapshot();
const syncedRuns = mergeActiveRun(
step2RunsRef.current,
activeStep2RunIdRef.current,
currentSnapshot,
step3Report,
);
const nextRunNumber = syncedRuns.length + 1;
const newRunId = `step2-run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const newRun: DraftStep2RunSnapshot = {
id: newRunId,
title: `第 ${nextRunNumber} 次生成结果`,
createdAt: new Date().toISOString(),
source: result.mode,
selectedAgents: normalized,
threadIds: null,
coordinatorName: null,
step2RoundtableDialogues: [],
lastLeaderContent: "",
hasConsensus: false,
consensusPercentage: 0,
budgetLimit: step2.budgetLimit,
seatStubMessages: {},
orchestrationMode: result.mode,
// chain / dag 都来自业务链条,保留来源链名;recommend 无。
chain: result.mode === "recommend" ? null : result.chain ?? null,
orchestrationPlan: result.mode === "dag" ? result.plan ?? null : null,
dagExecMode: result.mode === "dag" ? result.dagExecMode ?? "sandbox" : undefined,
step3: null,
};
setStep2Runs([...syncedRuns, newRun]);
setActiveStep2RunId(newRunId);
setStep3Report(null);
// 开新一轮第二步 → 第三步必须基于这轮重新生成(含总结/流程图)。复位「已进入第三步」
// 闸门 + 中断上一轮第三步在途三流,否则再进第三步会沿用上一轮旧结果(bug:第三步与第二步对不上)。
step3EnteredRef.current = false;
summaryFlow.abort();
reportFlow.abort();
dashboardFlow.abort();
step2.resetStep2State();
step2.setSelectedAgents(normalized);
// per-seat 模型覆盖:业务链条为某些席位指定了模型 → 写进 agentConfigs。speakerId =
// 席位序号 + 2(与 selectedAgents 索引对齐,1 号是总控),与派活时
// `agentConfigs[meta.speakerId]?.model` 的读取一致。空 / 未指定 → model:""(跟随全局),
// 同时清掉上一轮选择残留的席位模型覆盖;prompt/temp/weight 沿用既有 Persona 配置。
step2.setAgentConfigs((prev) => {
const next = { ...prev };
result.agents.forEach((a, i) => {
const speakerId = i + 2;
const base = next[speakerId] ?? { model: "", weight: 85, temp: 0.3, prompt: "" };
next[speakerId] = { ...base, model: a.model ?? "" };
});
return next;
});
step2.resetInitGate();
// 这是从第一步确认席位、开启的一轮**实时**研讨(非查看历史/草稿) → 清掉
// “查看历史”闸门,否则之前看过历史记录留下的 true 会一直把「后台挂起」按钮藏掉。
drafts.loadedFromDraftRef.current = false;
// 新一轮研讨 → 允许共识达成后再次向父页面回传。
consensusEmittedRef.current = false;
prevHasConsensusRef.current = false;
// result.mode 决定 Step 2 编排:recommend = 总控自由派活;chain = 按链条顺序派活;
// dag = 分层并行(来源链条带 stages,携带 result.plan)。
setOrchestrationMode(result.mode);
// 席位执行模式:弹窗未带(旧调用)时回退默认 pro,保证行为可预期。
setSeatMode(result.seatMode ?? DEFAULT_SEAT_MODE);
// 会商技能识别强化:取所选业务链条里**每席位**的开关 → {agentId: bool} 映射
// (recommend / 旧调用未带 → 空 {},各席位仅靠其智能体自身开关)。
setSeatSkillDirectives(
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.seat_skill_directive ?? false])),
);
setHumanValidations(
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.human_validation ?? false])),
);
// 每席位推理深度覆盖:取所选业务链条里**每席位**单独配的 seatMode → {agentId: SeatMode|null}
// 映射(recommend / 未配 → null,跟随链条级 seatMode)。
setSeatModes(
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.seatMode ?? null])),
);
// 研讨前并行取数:取所选业务链条的开关(recommend / 旧调用未带 → false)。
setGatherFirst(result.gatherFirst ?? false);
setChainMeta(result.mode === "recommend" ? null : result.chain ?? null);
setOrchestrationPlan(result.mode === "dag" ? result.plan ?? null : null);
setDagExecMode(result.mode === "dag" ? result.dagExecMode ?? "sandbox" : "sandbox");
setIsRecommendDialogOpen(false);
setCurrentStep(2);
triggerToast(
result.mode === "dag"
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」分层并行研讨`
: result.mode === "chain"
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」顺序研讨`
: "成功确认!已切换至第二阶段圆桌研讨系统",
);
},
[buildCurrentStep2Snapshot, drafts, mergeActiveRun, step2, step3Report, triggerToast],
);
// 需求 0616 #2:Step1 左栏点击某条业务链 → 仅**勾选**该链(不直接进 Step 2)。
// 复用 autoChainResult 机制:用户在第一步完成意图澄清后,点「进入多智能体研讨」时
// onEnterRoundtable 的 `if (autoChainResult)` 分支会据此跳过选链弹窗、按该链进研讨。
// 再次点击同一条链 = 取消勾选。
const handleSelectChainFromSidebar = useCallback(
async (chain: BusinessChain) => {
if (lockBusinessChain) {
triggerToast("当前页面的业务链由管理员统一配置");
return;
}
if (autoChainResult?.chain?.id === chain.id) {
setAutoChainResult(null);
triggerToast(`已取消业务链「${chain.title}」`);
return;
}
try {
const agents = await listAgents().catch(() => []);
const candidates = filterRecommendCandidates(agents);
const result = buildChainSeatSelection(chain, candidates);
if (!result) {
triggerToast("该业务链条暂无法选用(匹配到的席位不足)");
return;
}
setAutoChainResult(result);
triggerToast(`已选择业务链「${chain.title}」,完成第一步澄清后点「进入多智能体研讨」`);
} catch {
triggerToast("选择业务链失败,请重试");
}
},
[autoChainResult, lockBusinessChain, triggerToast],
);
// ─── 会商自动化串联(模块 C) ──────────────────────────────────
// 消费 prefill 后清掉 history state,避免刷新 / 后退重放自动开跑与自动选链。
// 同时按路由 path 把 prefill 持久化进 sessionStorage:history state 清掉后,刷新一次
// navigation state 就没了,靠这份持久化在挂载时恢复深链会商模式(taskId 绑定 / 业务链自动
// 选用 / 底部快捷跳转栏 / 目的树)。深链恢复仅对带 taskId 的会商有意义,故仅此时落库。
useEffect(() => {
if (prefillClearedRef.current || !prefillRef.current) return;
prefillClearedRef.current = true;
if (prefillRef.current.taskId) {
persistDeeplinkPrefill(location.pathname, prefillRef.current);
}
try {
window.history.replaceState({ ...window.history.state, usr: null }, "");
} catch {
/* noop */
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// C1.5(无界 / 8BF 回显):带存储键时,挂载即取最新草稿回显。命中 → 抑制 autoStart
// (避免重复发首条消息);未命中 → 放行 autoStart 走全新任务。只跑一次。
useEffect(() => {
// 回显聊天记录按存储键:8BF 用独立 `storageTaskId`;xdfx-A 按行动id;其它深链按真实 taskId。
const tid = draftStorageTaskId;
if (!tid) return;
// 8BF 无 taskId 模式:每次进入开全新会话,跳过回显(历史下拉仍可手动打开旧会话)。
// 仍要解除 taskRestoreResolved,别把依赖它的 autoStart 闸门永久挂起。
if (skipInitialDraftRestore) {
setTaskRestoreResolved(true);
return;
}
let cancelled = false;
void (async () => {
try {
const restored = await drafts.loadLatestByTask(tid);
if (cancelled) return;
if (restored) autoStartedRef.current = true; // 命中历史 → 不再自动发首条消息
} finally {
if (!cancelled) setTaskRestoreResolved(true);
}
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // 仅挂载时执行一次
// 深链 taskId 模式:挂载即取目的树,抽出有序层级供消息列表上方的「策划流程示例图」。
// 与任务目的弹窗同一条接口(弹窗打开时再各自取一帧,互不影响);取不到则保持空、不显示。
useEffect(() => {
const tid = prefillRef.current?.taskId;
if (!tid) return;
let cancelled = false;
void fetchTaskPurposeDetail(tid)
.then((r) => {
if (!cancelled) setPurposeLevels(derivePurposeLevels(r.tree));
})
.catch(() => {
if (!cancelled) setPurposeLevels([]);
});
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // 仅挂载时执行一次
// C2:带 autoStart 时,等 Step 1 意图线程就绪后自动把「任务名称/描述」作为首条用户消息发出,
// 触发任务理解智能体自动分析(只发一次)。
useEffect(() => {
const prefill = prefillRef.current;
if (!prefill?.autoStart || autoStartedRef.current) return;
// 带 taskId 时,等「按任务回显」决策完成再决定是否 autoStart,避免与历史回显抢跑。
if (!taskRestoreResolved) return;
if (currentStep !== 1) return;
if (!step1.intentThreadId || step1.intentReady) return;
const title = prefill.taskTitle?.trim();
const goal = prefill.taskGoal?.trim();
const isXdfx = prefill.businessCode === "7BF";
// xdfx(行动分析):除任务名称/描述外,再带上「行动名称」一起交给任务理解智能体。
const actionName = isXdfx ? prefill.actionName?.trim() : "";
// 末尾附上任务 id(taskId),供智能体识别任务;
// xdfx(行动分析)额外附上「行动id(actionId)」。
const taskId = prefill.taskId?.trim();
const actionId = isXdfx ? prefill.actionId?.trim() : "";
const text = [
title ? `任务名称:${title}` : "",
goal ? `任务描述:${goal}` : "",
actionName ? `行动名称:${actionName}` : "",
taskId ? `任务id(taskId)为${taskId}` : "",
actionId ? `行动id(actionId)为${actionId}` : "",
]
.filter(Boolean)
.join("\n");
if (!text) return;
autoStartedRef.current = true;
void step1.sendIntentMessage(text);
}, [currentStep, taskRestoreResolved, step1.intentThreadId, step1.intentReady, step1.sendIntentMessage]);
// C3:据 prefill.businessCode 查业务映射 → 取 chainId → 拉公共链 + 候选智能体 → 构造自动选链结果。
// 解析成功后「进入研讨」会跳过选链弹窗直接据此进 Step 2;解析失败(未配置 / 链不存在 / 席位不足)
// 静默回退到弹窗手选。
// 不加「已启动」永久闸门 —— StrictMode 的 mount→unmount→remount 会让首次 run 在 cleanup
// 里被 cancelled,闸门又让 remount 跳过重启,导致 autoChainResult 永远设不上(与
// useStep1Intent 同款坑)。改为:每次 setup 都重跑,靠 cancelled 丢弃过期的首次结果,
// 末次 setup 正常落地(生产无 StrictMode 只跑一次)。
useEffect(() => {
const prefill = prefillRef.current;
if (!prefill?.chainId && !prefill?.businessCode) return;
setAutoChainLoading(true);
let cancelled = false;
void (async () => {
try {
// chainId 直传(无界抽屉)优先;否则据 businessCode 查业务映射拿 chainId。
let chainId: string | null | undefined = prefill.chainId;
if (!chainId && prefill.businessCode) {
const mappings = await listBusinessMappings();
chainId = mappings.find((m) => m.businessCode === prefill.businessCode)?.chainId;
}
if (!chainId) return;
const [chain, agents] = await Promise.all([
getChain(chainId),
listAgents().catch(() => []),
]);
if (cancelled || !chain) return;
const candidates = filterRecommendCandidates(agents);
const result = buildChainSeatSelection(chain, candidates);
if (!cancelled && result) setAutoChainResult(result);
} catch {
/* 解析失败 → 保持 null,回退弹窗手选 */
} finally {
if (!cancelled) setAutoChainLoading(false);
}
})();
return () => {
cancelled = true;
};
}, []);
// ── 启动加载遮罩(深链/预填自动会话)──────────────────────────────
// 是否是「自动会话」:深链 -A、taskId、businessCode/chainId 任一存在即自动进入问答,
// 用户没有手动操作,进入页面到问答之间必须给出明确加载反馈。
const isAutoSession = Boolean(
prefillRef.current?.autoStart ||
prefillRef.current?.taskId ||
prefillRef.current?.businessCode ||
prefillRef.current?.chainId,
);
// 「问答已开始」:自动发出的首条用户消息已入列 / 正在流式 / 已得到意图结果,任一为真即认为
// 已经动起来,可以撤掉遮罩交给 Step1Panel 自身的流式占位。
const conversationStarted =
step1.isIntentSending ||
step1.intentReady != null ||
step1.interactiveMessages.some((m) => m.sender === "user");
// 遮罩展示条件:自动会话 + 仍在 Step1 + 问答还没开始 + 没有初始化报错 + 没到安全超时。
const showBootLoading =
isAutoSession &&
currentStep === 1 &&
!conversationStarted &&
!step1.intentInitError &&
!bootLoadingExpired;
// 安全超时:无论如何最多遮 30s,避免初始化卡死锁住界面(用户仍可手动操作底层页面)。
useEffect(() => {
if (!showBootLoading) return;
const timer = window.setTimeout(() => setBootLoadingExpired(true), 30_000);
return () => window.clearTimeout(timer);
}, [showBootLoading]);
/** 组装无界回传载荷:总控共识 + 各智能体最终交付(剔除总控席位)。 */
const buildWujieConsensusPayload = useCallback(
() => ({
taskTitle: prefillRef.current?.taskTitle ?? null,
chainId: prefillRef.current?.chainId ?? null,
chainTitle: chainMeta?.title ?? null,
coordinatorName: step2.coordinatorName,
consensusText: step2.lastLeaderContent,
deliverables: collectRoundtableDeliverables(
step2.step2RoundtableDialogues,
step2.coordinatorName,
),
}),
[
chainMeta,
step2.coordinatorName,
step2.lastLeaderContent,
step2.step2RoundtableDialogues,
],
);
const emitConsensusToParent = useCallback(() => {
if (!inWujieEmbed) return false;
return emitWujieEvent("roundtable:consensus", buildWujieConsensusPayload());
}, [buildWujieConsensusPayload, inWujieEmbed]);
// 让前端报错上报器能把每条报错归属到当前草稿 / 任务(无需穿进每个底层 api 调用)。
useEffect(() => {
setRoundtableErrorContext({
draftId: drafts.currentDraftId ?? undefined,
taskId: prefillRef.current?.taskId ?? undefined,
});
}, [drafts.currentDraftId]);
const handleSettingsClick = useCallback(() => {
if (inWujieEmbed) {
const deliverables = buildWujieConsensusPayload().deliverables;
if (deliverables.length === 0) {
triggerToast("暂无可回传的智能体交付结果");
return;
}
if (emitConsensusToParent()) {
triggerToast(`已回传 ${deliverables.length} 个智能体交付结果`);
}
return;
}
// 管理员:打开「会商诊断日志」页(全流程报错排查)。非管理员维持原占位提示。
if (getStoredAuth()?.system_role === "admin") {
navigate("/page/strategy/admin/roundtable-diagnostics");
return;
}
triggerToast("系统管理面板拉取中(暂不开放外部审计)");
}, [buildWujieConsensusPayload, emitConsensusToParent, inWujieEmbed, navigate, triggerToast]);
// C4(无界回传):第二步**本次 live 研讨** newly 达成共识时,把总控结论 + 各智能体交付广播给父页面。
// 草稿/任务回显(抽屉重开)已在 hydrate 时 markRestoredConsensusAsEmitted,不再重复 emit。
useEffect(() => {
const prev = prevHasConsensusRef.current;
const now = step2.hasConsensus;
prevHasConsensusRef.current = now;
if (!now || prev) return;
if (consensusEmittedRef.current) return;
if (!inWujieEmbed) return;
consensusEmittedRef.current = true;
emitConsensusToParent();
}, [step2.hasConsensus, inWujieEmbed, emitConsensusToParent]);
// ── Step3 三个生成流提升到页面层(2026-06-13)────────────────────────────
// 总结报告 / 结果绘制(经典) / 大屏多页的流式 run **不随 Step3 子视图卸载而中断**:
// 用户切回第二步、在总结/绘制/最终方案视图间往返,流都在页面层继续;
// 回头进入对应视图即可续看进行中的过程或最终结果。
const step3SeatDeliveries = useMemo(
() =>
step2.step2RoundtableDialogues
.filter((d) => d.confidence === "子智能体交付")
.map((d) => ({
sender: String(d.sender ?? ""),
content: stripReasoning(String(d.content ?? "")),
})),
[step2.step2RoundtableDialogues],
);
const handleReportSaved = useCallback((snap: DraftStep3Snapshot) => {
// **合并**而非整体替换:snap 只带 HTML 报告字段,整体替换会把已存的
// summaryReport(总结报告快照)抹掉 —— 重新绘制后总结就丢了。
setStep3Report((prev) => ({ ...(prev ?? {}), ...snap }));
setStep2Runs((prev) =>
prev.map((run) =>
run.id === activeStep2RunIdRef.current
? { ...run, step3: { ...(run.step3 ?? {}), ...snap } }
: run,
),
);
setStep3SavedTick((t) => t + 1);
}, []);
const handleSummarySaved = useCallback((snap: NonNullable<DraftStep3Snapshot["summaryReport"]>) => {
// 把总结结果合并进 step3(与 HTML 报告并存,不互相覆盖)。
setStep3Report((prev) => ({ ...(prev ?? {}), summaryReport: snap }));
setStep2Runs((prev) =>
prev.map((run) =>
run.id === activeStep2RunIdRef.current
? { ...run, step3: { ...(run.step3 ?? {}), summaryReport: snap } }
: run,
),
);
setStep3SavedTick((t) => t + 1);
}, []);
// 业务链条层级(取 stages 的「本阶段目标」goal,有序)——taskId 深链模式自动结构化输出时
// 作流程图层级骨架(任务 → 层级1 → …)。memo 稳定数组身份,避免 run useCallback 频繁失效。
const chainLevels = useMemo(
() =>
(orchestrationPlan?.stages ?? [])
.map((s) => s.goal?.trim() ?? "")
.filter((g) => g.length > 0),
[orchestrationPlan],
);
// 普通会商:Markdown 报告完成后自动续跑结构化流程图;8BF:只完成报告即结束。
// 这个开关由入口显式传入,而不是从业务链/任务状态推断,防止两类会商串行为。
const autoSummaryFlow = hasFullStep3Outputs;
const summaryFlow = useStep3Summary({
intentReady: step1.intentReady,
seatDeliveries: step3SeatDeliveries,
consensusText: step2.lastLeaderContent,
selectedModel,
coordinatorPrompt: orchestrationPlan?.coordinatorPrompt ?? null,
chainLevels,
autoFlow: autoSummaryFlow,
flowEnabled: hasFullStep3Outputs,
savedSummary: step3Report?.summaryReport ?? null,
onSummarySaved: handleSummarySaved,
ingestAvailable,
// 入库仅深链(taskId)模式(会商 rwfx-A 等)才有;taskId 入库时必传给技能。
taskId: prefillRef.current?.taskId ?? null,
// 入库场景线索:适用性判定选中的技能 + 业务码/链名,入库时引导智能体挑对入库技能。
ingestSkill,
ingestBusinessCode,
ingestChainName: chainMeta?.title ?? null,
});
// render 期镜像总结报告的实时对话(文字 + 步骤条) + stub + 入库状态,供 getStep3Snapshot 落库。
step3SummaryConvoRef.current = {
dialogues: summaryFlow.dialogues,
seatStubMessages: summaryFlow.seatStubMessages,
ingestStatus: summaryFlow.ingestStatus,
};
const reportFlow = useStep3Report({
intentReady: step1.intentReady,
seatDeliveries: step3SeatDeliveries,
consensusText: step2.lastLeaderContent,
selectedModel,
savedReport: step3Report,
onReportSaved: handleReportSaved,
});
// render 期镜像经典看板的实时对话(文字 + 步骤条) + stub,供 getStep3Snapshot 落库。
step3ReportConvoRef.current = {
dialogues: reportFlow.dialogues,
seatStubMessages: reportFlow.seatStubMessages,
};
const dashboardFlow = useStep3Dashboard({
intentReady: step1.intentReady,
seatDeliveries: step3SeatDeliveries,
consensusText: step2.lastLeaderContent,
selectedModel,
themeMode: isDark ? "dark" : "light",
savedReport: step3Report,
onReportSaved: handleReportSaved,
});
// render 期镜像大屏的实时对话(文字 + 步骤条) + stub,供 getStep3Snapshot 落库。
step3DashConvoRef.current = {
dialogues: dashboardFlow.dialogues,
seatStubMessages: dashboardFlow.seatStubMessages,
};
// 进入第三步:总结报告 + 结果绘制(经典) + 大屏多页 **三流并行**自动启动(互无依赖);
// 已有存稿则恢复展示。只在「本次会话首次进入第三步」时编排一次 —— 之后进出第三步
// 全是续看(流在页面层不中断);切换草稿 / 新建任务时复位入口闸门。
const step3EnteredRef = useRef(false);
// 进第三步「错峰起跑」定时器。三流虽互无依赖、要并行展示进度,但若**同一刻**一起
// 调 start()(各自 init thread + run/stream),会把单 worker 网关 + 单连接 sqlite
// checkpoint 锁的瞬时压力顶满,回环 /runs/stream 概率性返回非 200 → 前端冒 502。
// 这里把后两个流的**起跑**各往后挪一点点(仅错开 start_run 的写尖峰,不是串行等前一个
// 跑完),削峰即可。定时器存 ref,切草稿 / 重新 hydrate / 新建任务时统一清掉,避免迟发的
// start() 打到已被复位/中断的上下文。
const step3StartTimersRef = useRef<number[]>([]);
const clearStep3StartTimers = useCallback(() => {
for (const t of step3StartTimersRef.current) {
if (typeof window !== "undefined") window.clearTimeout(t);
}
step3StartTimersRef.current = [];
}, []);
// step3Report 用 ref 持最新值,供 hydrate 同步读取(避免闭包取到旧草稿快照)。
const step3ReportRef = useRef(step3Report);
step3ReportRef.current = step3Report;
// 切草稿即在**渲染期**同步复位入口闸门:保证随后的 hydrate effect 能重新跑一次
// (此前闸门只在 currentStep 变化时复位,切历史记录若仍停在第三步 currentStep 不变,
// 大屏/报告就留着上一条记录的数据不刷新 —— 即本次修复的 bug 根因)。
const prevDraftIdRef = useRef(drafts.currentDraftId);
if (prevDraftIdRef.current !== drafts.currentDraftId) {
const wasRealDraft = prevDraftIdRef.current != null;
prevDraftIdRef.current = drafts.currentDraftId;
// 仅「真正切到另一份草稿」才复位入口闸门重新 hydrate。草稿**首次创建**(null→id,
// 多由本会话第一次自动保存触发)不算切换——若这时复位,正在并行跑的 Step3 三流(尤其
// 大屏)会被下方 hydrate 当成「未启动」重新 start(),既丢了在途产物又反复重画。
if (wasRealDraft) step3EnteredRef.current = false;
}
// 三流 hydrate/start(按当前草稿快照恢复或新建)。进第三步、切草稿后停留第三步都复用它,
// 保证总结/经典/大屏的展示数据跟随当前草稿实时切换。
const hydrateStep3Flows = useCallback(() => {
step3EnteredRef.current = true;
// 重新编排前先清掉上一轮可能还没触发的错峰定时器(切草稿重 hydrate 时)。
clearStep3StartTimers();
const rep = step3ReportRef.current;
// 错峰起跑助手:把一个尚未起跑的流延迟 delayMs 后再 start();触发前再校验
// step3EnteredRef(被新建任务 / 切草稿复位为 false 则跳过),避免迟发的 start()
// 打到已被中断的上下文。delay=0 表示立即(同步)起跑。
const staggerStart = (start: () => void, delayMs: number) => {
if (delayMs <= 0 || typeof window === "undefined") {
start();
return;
}
const id = window.setTimeout(() => {
if (!step3EnteredRef.current) return;
start();
}, delayMs);
step3StartTimersRef.current.push(id);
};
// ① 方案总结报告(主页,立即起跑)
const savedSum = rep?.summaryReport;
if (savedSum && (savedSum.md.trim() || (savedSum.closing ?? "").trim())) {
summaryFlow.hydrateSaved(savedSum);
} else {
summaryFlow.start();
}
if (hasFullStep3Outputs) {
// ② 结果绘制(经典模式一)。旧版草稿可能把大屏 HTML 存在 html 槽位(带 marker),
// 那不是经典产物 → 经典照常启动。错峰 ~300ms,削掉与总结的同刻 start 尖峰。
if (rep?.html && !isDashboardHtml(rep.html)) {
reportFlow.hydrateSaved(rep);
} else {
staggerStart(() => reportFlow.start(), STEP3_STAGGER_MS); // 仍并行绘制,只是起跑错开
}
// ③ 大屏多页(模式二):优先 dashboardJson(按当前主题渲染);旧版 marker html 兜底。
// 带上大屏生成过程的完整对话(文字 + 步骤条),恢复时整段回显。错峰 ~600ms。
const dashSaved = {
dialogues: rep?.dashboardDialogues,
seatStubMessages: rep?.dashboardSeatStubMessages,
};
if (rep?.dashboardJson) {
dashboardFlow.hydrateFromJson(rep.dashboardJson, dashSaved);
} else if (rep?.html && isDashboardHtml(rep.html)) {
dashboardFlow.hydrateSaved(rep.html, dashSaved);
} else {
staggerStart(() => dashboardFlow.start(), STEP3_STAGGER_MS * 2);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [summaryFlow, reportFlow, dashboardFlow, clearStep3StartTimers, hasFullStep3Outputs]);
// 切换草稿:先停掉旧草稿的在途 Step3 流(防串台)。声明在 hydrate effect **之前**,
// 保证同一提交内先 abort 旧流、再由下方 effect hydrate 新草稿,顺序不颠倒。
// **仅在真正切到另一份草稿时中断**——草稿首次创建(null→id)不是切换,那时三流可能正
// 跑着(尤其大屏绘制),误 abort 会让产物没存上、随后还被重新 hydrate 重画。
const abortPrevDraftIdRef = useRef(drafts.currentDraftId);
useEffect(() => {
const prev = abortPrevDraftIdRef.current;
abortPrevDraftIdRef.current = drafts.currentDraftId;
if (prev && drafts.currentDraftId && prev !== drafts.currentDraftId) {
clearStep3StartTimers(); // 切草稿:取消尚未触发的错峰 start,防打到新草稿上下文
summaryFlow.abort();
reportFlow.abort();
dashboardFlow.abort();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [drafts.currentDraftId]);
// 进第三步 / 切草稿后仍停留第三步:按当前草稿快照恢复或新建三流(闸门已在渲染期复位)。
useEffect(() => {
if (currentStep !== 3 || step3EnteredRef.current) return;
hydrateStep3Flows();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentStep, drafts.currentDraftId]);
// ── 「查看=接管回前端」(2026-06-13):查看运行中的后台作业 → 接管续跑 ──
// 取消后端作业 → 加载作业最近写回草稿的快照(含作业真实线程 + 完整对话)→ 解除
// 「看历史」只读闸门 → 由前端在那些线程上**继续实时流式编排**(leader 自由派活续轮)。
// 这样「后台挂起 → 查看」会把会商真正搬回前端,按钮/暂停/干预/再挂起全部回归,而不是
// 停在只读跟随的后台态。
const jobFollowUnsubRef = useRef<(() => void) | null>(null);
const stopJobFollow = useCallback(() => {
jobFollowUnsubRef.current?.();
jobFollowUnsubRef.current = null;
}, []);
const takeOverRunningJob = useCallback(
async (jobId: string, draftId: string) => {
stopJobFollow();
step2.stopOrchestration();
// 1. 取消后端作业:避免前后端双跑/抢同一线程(409),线程随后由前端接管续跑。
// executor.cancel 会 task.cancel() 中断在跑的 run,DB 同步置 cancelled。
await cancelJob(jobId, draftStorageTaskId).catch(() => null);
// 2. 加载作业最近写回草稿的快照:恢复 threadIds(作业真实线程)+ 协调名 + 完整对话。
// hydrateFromDraft 已同步写好 threadIds/coordinatorName 的 ref,供下一步接管即时读取。
await drafts.handleLoadDraft(draftId);
setCurrentStep(2); // 覆盖 hydrate 可能切到的 furthestStep,停在第二步继续研讨
// 3. 关掉「看历史」只读闸门 → 后台挂起/暂停/干预按钮回归,回到前端可交互态。
drafts.loadedFromDraftRef.current = false;
// 4. 前端接管:在作业线程上继续实时流式编排(无线程则回退为只读查看,不再续跑)。
step2.resumeLiveTakeover();
void drafts.refresh();
},
[stopJobFollow, step2, drafts, setCurrentStep],
);
// 卸载兜底:离开页面停止跟随(后台作业本身继续跑)。
useEffect(() => stopJobFollow, [stopJobFollow]);
// 把页面重置回「第一步全新任务」——新建任务 + 后台挂起后都复用。
// 注意:只清前端状态,不删后端已建的草稿 / 已挂起的后台作业(它们继续在后台跑,
// 在历史记录里可见)。
const resetToStep1 = useCallback(() => {
step2.stopOrchestration();
step2.resetStep2State();
setStep2Runs([]);
setActiveStep2RunId(null);
setOrchestrationMode("recommend");
setChainMeta(null);
setOrchestrationPlan(null);
setDagExecMode("sandbox");
setStep3Report(null);
// 停掉页面层的 Step3 三个生成流(新任务不该带着旧任务的流跑)+ 复位进入闸门,
// 并停止后台作业实时跟随(作业本身继续在后台跑)。
clearStep3StartTimers(); // 取消尚未触发的错峰 start
summaryFlow.abort();
reportFlow.abort();
dashboardFlow.abort();
stopJobFollow();
step3EnteredRef.current = false;
step1.stopIntentStream();
drafts.loadedFromDraftRef.current = false;
drafts.setCurrentDraftId(null);
// 重置后新一轮共识仍需回传父页面。
consensusEmittedRef.current = false;
prevHasConsensusRef.current = false;
setCurrentStep(1);
// 同步触发 Step 1 init,而不是依赖 useEffect —— 已经在 Step 1 时
// currentStep 不变,useEffect 不会 re-fire。
step1.runStep1Init();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [drafts, step1, step2]);
const handleStartNewTask = useCallback(() => {
resetToStep1();
triggerToast("已开始新任务,请在第一步与任务理解智能体澄清需求");
}, [resetToStep1, triggerToast]);
// 深链接(taskId)模式专用的「重新分析」:清空第一步会话、保留当前任务(prefill 不动),并复位
// autoStarted 闸门,让 C2 自动把「任务名称/描述」重新作为首条消息发出,对同一任务重做意图分析。
// 与「新建任务」(全新空白任务) 区分——深链接下任务是固定的,重来=重新分析这条任务。
const handleReanalyze = useCallback(() => {
autoStartedRef.current = false;
resetToStep1();
triggerToast("已重新分析当前任务");
}, [resetToStep1, triggerToast]);
// 无界抽屉保活复用:父页面重开抽屉时 `bus.$emit('roundtable:reset')` → 子应用回到第一步。
// 非无界环境下 onWujieEvent 返回 no-op,安全无副作用。
useEffect(() => {
return onWujieEvent("roundtable:reset", () => {
resetToStep1();
});
}, [resetToStep1]);
// 「挂起中」本地标记:点「后台挂起」后立刻跳转,建作业是 fire-and-forget——从点击到作业
// 真正建好的窗口里,用它让历史记录显示「挂起中」(作业建好后转 queued/running,由后端状态接管)。
// resetToStep1 不卸载本页,故该 state 跨「跳转」存活。
const [pendingSuspendIds, setPendingSuspendIds] = useState<Set<string>>(() => new Set());
// 整片脱敏:顶部页头(步骤导航 / 历史记录 / 标题等)的所有文本。
const headerDzRef = useDesensitizeSubtree<HTMLElement>();
const markPendingSuspend = useCallback((draftId: string) => {
setPendingSuspendIds((prev) => {
const next = new Set(prev);
next.add(draftId);
return next;
});
}, []);
const clearPendingSuspend = useCallback((draftId: string) => {
setPendingSuspendIds((prev) => {
if (!prev.has(draftId)) return prev;
const next = new Set(prev);
next.delete(draftId);
return next;
});
}, []);
// 「后台挂起」核心(手动按钮 / 离开页面自动挂起共用):幂等保证草稿存在 →
// 同草稿已有在跑作业则跳过 → 启动后台作业。后端另有「同草稿未终态作业幂等返回」
// 兜底(覆盖跨标签页 / beforeunload 与本函数并发触发),绝不重复建作业。
// 返回本次后台作业的 jobId(已在跑则返回既有作业 id),供「完成时提示」监听;
// 未发起(无席位)返回 null。
const startBackgroundJob = useCallback(async (): Promise<string | null> => {
const agents = step2.selectedAgents.map((a) => ({ agentId: a.agent_id, name: a.name }));
if (agents.length === 0) return null;
// 后台挂起发起前**立刻强制存一次**当前聊天(保住发起时刻的本地研讨记录,防丢)。
const draftId = await drafts.saveDraftNow(2);
// 后台作业按聊天记录存储键归属(xdfx-A=行动id):报告写回对应 task-draft 存储、去重一致。
const tid = draftStorageTaskId;
// 防重复:该草稿已有在跑作业就不再新建(避免重复作业 / 前后端双跑)。
const existing = draftId ? await getJobByDraft(draftId, tid).catch(() => null) : null;
const alreadyRunning =
existing &&
(existing.status === "running" ||
existing.status === "awaiting_input" ||
existing.status === "queued");
if (alreadyRunning) {
return existing?.id ?? null;
}
const job = await startJob({
draftId: draftId ?? undefined,
taskId: tid ?? undefined, // task 作业:报告写回独立 task-draft 存储、跨用户共享
intent: buildInitialIntent(),
agents,
model: selectedModel || undefined, // 模型沿用第二步选择
seatMode, // 席位执行模式沿用第二步选择(后台续跑同样按此模式跑席位)
seatSkillDirectives, // 每席位技能识别强化沿用所选业务链条里各席位的开关
seatModes, // 每席位推理深度覆盖沿用所选业务链条里各席位的配置
gatherFirst, // 研讨前并行取数沿用所选业务链条的开关
businessCode: prefillRef.current?.businessCode ?? undefined, // 深链接业务码 → 后台总结业务链完整性核对
// 后台作业引擎支持 dag(后端 _run_dag:stage 串行 / stage 内并行)——
// 直接把当前编排模式透传,业务链的分层 / 并行 / 阶段目标 / 总控提示词全部保留。
orchestrationMode,
chain: chainMeta,
// dag 模式:把整份分层计划带给后端(含 stages / 阶段目标 / 总控提示词 / finalSynthesis)。
// 非 dag 时为 null(后端按 mode 走 chain/recommend)。
orchestrationPlan: orchestrationMode === "dag" ? orchestrationPlan : null,
// 不传 threadIds:后台作业由真网关自建全新线程,绝不复用前端本地研讨的线程
// (那些线程可能有活跃 run,复用会撞 409)。
});
return job.id;
}, [
step2,
drafts,
selectedModel,
seatMode,
seatSkillDirectives,
seatModes,
gatherFirst,
orchestrationMode,
orchestrationPlan,
chainMeta,
buildInitialIntent,
]);
// 「后台挂起」按钮(2026-06-16 改「直接跳转」):点击后**立刻**跳回第一步并提示,挂起动作
// (存稿 → 去重 → 建后台作业)改为 fire-and-forget 在后台完成,不再等接口返回才跳转。
// 历史记录在作业真正建好前显示「挂起中」(pendingSuspendIds),建好后由后端状态(queued→
// running)接管。⚠️ resetToStep1 会清空 step2 等 live 状态,故挂起入参 + step2 快照必须在
// 跳转前同步冻结(getStep2SnapshotWithRuns 返回的是不可变快照对象,reset 替换 state 不影响它)。
const handleBackgroundSuspend = useCallback(() => {
const selected = step2.selectedAgents;
if (selected.length === 0) {
triggerToast("请先选择研讨席位再后台挂起");
return;
}
// —— 跳转前同步冻结所有需要的输入(reset 之后这些 live 状态都会被清空)——
const step2Snapshot = getStep2SnapshotWithRuns();
const agents = selected.map((a) => ({ agentId: a.agent_id, name: a.name }));
const intent = buildInitialIntent();
const model = selectedModel || undefined;
const seatModeSnap = seatMode;
const seatSkillDirectivesSnap = seatSkillDirectives;
const seatModesSnap = seatModes;
const gatherFirstSnap = gatherFirst;
const mode = orchestrationMode;
const chainSnap = chainMeta;
const planSnap = mode === "dag" ? orchestrationPlan : null;
const draftId = drafts.currentDraftId;
// 后台作业按聊天记录存储键归属(xdfx-A=行动id),与草稿存储一致。
const tid = draftStorageTaskId;
// 立刻:标记「挂起中」+ 跳回第一步 + 提示(不等接口)。
if (draftId) markPendingSuspend(draftId);
resetToStep1();
triggerToast("已转入后台,任务会自动跑完研讨、总结报告与结果绘制;可在「历史记录」查看进度");
// 后台 fire-and-forget:用冻结快照存稿 → 去重 → 建作业 → 注册完成通知。失败只提示、不挡跳转。
void (async () => {
let watchId: string | null = null;
try {
const savedId = (await drafts.saveStep2SnapshotNow(step2Snapshot, 2)) ?? draftId ?? null;
// 防重复:该草稿已有未终态作业就不再新建(同 startBackgroundJob 的客户端去重,
// 后端另有「同草稿未终态作业幂等返回」兜底)。
const existing = savedId ? await getJobByDraft(savedId, tid).catch(() => null) : null;
const alreadyRunning =
existing &&
(existing.status === "running" ||
existing.status === "awaiting_input" ||
existing.status === "queued");
if (alreadyRunning) {
watchId = existing?.id ?? null;
} else {
const job = await startJob({
draftId: savedId ?? undefined,
taskId: tid ?? undefined,
intent,
agents,
model,
seatMode: seatModeSnap,
seatSkillDirectives: seatSkillDirectivesSnap,
seatModes: seatModesSnap,
gatherFirst: gatherFirstSnap,
businessCode: prefillRef.current?.businessCode ?? undefined,
orchestrationMode: mode,
chain: chainSnap,
orchestrationPlan: planSnap,
});
watchId = job.id;
}
} catch (err) {
triggerToast(`后台挂起失败:${(err as Error).message}`);
} finally {
// 注册到全工作区通知器,作业完成时**跨页**弹「达成共识同款」提示。
if (watchId) watchJob(watchId);
// 清「挂起中」本地标记:此后历史记录的状态由后端作业(queued→running)权威接管。
if (draftId) clearPendingSuspend(draftId);
void drafts.refresh();
}
})();
}, [
step2,
drafts,
getStep2SnapshotWithRuns,
buildInitialIntent,
selectedModel,
seatMode,
seatSkillDirectives,
seatModes,
gatherFirst,
orchestrationMode,
orchestrationPlan,
chainMeta,
resetToStep1,
triggerToast,
watchJob,
markPendingSuspend,
clearPendingSuspend,
]);
// ── 自动后台挂起:研讨进行中离开本页面(路由卸载)或刷新 / 关标签页时,任务自动转后台 ──
// 最新状态进 ref:卸载 cleanup 与 beforeunload 都是「拍快照时刻」的同步回调,
// 不能被旧渲染的闭包钉死。
const autoSuspendRef = useRef<{ running: boolean; fire: () => void; beacon: () => void }>({
running: false,
fire: () => {},
beacon: () => {},
});
useEffect(() => {
autoSuspendRef.current = {
// 只认 isOrchestrating(本地编排循环**真正在生成中**的锁)——
// isRoundTableRunning 是「会商进行」的 UI 开关,查看聊天记录(加载草稿 hydrate)
// 后它可能为 true,曾导致看历史时切页/刷新被误触发后台挂起、从头重跑一单。
running: step2.isOrchestrating,
// 路由卸载用:可走完整异步链(ensureDraft → 去重 → startJob),fetch 卸载后照常完成。
fire: () => {
void startBackgroundJob().catch(() => {});
},
// beforeunload 用:无法 await —— 用 keepalive fetch 同步发出(浏览器保证发完)。
// draftId 取当前已存在的草稿(研讨启动时已 ensureDraft,见下方 effect)。
beacon: () => {
const agents = step2.selectedAgents.map((a) => ({ agentId: a.agent_id, name: a.name }));
if (agents.length === 0) return;
startJobKeepalive({
draftId: drafts.currentDraftId ?? undefined,
taskId: draftStorageTaskId ?? undefined,
intent: buildInitialIntent(),
agents,
model: selectedModel || undefined,
seatMode,
seatSkillDirectives,
seatModes,
gatherFirst,
businessCode: prefillRef.current?.businessCode ?? undefined,
orchestrationMode,
chain: chainMeta,
orchestrationPlan: orchestrationMode === "dag" ? orchestrationPlan : null,
});
},
};
});
// 研讨一启动(真正进入生成)就确保草稿存在:自动挂起 / beforeunload beacon 需要
// draftId 同步可取,历史下拉的「进行中」徽标也按 draftId 关联。ensureDraft 幂等。
useEffect(() => {
if (step2.isOrchestrating) void drafts.ensureDraft(2);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [step2.isOrchestrating]);
// 路由卸载(切到其它页面):正在研讨 → 自动转后台挂起。
useEffect(
() => () => {
const snap = autoSuspendRef.current;
if (snap.running) snap.fire();
},
[],
);
// 刷新 / 关标签页:keepalive 兜底。后端幂等闸门保证与其它触发源并发也不重复建作业。
useEffect(() => {
const handler = () => {
const snap = autoSuspendRef.current;
if (snap.running) snap.beacon();
};
window.addEventListener("beforeunload", handler);
return () => window.removeEventListener("beforeunload", handler);
}, []);
// 本地 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]);
// 独立业务页可只替换 Step 1 的外观;这里将通用状态/动作收敛为一份受控 props,
// 避免它们复制或分叉意图识别、附件上传、澄清和进入研讨的业务逻辑。
const step1PanelProps: Step1PanelProps = {
interactiveMessages: step1.interactiveMessages,
intentThreadId: step1.intentThreadId,
intentReady: step1.intentReady,
isIntentSending: step1.isIntentSending,
pendingIntentClarificationMsgId: step1.pendingIntentClarificationMsgId,
intentClarificationSelections: step1.intentClarificationSelections,
setIntentClarificationSelections: step1.setIntentClarificationSelections,
onSendMessage: (text, files) => void step1.sendIntentMessage(text, files),
onStopIntent: step1.stopIntentStream,
onSkipQuestion: handleSkipQuestion,
onFollowUp: handleAgentFollowUp,
// 多智能体会商页去掉「继续追问」「跳过此项」快捷键 —— 干预走输入框直接发送即可。
hideFollowupActions: true,
onEnterRoundtable: () => {
if (!step1.intentReady) {
triggerToast("请先与任务理解智能体完成澄清,生成任务摘要后再进入");
return;
}
// 会商自动化串联(模块 C):若任务页带来的业务链已解析成功,跳过选链弹窗,
// 直接据该业务链进入 Step 2 研讨(用户无需再手选)。
if (autoChainResult) {
const result = autoChainResult;
void drafts.ensureDraft(1).finally(() => handleConfirmAgents(result));
return;
}
if (lockBusinessChain) {
triggerToast(
autoChainLoading || lockedChainResolution === "loading"
? "正在加载管理员配置的业务链,请稍候…"
: lockedChainResolution === "unavailable"
? lockedChainUnavailableReason ?? "已配置的业务链暂不可用,请确认至少保留 2 个可用智能体后重试"
: "管理员尚未配置可用的业务链,请联系管理员处理",
);
return;
}
if (
inWujieEmbed &&
autoChainLoading &&
(prefillRef.current?.chainId || prefillRef.current?.businessCode)
) {
triggerToast("正在加载业务链条,请稍候…");
return;
}
// 先把草稿落地拿到 draft_id,推荐历史才有归属;失败也照常打开弹窗
// (弹窗在无 draftId 时退化为「直接推荐、不存历史」)。
void drafts.ensureDraft(1).finally(() => setIsRecommendDialogOpen(true));
},
onManualSave: drafts.handleManualSave,
onTriggerToast: triggerToast,
submitIntentClarifications: step1.submitIntentClarifications,
};
// 定制 chrome 仅服务第一阶段;第二、三阶段继续保留原有步骤导航与操作,
// 避免独立业务页为了复刻第一步视觉而收窄后续流程的可达性。
const useCustomStep1Chrome = currentStep === 1 && Boolean(headerLeftSlot);
// ─── Render ──────────────────────────────────────────────
return (
<div
data-roundtable-step={currentStep}
className={cn(
"roundtable-planning theme-transition relative flex h-full min-h-0 flex-col bg-[#fef6f6] font-sans text-slate-800 selection:bg-red-200",
isDark && "roundtable-planning--dark",
rootClassName,
)}
>
{/* 启动加载遮罩:深链/预填自动会话从进入页面到问答真正开始(建意图线程 / 回显历史草稿)
期间全屏覆盖,避免线程创建慢时页面像卡住。问答一旦开始或超时即撤掉。 */}
{showBootLoading && (
<div
className={cn(
"absolute inset-0 z-50 flex items-center justify-center",
isDark ? "bg-[#061b3b]" : "bg-white",
)}
role="status"
aria-live="polite"
>
<div className="flex flex-col items-center gap-7 px-8">
<div className="flex flex-col items-center gap-2 text-center">
<p className={cn(
"text-lg font-semibold tracking-wide",
isDark ? "text-[#e7f0ff]" : "text-slate-800",
)}>
正在准备多智能体会商
</p>
<p className={cn("text-sm", isDark ? "text-[#8aa0c4]" : "text-slate-400")}>
正在初始化任务理解智能体,请稍候…
</p>
</div>
<span className="inline-flex items-center gap-1.5">
<span className="h-2 w-2 animate-bounce rounded-full bg-red-400 [animation-delay:-0.3s]" />
<span className="h-2 w-2 animate-bounce rounded-full bg-red-400 [animation-delay:-0.15s]" />
<span className="h-2 w-2 animate-bounce rounded-full bg-red-400" />
</span>
</div>
</div>
)}
<RecommendAgentsDialog
open={isRecommendDialogOpen}
intent={step1.intentReady}
model={selectedModel || undefined}
draftId={drafts.currentDraftId}
onCancel={() => setIsRecommendDialogOpen(false)}
onConfirm={handleConfirmAgents}
/>
<BusinessChainListDialog
open={isChainListOpen}
onOpenChange={setIsChainListOpen}
onConfigure={(chainId) => {
setIsChainListOpen(false);
navigate(
chainId
? `/page/workspace/roundtable/chains?chainId=${encodeURIComponent(chainId)}`
: "/page/workspace/roundtable/chains",
);
}}
/>
{/* 导入会商弹窗:输入分享码 → 复制副本 → 加载到当前页面继续研讨 */}
<ImportRoundtableDraftDialog
open={isImportOpen}
onOpenChange={setIsImportOpen}
onImported={(draftId) => {
void drafts.refresh();
if (draftId) drafts.handleLoadDraft(draftId);
}}
/>
{/* 任务目的弹窗(深链 taskId 模式:查看线上当前策划进度/目的树,只读) */}
{prefillRef.current?.taskId && (
<TaskPurposeDialog
taskId={prefillRef.current.taskId}
open={isTaskPurposeOpen}
onOpenChange={setIsTaskPurposeOpen}
/>
)}
{/* 派活链路流程图弹窗(订阅进行中作业的真实 SSE 进度) */}
<DispatchChainJobModal
jobId={chainModalJobId}
taskId={draftStorageTaskId ?? null}
open={chainModalJobId !== null}
onOpenChange={(o) => {
if (!o) setChainModalJobId(null);
}}
onView={(job) => {
// 「查看」(2026-06-13 接管语义):done → 加载草稿(含 step3)看报告;
// **运行中/待澄清 → 接管回前端**:取消后端作业、加载聊天记录、解除只读,
// 由前端在作业线程上继续实时流式编排(不再是只读跟随后台)。
setChainModalJobId(null);
if (!job.draftId) return;
if (job.status === "running" || job.status === "awaiting_input") {
void takeOverRunningJob(job.id, job.draftId);
return;
}
void drafts.handleLoadDraft(job.draftId);
}}
/>
{taskArtifactSubmission && (
<AnalysisResultDetailDialog
item={seatDeliverable}
onOpenChange={(open) => {
if (!open) setSeatDeliverable(null);
}}
/>
)}
{showToast && (
<div className="fixed top-4 left-1/2 transform -translate-x-1/2 z-50 bg-primary text-white text-xs px-4 py-2.5 rounded-xl shadow-lg border border-primary/40 font-medium flex items-center gap-2 animate-bounce">
<Sparkles className="h-4 w-4 shrink-0" />
<span>{showToast}</span>
</div>
)}
{/* HEADER */}
<header ref={headerDzRef} className="relative z-[40] flex shrink-0 items-center justify-between gap-4 border-b border-slate-100 bg-white px-6 py-3 shadow-[0_1px_3px_rgba(0,0,0,0.02)] dark:border-border dark:bg-card dark:shadow-none">
{useCustomStep1Chrome ? headerLeftSlot : (
<StepNavigation
currentStep={currentStep}
intentReady={step1.intentReady}
hasConsensus={step2.hasConsensus}
onStepClick={(s) => setCurrentStep(s)}
triggerToast={triggerToast}
/>
)}
<div className="flex items-center gap-2">
{toolbarSlot}
{/* 深链 taskId 模式:查看线上当前策划进度(目的树)。与单智能体闸门同一条接口。 */}
{prefillRef.current?.taskId && (
<button
id="task-purpose-btn"
onClick={() => setIsTaskPurposeOpen(true)}
title="查看该任务在线上的当前策划进度(目的树)"
className="bg-white hover:bg-slate-50 border border-[#e2e8f0] text-[#334155] text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition dark:border-border dark:bg-secondary dark:text-foreground dark:hover:bg-accent"
>
<Layers className="w-3.5 h-3.5 text-primary" />
任务目的
</button>
)}
{/* 深链接(taskId)模式:业务链由 businessCode 自动决定,隐藏手动「业务链条」入口。 */}
{!lockBusinessChain && !inWujieEmbed && !prefillRef.current?.taskId && (
<button
id="business-chain-btn"
onClick={() => setIsChainListOpen(true)}
title="查看 / 配置可复用的业务链条(有序智能体编排)"
className="bg-white hover:bg-slate-50 border border-[#e2e8f0] text-[#334155] text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition dark:border-border dark:bg-secondary dark:text-foreground dark:hover:bg-accent"
>
<ListOrdered className="w-3.5 h-3.5 text-primary" />
业务链条
</button>
)}
{/* 8BF:第二步「人工干预」开关。开启后第二步每走一步暂停,等待用户输入 /
恢复后继续;关闭则自动推进(与原行为一致)。仅独立业务页传入受控回调时渲染。 */}
{onStep2InterventionChange && (
<label
id="step2-intervention-toggle"
title="开启后:第二步每完成一步暂停,可在下方输入修改意见或点击“恢复会商”继续;关闭后:自动完成整个研讨"
className="bg-white hover:bg-slate-50 border border-[#e2e8f0] text-[#334155] text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-2 transition cursor-pointer select-none dark:border-border dark:bg-secondary dark:text-foreground dark:hover:bg-accent"
>
<Switch
checked={step2InterventionEnabled ?? false}
onCheckedChange={onStep2InterventionChange}
className="scale-90"
/>
人工干预
</label>
)}
{/* 深链接(taskId)模式:任务固定,把「新建任务」换成「重新分析」——清空会话、对同一任务重做意图分析。 */}
{prefillRef.current?.taskId ? (
<button
id="reanalyze-task-btn"
onClick={handleReanalyze}
title="清空当前会话,对当前任务重新做意图分析"
className="bg-emerald-600 text-white hover:bg-emerald-700 text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition-all shadow-sm shadow-emerald-500/10 active:scale-95"
>
<RotateCw className="w-3.5 h-3.5" />
重新分析
</button>
) : (
<button
id="new-task-btn"
onClick={handleStartNewTask}
title="清空当前会话,从第一步开始一个全新任务"
className="bg-emerald-600 text-white hover:bg-emerald-700 text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition-all shadow-sm shadow-emerald-500/10 active:scale-95"
>
<Sparkles className="w-3.5 h-3.5" />
{useCustomStep1Chrome ? (newTaskLabel ?? "新建任务") : "新建任务"}
</button>
)}
{(!hideHeaderSaveDraft || !useCustomStep1Chrome) && (
<button
id="save-draft-header-btn"
onClick={drafts.handleManualSave}
className="bg-white hover:bg-slate-50 border border-[#e2e8f0] text-[#334155] text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition dark:border-border dark:bg-secondary dark:text-foreground dark:hover:bg-accent"
>
<Save className="w-3.5 h-3.5 text-slate-500" />
保存草稿
</button>
)}
{/* 「导入会商」按钮先隐藏(保留代码 + 弹窗逻辑,便于以后恢复)。 */}
{false && (
<button
id="import-roundtable-btn"
onClick={() => setIsImportOpen(true)}
title="输入分享码,把别人分享的会商复制到我的账号"
className="bg-white hover:bg-slate-50 border border-[#e2e8f0] text-[#334155] text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition dark:border-border dark:bg-secondary dark:text-foreground dark:hover:bg-accent"
>
<Download className="w-3.5 h-3.5 text-slate-500" />
导入会商
</button>
)}
<HistoryDropdown
innerRef={drafts.historyDropdownRef}
isDark={isDark}
isOpen={drafts.isHistoryOpen}
setIsOpen={drafts.setIsHistoryOpen}
drafts={drafts.drafts}
currentDraftId={drafts.currentDraftId}
pendingSuspendIds={pendingSuspendIds}
renamingDraftId={drafts.renamingDraftId}
renameDraftValue={drafts.renameDraftValue}
setRenameDraftValue={drafts.setRenameDraftValue}
onLoad={drafts.handleLoadDraft}
onOpen={() => void drafts.refresh()}
onOpenJob={(jobId) => {
drafts.setIsHistoryOpen(false);
setChainModalJobId(jobId);
}}
onDelete={drafts.handleDeleteDraft}
onStartRename={drafts.handleStartRename}
onCommitRename={drafts.handleCommitRename}
onCancelRename={drafts.handleCancelRename}
/>
{useCustomStep1Chrome && headerActionAfterHistory}
{(!hideHeaderSettings || !useCustomStep1Chrome) && <div className="h-6 w-[1px] bg-slate-200 mx-1" />}
{(!hideHeaderSettings || !useCustomStep1Chrome) && (
<button
id="settings-btn"
onClick={handleSettingsClick}
title={
inWujieEmbed
? "回传各智能体交付结果给宿主"
: getStoredAuth()?.system_role === "admin"
? "会商诊断日志"
: "系统设置"
}
className="p-1.5 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 transition-colors dark:text-muted-foreground dark:hover:bg-accent dark:hover:text-foreground"
>
<Settings className="w-4 h-4" />
</button>
)}
{compactChrome && (
<>
<ThemeSwitcher tone="content" />
<LayoutModeSwitcher tone="content" />
</>
)}
</div>
</header>
{/* MAIN */}
<Step2SandboxSidebarSync
currentStep={currentStep}
sidebarExpanded={step2SidebarExpanded}
setSidebarExpanded={setStep2SidebarExpanded}
/>
<main
data-step2-sidebar-expanded={
currentStep === 2 || currentStep === 3 ? String(step2SidebarExpanded) : undefined
}
className="relative z-0 flex-1 overflow-hidden p-4 flex gap-4 min-h-0"
>
{/* LEFT SIDEBAR */}
<LeftSidebar
currentStep={currentStep}
roles={roles}
agentNameToRole={step2.agentNameToRole}
budgetLimit={step2.budgetLimit}
intentReady={step1.intentReady}
sidebarExpanded={step2SidebarExpanded}
setSidebarExpanded={setStep2SidebarExpanded}
step2Runs={step2Runs}
activeStep2RunId={activeStep2RunId}
onSelectStep2Run={handleSelectStep2Run}
seatFilter={seatFilter}
setSeatFilter={setSeatFilter}
selectedChainId={autoChainResult?.chain?.id ?? null}
onSelectChain={handleSelectChainFromSidebar}
onOpenDraft={drafts.handleLoadDraft}
activeDraftId={drafts.currentDraftId}
entryRailTaskId={entryRailTaskId ?? recordTaskIdOf(prefillRef.current)}
historyTaskId={draftStorageTaskId}
entryRailBusinessCode={prefillRef.current?.businessCode ?? null}
lockedChainId={lockedChainId}
lockBusinessChain={lockBusinessChain}
entryRailBusinessChainSlot={entryRailBusinessChainSlot}
entryRailTaskCardSlot={entryRailTaskCardSlot}
renderStep1LeftSidebar={renderStep1LeftSidebarWithDeliveries}
renderStep2LeftSidebarHeader={renderStep2LeftSidebarHeader}
/>
{/* MIDDLE VIEWPORT */}
<section
id="middle-viewport"
className="flex-1 flex flex-col min-w-0 bg-white border border-slate-200/50 rounded-2xl shadow-[0_4px_16px_rgba(0,0,0,0.015)] overflow-hidden"
>
{currentStep === 1 && (
renderStep1 ? renderStep1({
...step1PanelProps,
selectedModel,
modelOptions: availableModels.map((model) => ({ label: model.name, value: model.name })),
onSelectedModelChange: setSelectedModel,
step2Dialogues: step2.step2RoundtableDialogues,
step2ThreadIds: step2.threadIds,
step2CoordinatorName: step2.coordinatorName,
step2SeatStubMessages: step2.seatStubMessages,
step3Summary: step3Report?.summaryReport ?? null,
}) : <Step1Panel
{...step1PanelProps}
headerLeftSlot={
// 「原任务已有结果」(目的树预览)只在 rwfx-A(6BF)模式显示;xdfx/3qfx 不显示。
prefillRef.current?.taskId &&
prefillRef.current?.businessCode === "6BF" &&
purposeLevels.length > 0 ? (
<PurposeFlowPreview
levels={purposeLevels}
onOpen={() => setIsTaskPurposeOpen(true)}
dark={isDark}
/>
) : undefined
}
/>
)}
{currentStep === 2 && (
<Step2Panel
useStep1InputAppearance={rootClassName?.includes("eightbf-roundtable") ?? false}
headerTitle={step2HeaderTitle}
headerRightSlot={step2HeaderRightSlot}
step2RoundtableDialogues={step2.step2RoundtableDialogues}
isInitializing={step2.isInitializing}
isRoundTableRunning={step2.isRoundTableRunning}
isOrchestrating={step2.isOrchestrating}
pendingClarification={step2.pendingClarification}
clarificationDraft={step2.clarificationDraft}
customAgentInput={step2.customAgentInput}
hasConsensus={step2.hasConsensus}
agentConfigs={step2.agentConfigs}
selectedAgentId={step2.selectedAgentId}
roles={roles}
seatFilter={seatFilter}
setSeatFilter={setSeatFilter}
parallelBatch={step2.parallelBatch}
selectedParallelSeats={step2.selectedParallelSeats}
isParallelRunning={step2.isParallelRunning}
onToggleParallelSeat={step2.toggleParallelSeat}
orchestrationMode={orchestrationMode}
orchestrationPlan={orchestrationPlan}
dagNodeStates={step2.dagNodeStates}
agentNameToRole={step2.agentNameToRole}
selectedModel={selectedModel}
availableModels={availableModels}
modelsLoading={modelsLoading}
setSelectedModel={setSelectedModel}
activeArtifactThreadId={step2.activeArtifactThreadId}
seatStubMessages={step2.seatStubMessages}
openArtifactFromStep={step2.openArtifactFromStep}
openArtifactPreview={step2.openArtifactPreview}
onPauseRoundtable={step2.pauseRoundtable}
onResumeRoundtable={step2.resumeRoundtable}
onHandleInjectToRoundtable={step2.handleInjectToRoundtable}
setClarificationDraft={step2.setClarificationDraft}
setCustomAgentInput={step2.setCustomAgentInput}
setAgentConfigs={step2.setAgentConfigs}
setSelectedAgentId={step2.setSelectedAgentId}
onSubmitClarification={step2.submitClarification}
onSavePersona={step2.handleSaveAgentAndRecalculate}
onProceedToStep3={() => {
if (!step2.hasConsensus) {
triggerToast("圆桌尚未自然收敛,请等待总控派活全部完成");
return;
}
setCurrentStep(3);
triggerToast(
"多角色智能体博弈共识达成,最终交付全套路线成果文档及方案图!",
);
}}
onBackgroundSuspend={handleBackgroundSuspend}
isViewingHistory={drafts.loadedFromDraftRef.current}
onTriggerToast={triggerToast}
taskArtifactSubmission={taskArtifactSubmission}
/>
)}
{currentStep === 3 && (
<Step3Panel
useStep1Chrome={rootClassName?.includes("eightbf-roundtable") ?? false}
headerTitle={step3HeaderTitle}
step3Mode={step3Mode}
threadIds={step2.threadIds}
coordinatorName={step2.coordinatorName}
consensusText={step2.lastLeaderContent}
hasConsensus={step2.hasConsensus}
step2RoundtableDialogues={step2.step2RoundtableDialogues}
agentNameToRole={step2.agentNameToRole}
intentReady={step1.intentReady}
selectedModel={selectedModel}
availableModels={availableModels}
modelsLoading={modelsLoading}
setSelectedModel={setSelectedModel}
savedReport={step3Report}
onReportSaved={handleReportSaved}
// 业务链总控编排提示 → 注入「总结报告」智能体(带 coordinatorPrompt 的链走 dag)。
coordinatorPrompt={orchestrationPlan?.coordinatorPrompt ?? null}
savedSummary={step3Report?.summaryReport ?? null}
onSummarySaved={handleSummarySaved}
// 页面层常驻的三个生成流(切走不断流,进入视图续看)。
summaryFlow={summaryFlow}
reportFlow={reportFlow}
dashboardFlow={dashboardFlow}
onReset={handleStartNewTask}
openArtifactPreview={step2.openArtifactPreview}
seatStubMessages={step2.seatStubMessages}
taskArtifactSubmission={taskArtifactSubmission}
/>
)}
</section>
{/* RIGHT SIDEBAR */}
{!hideDefaultStep1RightSidebar && <RightSidebar
currentStep={currentStep}
selectedModel={selectedModel}
setSelectedModel={setSelectedModel}
availableModels={availableModels}
modelsLoading={modelsLoading}
intentReady={step1.intentReady}
timelineEntries={step1.timelineEntries}
triggerToast={triggerToast}
onSaveIntent={handleSaveIntent}
/>}
</main>
{/* 深链 taskId 模式:底部「快捷跳转」栏(与单智能体问答共用,按业务取按钮管理配置)。 */}
{prefillRef.current?.taskId &&
prefillRef.current?.businessCode &&
BUSINESS_CODE_TO_TASK_BUSINESS[prefillRef.current.businessCode] && (
<TaskJumpBar
business={BUSINESS_CODE_TO_TASK_BUSINESS[prefillRef.current.businessCode]}
taskId={prefillRef.current.taskId}
actionId={prefillRef.current.actionId}
roundtable
/>
)}
{/* 任务分析会商(rwfx-A)深链:与单智能体共用 3q 预检闸门,未完成则引导前往三情**会商**(3qfx-A)。 */}
{prefillRef.current?.taskId &&
prefillRef.current?.businessCode &&
BUSINESS_CODE_TO_TASK_BUSINESS[prefillRef.current.businessCode] === "rwfx" && (
<RwfxSqReportGate
taskId={prefillRef.current.taskId}
targetGoPath="3qfx-A"
targetLabel="3qfx 会商"
/>
)}
</div>
);
}
// ────────────────────────────────────────────────────────────
// 子组件 —— 这些 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 (
<div className="flex items-center gap-1.5 rounded-2xl border border-slate-200/50 bg-slate-50 p-1.5 dark:border-border dark:bg-muted">
<StepButton
index={1}
label="任务意图理解"
active={currentStep === 1}
locked={false}
onClick={() => onStepClick(1)}
/>
<ChevronRight className="h-3 w-3 text-slate-300 dark:text-muted-foreground" />
<StepButton
index={2}
label="多智能体研讨"
active={currentStep === 2}
locked={step2Locked}
onClick={() => {
if (step2Locked) {
triggerToast("请先在第一步完成任务理解,确认[INTENT_READY]信号后再进入");
return;
}
onStepClick(2);
}}
/>
<ChevronRight className="h-3 w-3 text-slate-300 dark:text-muted-foreground" />
<StepButton
index={3}
label="方案结果展示"
active={currentStep === 3}
locked={step3Locked}
onClick={() => {
if (step3Locked) {
triggerToast(
intentReady
? "请先在第二步达成共识(总控自然收敛)再进入"
: "请先依次完成第一步和第二步",
);
return;
}
onStepClick(3);
}}
/>
</div>
);
}
function StepButton({
index,
label,
active,
locked,
onClick,
}: {
index: number;
label: string;
active: boolean;
locked: boolean;
onClick: () => void;
}) {
return (
<button
id={`step-${index}-btn`}
type="button"
onClick={onClick}
disabled={locked}
aria-disabled={locked}
title={locked ? "请先完成上一步" : undefined}
className={`flex items-center gap-2 px-4 py-1.5 rounded-xl text-xs font-semibold tracking-wide transition-all relative ${
active
? "bg-white text-primary shadow-sm font-bold scale-[1.02] dark:bg-background"
: locked
? "text-slate-300 cursor-not-allowed dark:text-slate-600"
: "text-slate-500 hover:text-slate-800 dark:text-muted-foreground dark:hover:text-foreground"
}`}
>
<span
className={`w-5 h-5 flex items-center justify-center rounded-full text-[10px] font-bold ${
active
? "bg-primary text-white"
: locked
? "border border-slate-200 text-slate-300 dark:border-slate-700 dark:text-slate-600"
: "border-2 border-slate-400 text-slate-500 dark:border-muted-foreground dark:text-muted-foreground"
}`}
>
{index}
</span>
<span>{label}</span>
{locked && <span className="ml-0.5 text-[9px]">锁</span>}
{active && (
<span className="absolute bottom-0 left-1/2 -translate-x-1/2 w-8 h-1 bg-primary rounded-full" />
)}
</button>
);
}
interface HistoryDropdownProps {
innerRef: React.MutableRefObject<HTMLDivElement | null>;
isDark: boolean;
isOpen: boolean;
setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
drafts: ReturnType<typeof useDraftPersistence>["drafts"];
currentDraftId: string | null;
/** 正在「挂起中」(已点后台挂起、作业尚未建好)的草稿 id 集合 —— 历史记录显示「挂起中」。 */
pendingSuspendIds: Set<string>;
renamingDraftId: string | null;
renameDraftValue: string;
setRenameDraftValue: React.Dispatch<React.SetStateAction<string>>;
onLoad: (id: string) => void;
/** 下拉展开时回调(刷新列表拿最新作业状态)。 */
onOpen?: () => void;
/** 点击「进行中 / 待澄清」的任务 → 打开派活链路流程图弹窗。 */
onOpenJob: (jobId: string) => void;
onDelete: (id: string) => void;
onStartRename: (d: ReturnType<typeof useDraftPersistence>["drafts"][number]) => void;
onCommitRename: (id: string) => void;
onCancelRename: () => void;
}
function HistoryDropdown(props: HistoryDropdownProps) {
const {
innerRef,
isDark,
isOpen,
setIsOpen,
drafts,
currentDraftId,
pendingSuspendIds,
renamingDraftId,
renameDraftValue,
setRenameDraftValue,
onLoad,
onOpen,
onOpenJob,
onDelete,
onStartRename,
onCommitRename,
onCancelRename,
} = props;
const panelBg = isDark ? "#122347" : "#ffffff";
const currentBg = isDark ? "#1a2f5a" : "#ecfdf5";
return (
<div className="relative" ref={innerRef}>
<button
id="history-dropdown-btn"
type="button"
onClick={() =>
setIsOpen((open) => {
const next = !open;
if (next) onOpen?.();
return next;
})
}
className="bg-white hover:bg-slate-50 border border-[#e2e8f0] text-[#334155] text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition dark:border-border dark:bg-secondary dark:text-foreground dark:hover:bg-accent"
>
<History className="w-3.5 h-3.5 text-slate-500" />
历史记录
<span className="text-[10px] font-mono text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded">
{drafts.length}
</span>
</button>
{isOpen && (
<div
className="rt-history-dropdown-panel absolute right-0 top-full mt-2 w-[360px] max-h-[60vh] overflow-y-auto border border-slate-200 rounded-2xl shadow-xl z-[1000] dark:border-border"
style={{
background: panelBg,
backgroundColor: panelBg,
backgroundImage: "none",
opacity: 1,
backdropFilter: "none",
WebkitBackdropFilter: "none",
}}
>
<div
className="rt-history-dropdown-header px-4 py-3 border-b border-slate-100 flex items-center justify-between sticky top-0 z-10 dark:border-border"
style={{
background: panelBg,
backgroundColor: panelBg,
backgroundImage: "none",
opacity: 1,
backdropFilter: "none",
WebkitBackdropFilter: "none",
}}
>
<span className="text-xs font-black text-slate-800 tracking-wide dark:text-foreground">历史草稿</span>
<span className="text-[10px] font-mono text-slate-400">{drafts.length} 条</span>
</div>
{drafts.length === 0 ? (
<div className="px-4 py-6 text-[11px] text-slate-400 italic text-center">
暂无历史。点击「保存草稿」或走完一步会自动保存到这里。
</div>
) : (
<ul className="divide-y divide-slate-100 dark:divide-border">
{drafts.map((d) => {
const isCurrent = d.id === currentDraftId;
const isRenaming = d.id === renamingDraftId;
// 「挂起中」:已点后台挂起、作业还没建好(本地标记),或作业刚建好仍排队(queued)。
const isSuspending = pendingSuspendIds.has(d.id) || d.status === "queued";
// 「进行中 / 待澄清」且有 jobId → 点击打开流程图弹窗,而非加载草稿。
const isActiveJob =
(d.status === "running" || d.status === "awaiting_input") && !!d.jobId;
const openOrLoad = () =>
isActiveJob && d.jobId ? onOpenJob(d.jobId) : onLoad(d.id);
return (
<li
key={d.id}
className="px-3 py-2.5"
style={isCurrent ? { backgroundColor: currentBg } : undefined}
>
<div className="flex items-start gap-2">
<div className="flex-1 min-w-0">
{isRenaming ? (
<input
type="text"
autoFocus
value={renameDraftValue}
onChange={(e) => 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"
/>
) : (
<button
type="button"
onClick={openOrLoad}
className="block w-full text-left"
title={isActiveJob ? "点击查看进度" : "点击加载"}
>
<span className="text-[11.5px] font-semibold text-slate-800 line-clamp-2 dark:text-foreground">
{d.name}
</span>
<span className="text-[10px] text-slate-400 mt-0.5 flex items-center gap-1 font-mono">
{isSuspending ? (
<span className="inline-flex items-center gap-1 text-sky-500 font-semibold">
<Loader2 className="w-3 h-3 animate-spin" />
挂起中
</span>
) : d.status === "running" ? (
<span className="inline-flex items-center gap-1 text-primary font-semibold">
<Loader2 className="w-3 h-3 animate-spin" />
进行中
</span>
) : d.status === "awaiting_input" ? (
<span className="inline-flex items-center gap-1 text-amber-500 font-semibold">
<span className="inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />
待澄清
</span>
) : d.status === "error" ? (
<span className="text-rose-500 font-semibold">出错</span>
) : (
<span>Step {d.furthestStep}</span>
)}
<span className="text-slate-300">·</span>
{new Date(d.updatedAt).toLocaleString("zh-CN", { hour12: false })}
</span>
</button>
)}
</div>
<div className="flex items-center gap-0.5 shrink-0">
{!isRenaming && (
<>
<button
type="button"
onClick={openOrLoad}
className="p-1 text-slate-500 hover:text-primary hover:bg-slate-100 rounded transition"
title={isActiveJob ? "查看进度" : "加载"}
>
{isActiveJob ? (
<Activity className="w-3.5 h-3.5 text-primary" />
) : (
<Upload className="w-3.5 h-3.5" />
)}
</button>
<button
type="button"
onClick={() => onStartRename(d)}
className="p-1 text-slate-500 hover:text-primary hover:bg-slate-100 rounded transition"
title="重命名"
>
<Pencil className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => onDelete(d.id)}
className="p-1 text-slate-500 hover:text-rose-600 hover:bg-rose-50 rounded transition"
title="删除"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</>
)}
</div>
</div>
</li>
);
})}
</ul>
)}
</div>
)}
</div>
);
}
interface LeftSidebarProps {
currentStep: number;
roles: RoleEntry[];
agentNameToRole: Record<
string,
{ speakerId: number; avatarType: string; displayName: string }
>;
budgetLimit: number;
intentReady: ReturnType<typeof useStep1Intent>["intentReady"];
sidebarExpanded: boolean;
setSidebarExpanded: React.Dispatch<React.SetStateAction<boolean>>;
step2Runs: DraftStep2RunSnapshot[];
activeStep2RunId: string | null;
onSelectStep2Run: (runId: string) => void;
/** 第二步「按席位筛选会商记录」—— 点角色卡片筛选,与中间消息头像共用。 */
seatFilter: SeatFilter | null;
setSeatFilter: React.Dispatch<React.SetStateAction<SeatFilter | null>>;
/** 需求 0616 #2:当前已勾选的业务链 id(高亮用),来自 autoChainResult.chain.id。 */
selectedChainId: string | null;
/** 需求 0616 #2:Step1 落地左栏「业务链」点击 → 勾选该链(不直接进研讨)。 */
onSelectChain: (chain: BusinessChain) => void;
/** 需求 0616 #2:Step1 落地左栏「分析记录」点击 → 打开历史会商分析(加载草稿)。 */
onOpenDraft: (draftId: string) => void;
/** 当前已加载草稿 id(分析记录选中高亮用),来自 drafts.currentDraftId。 */
activeDraftId: string | null;
/** 深链 taskId 模式:Step1 落地左栏「分析记录」只列该任务的草稿。 */
entryRailTaskId?: string | null;
/** 独立页面的历史草稿存储键。 */
historyTaskId?: string | null;
/** 深链业务码:左上角卡片据此决定显示「当前任务」(rwfx/3qfx) 还是「当前行动」(xdfx)。 */
entryRailBusinessCode?: string | null;
/** 独立页面禁止在左栏改选业务链。 */
lockBusinessChain?: boolean;
/** 独立页面锁定显示的业务链。 */
lockedChainId?: string | null;
/** 第一阶段替换默认业务链选择区的自定义内容。 */
entryRailBusinessChainSlot?: ReactNode;
/** 第一阶段由独立业务页提供的自定义任务卡片。 */
entryRailTaskCardSlot?: ReactNode;
/** 独立业务页替换第一步左侧工作区;仅提供已解析的意图状态。 */
renderStep1LeftSidebar?: (context: {
intentReady: object | null;
onCollapse?: () => void;
submittedSeatKeys?: string[];
onSeatClick?: (seat: ChainSeat) => void;
}) => ReactNode;
/** 独立业务页在第二步左栏顶部复用任务与意图区。 */
renderStep2LeftSidebarHeader?: (context: {
intentReady: object | null;
onCollapse: () => void;
}) => ReactNode;
}
function Step2SandboxSidebarSync({
currentStep,
sidebarExpanded,
setSidebarExpanded,
}: {
currentStep: number;
sidebarExpanded: boolean;
setSidebarExpanded: React.Dispatch<React.SetStateAction<boolean>>;
}) {
const { open } = useArtifacts();
const prevOpenRef = useRef(open);
const prevStepRef = useRef(currentStep);
useEffect(() => {
const enteredCollapsibleStep =
(currentStep === 2 || currentStep === 3) &&
prevStepRef.current !== currentStep;
prevStepRef.current = currentStep;
if (currentStep !== 2 && currentStep !== 3) {
prevOpenRef.current = open;
return;
}
const openedNow = open && !prevOpenRef.current;
const landedWithSandbox = enteredCollapsibleStep && open;
if ((openedNow || landedWithSandbox) && sidebarExpanded) {
setSidebarExpanded(false);
}
prevOpenRef.current = open;
}, [currentStep, open, setSidebarExpanded, sidebarExpanded]);
return null;
}
function LeftSidebar({
currentStep,
roles,
agentNameToRole,
budgetLimit: _budgetLimit,
intentReady,
sidebarExpanded,
setSidebarExpanded,
step2Runs,
activeStep2RunId,
onSelectStep2Run,
seatFilter,
setSeatFilter,
selectedChainId,
onSelectChain,
onOpenDraft,
activeDraftId,
entryRailTaskId,
historyTaskId,
entryRailBusinessCode,
lockBusinessChain,
lockedChainId,
entryRailBusinessChainSlot,
entryRailTaskCardSlot,
renderStep1LeftSidebar,
renderStep2LeftSidebarHeader,
}: LeftSidebarProps) {
// 整片脱敏:左侧面板(任务概览/参与角色/人工参与等)的所有文本——标题、动态内容、
// 嵌套子组件文本一并脱敏。消息列表与沙箱是另外的容器,不挂此 Hook,保持原文。
const dzRef = useDesensitizeSubtree<HTMLElement>();
const isStep2 = currentStep === 2;
// 仅第二步可按席位筛选会商记录;点中已选则取消(回到显示全部)。
const toggleSeatFilter = (filter: SeatFilter) =>
setSeatFilter((cur) => (cur === filter ? null : filter));
// Step 3:通用会商隐藏左栏以让方案展示撑满;8BF 复用第一步左栏,并和第二步一样可收起。
if (currentStep === 3) {
if (!renderStep1LeftSidebar) return null;
return (
<section
ref={dzRef}
id="left-sidebar"
data-sidebar-expanded={String(sidebarExpanded)}
className={cn(
"min-h-0 shrink-0 flex flex-col gap-3 pr-1 transition-[width] duration-200 ease-out overflow-y-auto",
sidebarExpanded ? "w-[280px]" : "w-[80px]",
)}
>
{!sidebarExpanded ? (
<button
type="button"
onClick={() => setSidebarExpanded(true)}
title="展开侧栏"
aria-expanded={false}
className="w-full shrink-0 flex h-10 items-center justify-center rounded-[4px] border border-slate-200/50 bg-white text-slate-500 hover:text-primary hover:border-primary/30 transition-colors shadow-[0_2px_8px_rgba(0,0,0,0.01)]"
>
<PanelLeftOpen className="h-4 w-4" />
</button>
) : (
renderStep1LeftSidebar({
intentReady,
onCollapse: () => setSidebarExpanded(false),
})
)}
</section>
);
}
return (
<section
ref={dzRef}
id="left-sidebar"
data-sidebar-expanded={isStep2 ? String(sidebarExpanded) : undefined}
className={cn(
"min-h-0 shrink-0 flex flex-col gap-3 pr-1 transition-[width] duration-200 ease-out",
isStep2 ? "overflow-y-auto" : "overflow-hidden",
isStep2 && !sidebarExpanded ? "w-[80px]" : "w-[280px]",
)}
>
{isStep2 && !sidebarExpanded && (
<button
type="button"
onClick={() => setSidebarExpanded(true)}
title="展开侧栏"
aria-expanded={false}
className="w-full shrink-0 flex h-10 items-center justify-center rounded-[4px] border border-slate-200/50 bg-white text-slate-500 hover:text-primary hover:border-primary/30 transition-colors shadow-[0_2px_8px_rgba(0,0,0,0.01)]"
>
<PanelLeftOpen className="h-4 w-4" />
</button>
)}
{currentStep === 2 ? (
sidebarExpanded ? (
<>
{renderStep2LeftSidebarHeader?.({
intentReady,
onCollapse: () => setSidebarExpanded(false),
}) ?? (
<IntentSummaryCard
intentReady={intentReady}
title="意图理解"
collapsible
sidebarToggle={{
expanded: sidebarExpanded,
onToggle: () => setSidebarExpanded((v) => !v),
}}
/>
)}
<div className="bg-white border border-slate-200/50 rounded-2xl p-4 shadow-[0_2px_8px_rgba(0,0,0,0.01)] flex-1 flex flex-col min-h-[240px]">
<div className="flex items-center gap-2 border-b border-slate-100 pb-2.5 mb-3">
<Users className="w-4 h-4 text-primary" strokeWidth={2.5} />
<h2 className="text-xs font-bold text-slate-900 uppercase tracking-widest">参与角色</h2>
</div>
<div className="space-y-2.5 overflow-y-auto flex-1 pr-1 custom-scrollbar">
{roles.map((role) => {
const filter = seatFilterForRole(role);
return (
<RoleRow
key={role.id}
role={role}
agentNameToRole={agentNameToRole}
active={seatFilter === filter}
onSelect={() => toggleSeatFilter(filter)}
/>
);
})}
</div>
</div>
<HumanParticipationCard
active={seatFilter === USER_SEAT_FILTER}
onSelect={() => toggleSeatFilter(USER_SEAT_FILTER)}
/>
<Step2RunSwitcher
runs={step2Runs}
activeRunId={activeStep2RunId}
onSelect={onSelectStep2Run}
/>
<TaskOverviewCard currentStep={currentStep} />
</>
) : (
<>
<CollapsedSidebarSection title="意图理解">
<IntentSectionIcon className="h-5 w-5" />
</CollapsedSidebarSection>
<CollapsedSidebarSection title="参与角色">
<div className="flex flex-col items-center gap-2">
{roles.map((role) => {
const filter = seatFilterForRole(role);
return (
<RoleAvatarBadge
key={role.id}
role={role}
agentNameToRole={agentNameToRole}
size="h-8 w-8"
showSpeakingAnimation
active={seatFilter === filter}
onSelect={() => toggleSeatFilter(filter)}
/>
);
})}
</div>
</CollapsedSidebarSection>
<CollapsedSidebarSection title="人工参与">
<button
type="button"
onClick={() => toggleSeatFilter(USER_SEAT_FILTER)}
aria-pressed={seatFilter === USER_SEAT_FILTER}
title={
seatFilter === USER_SEAT_FILTER
? "取消筛选,显示全部发言"
: "只看 用户 的发言"
}
className={cn(
"shrink-0 cursor-pointer rounded-full transition hover:opacity-80 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",
seatFilter === USER_SEAT_FILTER &&
"ring-2 ring-primary ring-offset-2 ring-offset-white",
)}
>
<Man1Avatar size="h-8 w-8" />
</button>
</CollapsedSidebarSection>
<CollapsedSidebarSection title="任务概览">
<Clipboard className="h-5 w-5 text-primary" strokeWidth={2.5} />
</CollapsedSidebarSection>
</>
)
) : (
// Step 1(落地,未开始研讨):左栏改为业务链 + 分析记录入口(需求 0616 #2)。
renderStep1LeftSidebar?.({ intentReady }) ?? (
<RoundtableEntryRail
selectedChainId={selectedChainId}
onSelectChain={onSelectChain}
onOpenDraft={onOpenDraft}
activeDraftId={activeDraftId}
taskId={entryRailTaskId ?? null}
historyTaskId={historyTaskId ?? null}
businessCode={entryRailBusinessCode ?? null}
lockBusinessChain={lockBusinessChain}
lockedChainId={lockedChainId ?? null}
businessChainSlot={entryRailBusinessChainSlot}
taskCardSlot={entryRailTaskCardSlot}
/>
)
)}
</section>
);
}
/** 「展开关系图」示例芯片的轮换配色(仅作视觉区分,无业务语义)。 */
const SEAT_CHIP_PALETTE = [
"bg-rose-50 text-rose-700 border-rose-200",
"bg-amber-50 text-amber-700 border-amber-200",
"bg-teal-50 text-teal-700 border-teal-200",
"bg-purple-50 text-purple-700 border-purple-200",
"bg-sky-50 text-sky-700 border-sky-200",
"bg-emerald-50 text-emerald-700 border-emerald-200",
];
/**
* 把业务链席位按 `stages`(分层并行编排)分组:组内并行、组间串行;无 `stages`
* (线性链)时每个席位单独成一层。仅供左栏「展开关系图」做编排示意展示。
*/
function getChainStageGroups(chain: BusinessChain): BusinessChain["seats"][] {
const byId = new Map(chain.seats.map((s) => [s.agent_id, s]));
if (chain.stages && chain.stages.length > 0) {
return chain.stages
.map((stage) =>
stage
.map((id) => byId.get(id))
.filter((s): s is BusinessChain["seats"][number] => Boolean(s)),
)
.filter((stage) => stage.length > 0);
}
return chain.seats.map((s) => [s]);
}
/** 分析记录「按业务链筛选」的两个特殊值:全部 / 无业务链(自由模式)。 */
const RECORD_FILTER_ALL = "__all__";
const RECORD_FILTER_FREE = "__free__";
/**
* 需求 0616 #2:多智能体会商 Step1(落地)左栏入口栏。
* - 业务链:仅公共链条(``listChains("public")``)前 3 个;点击以该链席位启动会商。
* - 分析记录:圆桌历史草稿(``useRoundtableDrafts``);点击打开对应历史会商分析。
* 进入研讨(Step 2/3)后左栏恢复为「参与角色 / 任务概览」工作面板。
*/
function RoundtableEntryRail({
selectedChainId,
onSelectChain,
onOpenDraft,
activeDraftId,
taskId,
historyTaskId,
businessCode,
lockedChainId,
lockBusinessChain = false,
businessChainSlot,
taskCardSlot,
}: {
selectedChainId: string | null;
onSelectChain: (chain: BusinessChain) => void;
onOpenDraft: (draftId: string) => void;
activeDraftId: string | null;
/** 深链 taskId 模式:分析记录只列该任务的草稿。 */
taskId?: string | null;
/** 独立页面的草稿存储键;不改变当前任务卡片/业务链区域的展示语义。 */
historyTaskId?: string | null;
/** 深链业务码:xdfx(7BF) 左上角显示「当前行动」,其余显示「当前任务」。 */
businessCode?: string | null;
/** 固定业务链时,左侧只展示这条链的流程图及放大入口。 */
lockedChainId?: string | null;
lockBusinessChain?: boolean;
businessChainSlot?: ReactNode;
taskCardSlot?: ReactNode;
}) {
const [chains, setChains] = useState<BusinessChain[]>([]);
const [chainSectionExpanded, setChainSectionExpanded] = useState(true);
const [expandedChainId, setExpandedChainId] = useState<string | null>(null);
const { drafts: records, refresh } = useRoundtableDrafts(historyTaskId ?? taskId);
// 分析记录「按业务链筛选」—— 选项从已加载草稿的 chainTitle 去重得到,
// 无业务链的草稿(自由 / recommend 模式)归入「自由模式」。
const [chainFilter, setChainFilter] = useState<string>(RECORD_FILTER_ALL);
const chainFilterOptions = useMemo(() => {
const titles = new Set<string>();
let hasFree = false;
for (const rec of records) {
const title = rec.chainTitle?.trim();
if (title) titles.add(title);
else hasFree = true;
}
const opts = Array.from(titles)
.sort((a, b) => a.localeCompare(b, "zh-CN"))
.map((title) => ({ value: title, label: title }));
if (hasFree) opts.push({ value: RECORD_FILTER_FREE, label: "自由模式" });
return opts;
}, [records]);
const filteredRecords = useMemo(() => {
if (chainFilter === RECORD_FILTER_ALL) return records;
if (chainFilter === RECORD_FILTER_FREE)
return records.filter((rec) => !rec.chainTitle?.trim());
return records.filter((rec) => rec.chainTitle?.trim() === chainFilter);
}, [records, chainFilter]);
// 草稿刷新后所选业务链可能已不存在(被删/改名)→ 回落到「全部」,避免列表空白无解。
useEffect(() => {
if (
chainFilter !== RECORD_FILTER_ALL &&
!chainFilterOptions.some((opt) => opt.value === chainFilter)
) {
setChainFilter(RECORD_FILTER_ALL);
}
}, [chainFilter, chainFilterOptions]);
// 深链接(taskId)模式:左上角不显示「业务链选择」(链条已由 businessCode 自动决定),改为展示
// 当前任务(rwfx/3qfx)或当前行动(xdfx)。xdfx 的根是「行动」,故展示行动名称 + 叙事。
const deeplink = Boolean(taskId);
const isXdfx = businessCode === "7BF";
const taskDetail = deeplink && !isXdfx ? readCopTaskDetail() : null;
const actionDetail = deeplink && isXdfx ? readActionDetail() : null;
useEffect(() => {
// 深链接模式不展示业务链选择 → 不必拉公共链条。
if (deeplink || lockBusinessChain) {
void refresh();
return;
}
let cancelled = false;
void listChains("public")
.then((all) => {
if (!cancelled) {
const usable = all.filter(isChainEnabled);
setChains(lockBusinessChain ? usable.filter((chain) => chain.id === lockedChainId) : usable);
}
})
.catch(() => {
/* 业务链非关键,静默忽略 */
});
void refresh();
return () => {
cancelled = true;
};
}, [refresh, deeplink, lockedChainId, lockBusinessChain]);
const formatTime = (value: string) => {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "";
return date.toLocaleString("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
};
return (
<div
className={cn(
"flex min-h-0 flex-1 flex-col gap-3",
lockBusinessChain && "overflow-y-auto pr-1 custom-scrollbar",
)}
>
{/* 深链接(taskId)模式:左上角展示「当前任务」(rwfx/3qfx)或「当前行动」(xdfx),替代业务链选择。 */}
{taskCardSlot ? (
<>
{taskCardSlot}
{lockBusinessChain && businessChainSlot}
</>
) : deeplink ? (
isXdfx ? (
<div className="bg-white border border-[#ECE7E4] rounded-2xl p-4 shadow-[0_4px_20px_rgba(0,0,0,0.02)]">
<div className="flex items-center gap-2 mb-3">
<span className="flex items-center justify-center w-5 h-5 rounded-md bg-primary text-primary-foreground">
<Target className="w-3 h-3" strokeWidth={2.5} />
</span>
<h2 className="theme-brand-title text-sm font-semibold tracking-wide text-slate-900">当前行动</h2>
</div>
<div>
<p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">行动名称</p>
<p className="mt-0.5 text-xs font-semibold leading-relaxed text-slate-800">
{actionDetail?.actionName?.trim() || "(未获取到行动名称)"}
</p>
</div>
</div>
) : (
<div className="bg-white border border-[#ECE7E4] rounded-2xl p-4 shadow-[0_4px_20px_rgba(0,0,0,0.02)]">
<div className="flex items-center gap-2 mb-3">
<span className="flex items-center justify-center w-5 h-5 rounded-md bg-primary text-primary-foreground">
<Clipboard className="w-3 h-3" strokeWidth={2.5} />
</span>
<h2 className="theme-brand-title text-sm font-semibold tracking-wide text-slate-900">当前任务</h2>
</div>
<div className="space-y-2">
<div>
<p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">任务名称</p>
<p className="mt-0.5 text-xs font-semibold leading-relaxed text-slate-800">
{taskDetail?.taskName?.trim() || "(未获取到任务名称)"}
</p>
</div>
<div>
<p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">任务描述</p>
<p className="mt-0.5 whitespace-pre-wrap text-[11px] leading-relaxed text-slate-600">
{taskDetail?.taskContent?.trim() || "(未获取到任务描述)"}
</p>
</div>
</div>
</div>
)
) : lockBusinessChain && businessChainSlot ? (
businessChainSlot
) : (
/* 业务链(公共列表,内部滚动) */
<div className="bg-white border border-[#ECE7E4] rounded-2xl p-4 shadow-[0_4px_20px_rgba(0,0,0,0.02)] transition-shadow duration-300 hover:shadow-[0_4px_24px_rgba(45,37,34,0.04)]">
<div className="flex items-center gap-2">
<span className="flex items-center justify-center w-5 h-5 rounded-md bg-primary text-primary-foreground">
<Layers className="w-3 h-3" strokeWidth={2.5} />
</span>
<h2 className="theme-brand-title text-sm font-semibold tracking-wide text-slate-900">业务链</h2>
<span className="ml-auto flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-neutral-100 text-sm font-bold tabular-nums leading-none text-neutral-500">
{chains.length}
</span>
<button
type="button"
onClick={() => setChainSectionExpanded((v) => !v)}
title={chainSectionExpanded ? "收起业务链" : "展开业务链"}
aria-expanded={chainSectionExpanded}
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-[#E6C9C4] bg-white text-neutral-400 transition-colors hover:border-primary/40 hover:text-primary"
>
<ChevronDown
className={cn(
"h-3.5 w-3.5 transition-transform duration-300 ease-out",
chainSectionExpanded && "rotate-180",
)}
/>
</button>
</div>
<div
className="grid overflow-hidden transition-all duration-300 ease-out"
style={{
gridTemplateRows: chainSectionExpanded ? "1fr" : "0fr",
marginTop: chainSectionExpanded ? 12 : 0,
opacity: chainSectionExpanded ? 1 : 0,
}}
>
<div className="min-h-0 overflow-hidden">
{chains.length === 0 ? (
<p className="text-xs text-slate-400 py-1.5">暂无公共业务链</p>
) : (
<div className="max-h-[292px] overflow-y-auto pr-1 -mr-1 custom-scrollbar">
<div className="flex flex-col gap-2.5 py-0.5">
{chains.map((chain) => {
const selected = selectedChainId === chain.id;
const graphOpen = expandedChainId === chain.id;
const stageGroups = getChainStageGroups(chain);
let seatColorIndex = 0;
return (
<div
key={chain.id}
className={cn(
"min-h-[88px] rounded-xl border transition-all duration-200",
selected
? "border-primary/25 bg-primary/5 ring-1 ring-primary/20 shadow-sm"
: "border-[#ECE7E4] bg-neutral-50/50 hover:border-neutral-300 hover:bg-neutral-50",
)}
>
<button
type="button"
onClick={() => onSelectChain(chain)}
title={selected ? "再次点击取消勾选" : `勾选业务链「${chain.title}」`}
aria-pressed={selected}
className="w-full rounded-xl p-3 text-left"
>
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
{/* 单选圆点 */}
<span
className={cn(
"flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full border transition-all",
selected
? "border-primary bg-primary"
: "border-neutral-300 bg-white",
)}
>
{selected && <span className="h-1.5 w-1.5 rounded-full bg-white" />}
</span>
<span
className={cn(
"truncate text-xs font-semibold",
selected ? "text-primary" : "text-neutral-800",
)}
>
{chain.title}
</span>
</div>
<span
className={cn(
"shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-semibold",
selected
? "bg-primary/10 text-primary"
: "bg-neutral-100 text-neutral-500",
)}
>
{chain.seats.length} 席
</span>
</div>
{chain.description ? (
<p className="mt-1.5 line-clamp-2 text-[10.5px] leading-relaxed text-neutral-500">
{chain.description}
</p>
) : (
<p className="mt-1.5 text-[10px] font-medium text-neutral-400">
{selected ? "已选 · 再次点击取消" : "点击勾选该业务链"}
</p>
)}
</button>
{/* 关系图示例:选中后可展开,把该链席位智能体用小图标排成编排示意 */}
{selected && (
<div className="mx-3 mb-3 border-t border-dashed border-[#E8D0CC]/60 pt-2.5">
<button
type="button"
onClick={() =>
setExpandedChainId(graphOpen ? null : chain.id)
}
className="flex w-full items-center justify-center gap-1 rounded-full border border-primary/15 bg-primary/5 px-3 py-1 text-[10.5px] font-semibold text-primary transition-colors hover:bg-primary/10"
>
<Layers className="h-3 w-3" />
<span>{graphOpen ? "收起关系图" : "展开关系图"}</span>
{graphOpen ? (
<ChevronUp className="h-3 w-3" />
) : (
<ChevronDown className="h-3 w-3" />
)}
</button>
{graphOpen && (
<div className="mt-2 rounded-xl border border-dashed border-[#E8D0CC]/60 bg-[#FAF6F5] p-2.5">
{stageGroups.length === 0 ? (
<p className="py-2 text-center text-[10px] text-neutral-400">
该业务链暂无智能体席位
</p>
) : (
<div className="flex flex-row flex-wrap items-center justify-center gap-1">
{stageGroups.flatMap((stage, si) => {
// 横向编排:阶段从左到右排列,阶段之间用 → 串联;并行阶段的
// 席位在该列内竖向堆叠(宽度可控,符合「同层并行·层间串行」示意)。
const items: React.ReactNode[] = [];
if (si > 0) {
items.push(
<ChevronRight
key={`arrow-${si}`}
className="h-3 w-3 shrink-0 text-neutral-300"
/>,
);
}
items.push(
<div
key={`stage-${si}`}
className="flex flex-col items-center gap-1"
>
{stage.length > 1 && (
<span className="rounded-full bg-primary/5 px-1.5 text-[8.5px] font-semibold text-primary">
并行 {stage.length}
</span>
)}
<div className="flex flex-col items-center gap-1.5">
{stage.map((seat, sj) => {
const palette =
SEAT_CHIP_PALETTE[
seatColorIndex++ %
SEAT_CHIP_PALETTE.length
];
return (
<Tooltip key={`${si}-${sj}-${seat.agent_id}`}>
<TooltipTrigger asChild>
<span
className={cn(
"flex h-6 w-6 items-center justify-center rounded-full border",
palette,
)}
>
<Cpu className="h-3 w-3" />
</span>
</TooltipTrigger>
{/* 悬停浮层显示名称 / 描述。Radix Portal 渲染到 body,
不被折叠层的 overflow-hidden / 列表滚动容器裁剪。 */}
<TooltipContent
side="top"
className="max-w-[280px] rounded-lg bg-neutral-900 px-3 py-2 text-white shadow-lg"
>
<div className="whitespace-nowrap text-[16px] font-semibold">
{seat.name}
</div>
{seat.description && (
<div className="mt-1 text-[16px] leading-snug text-neutral-300">
{seat.description}
</div>
)}
</TooltipContent>
</Tooltip>
);
})}
</div>
</div>,
);
return items;
})}
</div>
)}
</div>
)}
</div>
)}
</div>
);
})}
</div>
</div>
)}
</div>
</div>
</div>
)}
{/* 分析记录(圆桌历史草稿) */}
<div className="bg-white border border-[#ECE7E4] rounded-2xl p-4 shadow-[0_4px_20px_rgba(0,0,0,0.02)] flex-1 flex flex-col min-h-[200px] overflow-hidden">
<div className="flex items-center gap-2 mb-3">
<span className="flex items-center justify-center w-5 h-5 rounded-md bg-primary text-primary-foreground">
<History className="w-3 h-3" strokeWidth={2.5} />
</span>
<h2 className="theme-brand-title text-sm font-semibold tracking-wide text-slate-900">分析记录</h2>
{/* 按业务链筛选 —— 仅当存在多于 1 个可选业务链时才显示图标按钮。 */}
{chainFilterOptions.length > 1 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
title="按业务链筛选"
aria-label="按业务链筛选"
className={cn(
"ml-auto flex h-6 w-6 shrink-0 items-center justify-center rounded-md border transition-colors",
chainFilter === RECORD_FILTER_ALL
? "border-[#ECE7E4] text-neutral-400 hover:border-primary/30 hover:text-primary"
: "border-primary/30 bg-primary/5 text-primary",
)}
>
<Filter className="h-3 w-3" strokeWidth={2.5} />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-[12rem]">
<DropdownMenuLabel className="text-[16px] text-neutral-500">
按业务链筛选
</DropdownMenuLabel>
<DropdownMenuRadioGroup
value={chainFilter}
onValueChange={setChainFilter}
>
<DropdownMenuRadioItem value={RECORD_FILTER_ALL} className="text-[16px]">
全部
</DropdownMenuRadioItem>
{chainFilterOptions.map((opt) => (
<DropdownMenuRadioItem
key={opt.value}
value={opt.value}
className="text-[16px]"
>
<span className="truncate">{opt.label}</span>
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
{records.length === 0 ? (
<p className="flex-1 text-xs text-neutral-400 text-center py-8">暂无分析记录</p>
) : filteredRecords.length === 0 ? (
<p className="flex-1 text-xs text-neutral-400 text-center py-8">
该业务链下暂无分析记录
</p>
) : (
<>
<div className="space-y-2 overflow-y-auto flex-1 px-1 py-0.5 custom-scrollbar">
{filteredRecords.map((rec) => {
// 已完成:进行到第 3 步(执行过方案总结报告)
const completed = rec.furthestStep === 3;
// 选中:当前已加载的草稿(正在查看的那条)
const active = activeDraftId === rec.id;
return (
<button
key={rec.id}
type="button"
onClick={() => onOpenDraft(rec.id)}
title={rec.title}
aria-current={active}
className={cn(
"group/rec w-full rounded-[5px] border px-3 py-2.5 text-left transition-all duration-200",
active
? "border-primary/40 bg-primary/5 ring-1 ring-primary/20 shadow-[0_2px_10px_rgba(45,37,34,0.05)]"
: "border-[#ECE7E4] bg-white hover:border-primary/30 hover:bg-neutral-50 hover:shadow-[0_2px_10px_rgba(45,37,34,0.05)]",
)}
>
{/* 上:标题(左) + 状态标签(右上、放大) */}
<div className="flex items-start justify-between gap-2">
<span
className={cn(
"truncate text-[13px] font-semibold",
active
? "text-primary"
: "text-neutral-800 group-hover/rec:text-primary",
)}
>
{rec.title}
</span>
<span
className={cn(
"inline-flex shrink-0 items-center gap-1 rounded-[5px] px-2 py-1 text-[11px] font-semibold",
completed
? "bg-emerald-50 text-emerald-600"
: "bg-amber-50 text-amber-600",
)}
>
<span
className={cn(
"h-1.5 w-1.5 rounded-full",
completed ? "bg-emerald-500" : "bg-amber-500",
)}
/>
{completed ? "已完成" : "未完成"}
</span>
</div>
{/* 下:时间(左下) + 业务链(右下,无链条显示「自由模式」) */}
<div className="mt-2 flex items-center justify-between gap-2">
<span className="font-mono text-[10px] text-neutral-400 shrink-0">
{formatTime(rec.updatedAt)}
</span>
<span
className="max-w-[60%] truncate rounded-[5px] bg-neutral-100 px-1.5 py-0.5 text-[10px] font-medium text-neutral-500"
title={rec.chainTitle || "自由模式"}
>
{rec.chainTitle || "自由模式"}
</span>
</div>
</button>
);
})}
</div>
<div className="mt-2 pt-2 border-t border-neutral-100 text-center text-[11px] text-neutral-400">
{chainFilter === RECORD_FILTER_ALL
? `共 ${records.length} 条分析记录`
: `筛选出 ${filteredRecords.length} / ${records.length} 条分析记录`}
</div>
</>
)}
</div>
</div>
);
}
function Step2RunSwitcher({
runs,
activeRunId,
onSelect,
}: {
runs: DraftStep2RunSnapshot[];
activeRunId: string | null;
onSelect: (runId: string) => void;
}) {
if (runs.length === 0) return null;
const formatTime = (value: string) => {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "";
return date.toLocaleString("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
};
const sourceLabel = (run: DraftStep2RunSnapshot) => {
if (run.source === "chain") return "业务链条";
if (run.source === "recommend") return "智能体推荐";
return "历史结果";
};
const statusLabel = (run: DraftStep2RunSnapshot) => {
if (run.step3) return "已生成报告";
if (run.hasConsensus) return "已达成共识";
if ((run.step2RoundtableDialogues?.length ?? 0) > 0) return "研讨记录";
return "待开始";
};
return (
<div className="bg-white border border-slate-200/50 rounded-2xl p-4 shadow-[0_2px_8px_rgba(0,0,0,0.01)]">
<div className="flex items-center gap-2 border-b border-slate-100 pb-2.5 mb-3">
<ListOrdered className="w-4 h-4 text-primary" strokeWidth={2.5} />
<h2 className="text-xs font-bold text-slate-900 uppercase tracking-widest">生成结果</h2>
</div>
<div className="space-y-2">
{runs.map((run) => {
const active = run.id === activeRunId;
return (
<button
key={run.id}
type="button"
onClick={() => onSelect(run.id)}
className={cn(
"roundtable-step2-run-card w-full rounded-xl border p-2.5 text-left transition-colors",
active
? "border-primary/40 bg-primary/5 text-slate-900"
: "border-slate-100 bg-slate-50/60 text-slate-600 hover:border-primary/20 hover:bg-white",
)}
>
<div className="flex items-center justify-between gap-2">
<span className="truncate text-xs font-extrabold">{run.title}</span>
{active ? (
<CheckCircle className="h-3.5 w-3.5 shrink-0 text-primary" />
) : null}
</div>
<div className="mt-1.5 flex items-center justify-between gap-2 text-[10px] font-semibold">
<span className="truncate text-slate-400">{sourceLabel(run)}</span>
<span className="shrink-0 text-slate-400">{formatTime(run.createdAt)}</span>
</div>
<div className="mt-2 flex items-center gap-1.5">
<span
className={cn(
"h-1.5 w-1.5 rounded-full",
run.step3
? "bg-emerald-500"
: run.hasConsensus
? "bg-primary"
: "bg-slate-300",
)}
/>
<span className="text-[10px] font-bold text-slate-500">{statusLabel(run)}</span>
</div>
</button>
);
})}
</div>
</div>
);
}
function TaskOverviewCard({ currentStep }: { currentStep: number }) {
return (
<div className="bg-white border border-slate-200/50 rounded-2xl p-4 shadow-[0_2px_8px_rgba(0,0,0,0.01)]">
<div className="flex items-center gap-2 border-b border-slate-100 pb-2.5 mb-2.5">
<Clipboard className="w-4 h-4 text-primary" strokeWidth={2.5} />
<h2 className="text-xs font-bold text-slate-900 uppercase tracking-widest">任务概览</h2>
</div>
<div className="space-y-3">
<div>
<span className="text-[10px] uppercase tracking-wider text-slate-400 font-bold block mb-1">
当前节点
</span>
<div className="flex items-center justify-between gap-2.5">
<span className="text-sm font-bold text-slate-800">初始任务</span>
<span
className={`text-[10px] font-bold px-2 py-0.5 rounded-md border shrink-0 ${
currentStep === 1
? "text-[#ff9500] bg-orange-50 border-orange-200/50"
: currentStep === 2
? "text-[var(--brand-900)] bg-[var(--brand-200)] border-red-200/50"
: "text-emerald-600 bg-emerald-50 border-emerald-200/50"
}`}
>
{currentStep === 1 ? "待澄清" : currentStep === 2 ? "研讨中" : "已规划交付"}
</span>
</div>
<p className="text-xs text-slate-500 mt-2.5 leading-relaxed bg-slate-50 border border-slate-100 p-2 rounded-lg">
围绕某复杂任务制定规划方案
</p>
</div>
</div>
</div>
);
}
function HumanParticipationCard({
active = false,
onSelect,
}: {
/** 当前筛选是否命中「用户」(命中则高亮)。 */
active?: boolean;
/** 传入则可点击,用于筛选出用户的插话 / 澄清回复。 */
onSelect?: () => void;
} = {}) {
const clickable = Boolean(onSelect);
return (
<div className="bg-white border border-slate-200/50 rounded-2xl p-4 shadow-[0_2px_8px_rgba(0,0,0,0.01)]">
<div className="flex items-center gap-2 border-b border-slate-100 pb-2.5 mb-2.5">
<Activity className="w-4 h-4 text-primary" strokeWidth={2.5} />
<h2 className="text-xs font-bold text-slate-900 uppercase tracking-widest">人工参与</h2>
</div>
<div
role={clickable ? "button" : undefined}
tabIndex={clickable ? 0 : undefined}
aria-pressed={clickable ? active : undefined}
title={
clickable
? active
? "取消筛选,显示全部发言"
: "只看 用户 的发言"
: undefined
}
onClick={onSelect}
onKeyDown={
clickable
? (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onSelect?.();
}
}
: undefined
}
className={cn(
"roundtable-step2-human-row flex min-h-[56px] items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50 p-3 transition",
clickable && "cursor-pointer hover:border-primary/30 hover:bg-primary/5",
active && "ring-2 ring-primary ring-offset-1 ring-offset-white !border-primary/40",
)}
>
<div className="flex min-w-0 items-center gap-3">
<Man1Avatar size="h-10 w-10" />
<span className="truncate text-sm font-bold leading-5 text-slate-800">用户</span>
</div>
<div className="flex shrink-0 items-center gap-1.5 rounded-full border border-white/70 bg-white/70 px-2 py-1">
<span className="flex h-1.5 w-1.5 relative">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
<span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"></span>
</span>
<span className="whitespace-nowrap text-xs font-bold leading-none text-emerald-600">在线</span>
</div>
</div>
</div>
);
}
interface ModelSelectorCardProps {
selectedModel: string;
setSelectedModel: React.Dispatch<React.SetStateAction<string>>;
availableModels: ReadonlyArray<{ name: string; display_name?: string }>;
modelsLoading: boolean;
}
function ModelSelectorCard({
selectedModel,
setSelectedModel,
availableModels,
modelsLoading,
}: ModelSelectorCardProps) {
return (
<div className="bg-white border border-slate-200/50 rounded-2xl p-4 shadow-[0_2px_8px_rgba(0,0,0,0.01)]">
<div className="flex items-center gap-2 border-b border-slate-100 pb-2.5 mb-2.5">
<Cpu className="w-4 h-4 text-primary" strokeWidth={2.5} />
<h2 className="text-xs font-bold text-slate-900 uppercase tracking-widest">推理模型</h2>
</div>
<select
id="global-model-select"
value={selectedModel}
onChange={(e) => setSelectedModel(e.target.value)}
disabled={modelsLoading || availableModels.length === 0}
title={
modelsLoading
? "正在加载模型列表…"
: availableModels.length === 0
? "未在 config.yaml 中配置任何模型"
: "切换全局推理模型;不影响 Persona 抽屉里已设置的 per-seat 覆盖"
}
className="w-full bg-slate-50/50 border border-slate-100 rounded-xl px-3 py-2 text-xs font-bold text-slate-700 cursor-pointer focus:outline-none focus:border-primary focus:ring-1 focus:ring-[var(--brand-200)]/50 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-secondary dark:text-foreground dark:border-border"
>
{availableModels.length === 0 && (
<option value="">{modelsLoading ? "加载中…" : "未配置模型"}</option>
)}
{availableModels.map((m) => (
<option key={m.name} value={m.name}>
{m.display_name && m.display_name !== m.name
? `${m.display_name} (${m.name})`
: m.name}
</option>
))}
</select>
</div>
);
}
/**
* 「当前意图摘要」编辑态:目标(单行/多行文本)、约束、关键假设(均为可增删的列表)。
* 受控本地草稿,保存时过滤空行、要求目标非空,再上抛 {@link IntentSummary}。
*/
function IntentSummaryEditor({
initial,
title,
onSave,
onCancel,
}: {
initial: IntentSummary;
title: string;
onSave: (next: IntentSummary) => void;
onCancel: () => void;
}) {
const [objective, setObjective] = useState(initial.objective ?? "");
const [constraints, setConstraints] = useState<string[]>(
initial.constraints?.length ? [...initial.constraints] : [""],
);
const [assumptions, setAssumptions] = useState<string[]>(
initial.assumptions?.length ? [...initial.assumptions] : [],
);
const objectiveInvalid = objective.trim().length === 0;
const updateRow = (
setter: React.Dispatch<React.SetStateAction<string[]>>,
idx: number,
value: string,
) => setter((prev) => prev.map((v, i) => (i === idx ? value : v)));
const removeRow = (setter: React.Dispatch<React.SetStateAction<string[]>>, idx: number) =>
setter((prev) => prev.filter((_, i) => i !== idx));
const addRow = (setter: React.Dispatch<React.SetStateAction<string[]>>) =>
setter((prev) => [...prev, ""]);
const handleSave = () => {
if (objectiveInvalid) return;
onSave({
objective: objective.trim(),
constraints: constraints.map((c) => c.trim()).filter(Boolean),
assumptions: assumptions.map((a) => a.trim()).filter(Boolean),
});
};
const rowList = (
label: string,
rows: string[],
setter: React.Dispatch<React.SetStateAction<string[]>>,
placeholder: string,
) => (
<div className="space-y-1.5">
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">{label}</span>
<div className="space-y-1.5">
{rows.map((row, i) => (
<div key={i} className="flex items-center gap-1.5">
<input
value={row}
onChange={(e) => updateRow(setter, i, e.target.value)}
placeholder={placeholder}
maxLength={200}
className="min-w-0 flex-1 rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-[11.5px] text-slate-700 focus:border-primary focus:outline-none focus:ring-1 focus:ring-[var(--brand-200)]/50"
/>
<button
type="button"
onClick={() => removeRow(setter, i)}
title="删除该项"
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-slate-400 hover:bg-rose-50 hover:text-rose-500 transition-colors"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
))}
<button
type="button"
onClick={() => addRow(setter)}
className="inline-flex items-center gap-1 text-[11px] font-bold text-slate-500 hover:text-primary transition-colors"
>
<Plus className="h-3.5 w-3.5" />
添加{label}
</button>
</div>
</div>
);
return (
<div className="bg-white border border-primary/30 rounded-2xl p-4.5 shadow-[0_2px_8px_rgba(0,0,0,0.01)]">
<div className="flex items-center justify-between gap-2 border-b border-slate-100 pb-2.5 mb-3">
<div className="flex items-center gap-2 min-w-0">
<IntentSectionIcon className="w-4 h-4" />
<h2 className="text-xs font-bold text-slate-900 uppercase tracking-widest truncate">
编辑{title}
</h2>
</div>
<div className="flex items-center gap-1 shrink-0">
<button
type="button"
onClick={handleSave}
disabled={objectiveInvalid}
title="保存"
className="flex h-7 items-center gap-1 rounded-lg bg-primary px-2.5 text-[11px] font-bold text-white hover:bg-[var(--brand-900)] disabled:bg-slate-300 disabled:cursor-not-allowed transition-colors"
>
<Check className="h-3.5 w-3.5" />
保存
</button>
<button
type="button"
onClick={onCancel}
title="取消"
className="flex h-7 w-7 items-center justify-center rounded-lg text-slate-500 hover:bg-slate-50 hover:text-slate-700 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
<div className="space-y-3">
<div className="space-y-1.5">
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">核心目标</span>
<textarea
value={objective}
onChange={(e) => setObjective(e.target.value)}
rows={3}
maxLength={500}
placeholder="一句话说明本次要达成什么"
className={cn(
"w-full resize-y rounded-lg border bg-white px-2.5 py-1.5 text-[11.5px] leading-relaxed text-slate-700 focus:outline-none focus:ring-1",
objectiveInvalid
? "border-rose-300 focus:border-rose-400 focus:ring-rose-200/50"
: "border-slate-200 focus:border-primary focus:ring-[var(--brand-200)]/50",
)}
/>
{objectiveInvalid && (
<p className="text-[10px] text-rose-500">核心目标不能为空</p>
)}
</div>
{rowList("约束", constraints, setConstraints, "如:预算 / 时间 / 合规 / 范围")}
{rowList("假设", assumptions, setAssumptions, "智能体为你做的假设(可选)")}
</div>
</div>
);
}
interface IntentSummaryCardProps {
intentReady: ReturnType<typeof useStep1Intent>["intentReady"];
title?: string;
/** Step 2 侧栏: 收起时仅展示目标,展开后显示约束与假设。 */
collapsible?: boolean;
/** 侧栏整体收起按钮,放在标题栏右侧。 */
sidebarToggle?: {
expanded: boolean;
onToggle: () => void;
};
/**
* 提供则显示「编辑」按钮,允许用户手动修改识别出的意图(目标 / 约束 / 假设)并保存。
* 保存后回调上抛新意图,由页面覆盖 `intentReady` 并持久化草稿。不传 = 只读。
*/
onSave?: (next: IntentSummary) => void;
}
function IntentSummaryCard({
intentReady,
title = "当前意图摘要",
collapsible = false,
sidebarToggle,
onSave,
}: IntentSummaryCardProps) {
const [expanded, setExpanded] = useState(!collapsible);
const showFullDetail = !collapsible || expanded;
const [editing, setEditing] = useState(false);
if (editing && intentReady) {
return (
<IntentSummaryEditor
initial={intentReady}
title={title}
onCancel={() => setEditing(false)}
onSave={(next) => {
onSave?.(next);
setEditing(false);
}}
/>
);
}
return (
<div className="bg-white border border-slate-200/50 rounded-2xl p-4.5 shadow-[0_2px_8px_rgba(0,0,0,0.01)]">
<div className="flex items-center justify-between gap-2 border-b border-slate-100 pb-2.5 mb-2.5">
<div className="flex items-center gap-2 min-w-0">
<IntentSectionIcon className="w-4 h-4" />
<h2 className="text-xs font-bold text-slate-900 uppercase tracking-widest truncate">{title}</h2>
</div>
<div className="flex items-center gap-1 shrink-0">
{onSave && intentReady && (
<button
type="button"
onClick={() => setEditing(true)}
title="编辑意图"
className="flex h-7 w-7 items-center justify-center rounded-lg text-slate-500 hover:text-primary hover:bg-slate-50 transition-colors"
>
<Pencil className="h-3.5 w-3.5" />
</button>
)}
{sidebarToggle && (
<button
type="button"
onClick={sidebarToggle.onToggle}
title={sidebarToggle.expanded ? "收起侧栏" : "展开侧栏"}
aria-expanded={sidebarToggle.expanded}
className="flex h-7 w-7 items-center justify-center rounded-lg text-slate-500 hover:text-primary hover:bg-slate-50 transition-colors"
>
{sidebarToggle.expanded ? (
<PanelLeftClose className="h-4 w-4" />
) : (
<PanelLeftOpen className="h-4 w-4" />
)}
</button>
)}
</div>
</div>
<div className="p-3 bg-slate-50/50 border border-slate-100 rounded-xl space-y-3 mr-0.5">
{intentReady ? (
<>
<ul className="text-xs text-slate-700 space-y-2.5 font-normal">
<li className="flex items-start gap-2 leading-relaxed">
<span className="text-primary text-base leading-none pt-0.5">•</span>
<span
className={cn(
"min-w-0 leading-relaxed",
collapsible && !expanded && "line-clamp-3",
)}
>
<b className="text-slate-900 font-bold">目标</b>: {intentReady.objective}
</span>
</li>
</ul>
{collapsible && (
<div className="flex justify-end">
<button
type="button"
onClick={() => setExpanded((v) => !v)}
className="inline-flex items-center gap-0.5 text-xs font-bold text-slate-500 hover:text-primary transition-colors"
aria-expanded={expanded}
>
{expanded ? (
<>
收起
<ChevronUp className="w-3.5 h-3.5" />
</>
) : (
<>
展开
<ChevronDown className="w-3.5 h-3.5" />
</>
)}
</button>
</div>
)}
{showFullDetail && (
<ul className="text-xs text-slate-700 space-y-2.5 font-normal">
{(intentReady.constraints ?? []).map((c, i) => (
<li key={`c-${i}`} className="flex items-baseline gap-2 leading-relaxed">
<span className="text-primary text-base leading-none">•</span>
<span>
<b className="text-slate-900 font-bold">约束</b>: {c}
</span>
</li>
))}
{(intentReady.assumptions ?? []).map((a, i) => (
<li key={`a-${i}`} className="flex items-baseline gap-2 leading-relaxed">
<span className="text-slate-400 text-base leading-none">•</span>
<span className="text-slate-500">
<b className="text-slate-700 font-bold">假设</b>: {a}
</span>
</li>
))}
</ul>
)}
</>
) : (
<p className="text-xs text-slate-400 italic leading-relaxed">
等待任务理解智能体澄清完成...
</p>
)}
</div>
</div>
);
}
function IntentSectionIcon({ className }: { className?: string }) {
return (
<svg
className={cn("text-primary shrink-0", className)}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
>
<circle cx="12" cy="12" r="10" />
<circle cx="12" cy="12" r="6" />
<circle cx="12" cy="12" r="2" />
</svg>
);
}
function CollapsedSidebarSection({
title,
children,
className,
}: {
title: string;
children: React.ReactNode;
className?: string;
}) {
return (
<div
title={title}
className={cn(
"w-full shrink-0 bg-white border border-slate-200/50 rounded-[4px] p-2 shadow-[0_2px_8px_rgba(0,0,0,0.01)] flex flex-col items-center justify-center",
className,
)}
>
{children}
</div>
);
}
function renderRoleAvatar(
role: RoleEntry,
agentNameToRole: Record<
string,
{ speakerId: number; avatarType: string; displayName: string }
>,
size: string,
) {
if (role.type === "human") {
return <Man1Avatar size={size} />;
}
return getAvatar(
role.agentId ? agentNameToRole[role.agentId]?.avatarType ?? "blue" : "blue",
size,
);
}
function RoleAvatarBadge({
role,
agentNameToRole,
size = "h-7 w-7",
showSpeakingAnimation = false,
active = false,
onSelect,
}: {
role: RoleEntry;
agentNameToRole: Record<
string,
{ speakerId: number; avatarType: string; displayName: string }
>;
size?: string;
showSpeakingAnimation?: boolean;
/** 当前筛选是否命中本席位(命中则头像高亮)。 */
active?: boolean;
/** 传入则头像可点击,用于「按席位筛选会商记录」(收起态)。 */
onSelect?: () => void;
}) {
const isOngoing = role.status === "研讨中";
const isDone = role.status === "已完成";
const animate = showSpeakingAnimation && isOngoing;
const clickable = Boolean(onSelect);
const inner = (
<div
className={cn(
"relative shrink-0 rounded-full",
animate && "ring-2 ring-primary/50 ring-offset-2 ring-offset-white",
active && "ring-2 ring-primary ring-offset-2 ring-offset-white",
)}
>
{animate && (
<span className="pointer-events-none absolute inset-0 rounded-full border-2 border-primary/35 animate-ping" />
)}
<div className={cn("relative rounded-full", animate && "animate-pulse")}>
{renderRoleAvatar(role, agentNameToRole, size)}
</div>
{/* 收起态:输出完成的席位在头像右下角叠加「已完成」勾选角标。 */}
{isDone && (
<span className="pointer-events-none absolute -bottom-0.5 -right-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-emerald-500 ring-2 ring-white">
<Check className="h-2.5 w-2.5 text-white" strokeWidth={3} />
</span>
)}
</div>
);
if (!clickable) {
return <div title={`${desensitize(role.name)} · ${role.status}`}>{inner}</div>;
}
return (
<button
type="button"
onClick={onSelect}
aria-pressed={active}
title={active ? "取消筛选,显示全部发言" : `只看 ${desensitize(role.name)} 的发言`}
className="shrink-0 cursor-pointer rounded-full transition hover:opacity-80 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60"
>
{inner}
</button>
);
}
function RoleRow({
role,
agentNameToRole,
active = false,
onSelect,
}: {
role: RoleEntry;
agentNameToRole: Record<
string,
{ speakerId: number; avatarType: string; displayName: string }
>;
/** 当前筛选是否命中本席位(命中则整卡高亮)。 */
active?: boolean;
/** 传入则整卡可点击,用于「按席位筛选会商记录」。 */
onSelect?: () => void;
}) {
const isActive =
role.status === "在线" || role.status === "研讨中" || role.status === "已完成";
const isOngoing = role.status === "研讨中";
const isBootingUp = role.status === "正在上线";
const clickable = Boolean(onSelect);
return (
<div
id={`role-item-${role.id}`}
role={clickable ? "button" : undefined}
tabIndex={clickable ? 0 : undefined}
aria-pressed={clickable ? active : undefined}
title={
clickable
? active
? "取消筛选,显示全部发言"
: `只看 ${desensitize(role.name)} 的发言`
: undefined
}
onClick={onSelect}
onKeyDown={
clickable
? (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onSelect?.();
}
}
: undefined
}
className={cn(
"roundtable-step2-role-row flex min-h-[60px] items-center justify-between gap-3 rounded-xl p-3 transition",
isActive
? "bg-slate-50 border border-slate-100"
: isBootingUp
? "bg-amber-50/60 border border-amber-100"
: "opacity-60",
clickable && "cursor-pointer hover:border-primary/30 hover:bg-primary/5",
active &&
"ring-2 ring-primary ring-offset-1 ring-offset-white !border-primary/40 !opacity-100",
)}
>
<div className="flex min-w-0 items-center gap-3">
<RoleAvatarBadge role={role} agentNameToRole={agentNameToRole} size="h-10 w-10" />
<div className="flex min-w-0 flex-col gap-0.5">
<span className="truncate text-sm font-bold leading-5 tracking-tight text-slate-800">
{desensitize(role.name)}
</span>
{role.type === "agent" && (
<span className="text-[11px] text-primary font-medium leading-4">AI 智能体</span>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-1.5 rounded-full border border-white/70 bg-white/70 px-2 py-1">
{isOngoing ? (
<span className="flex h-1.5 w-1.5 relative">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary/60 opacity-75"></span>
<span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-primary"></span>
</span>
) : role.status === "在线" ? (
<span className="flex h-1.5 w-1.5 relative">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
<span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"></span>
</span>
) : role.status === "已完成" ? (
<Check className="h-3.5 w-3.5 text-emerald-500 font-bold" />
) : isBootingUp ? (
<Loader2 className="h-3 w-3 text-amber-500 animate-spin" />
) : (
<span className="h-1.5 w-1.5 rounded-full bg-slate-300" />
)}
<span
className={`whitespace-nowrap text-xs font-semibold leading-none ${
isOngoing
? "text-[var(--brand-900)]"
: role.status === "在线"
? "text-emerald-600 font-bold"
: role.status === "已完成"
? "text-emerald-600"
: isBootingUp
? "text-amber-600"
: "text-slate-400"
}`}
>
{role.status}
</span>
</div>
</div>
);
}
interface RightSidebarProps {
currentStep: number;
selectedModel: string;
setSelectedModel: React.Dispatch<React.SetStateAction<string>>;
availableModels: ReadonlyArray<{ name: string; display_name?: string }>;
modelsLoading: boolean;
intentReady: ReturnType<typeof useStep1Intent>["intentReady"];
timelineEntries: ReturnType<typeof useStep1Intent>["timelineEntries"];
triggerToast: (msg: string) => void;
/** 用户编辑并保存意图的回调(透传给 IntentSummaryCard)。 */
onSaveIntent: (next: IntentSummary) => void;
}
/**
* 深链 taskId 模式 · Step 1 消息列表头部左侧的「策划流程」小图。
*
* 取代默认标题(任务意图理解),按目的树层级(目的 → 行为体 → … → 叙事)横向排列
* 彩色小图标、图标间用箭头串联,配色与流程图画布节点一致(FLOW_NODE_TYPE_META)。
* 点击整条 → 打开任务目的流程图弹窗看完整大图(不再单独放「查看」按钮)。
* 无层级数据时由调用方退回默认标题(此处 levels 必非空)。
*/
/** 各层级(流程图节点类型)对应的小图标;未列出的类型回退 Layers。 */
const LEVEL_ICON: Partial<Record<FlowNodeType, React.ComponentType<{ className?: string }>>> = {
stage: Target, // 目的
role: Users, // 行为体
task: Activity, // 预期行为
decision: Zap, // 驱动因素
deliverable: BookOpen, // 叙事
};
function PurposeFlowPreview({
levels,
onOpen,
dark = false,
}: {
levels: PurposeLevel[];
onOpen: () => void;
dark?: boolean;
}) {
if (levels.length === 0) return null;
const meta = flowNodeMeta(dark);
return (
<button
type="button"
onClick={onOpen}
title="点击查看完整策划流程图"
className="group/flow custom-scrollbar flex min-w-0 cursor-pointer items-center gap-2 overflow-x-auto rounded-lg text-left transition-opacity hover:opacity-90"
>
<span className="inline-flex shrink-0 items-center gap-1.5 text-[11px] font-bold text-slate-500">
<Layers className="h-3.5 w-3.5 text-primary" />
原任务已有结果
</span>
{levels.map((lv, i) => {
const m = meta[lv.type];
const Icon = LEVEL_ICON[lv.type] ?? Layers;
return (
<span key={`${lv.label}-${i}`} className="flex shrink-0 items-center gap-1">
{i > 0 && <ChevronRight className="h-3.5 w-3.5 shrink-0 text-slate-300" />}
<span
title={lv.label}
style={{ background: m.bg, borderColor: m.border, color: m.text }}
className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10.5px] font-semibold"
>
<Icon className="size-3 shrink-0" />
{lv.label}
</span>
</span>
);
})}
</button>
);
}
function RightSidebar({
currentStep,
selectedModel,
setSelectedModel,
availableModels,
modelsLoading,
intentReady,
timelineEntries,
triggerToast,
onSaveIntent,
}: RightSidebarProps) {
// 整片脱敏:右侧面板(推荐模型 / 意图摘要 / 澄清记录)所有文本。
const dzRef = useDesensitizeSubtree<HTMLElement>();
// Step 2 侧栏内容已迁至左侧;Step 3 沿用原逻辑不展示右侧栏。
if (currentStep !== 1) return null;
return (
<section
ref={dzRef}
id="right-sidebar"
className="w-[300px] shrink-0 flex flex-col gap-4 overflow-y-auto pl-1"
>
<ModelSelectorCard
selectedModel={selectedModel}
setSelectedModel={setSelectedModel}
availableModels={availableModels}
modelsLoading={modelsLoading}
/>
<IntentSummaryCard intentReady={intentReady} onSave={onSaveIntent} />
{/* 澄清记录 Timeline */}
<div className="bg-white border border-slate-200/50 rounded-2xl p-4.5 shadow-[0_2px_8px_rgba(0,0,0,0.01)] flex-1 flex flex-col min-h-[300px]">
<div className="flex items-center gap-2 border-b border-slate-100 pb-2.5 mb-3 shrink-0">
<Clock className="w-4 h-4 text-primary" strokeWidth={2.5} />
<h2 className="text-xs font-bold text-slate-900 uppercase tracking-widest">澄清记录</h2>
</div>
<div className="flex-1 overflow-y-auto pr-1 font-normal custom-scrollbar">
<div className="relative ml-2 space-y-4 border-l border-red-50 pb-2 pl-4 pt-1.5">
{timelineEntries.map((entry) => (
<div
key={entry.id}
className="roundtable-clarification-entry relative rounded-lg px-1.5 py-1 transition-colors hover:bg-slate-50/80"
>
<div className="absolute -left-[20.5px] top-2 h-3 w-3 rounded-full bg-primary border-2 border-white ring-2 ring-[var(--brand-200)]" />
<div className="grid grid-cols-[68px_minmax(0,1fr)] gap-x-2">
<span className="font-mono text-xs leading-5 tracking-tight text-slate-400">
{entry.time}
</span>
<div className="min-w-0">
<h4 className="break-words text-sm font-bold leading-5 tracking-tight text-slate-800">
{entry.title}
</h4>
<p className="mt-1 break-words text-xs leading-5 text-slate-500">
{entry.desc}
</p>
</div>
</div>
</div>
))}
</div>
</div>
<div className="shrink-0 pt-2.5 border-t border-slate-100 flex items-center justify-between text-xs mt-2.5">
<span className="text-slate-400 font-medium">共 {timelineEntries.length} 条记录</span>
<button
onClick={() =>
triggerToast(`正在渲染全部 ${timelineEntries.length} 个历史事件归档`)
}
className="text-primary hover:text-[var(--brand-900)] font-bold hover:underline"
>
查看全部 &gt;
</button>
</div>
</div>
</section>
);
}