Compare commits

...
114 Commits
Author SHA1 Message Date
Rocky Kwok ab305b3514 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-06-22 14:44:24 +08:00
Rocky Kwok b89933e60a chore: ignore 2026-06-22 10:55:00 +08:00
董宏凯 6e3896fed3 Merge branch 'dhk-1' 2026-06-21 20:43:32 +08:00
董宏凯andClaude Opus 4.8 545ec178b8 fix(roundtable): 第三步重新分析前复位入库状态,避免重分析后仍问是否入库
重跑总结/重新或修改流程图前整体复位 ingest 状态为 idle(隐藏旧产物的入库
询问卡/协助卡/手动入库按钮);流程图类重分析出新图后 runFlowExtract 在 idle
时重新询问,重新生成报告则在报告重写完成后(若已有流程图)重新询问是否入库。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 20:43:06 +08:00
董宏凯andClaude Opus 4.8 6dd1f9c017 fix(roundtable): 模型容错提示顺序前置 + 回看历史时残留「加载中」气泡强制收尾
- 第二步模型自动容错:系统提示气泡改为插入到失败气泡正前方,使「已切换其他
  模型」先于新模型重答过程显示(旧实现追加到列表末尾,反而排在答案之后)。
- 加载历史草稿(hydrateFromDraft)时把任何残留 streaming 的气泡强制收尾为静止
  态(去加载光标、角标改「已结束」、空正文补「(已结束)」),避免用户点聊天
  记录回看时误以为研讨仍在进行。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 20:42:54 +08:00
董宏凯andClaude Opus 4.8 6b963fd918 fix(roundtable): 修复管理员连续编辑第二条他人业务链保存 404「已删除」
编辑器 chainId 闸门由「整组件生命周期只加载一次」改为「按已应用的 chainId 追踪、变化即重载」。
此编辑器实例在多次导航间可能不卸载(从业务链弹窗进来时尤甚),旧闸门导致第二次打开另一条链条
时根本不加载,currentChainId 停在上一条 → 保存打到错误 id → 后端 404,必须重新登录才恢复。
同一 chainId 不重复加载、也不覆盖编辑器内的手动切换;getChain 取不到时给出明确提示。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 20:21:49 +08:00
董宏凯andClaude Opus 4.8 f13a1bb7fe feat(roundtable): 业务链条配置增加管理员权限,管理员可配所有链条
- 后端 store/路由:scope=all(仅管理员)列全量;get/update/delete 加 is_admin 旁路,管理员可操作任意 owner 链条且不转移归属;非管理员请求 all 退化为 mine
- 前端列表页/会商弹窗:管理员多「全部链条」筛选 tab,canManage=isAdmin||isMine 放开发布/设置/删除
- 编辑器:管理员可见发布按钮;按 chainId 找不到本地列表时直接 getChain 拉取(修复管理员从「全部链条」进编辑器空白),并修掉自身无链条时加载卡死的边界

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 17:17:19 +08:00
董宏凯 02115bccfe Merge branch 'dhk-1' into 'master'
feat(roundtable): 会商席位「技能识别强化」改为按需开关(智能体级 + 链条每席位级)

See merge request knowledge-base-bj/deerflow-server!141
2026-06-21 08:59:10 +00:00
董宏凯andClaude Opus 4.8 48744441ba fix(roundtable): 修复会商消息列表滚动条被分栏手柄抢占、且过细难抓
- Step2/Step3 分栏拖拽手柄 ::after 命中区(16px,居中跨分隔线)向左探出 8px
  压住左侧消息列表纵向滚动条,抓滑块误触发左右拖动;改为命中区整体移到
  分隔线右侧(沙箱一侧),左侧滚动条让出
- 会商页滚动条 6px→12px(透明边框+background-clip 收成带内边距圆条),更易抓
- 覆盖 Step1/Step2/Step3(summary/report)所有消息列表,含有沙箱与流程图分栏场景

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 00:42:40 +08:00
董宏凯andClaude Opus 4.8 5ae6261e82 fix(roundtable): 结构化抽取按实际产出抽全(不固定条数/不编造),提升准确度
不动 rwfx 链路结构(任务→目的→行为体→预期行为→驱动因素→叙事;仅预期行为↔驱动因素
1:1,其余皆 1:N)。只修准确度:

- 叙事不再凭空多出来一堆:驱动因素→叙事 仍是 1:N,但叙事条数严格按报告/叙事席位
  实际写出的来(写几条抽几条),删掉「每个驱动因素抽出它名下的若干条叙事」这种诱导
  逐驱动因素编造的措辞——根治「叙事席位只产 3 条、流程图却冒出十几条」
- 去掉所有写死的条数假设(目的「通常3个」、预期行为「3-5条」、叙事「2-4条」、
  候选「10→3」)——各席位交付条数本就不固定,一律以实际产出为准,不漏不多不硬凑

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 00:34:00 +08:00
董宏凯andClaude Opus 4.8 a76e28e018 fix(roundtable): 结构化抽取严格以报告为准,根治从席位候选池抽出一堆目的
报告只锁定 3 个目的(从 10 个候选里取舍),但流程图抽出一堆目的——根因是之前
「候选项也要抽全」+ 把各席位原始交付当补充来源,诱导模型去席位候选池里把被淘汰的
候选也抽进来。

按用户原则修正优先级(优先方案总结报告及其文件内容,只有报告不足/缺失才看席位产物):
- extraction_spec _SOURCE_NOTE:改为「严格以报告为准;席位仅兜底(报告整层缺失/只说N条
  没逐条列才用),绝不用席位扩充报告已取舍的层、淘汰候选一律不抽」
- _COMPLETENESS_NOTE:由「候选项也要抽全(含落选)」改为「按报告逐条抽全、不漏也不多」——
  报告列几条抽几条(不漏),但报告已锁定 N 条的层只抽这 N 条、不去候选池凑数(不多)
- rwfx completeness_note 目的/叙事:抽报告最终采用的(3 个目的/几条叙事),不抽候选池
- flow_extract._material:席位交付明确标为「兜底参考,仅报告不足时用」,禁止扩充已取舍层
- _extract_messages / _validate_messages:同步改为报告为准、补漏但不新增被淘汰候选

经核对:本次方案总结报告本身准确(3 目的=席位最终 Top3、3 行为体、12 预期行为↔12 驱动
因素已做 1:1 配对、3 叙事),问题只在抽取从席位候选池过度抽取。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 00:08:23 +08:00
董宏凯andClaude Opus 4.8 f63a1faf3b fix(roundtable): rwfx 结构化抽取纯树·单父兜底,根治叙事多对一乱线
rwfx 全链是一棵树:除预期行为↔驱动因素 1:1 外其余皆 1:N,任何节点只有一个父节点、
绝无多对一/多对多/汇聚。但弱模型常把「叙事」连到一片驱动因素 → 汇聚乱线。

- extraction_spec:ChainSpec 加 single_parent 标志(rwfx=True,xdfx 有汇聚=False);
  helper is_single_parent_chain / chain_level_rank;强化 rwfx ②「叙事只有一个父驱动因素」
  + 新增④「全链是树,每个非根节点恰一个 from」
- flow_extract:_collapse_to_single_parent 确定性兜底——纯树业务把每个节点的多父入边
  收敛到「紧邻上一层」的单一父节点(只删多余入边、不新增、不动节点),在 final 前执行;
  非纯树业务(xdfx)跳过
- dag-types/types:DAG 派活忠实本阶段目标——不擅自加数量上限/精简、不替席位加体例风格、
  逐条全部输出、不诱导脱离输入编造(前后台同步)
- Tests: tests/test_flow_extract_single_parent.py

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 23:37:49 +08:00
董宏凯andClaude Opus 4.8 3d75040297 fix(roundtable): 会商消息列表只竖向滚,修复滑块被横向拖动抢占难点击
消息列表用 `overflow-y-auto` 单写时,按 CSS 规范另一轴(overflow-x)会被计算成
auto——任何子元素溢出一两像素就让整列横向可滚,鼠标移到右侧竖滚条滑块时极易误
触发横向拖动、抓不住滑块。给消息流容器补 `overflow-x-hidden` 只保留竖向滚动;
宽内容(代码块/表格)在各自气泡内已有 max-w-full + overflow-x-auto 自带横滚,裁掉
列表横向不影响查看。

覆盖 Step1/Step2(会商)/Step3 总结·报告·大屏 五处聊天消息流容器。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 22:58:44 +08:00
董宏凯andClaude Opus 4.8 8447790c47 fix(roundtable): 预期行为↔驱动因素严格 1:1,根治结构化抽取多对一/一节点多出边
报告把某行为体的多个驱动因素合并写进一个表格单元格(其余预期行为行留空),
导致结构化抽取把「多条预期行为汇聚到一个驱动因素」(多对一)、或一个节点冒出
多条连线。根因:1:1 两层节点数不相等时,模型与确定性补边(_derive_layered_edges)
都只能退化成多对一/比例平铺。

修复(让两层严格等量、一一配对):
- extraction_spec rwfx relations_note①: 强化为「严格 1:1」——为每条预期行为归纳
  那一个核心驱动因素、两层等量、每个驱动因素 from 只连一条预期行为、严禁多对一/
  一节点多出边;源数据把多个驱动因素合并在一处时必须按预期行为拆开/重新归纳成等量
- extraction_spec completeness_note: 驱动因素层节点数=预期行为层节点数(1:1 特例)
- build_summary_directive: 让报告本身把 1:1 相邻层写成逐条配对表(一行一对、数量相等),
  不要把多个下层条目用「+」合并塞进一个单元格或只写第一行——从源头消除多对一
- flow_extract 校验新增「一对一层级必须严格 1:1、绝不多对一」必查必补项

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 22:43:48 +08:00
董宏凯andClaude Opus 4.8 b5f11ad790 fix(roundtable): 结构化抽取逐条抽全(候选项不漏)+报告不足回看席位交付
修复深链接(rwfx等)结构化流程图抽取「同层多条只抽一条」的准确性问题:
报告里 3 个候选目的只抽出 1 个、每个行为体名下多条预期行为被合并成 1 条、
3 组候选叙事只画 2 个且连线错。

- extraction_spec: 新增业务无关的 _COMPLETENESS_NOTE「逐条抽全、候选项也要抽」
  注入通用规范+写实规范; rwfx completeness_note 显式点名候选目的/每行为体多条
  预期行为/候选叙事都要全抽; _SOURCE_NOTE 改为「报告为主+席位交付补充」
- flow_extract._material: 报告与各席位原始交付一起喂给模型(报告把某层条目压缩
  时回到交付逐条抽全,冲突以报告为准),不再 report present 就只用报告
- flow_extract 抽取/校验 prompt: 补「逐条抽全+候选项全抽+不许合并+不要只照搬
  方案总纲精简主干」,校验新增「候选/多条目是否抽全」必查必补项

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 22:16:27 +08:00
董宏凯andClaude Opus 4.8 d383b0e9dd feat(roundtable): 第二/三步模型自动容错(出问题自动换下一个模型)
模型出问题时按 config.yaml models[] 顺序自动切到下一个模型继续,并告知用户
「『X』模型异常 → 已切换『Y』继续」。前台实时 + 后台挂起两条路径都覆盖。

- 中间件兜底/熔断 AIMessage 打 LLM_ERROR_MARKER 标记,is_llm_error_message 可识别
- roundtable_model_fallback: fallback_model_chain 候选链 + reason_text + 总开关
  env ROUNDTABLE_MODEL_FALLBACK
- 触发: 异常(start_run失败/idle卡死) / 兜底错误文案 / 交付为空(仅seat/leader)
- 后台 InProcessRoundtableGateway._run_turn_with_fallback 包住每轮 run
- 前台 _special_run/_leader_run 收尾检测失败→model_switch 帧+换模型重流
- 结构化抽取 flow_extract round1 astream 同款换模型循环
- Step2 单席位异常隔离: 单席位失败不拖垮整批/整链/整个作业
- 时间线插「系统提示」气泡 + toast + 诊断 model_switch 事件
- Tests: test_roundtable_model_fallback.py

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 21:37:45 +08:00
董宏凯andClaude Opus 4.8 ae2706dad3 feat(roundtable): xdfx 行动名喂入 summary/抽取 + 第三步意图理解增强
- xdfx:把本次「行动名称」喂进 summary 材料(buildMaterials 加 actionName) 与结构化抽取
  材料(flow_extract._material 加【本次行动】抬头),让报告/流程图都贴着该行动展开
- 第三步意图识别(classify_flow_intent)增强:新增 can_ingest 上下文 + ingest 意图;重写
  _INTENT_SYS 走语义理解——「介绍/解释/为什么/总结一下」等对内容的提问→qa(文字答);
  「帮我入库」(可入库时)→ingest→直接入库;能判断就给具体意图不轻易 unclear;
  不可入库时误判 ingest 自动降级 qa。前端 classifyFlowIntent 传 canIngest,ask 新增 ingest 分支

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 20:39:24 +08:00
董宏凯 fba417918f feat(roundtable): xdfx 左上角只显行动名/cop-task-detail可mock/抽取根节点用行动名
- xdfx 深链左上角「当前行动」只显示行动名称,去掉行动叙事
- cop-task-detail 加本地假数据开关 VITE_MOCK_COP_TASK_DETAIL(仿 VITE_MOCK_SQ_REPORT):
  true 走 mockCopTaskDetail(dev=true,sit/network=false);真实接口未就绪时调试用
- 结构化抽取(flow-json):FlowExtractRequest 加 root_label,xdfx 强制根节点 n1 的 label
  用本次「行动名称」(前端 useStep3Summary 传 readActionDetail().actionName);extract+validate 两段都注入

注:行动详情 mock(actionName/narration) 在 config.yaml(按惯例不提交)。
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 20:18:02 +08:00
董宏凯andClaude Opus 4.8 b513a0d56c feat(roundtable): 深链接第一步任务/行动展示 + xdfx 行动详情接入会商
- Step1 深链接(taskId)下:左栏顶部「业务链选择」隐藏,改显当前任务(rwfx/3qfx:任务名称+描述)
  或当前行动(xdfx:行动名称+叙事);顶栏「业务链条」入口隐藏;「新建任务」改「重新分析」
  (复位 autoStarted + resetToStep1,对同一任务重做意图分析)
- xdfx 行动详情接入会商:fetchActionDetail 取到即 persistActionDetail 缓存;新增
  readActionDetail/persistActionDetail + ACTION_DETAIL_STORAGE_KEY;resolveTaskDeeplinkTarget
  会商分支为 xdfx 把 actionId/actionName 带入 roundtablePrefill
- xdfx 首条交给任务理解的消息 = 任务名称 + 任务描述 + 行动名称
- 「原任务已有结果」(目的树预览 headerLeftSlot) 仅 rwfx-A(6BF) 显示

注:行动详情 mock(actionName/narration) 在 config.yaml(按惯例不提交,单独管理)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 20:05:27 +08:00
董宏凯andClaude Opus 4.8 b1b1ff98f5 feat(roundtable): 深链接业务链抽取规范 + 总结报告文件干净/对话强制核对
深链接会商(taskId+goPath,businessCode)下按所选业务链完整层级强制校正
结构化抽取(flow-json) 与 方案总结报告:

- 新增 harness 层 extraction_spec(app+harness 共用,单份领域知识两角色用法):
  build_structure_directive / build_summary_directive 按 businessCode 取
  · rwfx(6BF):线性 任务→目的→行为体→预期行为→驱动因素→叙事;预期行为↔驱动因素 1:1、余 1:N
  · xdfx(7BF):分叉汇聚 DAG,根=行动;行动→受众目标/关键传播节点(1:N)→脆弱点(1:N)→策略(多对一)
  · 其余业务通用规范(强约束完整性+命名+取数、不套固定模板);business_code 空→零副作用
- 结构化抽取:flow_extract._hierarchy_hint + _validate_messages 用 structure_directive
  权威覆盖默认层级(根治"无论什么业务都按目的→行为体抽/停在行为体");前端 streamFlowExtract
  传 business_code(源 ingestBusinessCode)
- 方案总结报告:前台 multi_agent._special_run(summary) + 后台 build_summary_prompt 注入
  business 完整性核对(StartJobRequest/StartParams 透传)
- 报告产物策略:.md 报告文件保持完整、干净、无需修改(不写 待补充/不足/⚠️);
  「核对说明」(意图对齐+业务链完整性+不足/可补充)改为只在对话回复正文、且每次必出
- 种子 roundtable-structure SOUL 层级顺序改 spec-driven、去 rwfx 写死示例

Tests: test_roundtable_extraction_spec / test_roundtable_summary_prompt

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 18:13:03 +08:00
董宏凯andClaude Opus 4.8 3ab674e438 feat(roundtable): Step2 提速四件套 + 方案总结报告意图对齐
Step2 提速:
- 每席位推理深度覆盖(seat_mode): 业务链条逐席位可配 flash/thinking/pro/ultra,
  覆盖链条级 seatMode;前台三处 dispatch + 后台 job 透传, run_seat 用 _SEAT_MODE_PARAMS 解析
- recommend 后端批内并行: engine._run_recommend 由串行 for 改 asyncio.gather(对齐前端)
- 研讨前并行取数两段式(gather_first, 业务链条 opt-in): 研讨前全席位并行只取数,
  产出作为共享资料注入研讨轮(_seat_message gathered + 前台 runGatherPhase);
  新增 gather_first 列(migration 20260620_02 + idempotent SQL)
- 削减重复广播: suppressPreBroadcast 扩到 recommend(round>=2)/chain(i>0)/chain收口,
  保留首轮背景打底,省 N 次读写大 thread

方案总结报告效果:
- summary 加"意图对齐+缺口核对+防幻觉护栏": SOUL + 后端 build_summary_prompt +
  前端 buildSummaryPrompt 三处对齐; 推断标注(综合推断)、缺真实信息标注待补充交给用户、绝不凭空编

Tests: test_roundtable_seat_modes / test_roundtable_gather_phase / test_roundtable_summary_prompt

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 16:28:02 +08:00
董宏凯andClaude Opus 4.8 9a1b674950 feat(roundtable): 会商席位「技能识别强化」改为按需开关(智能体级 + 链条每席位级)
弱模型补偿指令从全域生效改为默认关闭、两个 opt-in 开关取 OR:
- 智能体级: AgentConfig.seat_skill_directive(config.yaml),在智能体编辑弹窗
  (agent-card / agent-detail-panel)开关;agents 路由 create/update/读写全程穿。
- 业务链条每席位级: 存进链条 seats JSON(ChainSeatSchema.seat_skill_directive,
  无需 DB 列/迁移),在链条编辑器每个席位卡片右侧 ✨ 图标→下拉框(开关+说明)配置;
  按 agentId 查表穿到前台 useStep2Orchestration 各席位调用 + 后台作业
  seat_skill_directives:{agentId:bool} → InProcessRoundtableGateway.run_seat。
- ROUNDTABLE_SEAT_SKILL_DIRECTIVE 降级为总熔断开关(默认放行,不再 force-on)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 13:37:29 +08:00
董宏凯 9278fd772f Merge branch 'dhk-1' into 'master'
fix(roundtable): 会商 Step2/Step3 沙箱产物按对话创建者解析,修复历史/跨用户查看不了

See merge request knowledge-base-bj/deerflow-server!140
2026-06-19 15:47:18 +00:00
董宏凯 a8c06ca7dc 代码提交 2026-06-19 23:46:53 +08:00
董宏凯andClaude Opus 4.8 762d3620c4 feat(roundtable): 会商前端调用报错收集 + 诊断页用户名/范围切换
- 前端调用报错收集(用户实际遇到的报错,服务端诊断看不到的也收):新增
  POST /api/roundtable-diagnostics/report(非 admin,scope="client")+ 前端上报器
  roundtable-planning/api/diagnostics-report.ts。streamMultiAgent(第二步席位 +
  第三步报告/结构化/绘制/大屏)覆盖 HTTP 错误(502)、SSE error 帧、worker error 帧
  (模型没调用成功)、fetch 网络不可达、流式中途中断,reported 去重;initMultiAgent /
  intent / recommend / 后台作业接口同步上报。
- 诊断页:每条报错显示上报用户名(👤,user_id→邮箱@前缀,后端 best-effort 解析);
  第一个筛选改为「后台挂起 / 前台调用」切换(前台调用=foreground,client,后端 scope
  支持逗号多值),阶段下拉随范围联动(后台→二三步;前台→一二三步)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 23:45:34 +08:00
董宏凯andClaude Opus 4.8 4a403c95c5 feat(roundtable): 会商诊断日志 + 后台挂起卡死兜底(idle 超时)
- 新增会商全流程诊断日志:新表 roundtable_diagnostics + 仓储 + admin API
  (/api/roundtable-diagnostics) + 管理员诊断页(会商页右上角设置按钮入口),
  覆盖第一/二/三步及后台执行器/进程内网关各处报错与关键事件,支持按
  范围/阶段/级别/事件/关键词筛选 + 分页。诊断写入全程 best-effort,绝不打断会商。
- 修复后台挂起「执行完第一个席位后永久卡死」:进程内网关每轮 agent run 改为
  idle(无活动)超时(默认 20min)——只要还在持续产出 token/工具事件就一直等,
  仅当连续无任何输出才判卡死并取消+报错+落 seat_turn_timeout 诊断;慢但活着的
  生成绝不打断。可经 ROUNDTABLE_SEAT_IDLE_TIMEOUT_SECONDS 调整。
- 一并提交进行中的会商 seat-skill 注入 / 业务链条编辑器相关改动。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 22:55:56 +08:00
fengxiangdebaoziandClaude Opus 4.8 8ca16c74bc fix(roundtable): 会商第三步各席位产物弹窗经 portal 挂 body,修复顶部被顶栏盖住
页面 <main> 的 `relative z-0` 新建层叠上下文,把内部 fixed 弹窗困在 z-0 层级,
被会商页头(z-40)/全局顶栏(z-45)盖住标题栏。ContentModal 与 ArtifactPreviewModal
改用 createPortal 挂到 document.body,脱离该上下文后正常盖在顶栏之上。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 22:12:45 +08:00
fengxiangdebaoziandClaude Opus 4.8 60626c384a fix(roundtable): 会商 Step2/Step3 沙箱产物按对话创建者解析,修复历史/跨用户查看不了
圆桌会商系统线程(metadata.thread_type==roundtable)的 Step2 席位/总控 +
Step3 报告/总结/大屏/结构化 沙箱产物(md/流程图/报告)落在创建者目录下,
之前按当前登录解析路径 + owner_check 校验 → 历史草稿重开或 taskId 会商被
其他账号打开时 403/404 查看不了。沿用任务深链对话方案(23e6685)扩展到圆桌:

- thread_paths._is_creator_shared_thread:taskId 或 thread_type==roundtable
  都解析到对话创建者(threads_meta.user_id),覆盖所有线程路径关口
- ThreadMetaRepository.check_access:圆桌系统线程同样跳过 owner 过滤
  (artifacts 路由 owner_check 据此放行其他账号/历史查看)

线程 id 仅存在于草稿中,无关账号无法发现,与 taskId 共享模型一致。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 20:51:05 +08:00
董宏凯 551c748aa8 Merge branch 'dhk-1' into 'master'
feat(roundtable): 第三步「数据入库」由结构化输出智能体自行调用技能

See merge request knowledge-base-bj/deerflow-server!139
2026-06-19 09:59:51 +00:00
fengxiangdebaoziandClaude Opus 4.8 03c155f8a7 feat(roundtable): 第三步「数据入库」由结构化输出智能体自行调用技能
- 入库改为让 roundtable-structure 走完整 agent 运行时(ingest run policy)
  自行挑选/读取/调用入库技能并传入 taskId,不再前端代调演示
- 新增 /api/flow-extract/ingest-eligibility(智能体判断当前业务场景是否有
  合适入库技能,决定入库按钮是否显示)+ /api/multi-agent/structure/init
- 入库前判断是否已生成流程图:无则发起「是否先生成流程图」用户协助
- 「知识库入库」更名为「数据入库」

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 17:58:36 +08:00
董宏凯 3b165d9ea5 Merge branch 'dhk-1' into 'master'
feat(agent-sidebar): 独立问答智能体列表栏增加「最近的对话」区(参考首页)

See merge request knowledge-base-bj/deerflow-server!138
2026-06-19 09:53:27 +00:00
董宏凯andClaude Opus 4.8 a85d2480b4 feat(auth): 独立登录会话开关(设置-外观)—— 同浏览器多账号互不覆盖
复用 iframe 嵌入的按标签页隔离机制:新增 ?isolate=1 标志,authStorage()
从「仅嵌入」放宽为 isEmbedActive() || isIsolatedSession(),独立态走
sessionStorage 故本标签页登录态不被其它标签页覆盖。设置→外观→「登录会话」
加 Switch,开启时先 migrateAuthToSession() 把 localStorage 受保护键快照搬进
sessionStorage 再翻标志,无感不登出;AuthSyncWatcher 跨标签监听对隔离态实时
忽略,运行时开关即刻生效。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 17:51:08 +08:00
fengxiangdebaoziandClaude Opus 4.8 a9f01bec79 feat(task-buttons): 外链按钮新增「打开方式」(新窗口/当前窗口)
按钮管理(/page/strategy/admin/task-buttons)的 url 外链按钮可配置打开方式:
- blank=新窗口(默认,window.open(_blank),行为同改前)
- self=当前窗口(window.location.assign,嵌入态即当前 iframe)

新增 TaskButton.openMode 字段贯通前后端:前端 task-buttons.ts 类型+种子+
runTaskButton 打开逻辑、api 客户端 snake⇄camel 映射、TaskButtonsPage 下拉;
后端 router schema + ORM open_mode 列(可空默认 blank,启动自动 ALTER 补列,
无需手动迁移)+ sql/memory store 归一化。仅 url 类型生效。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 16:09:01 +08:00
吉鑫升andClaude Opus 4.8 e906a911b2 feat(agent-sidebar): 「智能体」区支持收起/展开
标题栏改为可折叠头(chevron 切换),收起后仅留标题栏并隐藏来源下拉/搜索/列表,
下方「最近的对话」占满剩余空间;收起状态持久化到 localStorage。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 16:09:01 +08:00
吉鑫升andClaude Opus 4.8 8cc2650e98 feat(agent-sidebar): 独立问答智能体列表栏增加「最近的对话」区(参考首页)
左栏改为上下双区:上半智能体列表(来源下拉+名称搜索),下半新增「最近的对话」——
跨智能体近期会话、计数徽标、历史搜索、点击打开/当前高亮/置顶标记,含重命名/置顶/
收藏/分享/导出/删除菜单。会话链接走 usePathOfThread,自动带路由命名空间与 agent_id。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 16:09:01 +08:00
Administrator 593daa91ec Merge branch 'ji' into master 2026-06-19 15:43:23 +08:00
董宏凯 a6dd0fdd85 Merge branch 'dhk-1' into 'master'
fix(dashboard): 抽取 report-json 前剥离 <think> 思考过程做容错

See merge request knowledge-base-bj/deerflow-server!137
2026-06-19 07:42:29 +00:00
董宏凯andClaude Opus 4.8 30cf0fed91 fix(dashboard): 抽取 report-json 前剥离 <think> 思考过程做容错
推理模型(DeepSeek-R1/QwQ 等)输出的 <think>...</think> 思考里常含
```json/裸 {…},会被误当候选导致抽到错误/残缺数据。抽取前先剥离 think:
- 前端 report-template.ts::extractReportData 开头 stripReasoning(复用 reasoning.ts,
  兼容完整/多段/流式未闭合/只吐闭合四形态)
- 后端 report_json.py 新增 _strip_reasoning 在 extract_report_json 开头调用
- report-template.test.ts +3 例(均通过)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 15:36:34 +08:00
吉鑫升andClaude Opus 4.8 1f2a1aaa76 feat(agent-sidebar): 「智能体」区支持收起/展开
标题栏改为可折叠头(chevron 切换),收起后仅留标题栏并隐藏来源下拉/搜索/列表,
下方「最近的对话」占满剩余空间;收起状态持久化到 localStorage。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 15:04:30 +08:00
吉鑫升andClaude Opus 4.8 c1c23d9136 feat(agent-sidebar): 独立问答智能体列表栏增加「最近的对话」区(参考首页)
左栏改为上下双区:上半智能体列表(来源下拉+名称搜索),下半新增「最近的对话」——
跨智能体近期会话、计数徽标、历史搜索、点击打开/当前高亮/置顶标记,含重命名/置顶/
收藏/分享/导出/删除菜单。会话链接走 usePathOfThread,自动带路由命名空间与 agent_id。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 14:42:40 +08:00
Administrator 4b2a93a542 Merge branch 'ji' into master
合并 md/产物按对话创建者解析路径修复(切换账号找不到文件)与 master 现有前端改动。
2026-06-19 14:39:54 +08:00
AdministratorandClaude Opus 4.8 23e6685977 fix(task-deeplink): 共享任务对话的 md/产物按对话创建者解析路径,修复切换账号后找不到文件
xdfx/rwfx/3qfx 任务深链对话按 metadata.taskId 全局共享、不区分用户,但生成的
md/artifacts 与上传文件物理存在 users/{user_id}/threads/{thread_id}/ 下,user_id
之前取当前登录账号。导致 A 账号生成的文件,B 账号打开同一共享对话时后端去
users/B/ 找 → 404「找不到」。

新增 deerflow/runtime/thread_paths.py(resolve_path_user_id /
aresolve_path_user_id):带 taskId 的共享对话统一解析到对话创建者
(threads_meta.user_id),个人对话仍走当前登录(行为不变)。在所有线程文件路径关口替换:
写入源 ThreadDataMiddleware、present_files、uploads(manager+middleware+router)、
产物读写(path_utils → artifacts/skills router)、嵌入式 client.get_artifact。
正向结果进程内缓存;无 DB/内存态/无行均安全回退到当前登录。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 14:35:22 +08:00
董宏凯 bc9936bb2b Merge branch 'dhk-1' into 'master'
feat(dashboard-agent): 深链大屏接入研判情报报告接口 selectSqReport + 样例假数据

See merge request knowledge-base-bj/deerflow-server!136
2026-06-19 06:30:58 +00:00
fengxiangdebaozi ef615bbfb6 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-19 14:15:13 +08:00
董宏凯 d8f32690a3 feat(dashboard-agent): 真实模式先请求数据再抽取 + 重新生成/编辑闸门
- dashboard-input: 缓存仅 mock 开发用,真实模式不读缓存、不兜底假数据,
  只用接口真实返回;新增 forceRefresh 跳过缓存强拉最新数据
- DashboardAgentPage: 请求期间「正在请求任务数据…」加载态 + 失败提示/重试;
  重新生成(redraw)/编辑(ask)前先 forceRefresh 拉最新数据,
  guardedGenerate 闸门——拿到数据才生成,拿不到 toast 取消(防并发)
2026-06-19 14:04:42 +08:00
fengxiangdebaoziandClaude Opus 4.8 31f9838095 feat(embed): iframe 嵌入模式(去 chrome + 主题隔离 / hideJump / 登录用户隔离)
外部系统用 iframe 套用深链单智能体问答/多智能体会商时,三个按标签页(sessionStorage)
开关,由深链 URL 参数开启、跨登录跳转/刷新/页内导航存活,绝不跨标签污染正常系统页:

- embed=1(可带 theme=):去全局导航栏 + 侧边栏;按外部主题色强制明/暗,走
  next-themes forcedTheme(不写 localStorage),嵌入侧不调 setTheme/persistSidebarEnabled
- hideJump=1:隐藏深链底部「快捷跳转」栏 TaskJumpBar(底部「下一步」按钮 + 右侧悬浮菜单)
- 登录隔离:嵌入态鉴权/身份键(deerflow.auth/userInfo/login.*/tools_token 等)改走
  sessionStorage(core/auth/scoped-storage.ts 的 authStorage),iframe 登录用户与正常
  登录用户完全隔离、互不覆盖;token 读取统一过 getStoredAuth,改中心函数即全体生效;
  跨标签账号变更监听 AuthSyncWatcher 嵌入态禁用

嵌入会话在 main.tsx 渲染前同步启用(早于任何鉴权写入)。正常标签页 isXxx() 恒 false,
行为零变化。新增 core/embed/embed-session.ts、core/auth/scoped-storage.ts。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 12:02:36 +08:00
吉鑫升andClaude Opus 4.8 13ef1942f2 feat(agent-sidebar): 独立问答智能体列表栏顶部增加智能体名称模糊搜索
下拉来源切换下面加搜索框:防抖 300ms 走服务端 search(按原始名 + 内置缩写
脱敏映射匹配,与智能体管理页一致),在当前来源(我的/某广场)内搜全量;
带清除按钮、无结果显示「未找到匹配的智能体」、搜索中复用 isFetching 半透明指示。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 11:16:39 +08:00
董宏凯andClaude Opus 4.8 2b58fe6c8b feat(dashboard-agent): 深链大屏接入研判情报报告接口 selectSqReport + 样例假数据
- dashboard-input: 请求 {consumer}/cop/selectSqReport?taskId=,新增 extractSqReport
  反序列化各条 contentJson、按 categoryType 归类成干净结构喂给智能体
- 真实接口未就绪:新增 sq-report-mock(.json/-data.ts) 样例假数据 + adapter,
  request.ts 按 VITE_MOCK_SQ_REPORT 开关挂载(机制同 cop-task-detail)
- env:dev=true 走假数据,prod/network/sit=false 真实接口

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:19:31 +08:00
fengxiangdebaozi 81ca13280b Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-19 10:03:10 +08:00
fengxiangdebaozi bb7283dcd9 接口 2026-06-19 10:03:00 +08:00
吉鑫升andClaude Opus 4.8 0bd4524334 feat(task-deeplink): 首次进入且任务无历史时自动发送,无需手动点开始回答/覆盖
新增「首次进入且该任务无聊天对话」信号 taskAutoStart:TaskFxIndexResolver 在
「无历史 → /new」时注入 state,用户主动点「新建对话」则不带。

- 3qfx/xdfx:taskAutoStart 时自动发出开场词(一次性 ref,不受 mount 时 threadId
  抖动影响、不会重复发),不显示「开始回答」按钮;用户主动新建对话才显示按钮手动发。
- rwfx:闸门 autoStartWhenEmpty = autoStartWhenPurposeEmpty && taskAutoStart,即仅
  首次无对话历史时目的树为空才自动开始;目的树有数据始终弹「覆盖并开始问答」确认(不误删 B 系统数据)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 09:51:50 +08:00
fengxiangdebaozi ce78cbf936 代码提交 2026-06-18 21:09:37 +08:00
吉鑫升andClaude Opus 4.8 6aaa4c841e feat(task-deeplink): 3qfx/xdfx 新建对话改手动「开始回答」+ xdfx 行动详情卡片 + 独立问答智能体列表栏
- AgentChatPage: 纯绑定深链(3qfx/xdfx)不再自动发开场信息,改由右上角「开始回答」按钮手动触发,从根上消除新建对话竞态导致的重复发送;移除 autoSentArmedRef/streamThreadId 相关逻辑
- task-deeplink.ts: 抽出 fetchActionDetail 返回整包 ActionDetail,fetchTaskIdFromAction 复用之
- TaskFxWorkspace: xdfx 左栏「当前任务」下新增「行动详情」卡片(行动名称/叙事)
- StrategyRoutes/WorkspaceRoutes: 独立智能体问答整页新增最左「智能体列表」栏(showAgentList);xdfx 右侧宿主改用 TaskBindChat(精简版)
- 新增 agent-chat-sidebar.tsx

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 20:55:41 +08:00
吉鑫升 179a3f2b2f Merge branch 'ji' into master 2026-06-18 19:24:03 +08:00
吉鑫升andClaude Opus 4.8 678035afed fix(frontend): 修复 3qfx/xdfx「新建对话」开场白重复发送两次
根因:mount 进入 /new 时 useThreadChat 会抖动 threadId(useState 先给一个 uuid,
紧接着 effect 又 setThreadId(新 uuid))。旧去重用 taskAutoSentRef,而 reset effect
依赖 threadId,被抖动重置回 false;此时 onCreated 未回、streamThreadId 仍为
undefined(守卫放行),自动发送 effect 二次触发 → 发两次、创建两个线程,回答开始时
切到最终线程,表现为「开始回答后突然变成一个」。

改为「武装」标志去重,只在会话真正创建完成(isNewThread→false)后才重新武装,
对 threadId 抖动免疫,保证每个新建会话恰好自动发一次。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 19:19:23 +08:00
董宏凯 758a8fda09 Merge branch 'dhk-1' into 'master'
feat(roundtable): taskId 会商记录独立存储(不分权) + 第三步生成过程对话/步骤条入库

See merge request knowledge-base-bj/deerflow-server!135
2026-06-18 11:18:24 +00:00
fengxiangdebaoziandClaude Opus 4.8 3a315798e9 feat(roundtable): 深链会商页引入底部快捷跳转栏(去编辑/弹框查看)
抽出 TaskJumpBar 为独立组件,单智能体问答与多智能体会商共用;会商深链
taskId 模式按业务渲染按钮管理配置,并隐藏「编辑」与「弹框查看」按钮。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 19:17:45 +08:00
董宏凯andClaude Opus 4.8 bd5623ebc5 fix(dashboard): 大屏绘制独立页顶栏深色适配 + 修复卡 loading/重绘无数据
- 顶栏(dashboard-agent-topbar)深色下改深蓝(《深蓝色 UI 规范》卡片#122347/
  页面#0C1836/边框#1A2F5A/文字#C5CFE0),不再白底;仅作用于顶栏。
- init effect 始终并行拉输入 JSON 写入 inputRef,恢复历史后「重新绘制」/续问
  才有源数据,否则回退空 prompt 生成不出数据。
- 修复卡在「正在加载任务大屏…」:init effect 改为只依赖 [taskId]、start/
  hydrateTranscript 经 ref 读取、finally 无条件 setLoading(false),避免模型异步
  加载触发 cleanup 把首跑标记 cancelled 后 loading 永不置 false。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 18:01:30 +08:00
fengxiangdebaozi 6a8f118ad0 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1
# Conflicts:
#	CLAUDE.md
2026-06-18 17:53:23 +08:00
董宏凯andClaude Opus 4.8 3758122cf7 style(workspace): 全量模式通用问答左栏深色深蓝玻璃适配
深色(.dark)主题下,全量模式聊天页左栏(GeneralQaSidebar)由扁平 bg-sidebar
改为「深蓝主题底图 + 半透明蓝罩」玻璃面板:与右侧 workspace-chat-bg 主区同一张
fixed 底图、左右连续,叠蓝罩略深一档作面板区分。浅色/浅蓝主题不命中,仍用
sidebar token,内部元素走语义 token 自适配。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 17:45:17 +08:00
董宏凯andClaude Opus 4.8 03b6fb724c feat(roundtable): 深链策划流程小图 + 流程图弹窗横向/缩略图/深蓝适配
- Step1 消息列表头部:深链 taskId 模式取到目的树后,左侧标题换成「策划流程」
  彩色层级小图(任务→目的→…→叙事,每级配色对齐流程图节点 + 类型小图标),
  点击打开任务目的流程图弹窗;仅第一步、有数据时出现。
- TaskPurposeDialog 流程图:横向(LR)布局 + 右下角缩略图(MiniMap)。
- FlowGraphPanel 深蓝主题适配(随 ThemeContext):容器/头部/画布点阵/连线/图例/
  小地图/节点详情弹窗 + 节点配色(FLOW_NODE_TYPE_META_DARK),浅色红主题不受影响。
- 圆桌侧栏深色兜底:neutral 家族 + 米色 hex(#FAF6F5/#ECE7E4/#E8D0CC) 映射到深蓝
  token(关系图背板、第N步 tag 等不再泛白)。

附带提交工作区其余暂存改动(AI 写作等),不含 config.yaml。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 17:39:19 +08:00
吉鑫升 3aa629f0df Merge branch 'ji' into master 2026-06-18 17:17:11 +08:00
吉鑫升andClaude Opus 4.8 e5ca717783 fix(frontend): 修复 3qfx/xdfx 任务深链「新建对话」开场白发进上一个会话
根因竞态:从已有会话点「新建对话」时 isNewThread 立刻翻 true,但 useThreadStream
的 onStreamThreadId 慢一帧才归零;自动发送 effect 同帧 submit,而 SDK 的
SubmitOptions.threadId 仅在 hook 线程为空时生效,于是开场白发进了上一个对话
(表现为「一直在同一个聊天框里发消息」,首次正常、之后每次都串)。

- useThreadStream 追加返回当前绑定的流线程 id onStreamThreadId(向后兼容)
- AgentChatPage 自动发送 effect 增加守卫 streamThreadId == null:等底层 stream
  切到全新线程后再发,开场白即落到新建对话

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 17:16:19 +08:00
fengxiangdebaoziandClaude Opus 4.8 85cca36ddb feat(roundtable): 入库门控——未挂载入库技能则不显示入库按钮、也不执行入库
- 门控改为「是否挂载了入库相关技能」:按 name/name_zh/description 含 `ingest` 或「入库」
  识别任意启用的入库相关技能,不写死示例技能名(真实入库技能改名也能自动识别;
  知识库检索类技能不误命中)。
- 操作层加保险:runIngest 在 ingestAvailableRef 为假时直接 no-op,未挂载技能/非深链
  即使被触发也不执行任何入库动作。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 17:05:53 +08:00
吉鑫升andClaude Opus 4.8 29cc004b69 feat(frontend): 任务工作区/目的树脱敏 — 业务名→业务码 + 数据值过 desensitize
- 种子脱敏表新增 任务分析→rwfx / 三情分析→3qfx / 行动分析→xdfx(整词在前,优先于「任务」「行动」匹配)
- TaskFxWorkspace:左上业务名 + 底部快捷跳转按钮标签过 desensitize
- TaskPurposePanel:目的树表头/单元格正文/理由过 desensitize
- 硬编码 UI 文案与 admin 按钮管理页保持原文(与菜单管理一致)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 16:52:59 +08:00
fengxiangdebaoziandClaude Opus 4.8 19028ba627 feat(roundtable): 第三步流程图后入库(示例技能 · 仅深链 taskId 模式)
- 流程图生成完成后,发起用户协助询问是否入库:现在 / 稍后 / 不入库。
- 仅**深链(taskId)模式**(会商 rwfx-A / 3qfx-A / xdfx-A 等)且入库技能启用时才出现入库
  询问 / 协助卡 / 手动入库按钮;普通会商不受影响。
- 「稍后入库」后输入框自由文字做意图识别(后端 /api/flow-extract/ingest-intent:
  start_ingest / add_data / other / unclear),模糊则发起入库协助;另提供手动入库按钮。
- 入库执行复用总结智能体的同一线程,在消息列表出一条「知识库入库」气泡并显示步骤条
  (调度 → 调用入库技能 →(补充内容)→ 提交 → 完成),与第二步同款。
- 入库数据以**用户最后修改后的流程图**为准;并把深链 **taskId 一并传给入库技能**(技能必需)。
- 入库状态(asking/later/done 等)随第三步草稿存取,重载不重复询问。
- 入库技能先用示例(演示用):skills/public/knowledge-base-ingest/SKILL.md(force-add,
  skills/ 目录默认 gitignore),后续替换为真实入库技能时沿用同名即无缝切换。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 16:49:36 +08:00
吉鑫升 77aa895a70 Merge branch 'ji' into master
# Conflicts:
#	offline-backend-20260512/backend/CLAUDE.md
#	offline-backend-20260512/backend/app/gateway/app.py
#	offline-backend-20260512/backend/app/gateway/deps.py
2026-06-18 16:36:30 +08:00
AdministratorandClaude Opus 4.8 f762a76ecf feat: 任务工作区 UI 细化(底部按钮主题色/左上业务名/右侧智能体信息默认收起/xdfx目的弹框按行动id解析)
- 底部「快捷跳转」按钮改用主题色 var(--color-main)(随红/蓝主题自适配),hover 用 --brand-950
- 三个工作区左上角标明当前分析页面(任务分析/三情分析/行动分析)
- 进入任务工作区(taskGate/taskBind)时右侧「智能体信息」面板默认收起(AgentDetailPanel defaultCollapsed)
- xdfx「弹框查看」目的树:先用行动id换回任务id 再查(TaskPurposeDialog resolveFromActionId);
  仅深链原始行动id(≠任务id)时触发,切换业务进入不误解析

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 16:19:02 +08:00
AdministratorandClaude Opus 4.8 095469b8a9 feat: 任务深链对话(metadata.taskId)全局共享、不区分用户
任务工作区(rwfx/3qfx/xdfx)的对话改为按 taskId(+agent_id) 全局共享、跨用户可见可续聊,
不再按创建者隔离;普通个人对话仍按 owner 隔离不变。

- ThreadMetaStore.search/count:metadata 含 taskId 时跳过 owner 过滤(SQL+Memory)
- check_access / _check_ownership / update_metadata / delete / _get_owned_record:
  行 metadata 含 taskId 时视为共享,任何登录用户可读/写/续聊/改标题状态/删除
- 覆盖 require_permission(owner_check) + runs 续聊 owner 校验 + 列表
- 测试 tests/test_thread_meta_task_sharing.py(SQL 跨用户可见/隔离/check_access)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 15:54:51 +08:00
AdministratorandClaude Opus 4.8 16afa9bcbb feat: 任务工作区可配置跳转按钮(按钮管理) + 底部快捷跳转栏 + 目的树收起/空自动问答
- 新增「按钮管理」admin 页(/admin/task-buttons):按业务(rwfx/3qfx/xdfx)配置跳转按钮,
  支持改名称/类型(外链·切换业务·目的树弹框)/目标/追加参数名(id·task_id)/任务id·行动id/启停/排序
- 跳转按钮从左侧栏移到工作区底部「快捷跳转」栏:红底白字、靠右、变大;rwfx 历史 4 按钮纳入配置
- 后端新增全局共享 store /api/task-buttons (table task_buttons,admin 整体替换)
- xdfx 行动id/任务id:登录暂存原始行动id,按钮可选追加任一;id 参数名可自定义
- rwfx 清除记录移到「新建对话」下、去掉任务操作框;查询任务目的为空时自动发第一次问答
- 目的树面板默认收起;「弹框查看」抽成可复用 TaskPurposeDialog,可作为按钮配置到任意页面
- 文档(根/后端 CLAUDE.md) + 后端测试 tests/test_task_buttons.py

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 15:41:05 +08:00
fengxiangdebaozi b04b830039 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1
# Conflicts:
#	frontend-web/src/roundtable-planning/hooks/useStep3Dashboard.ts
2026-06-18 15:18:41 +08:00
fengxiangdebaoziandClaude Opus 4.8 a8da6c2632 feat(roundtable): taskId 会商记录独立存储(不分权) + 第三步生成过程对话/步骤条入库
taskId 深链会商存储独立化:
- 新增独立表 roundtable_task_drafts + 路由 /api/roundtable-task-drafts,只按 task_id
  归属、完全不按 user 分权(created_by 仅审计),与个人 roundtable_drafts 物理分离;
  个人草稿表恢复严格按用户隔离(去掉原 task 放权)。
- 后台研讨作业按 taskId 共享:roundtable_jobs 加 task_id,get/get_by_draft/stream/
  resume/cancel 支持 ?task_id= 跨用户读取与控制,作业报告写回 task-draft 存储。
- 前端:新增 api/task-drafts.ts 客户端,useDraftPersistence / useRoundtableDrafts /
  roundtable-jobs / DispatchChainJobModal / RoundtablePlanningPage 按 taskId 路由读写。
- 迁移 20260618_01 + column_additions_mysql.sql(jobs.task_id) + 数据搬迁脚本
  scripts/migrate_roundtable_task_drafts.py(把历史 task_id 行迁出个人表)。

第三步聊天记录像第二步一样存全:
- 总结报告 / 经典看板 / 大屏 三条流的生成过程对话(中间文字 + 步骤条 + stub)落库,
  加载草稿整段回显,而非只剩最终 md / 流程图 / HTML。DraftStep3Snapshot 扩展
  dialogues/seatStubMessages 槽位;存稿走页面 render 期 ref,恢复走各 hook hydrateSaved
  (旧草稿无字段则回退单条「历史记录」气泡)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 15:11:50 +08:00
董宏凯 62549ab976 Merge branch 'dhk-1' into 'master'
feat: 圆桌第3步大屏多页改用专职智能体 + 健壮 report-json 抽取

See merge request knowledge-base-bj/deerflow-server!134
2026-06-18 06:27:18 +00:00
董宏凯andClaude Opus 4.8 32772b7448 feat(dashboard): 大屏绘制智能体独立页面(按 taskId 存取,不分权)
- 新增带导航+侧边栏的独立页面 DashboardAgentPage:按 taskId 取/存会话,
  有有效 report-json 直显大屏(DashboardApp),否则进生成过程(不自动跳)+输入框可改
- 后端 dashboard_sessions 存储(model/sql/__init__)+路由/by-task(GET/PUT 不分权)
  + deps/app/models 接线;新表靠 create_all 建,无迁移
- 扩展 useStep3Dashboard:buildInitialPrompt(输入任务JSON) + hydrateTranscript(恢复聊天记录)
- 抽出共享 DashboardChatPanel;report-template 增 buildDashboardPromptFromJson
- 输入 seam core/auth/dashboard-input:JSON 接口未就绪先用占位/演示数据兜底
- 路由 StrategyRoutes dashboard-agent + 侧边栏「问答管理→大屏绘制」
- 圆桌业务链卡片「关系图」改横向布局
- 顺带提交:AIWritingContext 登录切换处理、thread-access-error helper

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 14:26:27 +08:00
吉鑫升andClaude Opus 4.8 ecb79ce49c feat: 3qfx/xdfx 任务深链 1:N 工作区 + xdfx 行动id解析 + 3q详情链接
- 3qfx/xdfx 单智能体改走任务工作区(TaskFxWorkspace):按 taskId+agent_id 隔离的
  1:N 对话列表;3qfx 纯绑定(taskBind 自动发开场信息),xdfx 带目的树闸门(taskGate)
- 左上角「当前任务」卡片:留存查询到的任务名称+简介(readCopTaskDetail)
- rwfx 工作区新增「切换到三情分析」按钮,带同一 taskId 进入 3qfx
- xdfx 深链传入的是行动id:resolveDeeplinkTaskId 经 action 接口解析出真正任务id
  (可配置 action_detail_url + action_test/mock.action_detail,离线可测)
- 目的树面板「弹框查看」旁新增可配置「3q详情」链接(detail_3q_url + ?id=任务id)
- AgentChatPage 拆分 taskGate/taskBind;use-task-threads 增加 agentId 过滤隔离

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 11:37:05 +08:00
fengxiangdebaoziandClaude Opus 4.8 500a562bb6 fix(roundtable): 校验环节真正"逐个查 from 缺则补"——删掉自相矛盾的"你不用管连线"
校验本就把第一次抽取的完整 JSON(extracted)传给模型,但开头一句"连线由系统按
层级自动生成、你不用管连线"与第①要点"查每个非根节点 from 缺则补"自相矛盾,
模型读到前者就跳过补 from。删掉该句,改成明确指令:逐个节点检查上面这份 JSON
是不是缺字段,只要某节点缺 from 就补上正确的 from,绝不让非根节点悬空。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 23:32:59 +08:00
fengxiangdebaoziandClaude Opus 4.8 b5744a1378 feat(roundtable): 结构化抽取连线质量加固——尊重模型 from + 弱模型层级兜底
- parse_flow_graph 选边改为两全策略:模型把连线连全了(仅根节点无入边)→直接用
  模型的 from/edges;模型漏连(≥2 节点无入边,最常见就是漏 from 导致平铺)→按 group
  层级关系确定性推导补全,永不平铺,连线质量与模型能力解耦。
- SOUL.md 增加正确/错误节点示例(带 from vs 漏 from)+ 硬性要求:除根节点外每个
  节点都必须填 from;画法④拆成 group/对应顺序/from 三件事并强调"漏 from 最常见"。
- 校验 prompt 把"连接关系"提为第①要点:逐个检查非根节点是否有 from,缺了必须补对。
- _STRUCTURE 兜底 prompt 同步要求填 from。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 23:28:07 +08:00
fengxiangdebaoziandClaude Opus 4.8 b8b71523b5 fix: 流程图连线推导加固——个别节点漏 group 时按发射顺序就近归层(carry-forward)
弱模型可能漏标个别节点的 group,原逻辑一漏标就整体放弃推导导致节点平铺。改为漏 group 的
节点沿用前一节点的层级,只有开头无 group / 全程无 group 才回退模型连边。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 23:18:05 +08:00
fengxiangdebaoziandClaude Opus 4.8 cc06d3f4d2 feat: 流程图连线后端确定性推导(弱模型也连对) + 校验不删边/不简化理由 + 调度中即时反馈
- 连线质量:新增 _derive_layered_edges——连线不再信任模型,后端按节点 group 分层 +
  层级对应关系确定性推导(任务→各目的扇出、相邻等量层按下标一一对应、不规则层对回退模型边)。
  模型只需 group 标对 + 各层内按相同对应顺序排列,连线就一定对。SOUL/_STRUCTURE 据此调整。
- 校验不删边:validate 要求节点数≥原图 + gen() 兜底「校验后节点/边变少则回退抽取结果」。
- 不简化理由:_SHAPE + SOUL detail 改为完整理由原样保留、不简化/精简。
- 调度中即时反馈:ask() 意图分类前立刻建「调度中」气泡,定意图后各分支复用(relabelDialogue
  + runFlowExtract.bubbleId),不再等 intent 接口返回才出内容。
- 测试 tests/test_flow_extract_parse.py 加层级连线推导 3 例(共 10 过)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 22:56:04 +08:00
fengxiangdebaoziandClaude Opus 4.8 0890b3c375 feat: 第三步流程图后端抽取智能体 + 意图识别 + 问答/画布编辑
- 新增专职「结构化抽取智能体」roundtable-structure(种子资产 SOUL+config,注册进 seeder
  启动 seed+sync 进 DB,可在智能体管理页编辑、未来挂入库技能)。
- /api/flow-extract/stream 改用该 agent 的 SOUL(load_agent_soul,缺失回退内置默认) +
  模型(前端所选 > agent 配置 > 默认);抽取/校验/编辑统一。SOUL 先输出简要分析过程再出
  flow-json,模型慢时也有实时反馈(含 <think> 思考流)。
- 新增 /api/flow-extract/intent 意图识别(参考 ai_writing 一次性 JSON 范式):识别
  重做报告/改流程图/重画流程图/提问/模糊;前端按意图分流,模糊则发起澄清让用户点选,
  不再用关键词硬路由(修「说重做报告却出流程图」)。
- Phase 2 问答修改:edit 模式(当前图+指令→改图→校验);Phase 3 画布手动改/删节点。
- 修:用户消息发送即上屏(不等模型/分类返回);regenerate_report 不再清空对话历史;
  全屏 portal 到 body 工具栏恢复;解析兼容独立 edges 数组。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 22:19:02 +08:00
董宏凯andClaude Opus 4.8 ed887f762e feat: 圆桌第3步大屏多页改用专职智能体 + 健壮 report-json 抽取
修复「大屏多页抽取 json 又失败」:旧实现复用画 HTML 的 roundtable-report
智能体 + rfind 围栏 + 单次 json.loads 的简单粗暴抽取,弱模型跑偏/格式偏差即失败。

- 新内置专职单例 roundtable-dashboard「大屏多页数据智能体」:SOUL 专讲逐席位
  分析 → report-json 契约,禁工具/禁文件/禁 HTML;新 run policy dashboard 禁用一切工具
- harness 新增 report_json.py:多策略抽取(report-json/json/裸 JSON/截断)+ schema
  归一化(移植前端 extractReportData/coerceReportData),返回可直接渲染的归一化 JSON
- 后台 run_dashboard_data 改用专职 agent + dashboard policy + 健壮抽取
- 新增 /api/multi-agent/dashboard/init;前端 initDashboardThread + useStep3Dashboard 改用之

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 21:47:21 +08:00
fengxiangdebaozi bb05f7b1de Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-17 21:31:30 +08:00
fengxiangdebaozi d3880f51b3 第三步结构化输出优化 2026-06-17 21:31:22 +08:00
董宏凯 a2fcd85746 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-17 20:41:56 +08:00
吉鑫升andClaude Opus 4.8 47bf0c2a1b Merge branch 'ji' into master
合入 ji 的两处前端修复(任务深链开场信息补 task_id + 加宽任务目的弹框)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 20:40:47 +08:00
吉鑫升andClaude Opus 4.8 85dc5466c5 fix(frontend): 任务深链开场信息补充 task_id + 加宽任务目的弹框
- rwfx 任务深链开场信息末尾追加「任务id(task_id)为xxx」,让后端能识别任务
  (buildOpeningText 增加 taskId 参数,覆盖 pendingAgentMessage 与任务上下文两条路径)。
- 任务目的「弹框查看」用 sm:!max-w-[90vw] 覆盖 DialogContent 基类的 sm:max-w-lg
  (此前无前缀的 max-w-4xl 被基类响应式类压回 512px,故加宽不生效)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 20:39:22 +08:00
董宏凯 c97d88d33f Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-17 20:38:59 +08:00
董宏凯 60cc6665ce tij 2026-06-17 20:38:51 +08:00
董宏凯 d82973c8c8 Merge branch 'dhk-1' into 'master'
feat: 业务链条配置管理导航与顶栏用户名统一

See merge request knowledge-base-bj/deerflow-server!133
2026-06-17 12:25:17 +00:00
fengxiangdebaoziandClaude Opus 4.8 fca39eeaee feat: taskId 深链会商按任务隔离草稿 + 第三步自动结构化流程图
- 深链 ?taskId=&goPath=*-A 透传 taskId 进会商,按 taskId 隔离存取草稿(一个 taskId 多条、可新建);
  后端新增 GET /api/roundtable-drafts/by-task/{id} 列表 + RoundtableJobRepository.status_map_by_drafts 富化。
- 第三步生成 md 报告后自动结构化输出流程图(仅 taskId 模式):有报告基于报告、无报告基于各席位交付,
  整段内联数据来源逐条抽取;层级优先用业务链总控提示词写明的层级,否则用 stages 的 goal。
- 流程图节点加 group(层级名)标签 + detail(条目名称+理由);强 prompt 压制 coordinatorPrompt 报告锚定,
  禁阶段编号节点;FLOW_STRUCTURE_RULE 精确画法(根=任务、每层每条成节点、按对应关系串分支、排除汇总段落)。
- flow-graph 解析容错:JSON.parse 失败退回正则逐字段抽取,兼容裸换行/尾逗号,避免节点被整体丢弃。
- 修:重开第二步后第三步基于新一轮分析重新生成(复位 step3 闸门 + 中断旧三流)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 19:45:35 +08:00
董宏凯andCursor e6a41dbc97 Merge branch 'master' into dhk-1
Integrate task deeplink/FX workspace updates from master while keeping dhk-1 menu-overrides and sensitive-words documentation in CLAUDE.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-17 19:39:14 +08:00
董宏凯andClaude Opus 4.8 6746fe4a78 feat: 导航/侧边栏菜单脱敏 + 圆桌会商各步输入框自适应高度
- 菜单标签展示层脱敏:useSidebarMenuItems 直接用 /api/sensitive-words
  结果构造脱敏器,覆盖导航栏/三套侧边栏皮肤/三级子导航;菜单管理页用原始树不受影响
- 新增可复用 AutoGrowTextarea(自适应高度多行框),替换圆桌 Step1/2/3 输入框:
  多行时自动扩展、到上限框内滚动;Step2 两个单行 input 改多行;统一 Enter 发送/Shift+Enter 换行
- 各步输入框最大展开高度翻倍(Step1 320 / Step2 280 / Step3 224)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 19:13:48 +08:00
董宏凯andClaude Opus 4.8 25e4e3dbc9 feat: 敏感词管理页面(脱敏词后台化,限 lqq 账号)
- 后端 /api/sensitive-words:全局共享词表,开放读、admin 或 lqq 整体替换写
- 前端 desensitize 种子化:SEED_DESENSITIZE_MAP + 运行时 replaceDesensitizeMap
- 启动加载后台配置回灌脱敏映射;管理页支持增删改启停 + 一键导入种子词
- 入口置于左下角设置下拉(全量/简洁两种侧边栏均有),仅用户名 lqq 可见

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 18:05:07 +08:00
吉鑫升 af8db1d24c Merge branch 'ji' into master 2026-06-17 17:39:23 +08:00
Administrator bb2e896fba Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-17 17:37:48 +08:00
AdministratorandClaude Opus 4.8 0dca637645 style: 任务FX工作区操作区从右下角浮层移入左侧任务栏底部
- TaskFloatingActions 重命名为 TaskActionsPanel,挂到对话列表底部
- 不再 absolute 覆盖右侧聊天输入框;编辑/下一步/清除记录改为操作卡片
- 左侧栏样式增强(标题/会话数/选中态高亮)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:37:35 +08:00
吉鑫升andClaude Opus 4.8 54fff09e74 feat(frontend): 不带 sidebar 的聊天页顶栏右侧也展示名称+岗位
紧凑布局(无全局 Header)下复用 UserIdentityBadge,数据源与全量模式 Header 一致,仅在 !compactChrome 时渲染,避免与全局顶栏重复。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:36:39 +08:00
董宏凯andClaude Opus 4.8 39d7dab3e2 chore: 提交 AI 写作研究侧栏改动与前端开发环境变量
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:32:40 +08:00
董宏凯andClaude Opus 4.8 fc7576fea3 feat: 圆桌会商 Step1 左栏样式优化(业务链关系图/分析记录卡片)
- 业务链:红色主题卡片头+单选圆点+席位胶囊+描述;选中可展开关系图,
  席位按 stages 分组用彩色圆形小图标排列,悬停浮层显示名称/描述
- 分析记录:圆角改 5px,新增已完成/未完成标签与「第 N 步」进度,
  标题/状态/时间/步骤四角布局,加选中高亮与 hover 阴影
- 修复滚动容器 overflow 裁剪导致卡片左边框被切

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:31:24 +08:00
吉鑫升 6c47da82c4 Merge branch 'ji' into master 2026-06-17 17:21:15 +08:00
吉鑫升andClaude Opus 4.8 392394b4c9 fix(db): 修复 alembic 多 head 导致后端启动失败
迁移图存在两处问题导致 `alembic upgrade head`(网关启动时执行)报
"Multiple head revisions are present":
1. 20260612_01 分叉出 20260615_01 与 20260616_03 两个 head 未合并;
2. 20260611_01、20260616_02 各被两个文件重复占用,污染 DAG 产生幽灵 head。

处理:
- roundtable_draft_task_id 20260611_01 -> 20260611_02(接在 square_id 之后),
  20260612_01 父节点改指 20260611_02;
- skill_favorites 20260616_02 -> 20260616_04(接在 knowledge_folders 之后),
  20260616_03 父节点改指 20260616_04;
- 新增 no-op 合并迁移 20260617_01 合并 (20260615_01, 20260616_03)。

保留 20260611_01 / 20260616_02 原 id 不变,仅重命名重复副本,已 stamp 的库不受影响;
所有迁移均有 _has_table/_has_column 守卫,全链路在已建表的库上重跑为安全 no-op。
`alembic heads` 现仅余单一 head 20260617_01,无重复告警。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:19:29 +08:00
吉鑫升andClaude Opus 4.8 a2bb8c80a2 feat: 任务目的树表格化展示 + 切换会话停止老对话服务端 run
- task-purpose: normalizeNode 容错(未知 *Dto 兜底/文本字段改名兜底);新增 flattenPurposeTree 拍平目的树
- TaskPurposePanel: 目的树改表格展示(列数自适应),支持弹框放大查看
- threads/hooks: 新增 stopThreadRun,真正取消服务端 run(非仅断开本地 SSE)
- AgentChatPage: taskGate 下切换/卸载会话时停掉老对话服务端 run
- TaskFxWorkspace: 操作按钮(编辑/下一步/清除)改右下角常驻红色浮层

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 16:42:05 +08:00
AdministratorandClaude Opus 4.8 ba0ec20532 chore: .env.development 也开启 cop-task-detail mock(VITE_MOCK_COP_TASK_DETAIL=true)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 16:10:57 +08:00
AdministratorandClaude Opus 4.8 138a5adb1c chore: 前端 cop-task-detail 走 mock + 后端 task_deeplink 同步到 backend/config.yaml
- frontend-web/.env.production: VITE_MOCK_COP_TASK_DETAIL=true(consumer 外网不可达,登录深链任务详情走本地假数据)
- backend/config.yaml: 补上 task_deeplink 段(test/delete_test=true 走 mock),与外层 config.yaml 对齐;服务器实际加载的是 backend/config.yaml,否则 /api/public/config/task-deeplink 返回空导致 rwfx 目的树闸门失效

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 16:08:54 +08:00
吉鑫升andClaude Opus 4.8 a2d767e2db feat: rwfx 任务深链支持目的树闸门 + 任务↔对话(1:N)绑定
后端
- config.yaml 新增 task_deeplink 段:完整 URL(无 base)+ test/delete_test 两个独立测试开关
  + mock 假数据(目的树 / delete 结果,可随时编辑)
- 新增 TaskDeeplinkConfig 模型挂到 AppConfig;新增公开只读接口
  GET /api/public/config/task-deeplink 暴露给前端(/api/public 已在鉴权白名单)

前端
- 登录深链 goPath=rwfx 进入「任务工作区」:左侧按 metadata.taskId 过滤的对话列表
  (新建对话 / 编辑 / 下一步 / 清除任务记录)+ 右侧问答
- 新建对话(含首次进入)顶部展示目的树闸门:有数据弹覆盖确认→调 delete,success 才开始问答;
  恢复历史对话不跑闸门
- 新建 thread 打 metadata.taskId 标签实现「一个任务挂多个对话」(1:N)
- 地址/开关/假数据全部走后端配置,拿不到时用内置默认值兜底;test/delete_test=true 走假数据

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 15:59:02 +08:00
董宏凯andClaude Opus 4.8 ef1a12ab74 feat: zzJC/zzXD 左栏智能体列表对齐全量版彩色卡片样式
- 抽出共享配色助手 agent-icon-color.ts(按 id 散列、分浅色/深蓝主题),
  general-qa-sidebar 与 agent-module-sidebar 共用
- AgentModuleSidebar:背景改白底、去毛玻璃;智能体项改为彩色渐变图标卡片
  (图标+名称+两行简介+选中态主色描边/右侧主色条);分组标题与聊天记录配色统一
- 保留按类型分组/折叠与会话过滤逻辑

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 13:11:27 +08:00
董宏凯andClaude Opus 4.8 1c8b5b23a1 feat: 菜单管理(侧边栏覆盖层)
管理员可对一/二/三级菜单(含注入的 iframe 轻应用节点)改名、停用/启用、
排序、跨层级移动。静态菜单仍是图标/路由来源,后端只存每节点覆盖项。

后端: /api/menu-overrides(全局共享;开放读、admin 原子替换;≤3 级校验),
新增 persistence/menu_overrides 持久化层(create_all 自动建表)。
前端: 合并逻辑 menu-overrides.ts、MenuManagementPage(@dnd-kit 拖拽+移动到
父级选择器+上下箭头+改名/停用)、左下角设置入口、Header/侧边栏自动生效。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 23:34:12 +08:00
fengxiangdebaozi 8d0759123a chore: 同步 backend CLAUDE.md 文档换行格式 2026-06-16 22:43:18 +08:00
fengxiangdebaozi 318f6c0c0c feat: 业务链条配置管理导航与顶栏用户名统一
业务链条页增加配置管理入口与返回导航;配置管理页通过 aliasPaths 保持侧栏选中;顶栏用户名与设置个人信息页共用 getAccountDisplayName。
2026-06-16 22:42:42 +08:00
fengxiangdebaozi d8102e8db8 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 22:18:22 +08:00
AdministratorandClaude Opus 4.8 5b610fd807 feat: 上下文压缩支持状态持久化缓存,前端过滤隐藏消息
- summarization_middleware 摘要缓存写入 LangGraph thread state,跨进程/重启可复用
- 摘要消息改为 SystemMessage,提示模型静默使用、不泄露
- thread_state 新增 context_summary_cache 字段
- app_config 加载时记录 summarization 配置日志
- config.yaml 压缩触发/保留阈值调整为生产值(token 预算)
- 前端 input-box / message-list 过滤 hide_from_ui 消息

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 22:16:06 +08:00
董宏凯 7afdf5b363 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 22:01:18 +08:00
董宏凯 6c5a2cffe3 配置页面修改 2026-06-16 22:01:06 +08:00
fengxiangdebaozi 0bad0eb306 代码隐藏 2026-06-16 22:00:30 +08:00
248 changed files with 23729 additions and 2967 deletions

No files matched your search

+3
View File
@@ -104,3 +104,6 @@ docs/backups
# uv lockfile (not tracked per project preference)
offline-backend-20260512/backend/uv.lock
# misc
.DS_Store
+5 -1
View File
@@ -80,11 +80,15 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA:
- **Routing**: React Router v7; top-level routes in `src/pages/PageRoutes.tsx`, workspace sub-routes in `src/pages/WorkspaceRoutes.tsx`
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
- **轻应用中心 (Light App Center)**: a sibling of 任务管理 in the sidebar with two pages — 应用管理 (admin registers `window_open` or `iframe` mini-apps with a route-param builder: login params resolved from `localStorage.userInfo`, theme params literal) and 应用列表 (card grid of `window_open` apps, `window.open` launch). `iframe` apps are mounted under a chosen parent menu (XK/PG/TY/综合管理) and **dynamically injected into the sidebar** by `core/page-layout/use-sidebar-menu.ts` (`useSidebarMenuItems`), opening in the `LightAppIframeView` host. Client + React Query hooks in `strategy-components/api/light-apps.ts`; URL builder/constants in `strategy-components/lib/light-app.ts`. Backend: `/api/light-apps` (global/shared, admin-gated writes).
- **菜单管理 (Menu Management, admin-only)**: an **overlay** over the static sidebar menu — `MenuManagementPage` (`pages/MenuManagementPage.tsx`, route `/page/strategy/admin/menu-management`, opened from the admin-only 「菜单管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`). Admins rename / 停用·启用 / reorder (↑↓ or @dnd-kit drag) / re-parent (horizontal drag **or** the edit dialog's 「移动到」parent selector) any node across 一级/二级/三级, **including injected iframe light-app nodes** (`light-app-<appId>`). The static tree (`core/page-layout/sidebar-menu.ts`) stays the source of icons/routes; only per-node deltas (`label`/`disabled`/`parentId`/`sortOrder`) persist to the backend. Merge logic in `core/page-layout/menu-overrides.ts` (`applyMenuOverrides`, applied in `use-sidebar-menu.ts` after light-app injection, before role filter; disabling a node hides its whole subtree) — strict **3-level cap** (`wouldExceedDepth`). Client `strategy-components/api/menu-overrides.ts`. Backend: `/api/menu-overrides` (global/shared; open read, admin atomic replace-all).
- **敏感词管理 (Sensitive Word Management)**: configures the **展示层脱敏映射** (原始词 → 替换词). **Gated on the username `lqq`** (not the admin role) — `getAccountDisplayName().toLowerCase() === "lqq"` (username = email `@` prefix, else `user_id`, same as the profile page); the dropdown entry, the route guard, and the page-level guard all use this check. `src/lib/desensitize.ts` ships a frozen seed map `SEED_DESENSITIZE_MAP` (the deployment seed) plus a live mutable `DESENSITIZE_MAP` (initialized from the seed so `desensitize()` works before any fetch). `DesensitizeWordsLoader` (mounted in `App.tsx` `AppProviders`) fetches `/api/sensitive-words` on startup and, if non-empty, calls `replaceDesensitizeMap(...)` to make the backend config the source of truth (empty/failed → keep seed). Page `SensitiveWordsPage.tsx` (route `/page/strategy/admin/sensitive-words`, opened from the 「敏感词管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`, present in **both** full + collapsed sidebar modes) lists/adds/edits/启停/deletes words and saves the **whole set atomically** (replace-all); a 「导入种子词」 button merges any missing `SEED_DESENSITIZE_MAP` entries into the editor. Client + hooks in `strategy-components/api/sensitive-words.ts` (`wordsToMap` folds enabled rows into the runtime map). Backend: `/api/sensitive-words` (global/shared; open read, write allowed for admin **or** the `lqq` account), mirroring 菜单管理's store shape. **侧边栏 + 导航栏 menu labels are desensitized** at the data source: `useSidebarMenuItems`/`useActiveThirdLevel` (`core/page-layout/use-sidebar-menu.ts`) map every node's `label` through a desensitizer built **directly from the `/api/sensitive-words` query** (`makeDesensitizer(wordsToMap(words))`, falling back to the global seed `desensitize` while empty) — this sidesteps the `replaceDesensitizeMap` effect-timing race. Only `label` is rewritten; `path`/`id`/`icon` are untouched so routing/highlight are unaffected. All nav surfaces (`page-sidebar.tsx`, `page-sidebar-dark.tsx`, `page-sidebar-v1.tsx`, `strategy-components/Header.tsx`, `PageRoutes.tsx`) consume this hook and are covered; `MenuManagementPage` uses the raw tree so admins still edit real labels.
- **按钮管理 (Task Button Management, admin-only)**: configures the **可配置跳转按钮** rendered in the left task panel of the task deep-link workspaces (rwfx / 3qfx / xdfx, see `TaskFxWorkspace`). Each button = `{business, label, linkType, target, appendTaskId, idParam, idKind, enabled, sortOrder}`; `linkType` is `url` (外链 `window.open`, optional append of `?{idParam}={id}` — **`idParam` is the editable query-param name**, e.g. `id`/`task_id`), `business` (内部切换到另一业务, reuses `resolveTaskDeeplinkTarget`, always task id), or `purpose` (弹出当前任务的「任务目的」表格 via the shared `TaskPurposeDialog`, no target — configurable for any page incl. xdfx). **`idKind` (`task`/`action`) only matters for xdfx**: its deep-link `?taskId=` is an 行动id and the 任务id is resolved at login (`fetchTaskIdFromAction`) — `TaskContext` now also stashes the raw `actionId`, so a url button can append either (default `task`). Page `TaskButtonsPage.tsx` (route `/page/strategy/admin/task-buttons`, **admin-gated**, entry「按钮管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both full + collapsed modes) has per-business tabs, edits name/type/target/启停/排序/增删, saves the **whole set atomically** (replace-all), plus 「导入默认」 to merge code-seed defaults. **Seed/fallback** (like 敏感词管理): only when the whole table is empty (fresh deploy, never saved) do the workspace + page fall back to `defaultTaskButtons(cfg)` — rwfx's url buttons (编辑/下一步/3q详情) built from the **live** `/api/public/config/task-deeplink` plus cross-business switch buttons for **all three** businesses (each switches to the other two — rwfx→三情/行动, 3qfx→任务/行动, xdfx→任务/三情). Once saved, the store is the sole source of truth. The old hardcoded jump buttons were migrated out: `TaskFxWorkspace` no longer hardcodes 切换到三情分析, `TaskActionsPanel` keeps only the non-jump 清除记录, and `TaskPurposePanel` dropped its 3q详情 button (now configurable) **and defaults the 目的树 table to collapsed** (chevron toggle). Helpers `core/auth/task-buttons.ts` (`TaskButton`, `defaultTaskButtons`, `resolveTaskButtons`, `buttonsForBusiness`, `runTaskButton`), client+hooks `strategy-components/api/task-buttons.ts`. Backend: `/api/task-buttons` (global/shared; open read, admin replace-all), store `deerflow.persistence.task_buttons` (table `task_buttons`, auto-created by `create_all`), wired `app.state.task_button_store`. Tests: `tests/test_task_buttons.py`.
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A (resolved via `/api/business-mapping`, opening message in `sessionStorage.pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats/:thread_id}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. The agent chat is rendered via `TaskEmbeddedAgentChat`, which passes `AgentChatPage`'s `chatBasePath` prop so the post-send URL rewrite + new-chat button stay in the task-management context (instead of the standalone `/agents/...` route). Any failure (no consumer URL / fetch error / unmapped goPath / no configured agent) silently falls back to the default home. Helpers: `core/auth/task-deeplink.ts`.
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. The roundtable target also threads the URL `taskId` into `roundtablePrefill.taskId` (`resolveTaskDeeplinkTarget(goPath, detail, taskId)`), which turns on two taskId-scoped behaviors: (1) **separate, unpartitioned per-task storage** — taskId 会商聊天记录 live in their **own** store/table (`roundtable_task_drafts`), keyed **only by `task_id`** (one taskId = many records, shared across users, **no user 分权** at all; `created_by` is audit-only), kept entirely out of the per-user personal store (`roundtable_drafts`, now strictly per-user) so the two never mix. Backend router `/api/roundtable-task-drafts` (`GET /by-task/{id}` + `/by-task/{id}/latest`, `POST`, `GET/PUT/DELETE /{id}` — all user-agnostic); frontend client `roundtable-planning/api/task-drafts.ts`, and `useDraftPersistence`/`useRoundtableDrafts` route **all** CRUD to it when a `taskId` is present (else the personal `drafts.ts`). The matching **background jobs** are shared by task too: `roundtable_jobs.task_id` marks a task job; reads/dedup/stream/resume/cancel pass `?task_id=` so any user opening the task sees the same running 研讨 (progress/flowchart), and the executor writes the final report back to the task-draft store. Existing rows are moved over by `scripts/migrate_roundtable_task_drafts.py` (migration `20260618_01`). The history dropdown filters to the task and 新建 keeps the binding; (2) **Step-3 auto structured output** — after the `roundtable-summary` agent writes the Markdown report it automatically runs a second round emitting a `flow-json` flowchart (`useStep3Summary` `autoFlow`+`chainLevels`), whose hierarchy follows the business chain's stage goals (任务 → 目的 → 行为体 → …; coordinatorPrompt-specified hierarchy wins) and whose nodes never carry 阶段编号/阶段名 (the prior bug). **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. **All three single-agent businesses share `TaskFxWorkspace`** (`task-components/TaskFxWorkspace.tsx`): left = a「当前任务」card (`readCopTaskDetail()` 任务名称 + 简介, desensitized, 留存 above 新建对话) + per-task 1:N conversation list (`useTaskThreads(taskId, agentId)` — filtered by **both** `metadata.taskId` AND `metadata.agent_id` so the three businesses' conversations stay isolated even though they share one taskId) + 新建对话; the `…/chats` index (`TaskFxIndexResolver`) opens the latest task thread or 新建. The right `:thread_id` host differs by business: **rwfx** → `TaskFxChat` (`AgentChatPage taskGate`) = full workspace (non-`lite`): 目的树闸门 panel + 清除记录 (placed under 新建对话); **xdfx** → also `TaskFxChat` (same 目的树闸门 query+display, same `purpose_detail_url`) but workspace passed `lite`; **3qfx** → `TaskBindChat` (`AgentChatPage taskBind`, `lite`) = 1:N list only, no gate, and 新建对话 **auto-sends** the task opening text (`taskAutoSendText`; gate Line truncated
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
### Configuration
+7 -1
View File
@@ -5,7 +5,13 @@
VITE_USE_REAL_DATA=true
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(consumer 外网不可达时调试用)。
VITE_MOCK_COP_TASK_DETAIL=false
VITE_MOCK_COP_TASK_DETAIL=true
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:true 走本地样例假数据(真实接口未就绪时调试用);联调通过后置 false。
VITE_MOCK_SQ_REPORT=true
# 深链任务详情(cop-task-detail:任务名称/描述)数据源:true 走本地假数据(真实接口未就绪时调试用);联调通过后置 false。
VITE_MOCK_COP_TASK_DETAIL=true
# Gateway / DeerFlow API
VITE_BACKEND_BASE_URL=http://127.0.0.1:8001
+6
View File
@@ -7,6 +7,12 @@ VITE_USE_REAL_DATA=true
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
VITE_MOCK_COP_TASK_DETAIL=false
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:默认真实接口;真实接口未就绪可改 true 走本地样例假数据。
VITE_MOCK_SQ_REPORT=false
# 深链任务详情(cop-task-detail)数据源:默认真实接口;真实接口未就绪可改 true 走本地假数据。
VITE_MOCK_COP_TASK_DETAIL=false
# Gateway / DeerFlow API
VITE_BACKEND_BASE_URL=http://47.88.25.99:7001
VITE_LANGGRAPH_BASE_URL=http://47.88.25.99:7001/api
+3
View File
@@ -7,6 +7,9 @@ VITE_USE_REAL_DATA=true
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
VITE_MOCK_COP_TASK_DETAIL=false
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:默认真实接口;真实接口未就绪可改 true 走本地样例假数据。
VITE_MOCK_SQ_REPORT=false
# Gateway / DeerFlow API
VITE_BACKEND_BASE_URL=https://ch1.b.uat.4.cn/deerflow
VITE_LANGGRAPH_BASE_URL=https://ch1.b.uat.4.cn/deerflow/api
+6
View File
@@ -7,6 +7,12 @@ VITE_USE_REAL_DATA=true
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
VITE_MOCK_COP_TASK_DETAIL=false
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:默认真实接口;真实接口未就绪可改 true 走本地样例假数据。
VITE_MOCK_SQ_REPORT=false
# 深链任务详情(cop-task-detail)数据源:默认真实接口;真实接口未就绪可改 true 走本地假数据。
VITE_MOCK_COP_TASK_DETAIL=false
# Gateway / DeerFlow API
VITE_BACKEND_BASE_URL=https://ch1.b.sit.4.cn/deerflow
VITE_LANGGRAPH_BASE_URL=https://ch1.b.sit.4.cn/deerflow/api
+16 -1
View File
@@ -1,7 +1,8 @@
import { useMemo } from "react";
import { useEffect, useMemo } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { DesensitizeWordsLoader } from "@/components/desensitize-words-loader";
import { FontScaleApplier } from "@/components/font-scale";
import { QueryClientProvider } from "@/components/query-client-provider";
import { AuthSyncWatcher } from "@/core/auth/sync";
@@ -16,6 +17,10 @@ import {
} from "@/core/embed/params";
import { usePublicEmbedTheme } from "@/core/embed/background";
import { readWujieProps } from "@/core/embed/wujie";
import {
resolveForcedEmbedTheme,
syncEmbedSessionFromSearch,
} from "@/core/embed/embed-session";
import { HashRouter, useLocation } from "react-router-dom";
@@ -40,7 +45,16 @@ function AppProviders({ children }: { children: React.ReactNode }) {
const locale = useMemo(() => detectLocale(), []);
const location = useLocation();
const publicEmbedTheme = usePublicEmbedTheme();
// iframe 嵌入会话(按标签页 sessionStorage)集中在此同步:任何带 `&embed=1` 的入口(深链登录页
// 或直接深链路由)一进来就启用、`embed=0` 关闭,后续干净路由靠会话维持去 chrome + 强制主题。
useEffect(() => {
syncEmbedSessionFromSearch(location.search);
}, [location.search]);
const forcedTheme = useMemo(() => {
// iframe 嵌入模式(外部系统 `&embed=1`)最高优先:按本标签页的嵌入主题强制明/暗。
// 走 next-themes forcedTheme(不写 localStorage)→ 同浏览器另开的正常系统页不受影响。
const embedTheme = resolveForcedEmbedTheme(location.search);
if (embedTheme) return embedTheme;
const routeTheme = resolveForcedThemeForPath(location.pathname);
if (routeTheme) return routeTheme;
if (location.pathname === "/embed/roundtable") {
@@ -76,6 +90,7 @@ function AppProviders({ children }: { children: React.ReactNode }) {
<ThemeProvider>
<ChatProvider>
<AuthSyncWatcher />
<DesensitizeWordsLoader />
<FontScaleApplier />
{children}
</ChatProvider>
@@ -0,0 +1,27 @@
import { useEffect } from "react";
import { replaceDesensitizeMap } from "@/lib/desensitize";
import { useSensitiveWords, wordsToMap } from "@/strategy-components/api/sensitive-words";
/**
* 启动时把后台「敏感词管理」配置加载进运行时脱敏映射表。
*
* - 后台返回**非空**时:用其中「启用」的词条整体替换运行时映射
* ({@link replaceDesensitizeMap}),后台即唯一真源,被删除的词不再生效。
* - 后台为空(全新部署还没配置)或拉取失败:什么都不做,保持使用
* `src/lib/desensitize.ts` 内置的种子映射。
*
* 渲染 `null`;挂在 `AppProviders` 里(QueryClientProvider 之内)。与「敏感词管理」
* 页共享同一份 React Query 缓存,保存后会自动刷新并回灌运行时映射。
*/
export function DesensitizeWordsLoader() {
const { data } = useSensitiveWords();
useEffect(() => {
if (data && data.length > 0) {
replaceDesensitizeMap(wordsToMap(data));
}
}, [data]);
return null;
}
@@ -6,6 +6,8 @@ import { getStoredAuth } from "@/core/auth";
import { isWujieEnv } from "@/core/embed/wujie";
import {
defaultExpandedIds,
menuItemContainsPath,
menuItemMatchesPath,
type MenuItem,
} from "@/core/page-layout/sidebar-menu";
import { useSidebarMenuItems } from "@/core/page-layout/use-sidebar-menu";
@@ -53,13 +55,7 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
}, 180);
};
const hasActiveChild = (item: MenuItem): boolean => {
if (item.path && (pathname === item.path || pathname.startsWith(item.path + "/"))) {
return true;
}
return item.children?.some(hasActiveChild) ?? false;
};
const hasActiveChild = (item: MenuItem): boolean => menuItemContainsPath(item, pathname);
// lazy init:仅在首次 render 计算一次 active id;之后由下面的 useEffect 跟随 pathname 同步
const [activeTopId, setActiveTopId] = useState<string>(
@@ -152,9 +148,9 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
const isSidebarItemActive = (item: MenuItem) =>
inWujieEnv
? item.id === activeTopId
: item.path
? pathname === item.path || pathname.startsWith(item.path + "/")
: hasActiveChild(item);
: item.path || item.aliasPaths?.length
? menuItemMatchesPath(item, pathname)
: menuItemContainsPath(item, pathname);
const handleSidebarItemClick = (item: MenuItem) => {
if (inWujieEnv) {
handleTopItemClick(item);
@@ -176,7 +172,9 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
{items.map((item) => {
const hasChildren = !!item.children?.length;
const isExpanded = expandedIds.has(item.id);
const isSelected = item.path ? pathname === item.path : hasActiveChild(item);
const isSelected = item.path || item.aliasPaths?.length
? menuItemMatchesPath(item, pathname)
: hasActiveChild(item);
return (
<div
+61 -14
View File
@@ -7,7 +7,10 @@ import {
ChevronsUpDown,
Folder,
FolderOpen,
ListTree,
MousePointerClick,
Settings,
ShieldAlert,
User,
Wrench,
} from "lucide-react";
@@ -21,13 +24,20 @@ import {
import { NotificationDialog } from "@/components/workspace/notification-dialog";
import { SettingsDialog } from "@/components/workspace/settings";
import { useTheme } from "@/contexts/ThemeContext";
import { getStoredAuth } from "@/core/auth";
import { getAccountDisplayName, getStoredAuth } from "@/core/auth";
/** 敏感词管理仅对用户名为 lqq 的账号可见(用户名 = 设置→个人信息页展示名)。 */
const SENSITIVE_WORDS_USERNAME = "lqq";
const canManageSensitiveWords = () =>
getAccountDisplayName().toLowerCase() === SENSITIVE_WORDS_USERNAME;
import { isWujieEnv } from "@/core/embed/wujie";
import { useI18n } from "@/core/i18n/hooks";
import { useUnreadCount } from "@/core/notifications";
import {
defaultExpandedIds,
getActiveThirdLevelItems,
menuItemContainsPath,
menuItemMatchesPath,
type MenuItem,
} from "@/core/page-layout/sidebar-menu";
import { useSidebarMenuItems } from "@/core/page-layout/use-sidebar-menu";
@@ -41,12 +51,8 @@ type PageSidebarProps = {
type SettingsSection = "account" | "appearance" | "memory" | "tools" | "about";
const hasActiveChild = (item: MenuItem, pathname: string): boolean => {
if (item.path && (pathname === item.path || pathname.startsWith(item.path + "/"))) {
return true;
}
return item.children?.some((child) => hasActiveChild(child, pathname)) ?? false;
};
const hasActiveChild = (item: MenuItem, pathname: string): boolean =>
menuItemContainsPath(item, pathname);
const findFirstRoutePath = (items?: MenuItem[]): string | null => {
if (!items?.length) {
@@ -116,9 +122,9 @@ function SecondaryNavSidebar() {
const secondaryItems = activeTopItem?.children ?? [];
const isItemActive = (item: MenuItem) =>
item.path
? pathname === item.path || pathname.startsWith(item.path + "/")
: hasActiveChild(item, pathname);
item.path || item.aliasPaths?.length
? menuItemMatchesPath(item, pathname)
: menuItemContainsPath(item, pathname);
const handleItemClick = (item: MenuItem) => {
const path = item.path ?? findFirstRoutePath(item.children);
@@ -200,6 +206,30 @@ function SecondaryNavSidebar() {
<User className="size-4" />
个人信息
</DropdownMenuItem>
{isAdmin && (
<DropdownMenuItem
onClick={() => navigate("/page/strategy/admin/menu-management")}
>
<ListTree className="size-4" />
菜单管理
</DropdownMenuItem>
)}
{isAdmin && (
<DropdownMenuItem
onClick={() => navigate("/page/strategy/admin/task-buttons")}
>
<MousePointerClick className="size-4" />
按钮管理
</DropdownMenuItem>
)}
{canManageSensitiveWords() && (
<DropdownMenuItem
onClick={() => navigate("/page/strategy/admin/sensitive-words")}
>
<ShieldAlert className="size-4" />
敏感词管理
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
) : null}
@@ -211,9 +241,8 @@ function SecondaryNavSidebar() {
<nav className="light-sidebar-subnav" aria-label="三级菜单">
{thirdItems.map((child) => {
const ChildIcon = child.icon;
const childActive = child.path
? pathname === child.path || pathname.startsWith(child.path + "/")
: hasActiveChild(child, pathname);
const childActive = menuItemMatchesPath(child, pathname)
|| (child.children?.length ? menuItemContainsPath(child, pathname) : false);
return (
<button
key={child.id}
@@ -301,7 +330,7 @@ function LegacyAccordionSidebar({
const renderLeaf = (item: MenuItem, depth = 0) => {
const Icon = item.icon;
const isActive = !!item.path && pathname === item.path;
const isActive = menuItemMatchesPath(item, pathname);
return (
<button
@@ -467,6 +496,24 @@ function LegacyAccordionSidebar({
<User className="size-4" />
个人信息
</DropdownMenuItem>
{isAdmin && (
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/menu-management")}>
<ListTree className="size-4" />
菜单管理
</DropdownMenuItem>
)}
{isAdmin && (
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/task-buttons")}>
<MousePointerClick className="size-4" />
按钮管理
</DropdownMenuItem>
)}
{canManageSensitiveWords() && (
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/sensitive-words")}>
<ShieldAlert className="size-4" />
敏感词管理
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
) : (
@@ -0,0 +1,59 @@
import * as React from "react";
export interface AutoGrowTextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
/** 内容增长高度上限(px),超过后框内滚动。默认 200。 */
maxHeight?: number;
}
/**
* 自适应高度的多行输入框。
*
* 内容增多时自动扩展高度(输入框处于底部布局时即「向上扩展」),到 `maxHeight` 后框内滚动。
* 体验对齐通用问答页(`/page/strategy/qa/general`)的 tdesign `autosize` 输入框,但保留原生
* `<textarea>`,从而沿用各调用处自带的 Tailwind 样式 / 边框 / 占位色,无需 TDesign 包裹层。
*
* 用法:当成普通受控 `<textarea>` 用(传 `value` + `onChange`)。高度在布局阶段随 `value` 重算,
* 也在 `onChange` 时即时重算(兼顾非受控/输入法场景)。最小高度交给调用方的 `min-h-*` className
* 或 `rows` 控制——本组件不强加最小高度。换行/发送(Enter/Shift+Enter)逻辑由调用方的
* `onKeyDown` 决定。
*/
export const AutoGrowTextarea = React.forwardRef<
HTMLTextAreaElement,
AutoGrowTextareaProps
>(function AutoGrowTextarea(
{ maxHeight = 200, value, onChange, onInput, style, rows = 1, ...rest },
ref,
) {
const innerRef = React.useRef<HTMLTextAreaElement | null>(null);
React.useImperativeHandle(ref, () => innerRef.current as HTMLTextAreaElement);
const resize = React.useCallback(() => {
const el = innerRef.current;
if (!el) return;
el.style.height = "auto";
const next = Math.min(el.scrollHeight, maxHeight);
el.style.height = `${next}px`;
el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden";
}, [maxHeight]);
// 受控值变化(含外部清空、粘贴大段文本)后在布局阶段重算,避免闪烁。
React.useLayoutEffect(() => {
resize();
}, [resize, value]);
return (
<textarea
ref={innerRef}
rows={rows}
value={value}
onChange={onChange}
onInput={(e) => {
onInput?.(e);
resize();
}}
style={{ resize: "none", ...style }}
{...rest}
/>
);
});
@@ -401,7 +401,7 @@ export function PositionManagementPage() {
};
return (
<div className="flex flex-col gap-4 p-6">
<div className="flex size-full min-h-0 flex-col gap-4 overflow-auto p-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-lg font-semibold">岗位管理</h1>
@@ -12,7 +12,7 @@ export function UserManagementPage() {
const { data: users, isLoading, error } = useAllUsers(true);
return (
<div className="flex flex-col gap-6 p-6">
<div className="flex size-full min-h-0 flex-col gap-6 overflow-auto p-6">
<SettingsSection
title={t.adminUsers.title}
description={t.adminUsers.description}
@@ -0,0 +1,35 @@
/**
* 智能体图标底色 —— 按 id 稳定散列到一组主题色,复刻参考图的彩色方块。
*
* 浅色模式沿用原高彩度彩色(不改);深蓝主题改用《深蓝 UI 规范》§1.1.7/§1.1.8 的蓝-青系
* (docs/ui规范-深蓝,克制、不刺眼),仅深蓝主题下生效,互不影响。
*
* 全量版通用问答左栏(GeneralQaSidebar)与 zzJC/zzXD 模块左栏(AgentModuleSidebar)共用,
* 保证彩色卡片配色完全一致。
*/
const AGENT_COLORS_LIGHT = [
{ from: "#fb7185", to: "#ef4444" },
{ from: "#60a5fa", to: "#3b82f6" },
{ from: "#fbbf24", to: "#f59e0b" },
{ from: "#34d399", to: "#10b981" },
{ from: "#a78bfa", to: "#8b5cf6" },
] as const;
const AGENT_COLORS_DARK = [
{ from: "#4096FF", to: "#1677FF" }, // 蓝(链接蓝 → 主色)
{ from: "#36CFC9", to: "#13C2C2" }, // 青(辅色)
{ from: "#6388FF", to: "#0958D9" }, // 紫蓝(装饰紫 → 主色深一档)
{ from: "#5CDBD3", to: "#08979C" }, // 浅青 → 深青
{ from: "#69B1FF", to: "#003EB3" }, // 浅蓝 → 主色按下
] as const;
/** 按 agent id 稳定散列出一对渐变色(from → to)。`isDark` 切换深蓝/浅色调色板。 */
export function agentColor(id: string, isDark: boolean) {
let hash = 0;
for (let i = 0; i < id.length; i++) {
hash = (hash * 31 + id.charCodeAt(i)) >>> 0;
}
const palette = isDark ? AGENT_COLORS_DARK : AGENT_COLORS_LIGHT;
return palette[hash % palette.length]!;
}
@@ -229,6 +229,10 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
);
const [editPublished, setEditPublished] = useState(agent.published);
const [editIsPrivate, setEditIsPrivate] = useState(agent.is_private);
// 会商席位「技能识别强化」开关(弱模型补偿)。默认关。
const [editSeatSkillDirective, setEditSeatSkillDirective] = useState(
agent.seat_skill_directive ?? false,
);
const [editSquareId, setEditSquareId] = useState(agent.square_id ?? "");
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
const { data: publishSquares } = usePublishSquares();
@@ -274,6 +278,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
setEditSquareId(agent.square_id ?? "");
setSelectedSkills(agent.skills ?? []);
setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions));
setEditSeatSkillDirective(agent.seat_skill_directive ?? false);
}, [
agent.common_questions,
agent.description,
@@ -282,6 +287,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
agent.published,
agent.square_id,
agent.skills,
agent.seat_skill_directive,
editOpen,
]);
@@ -295,6 +301,8 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
if (agentDetail) {
setEditSoul(agentDetail.soul ?? "");
setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions));
// 列表响应不带 config 额外字段(seat_skill_directive 为 null),详情才有真值。
setEditSeatSkillDirective(agentDetail.seat_skill_directive ?? false);
} else {
setEditSoul(agent.soul ?? "");
}
@@ -386,6 +394,8 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
request.skills = selectedSkills;
if (JSON.stringify(nextQuestions) !== JSON.stringify(baselineQuestions))
request.common_questions = nextQuestions;
if (editSeatSkillDirective !== ((agentDetail?.seat_skill_directive ?? agent.seat_skill_directive) ?? false))
request.seat_skill_directive = editSeatSkillDirective;
if (Object.keys(request).length === 0) {
setEditOpen(false);
@@ -960,6 +970,19 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
onChange={setEditCommonQuestions}
/>
</div>
<div className="flex items-center justify-between gap-3 rounded-md border p-3">
<div>
<p className="text-sm font-medium">会商技能识别强化</p>
<p className="text-muted-foreground text-xs">
作为会商席位时,把已配置技能(含 SKILL.md 路径与「先 read_file
再用」硬指令)拼进任务,补偿弱模型不识别技能。也可在业务链条配置里打开(任一即生效)。
</p>
</div>
<Switch
checked={editSeatSkillDirective}
onCheckedChange={setEditSeatSkillDirective}
/>
</div>
<div className="flex items-center justify-between rounded-md border p-3">
<div>
<p className="text-sm font-medium">公开发布</p>
@@ -0,0 +1,620 @@
"use client";
import {
Bot,
ChevronDown,
Download,
FileJson,
FileText,
Loader2,
MessageSquare,
MoreHorizontal,
Pencil,
Pin,
PinOff,
Search,
Share2,
Star,
Trash2,
X,
} from "lucide-react";
import Link from "next/link";
import { useParams, usePathname, useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { agentColor } from "@/components/workspace/agent-icon-color";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { ShareConversationDialog } from "@/components/workspace/thread-share-dialogs";
import { useTheme } from "@/contexts/ThemeContext";
import { useAgentsPaginated } from "@/core/agents";
import { getAPIClient } from "@/core/api";
import { useI18n } from "@/core/i18n/hooks";
import { useRouteBase } from "@/core/route-base";
import { usePublishSquares } from "@/core/system-settings/hooks";
import {
exportThreadAsJSON,
exportThreadAsMarkdown,
} from "@/core/threads/export";
import {
useDeleteThread,
useRenameThread,
useThreads,
useToggleThreadFavorite,
useToggleThreadPin,
} from "@/core/threads/hooks";
import type { AgentThread, AgentThreadState } from "@/core/threads/types";
import {
isThreadFavorite,
isThreadPinned,
sortThreadsPinnedFirst,
titleOfThread,
usePathOfThread,
} from "@/core/threads/utils";
import { env } from "@/env";
import { desensitize } from "@/lib/desensitize";
import { isIMEComposing } from "@/lib/ime";
import { cn } from "@/lib/utils";
/** 「我的」作用域的下拉选项值;其余选项值为各发布广场(publish square)的 id。 */
const MINE_SCOPE = "mine";
// 列表一次拉取的条数。超出时底部出现「查看全部」入口,跳到完整的智能体管理页,
// 避免静默截断。侧边栏只做快速切换,不在此分页。
const LIST_PAGE_SIZE = 50;
// 「最近的对话」未搜索时最多展示条数(与首页「通用问答」左栏一致)。
const MAX_RECENT_CHATS = 10;
/**
* 智能体问答页左侧「智能体列表 + 最近对话」栏(参考首页通用问答左栏)。
*
* 自上而下:
* 1. 顶部下拉:选「我的」(默认,= 我创建/收藏的)或任一「广场」(发布广场),
* 与「智能体管理」页主标签一致;下方为智能体名称模糊搜索框。
* 2. 智能体列表:所选作用域下的智能体;点击进入该智能体的新对话。当前智能体高亮。
* 3. 最近的对话:跨智能体的近期会话(参考首页),点击打开;支持重命名/置顶/收藏/
* 分享/导出/删除。当前会话高亮。
*
* 仅在独立的智能体问答整页展示;任务工作区 / zzJC·zzXD 模块 / 嵌入态不展示。
*/
export function AgentChatSidebar({ activeAgentId }: { activeAgentId?: string }) {
const { t } = useI18n();
const routeBase = useRouteBase();
const { theme } = useTheme();
const isDark = theme === "dark";
const { data: publishSquares } = usePublishSquares();
// 每个发布广场对应一个下拉选项;后端至少返回一个内置默认广场。
const squares = useMemo(
() => publishSquares?.squares ?? [],
[publishSquares?.squares],
);
// 作用域:MINE_SCOPE 或某个广场 id。默认「我的」。
const [scope, setScope] = useState<string>(MINE_SCOPE);
// 模糊搜索智能体名称:防抖 300ms 后走服务端 search(后端按原始名 / 脱敏名匹配),
// 在当前来源(我的 / 某广场)内过滤,能搜全量而非仅当前 50 条。
const [searchInput, setSearchInput] = useState("");
const [search, setSearch] = useState("");
useEffect(() => {
const timer = setTimeout(() => setSearch(searchInput.trim()), 300);
return () => clearTimeout(timer);
}, [searchInput]);
// 「智能体」区可收起(持久化);收起后只留标题栏,下方「最近的对话」占满剩余空间。
const [agentsCollapsed, setAgentsCollapsed] = useState(
() =>
typeof window !== "undefined" &&
localStorage.getItem("agent-chat-sidebar:agents-collapsed") === "true",
);
const toggleAgents = () =>
setAgentsCollapsed((v) => {
localStorage.setItem("agent-chat-sidebar:agents-collapsed", String(!v));
return !v;
});
// 若所选广场被管理员删除,回退到「我的」,避免指向不存在的广场。
useEffect(() => {
if (
scope !== MINE_SCOPE &&
squares.length > 0 &&
!squares.some((sq) => sq.id === scope)
) {
setScope(MINE_SCOPE);
}
}, [scope, squares]);
const isMine = scope === MINE_SCOPE;
const { agents, total, isLoading, isFetching } = useAgentsPaginated({
scope: isMine ? "mine" : "square",
sort: "time_desc",
page: 1,
pageSize: LIST_PAGE_SIZE,
square: isMine ? undefined : scope,
search: search || undefined,
});
return (
// 配色与 AgentModuleSidebar 一致:浅色白底,深蓝主题半透明深蓝玻璃面板。
<aside className="flex h-full w-(--sidebar-width) shrink-0 flex-col overflow-hidden border-r border-border/70 bg-white text-foreground backdrop-blur-md dark:border-[#2b8ffe]/45 dark:bg-[#032650]/80">
{/* 智能体(上半,可收起)。展开时:标题栏 + 来源下拉/名称搜索 + 列表;
收起时只留标题栏,下方「最近的对话」占满剩余空间。 */}
<div
className={cn(
"flex flex-col",
agentsCollapsed ? "shrink-0" : "min-h-0 flex-[3]",
)}
>
<button
type="button"
onClick={toggleAgents}
className="text-foreground/80 hover:bg-accent/40 flex shrink-0 items-center justify-between border-b border-border/60 px-3 py-2.5 text-[12px] font-semibold transition-colors select-none"
title={agentsCollapsed ? "展开智能体" : "收起智能体"}
>
<span>智能体</span>
<ChevronDown
className={cn(
"text-muted-foreground size-4 shrink-0 transition-transform duration-200",
agentsCollapsed && "-rotate-90",
)}
/>
</button>
{!agentsCollapsed && (
<>
{/* 来源下拉(我的 / 各广场)+ 智能体名称模糊搜索 */}
<div className="shrink-0 space-y-2 border-b border-border/60 px-3 py-2.5">
<Select value={scope} onValueChange={setScope}>
<SelectTrigger className="h-9 w-full text-sm" title="切换智能体来源">
<SelectValue />
</SelectTrigger>
<SelectContent position="popper" side="bottom" sideOffset={4}>
<SelectItem value={MINE_SCOPE}>我的</SelectItem>
{squares.map((sq) => (
<SelectItem key={sq.id} value={sq.id}>
{sq.name}
</SelectItem>
))}
</SelectContent>
</Select>
<div className="relative">
<Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2" />
<Input
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder="搜索智能体名称"
className="h-9 pl-8 pr-8 text-sm"
aria-label="搜索智能体名称"
/>
{searchInput && (
<button
type="button"
onClick={() => setSearchInput("")}
className="text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2"
title="清除"
aria-label="清除搜索"
>
<X className="size-3.5" />
</button>
)}
</div>
</div>
{/* 智能体列表(独立滚动) */}
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-2 py-3">
{isLoading && agents.length === 0 ? (
<div className="text-muted-foreground flex h-24 items-center justify-center gap-2 text-xs">
<Loader2 className="size-3.5 animate-spin" />
加载中…
</div>
) : agents.length === 0 ? (
<p className="px-3 py-1.5 text-xs text-muted-foreground/70">
{search
? "未找到匹配的智能体"
: isMine
? "暂无智能体"
: "该广场暂无智能体"}
</p>
) : (
<div
className={cn(
"flex flex-col gap-1 transition-opacity",
isFetching && "opacity-60",
)}
>
{agents.map((agent) => {
const href = `${routeBase}/agents/${agent.id}/chats/new`;
const isActive = agent.id === activeAgentId;
const { from, to } = agentColor(agent.id, isDark);
return (
<Link
key={agent.id}
href={href}
className={cn(
"group relative flex w-full items-start gap-2.5 rounded-xl border px-2.5 py-2 transition-colors",
isActive
? "border-primary/40 bg-primary/5"
: "border-transparent hover:border-border hover:bg-accent/50",
)}
>
<span
className="mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg text-white shadow-sm"
style={{
backgroundImage: `linear-gradient(135deg, ${from}, ${to})`,
}}
>
<Bot className="size-[18px]" />
</span>
<span className="min-w-0 flex-1">
<span
className={cn(
"block truncate text-[13px] font-semibold",
isActive ? "text-primary" : "text-foreground",
)}
>
{desensitize(agent.name)}
</span>
<span className="mt-0.5 block truncate text-[11px] leading-snug text-muted-foreground">
{agent.description
? desensitize(agent.description)
: "智能体助手"}
</span>
</span>
{isActive && (
<span className="absolute top-1/2 right-1 h-6 w-1 -translate-y-1/2 rounded-full bg-primary" />
)}
</Link>
);
})}
{/* 超出一页时引导到完整的智能体管理页(不在侧边栏静默截断) */}
{total > agents.length && (
<Link
href={`${routeBase}/agents`}
className="text-muted-foreground hover:text-foreground hover:bg-accent/50 mt-0.5 rounded-lg px-3 py-1.5 text-center text-xs transition-colors"
>
共 {total} 个,查看全部 →
</Link>
)}
</div>
)}
</div>
</>
)}
</div>
{/* 最近的对话(下半,独立滚动)—— 参考首页通用问答左栏 */}
<RecentChatsPane activeAgentId={activeAgentId} />
</aside>
);
}
/**
* 「最近的对话」面板(参考首页 GeneralQaSidebar 的「最近的对话」区块)。
* 跨智能体的近期会话,点击打开;支持重命名/置顶/收藏/分享/导出/删除。
*/
function RecentChatsPane({ activeAgentId }: { activeAgentId?: string }) {
const { t } = useI18n();
const pathname = usePathname();
const router = useRouter();
const pathOf = usePathOfThread();
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
const { data: threads = [] } = useThreads();
const { mutate: deleteThread } = useDeleteThread();
const { mutate: renameThread } = useRenameThread();
const { toggle: togglePin } = useToggleThreadPin();
const { toggle: toggleFavorite } = useToggleThreadFavorite();
const [query, setQuery] = useState("");
const [renameDialogOpen, setRenameDialogOpen] = useState(false);
const [renameThreadId, setRenameThreadId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [shareThreadId, setShareThreadId] = useState<string | null>(null);
// 排除调度/引导/会商类会话,与首页一致;置顶优先。
const visibleThreads = useMemo(
() =>
sortThreadsPinnedFirst(
threads.filter(
(thread) =>
thread.metadata?.thread_type !== "scheduler" &&
thread.metadata?.thread_type !== "bootstrap" &&
thread.metadata?.thread_type !== "roundtable",
),
),
[threads],
);
const filteredThreads = useMemo(() => {
const q = query.trim().toLowerCase();
const list = q
? visibleThreads.filter((thread) =>
titleOfThread(thread, t.pages.newChat).toLowerCase().includes(q),
)
: visibleThreads;
return q ? list : list.slice(0, MAX_RECENT_CHATS);
}, [visibleThreads, query, t.pages.newChat]);
const handleDelete = useCallback(
(threadId: string) => {
deleteThread({ threadId });
if (threadId === threadIdFromPath) {
const threadIndex = threads.findIndex((th) => th.thread_id === threadId);
let nextThreadPath = pathOf("new", { agent_id: activeAgentId });
if (threadIndex > -1) {
if (threads[threadIndex + 1]) {
nextThreadPath = pathOf(threads[threadIndex + 1]!);
} else if (threads[threadIndex - 1]) {
nextThreadPath = pathOf(threads[threadIndex - 1]!);
}
}
void router.push(nextThreadPath);
}
},
[activeAgentId, deleteThread, pathOf, router, threadIdFromPath, threads],
);
const handleRenameClick = useCallback(
(threadId: string, currentTitle: string) => {
setRenameThreadId(threadId);
setRenameValue(currentTitle);
setRenameDialogOpen(true);
},
[],
);
const handleRenameSubmit = useCallback(() => {
if (renameThreadId && renameValue.trim()) {
renameThread({ threadId: renameThreadId, title: renameValue.trim() });
setRenameDialogOpen(false);
setRenameThreadId(null);
setRenameValue("");
}
}, [renameThread, renameThreadId, renameValue]);
const handleExport = useCallback(
async (thread: AgentThread, format: "markdown" | "json") => {
try {
const apiClient = getAPIClient();
const state = await apiClient.threads.getState<AgentThreadState>(
thread.thread_id,
);
const messages = state.values?.messages ?? [];
if (messages.length === 0) {
toast.error(t.conversation.noMessages);
return;
}
if (format === "markdown") exportThreadAsMarkdown(thread, messages);
else exportThreadAsJSON(thread, messages);
toast.success(t.common.exportSuccess);
} catch {
toast.error("Failed to export conversation");
}
},
[t],
);
const isStatic = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
return (
<div className="flex min-h-0 flex-[2] flex-col overflow-y-auto border-t border-border/60 px-2 py-3">
<h2 className="mb-1 flex items-center gap-1.5 px-3 py-1 text-[11px] font-semibold tracking-[0.04em] text-muted-foreground/80 select-none">
<span>{t.sidebar.recentChats}</span>
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-normal text-muted-foreground tabular-nums">
{visibleThreads.length}
</span>
</h2>
{/* 历史会话搜索框 */}
<div className="relative mb-1.5 px-1">
<Search className="text-muted-foreground/60 pointer-events-none absolute top-1/2 left-3.5 size-3.5 -translate-y-1/2" />
<Input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="搜索历史会话…"
className="h-8 rounded-lg border-border bg-card pl-8 text-[12px]"
/>
</div>
<div className="flex flex-col gap-0.5">
{filteredThreads.length === 0 ? (
<div className="text-muted-foreground/70 px-3 py-4 text-center text-[12px]">
{query ? "没有匹配的会话" : t.chats.noChats}
</div>
) : (
filteredThreads.map((thread) => {
const href = pathOf(thread);
const isActive = href === pathname;
const pinned = isThreadPinned(thread);
const favorited = isThreadFavorite(thread);
return (
<div
key={thread.thread_id}
className="group/item relative flex items-center"
>
<Link
href={href}
className={cn(
"relative flex h-9 min-w-0 flex-1 items-center gap-2 rounded-lg px-2.5 text-[13px] transition-colors",
isActive
? "border border-primary/40 bg-primary/5 font-medium text-primary"
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
)}
>
<MessageSquare
className={cn(
"size-3.5 shrink-0",
isActive ? "text-primary" : "text-muted-foreground/70",
)}
/>
{pinned && (
<Pin className="text-muted-foreground/70 size-3 shrink-0" />
)}
<span className="truncate">
{desensitize(titleOfThread(thread, t.pages.newChat))}
</span>
{isActive && (
<span className="absolute top-1/2 right-1 h-5 w-1 -translate-y-1/2 rounded-full bg-primary" />
)}
</Link>
{!isStatic && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:bg-background group-hover/item:opacity-100 data-[state=open]:opacity-100 absolute right-1 flex size-6 items-center justify-center rounded-md opacity-0 transition-opacity"
>
<MoreHorizontal className="size-4" />
<span className="sr-only">{t.common.more}</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-48 rounded-lg"
side="right"
align="start"
>
<DropdownMenuItem
onSelect={() =>
handleRenameClick(
thread.thread_id,
titleOfThread(thread, t.pages.newChat),
)
}
>
<Pencil className="text-muted-foreground" />
<span>{t.common.rename}</span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => togglePin(thread.thread_id, !pinned)}
>
{pinned ? (
<PinOff className="text-muted-foreground" />
) : (
<Pin className="text-muted-foreground" />
)}
<span>{pinned ? t.common.unpin : t.common.pin}</span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() =>
toggleFavorite(thread.thread_id, !favorited)
}
>
<Star
className={
favorited
? "fill-amber-400 text-amber-400"
: "text-muted-foreground"
}
/>
<span>
{favorited ? t.common.unfavorite : t.common.favorite}
</span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => setShareThreadId(thread.thread_id)}
>
<Share2 className="text-muted-foreground" />
<span>{t.common.share}</span>
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Download className="text-muted-foreground" />
<span>{t.common.export}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem
onSelect={() => handleExport(thread, "markdown")}
>
<FileText className="text-muted-foreground" />
<span>{t.common.exportAsMarkdown}</span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => handleExport(thread, "json")}
>
<FileJson className="text-muted-foreground" />
<span>{t.common.exportAsJSON}</span>
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={() => handleDelete(thread.thread_id)}
>
<Trash2 className="text-muted-foreground" />
<span>{t.common.delete}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
);
})
)}
</div>
{/* 重命名弹窗 */}
<Dialog open={renameDialogOpen} onOpenChange={setRenameDialogOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>{t.common.rename}</DialogTitle>
</DialogHeader>
<div className="py-4">
<Input
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
placeholder={t.common.rename}
onKeyDown={(e) => {
if (e.key === "Enter" && !isIMEComposing(e)) {
e.preventDefault();
handleRenameSubmit();
}
}}
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setRenameDialogOpen(false)}>
{t.common.cancel}
</Button>
<Button onClick={handleRenameSubmit}>{t.common.save}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 分享弹窗 */}
<ShareConversationDialog
threadId={shareThreadId}
open={shareThreadId !== null}
onOpenChange={(o) => {
if (!o) setShareThreadId(null);
}}
/>
</div>
);
}
@@ -76,6 +76,8 @@ interface AgentDraft {
published: boolean;
featured: boolean;
templateName: string;
/** 会商席位「技能识别强化」开关。 */
seatSkillDirective: boolean;
}
function draftFromAgent(agent: Agent): AgentDraft {
@@ -88,6 +90,7 @@ function draftFromAgent(agent: Agent): AgentDraft {
published: agent.published,
featured: agent.featured_order != null,
templateName: agent.template_name ?? "",
seatSkillDirective: agent.seat_skill_directive ?? false,
};
}
@@ -131,14 +134,17 @@ export function AgentDetailPanel({
agentName,
onAskQuestion,
disabled,
defaultCollapsed,
}: {
agent: Agent | null | undefined;
agentName: string;
onAskQuestion: (text: string) => void;
disabled?: boolean;
/** 初始收起(任务工作区进入时默认收起智能体信息面板)。 */
defaultCollapsed?: boolean;
}) {
const router = useRouter();
const [collapsed, setCollapsed] = useState(false);
const [collapsed, setCollapsed] = useState(defaultCollapsed ?? false);
const [mobileOpen, setMobileOpen] = useState(false);
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState<AgentDraft | null>(null);
@@ -292,6 +298,8 @@ export function AgentDetailPanel({
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
if (draft.templateName.trim() !== (agent.template_name ?? ""))
request.template_name = draft.templateName.trim();
if (draft.seatSkillDirective !== (agent.seat_skill_directive ?? false))
request.seat_skill_directive = draft.seatSkillDirective;
if (nextPublished !== agent.published) request.published = nextPublished;
if (JSON.stringify(draft.skills) !== JSON.stringify(agent.skills ?? []))
request.skills = draft.skills;
@@ -558,6 +566,21 @@ export function AgentDetailPanel({
配置后,对话生成的 Markdown 文件可一键发布到知识入库接口。
</p>
</div>
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
<div className="pr-3">
<p className="text-sm font-medium">会商技能识别强化</p>
<p className="text-muted-foreground text-xs">
作为会商席位时,把已配置技能(含 SKILL.md 路径与「先 read_file
再用」硬指令)拼进任务,补偿弱模型不识别技能。也可在业务链条配置中打开(任一即生效)。
</p>
</div>
<Switch
checked={draft.seatSkillDirective}
onCheckedChange={(checked) =>
setDraft({ ...draft, seatSkillDirective: checked })
}
/>
</div>
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
<div>
<p className="text-sm font-medium">公开发布</p>
@@ -364,7 +364,7 @@ export function AgentGallery() {
};
return (
<div className="flex size-full flex-col">
<div className="flex size-full min-h-0 flex-col">
{/* Page header */}
<div className="flex items-center justify-between border-b px-6 py-4">
<div>
@@ -392,7 +392,7 @@ export function AgentGallery() {
setSort("time_desc");
setPublisher(null);
}}
className="flex flex-1 flex-col overflow-hidden"
className="flex min-h-0 flex-1 flex-col overflow-hidden"
>
<div className="mx-6 mt-4 flex flex-col gap-3">
<div className="flex items-center justify-between gap-3">
@@ -5,6 +5,8 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { useMemo, useState } from "react";
import { agentColor } from "@/components/workspace/agent-icon-color";
import { useTheme } from "@/contexts/ThemeContext";
import { useAgents } from "@/core/agents";
import type { Agent } from "@/core/agents";
import { useAgentModuleConfig } from "@/core/system-settings/hooks";
@@ -125,6 +127,9 @@ export function AgentModuleSidebar({
}) {
const routeBase = useRouteBase();
const pathname = usePathname();
// 智能体图标配色分主题:深蓝主题用规范蓝-青系,其它(浅色)保持原高彩度色,互不影响。
const { theme } = useTheme();
const isDark = theme === "dark";
const { agents } = useAgents();
const { data: threads = [] } = useThreads();
const { data: moduleConfig } = useAgentModuleConfig(moduleKey);
@@ -165,7 +170,10 @@ export function AgentModuleSidebar({
});
return (
<aside className="flex h-full w-(--sidebar-width) shrink-0 flex-col overflow-hidden border-r border-border/70 bg-card/60 backdrop-blur-sm">
// 原有布局不变,仅做配色适配:深色下左栏改为半透明深蓝玻璃面板(对齐 .sidebar-contents:
// bg rgba(3,38,80,.8) + 蓝色发光边框),叠 backdrop-blur 让外壳的深蓝底图朦胧透出;
// 浅色保持白底。其余颜色已走语义 token 自适配。
<aside className="flex h-full w-(--sidebar-width) shrink-0 flex-col overflow-hidden border-r border-border/70 bg-white text-foreground backdrop-blur-md dark:border-[#2b8ffe]/45 dark:bg-[#032650]/80">
{onOpenSettings && (
<div className="flex shrink-0 items-center justify-between border-b border-border/60 px-3 py-2">
<span className="text-xs font-semibold text-foreground/80">智能体</span>
@@ -174,22 +182,22 @@ export function AgentModuleSidebar({
onClick={onOpenSettings}
title="模块设置"
aria-label="模块设置"
className="text-muted-foreground hover:text-foreground rounded-md p-1 transition-colors hover:bg-sidebar-accent/60"
className="text-muted-foreground hover:text-foreground rounded-md p-1 transition-colors hover:bg-accent/60"
>
<Settings className="size-4" />
</button>
</div>
)}
{/* 上半:按类型分组的智能体 */}
{/* 上半:按类型分组的智能体(彩色卡片,与全量版看齐) */}
<div className="flex min-h-0 flex-[3] flex-col overflow-y-auto px-2 py-3">
<h2 className="text-muted-foreground/70 px-2 mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
<h2 className="mb-1 px-3 py-1 text-[11px] font-semibold tracking-[0.04em] text-muted-foreground/80 select-none">
智能体类型
</h2>
{groups.length === 0 ? (
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">暂无智能体</p>
<p className="px-3 py-1.5 text-xs text-muted-foreground/70">暂无智能体</p>
) : (
<div className="flex flex-col gap-0.5">
<div className="flex flex-col gap-1.5">
{groups.map((group) => {
const isCollapsed = collapsed.has(group.key);
return (
@@ -197,11 +205,11 @@ export function AgentModuleSidebar({
<button
type="button"
onClick={() => toggleGroup(group.key)}
className="flex w-full items-center justify-between gap-1 rounded-lg px-2 py-1.5 text-xs font-semibold text-foreground/80 hover:bg-sidebar-accent/60"
className="flex w-full items-center justify-between px-3 py-1 text-[11px] font-semibold tracking-[0.04em] text-muted-foreground/80 transition-colors hover:text-muted-foreground select-none"
>
<span className="flex items-center gap-1.5 truncate">
<span className="truncate">{group.label}</span>
<span className="text-muted-foreground/60 text-[10px] font-normal tabular-nums">
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-normal text-muted-foreground tabular-nums">
{group.agents.length}
</span>
</span>
@@ -213,22 +221,48 @@ export function AgentModuleSidebar({
/>
</button>
{!isCollapsed && (
<div className="mt-0.5 flex flex-col gap-0.5 pl-1">
<div className="mt-1 flex flex-col gap-1">
{group.agents.map((agent) => {
const href = `${routeBase}/agents/${agent.id}/chats/new`;
const isActive = agent.id === activeAgentId;
const { from, to } = agentColor(agent.id, isDark);
return (
<Link
key={`${group.key}:${agent.id}`}
href={href}
className={cn(
"flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground hover:text-foreground hover:bg-sidebar-accent/60",
isActive &&
"bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary",
"group relative flex w-full items-start gap-2.5 rounded-xl border px-2.5 py-2 transition-colors",
isActive
? "border-primary/40 bg-primary/5"
: "border-transparent hover:border-border hover:bg-accent/50",
)}
>
<Bot className="size-3.5 shrink-0 text-muted-foreground/70" />
<span className="truncate">{desensitize(agent.name)}</span>
<span
className="mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg text-white shadow-sm"
style={{
backgroundImage: `linear-gradient(135deg, ${from}, ${to})`,
}}
>
<Bot className="size-[18px]" />
</span>
<span className="min-w-0 flex-1">
<span
className={cn(
"block truncate text-[13px] font-semibold",
isActive ? "text-primary" : "text-foreground",
)}
>
{desensitize(agent.name)}
</span>
<span className="mt-0.5 block truncate text-[11px] leading-snug text-muted-foreground">
{agent.description
? desensitize(agent.description)
: "智能体助手"}
</span>
</span>
{isActive && (
<span className="absolute top-1/2 right-1 h-6 w-1 -translate-y-1/2 rounded-full bg-primary" />
)}
</Link>
);
})}
@@ -241,13 +275,13 @@ export function AgentModuleSidebar({
)}
</div>
{/* 下半:聊天记录(仅本模块智能体会话) */}
{/* 下半:聊天记录(仅本模块智能体会话),简单列表、配色与全量版统一 */}
<div className="flex min-h-0 flex-[2] flex-col overflow-y-auto border-t border-border/60 px-2 py-3">
<h2 className="text-muted-foreground/70 px-2 mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
<h2 className="mb-1 px-3 py-1 text-[11px] font-semibold tracking-[0.04em] text-muted-foreground/80 select-none">
聊天记录
</h2>
{moduleThreads.length === 0 ? (
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">暂无聊天记录</p>
<p className="px-3 py-1.5 text-xs text-muted-foreground/70">暂无聊天记录</p>
) : (
<div className="flex flex-col gap-0.5">
{moduleThreads.map((thread) => {
@@ -258,15 +292,24 @@ export function AgentModuleSidebar({
key={thread.thread_id}
href={href}
className={cn(
"flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground hover:text-foreground hover:bg-sidebar-accent/60",
isActive &&
"bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary",
"relative flex h-9 min-w-0 items-center gap-2 rounded-lg px-2.5 text-[13px] transition-colors",
isActive
? "border border-primary/40 bg-primary/5 font-medium text-primary"
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
)}
>
<MessageSquare className="size-3.5 shrink-0 text-muted-foreground/70" />
<MessageSquare
className={cn(
"size-3.5 shrink-0",
isActive ? "text-primary" : "text-muted-foreground/70",
)}
/>
<span className="truncate">
{desensitize(titleOfThread(thread, "未命名对话"))}
</span>
{isActive && (
<span className="absolute top-1/2 right-1 h-5 w-1 -translate-y-1/2 rounded-full bg-primary" />
)}
</Link>
);
})}
@@ -86,6 +86,7 @@ import { desensitize } from "@/lib/desensitize";
import { isIMEComposing } from "@/lib/ime";
import { cn } from "@/lib/utils";
import { agentColor } from "./agent-icon-color";
import { SidebarCollapseButton } from "./workspace-header";
const NEW_CHAT_PATH = "/page/workspace/chats/new";
@@ -96,33 +97,8 @@ const MORE_CHATS_HREF = "/page/workspace/chats";
/** 常用智能体最多展示个数。 */
const MAX_FREQUENT = 4;
// 智能体图标统一用 Bot 机器人图标;底色按 id 稳定散列到一组主题色,复刻参考图的彩色方块。
// 浅色模式沿用原高彩度彩色(不改);深蓝主题改用《深蓝 UI 规范》§1.1.7/§1.1.8 的蓝-青系
// (docs/ui规范-深蓝,克制、不刺眼),仅深蓝主题下生效,互不影响。
const AGENT_COLORS_LIGHT = [
{ from: "#fb7185", to: "#ef4444" },
{ from: "#60a5fa", to: "#3b82f6" },
{ from: "#fbbf24", to: "#f59e0b" },
{ from: "#34d399", to: "#10b981" },
{ from: "#a78bfa", to: "#8b5cf6" },
] as const;
const AGENT_COLORS_DARK = [
{ from: "#4096FF", to: "#1677FF" }, // 蓝(链接蓝 → 主色)
{ from: "#36CFC9", to: "#13C2C2" }, // 青(辅色)
{ from: "#6388FF", to: "#0958D9" }, // 紫蓝(装饰紫 → 主色深一档)
{ from: "#5CDBD3", to: "#08979C" }, // 浅青 → 深青
{ from: "#69B1FF", to: "#003EB3" }, // 浅蓝 → 主色按下
] as const;
function agentColor(id: string, isDark: boolean) {
let hash = 0;
for (let i = 0; i < id.length; i++) {
hash = (hash * 31 + id.charCodeAt(i)) >>> 0;
}
const palette = isDark ? AGENT_COLORS_DARK : AGENT_COLORS_LIGHT;
return palette[hash % palette.length]!;
}
// 智能体图标配色(按 id 稳定散列、分主题)抽到共享模块 ./agent-icon-color,
// 与 zzJC/zzXD 模块左栏(AgentModuleSidebar)共用,保证彩色卡片配色完全一致。
/** 折叠区块标题(带 chevron 与可选计数徽标)。 */
function SectionLabel({
@@ -324,8 +300,10 @@ export function GeneralQaSidebar() {
const isStatic = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
return (
// 背景走 sidebar token(浅主题=白、深蓝主题=深蓝),不要写死 bg-white,否则全量版深蓝主题下侧栏仍是白底。
<div className="flex h-full min-h-0 flex-col bg-sidebar text-sidebar-foreground">
// 背景走 sidebar token(浅主题=白、浅蓝主题=浅蓝);深蓝(.dark)主题下由 gq-sidebar
// 改为「深蓝主题底图 + 半透明蓝罩」玻璃面板(见 globals.css),与右侧 workspace-chat-bg
// 主区同底图、略深一档作面板区分,不要写死 bg-white。
<div className="gq-sidebar flex h-full min-h-0 flex-col bg-sidebar text-sidebar-foreground">
{/* ── 顶部:新对话胶囊 + 收起按钮 ── */}
<div className="flex items-center gap-2 px-3 pt-3 pb-2">
{/* 新对话按钮:完全自定义样式(不复用 Button variant)。borderColor / color 走
@@ -61,8 +61,9 @@ import {
} from "@/components/ui/dropdown-menu";
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import { useI18n } from "@/core/i18n/hooks";
import { useModels } from "@/core/models/hooks";
import { useI18n } from "@/core/i18n/hooks";
import { isHiddenFromUIMessage } from "@/core/messages/utils";
import { useModels } from "@/core/models/hooks";
import type { AgentThreadContext } from "@/core/threads";
import { textOfMessage } from "@/core/threads/utils";
import { desensitize } from "@/lib/desensitize";
@@ -467,14 +468,15 @@ export function InputBox({
return;
}
const lastAi = [...thread.messages].reverse().find((m) => m.type === "ai");
const visibleMessages = thread.messages.filter((m) => !isHiddenFromUIMessage(m));
const lastAi = [...visibleMessages].reverse().find((m) => m.type === "ai");
const lastAiId = lastAi?.id ?? null;
if (!lastAiId || lastAiId === lastGeneratedForAiIdRef.current) {
return;
}
lastGeneratedForAiIdRef.current = lastAiId;
const recent = thread.messages
const recent = visibleMessages
.filter((m) => m.type === "human" || m.type === "ai")
.map((m) => {
const role = m.type === "human" ? "user" : "assistant";
@@ -20,9 +20,10 @@ import {
groupMessages,
hasContent,
hasPresentFiles,
hasReasoning,
hasToolCalls,
} from "@/core/messages/utils";
hasReasoning,
hasToolCalls,
isHiddenFromUIMessage,
} from "@/core/messages/utils";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
import { useSkills } from "@/core/skills/hooks";
@@ -151,7 +152,10 @@ export function MessageList({
});
}, []);
const allMessages = thread.messages;
const allMessages = useMemo(
() => thread.messages.filter((m) => !isHiddenFromUIMessage(m)),
[thread.messages],
);
const messages = useMemo(
() =>
hiddenMessageIds.size === 0
@@ -6,7 +6,7 @@ import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { clearStoredAuth, getStoredAuth } from "@/core/auth";
import { clearStoredAuth, getAccountDisplayName, getStoredAuth } from "@/core/auth";
import { SettingsSection } from "./settings-section";
@@ -37,8 +37,7 @@ export function AccountSettingsPage() {
);
}
const usernameFromEmail = (auth.email ?? "").split("@")[0] ?? "";
const displayName = usernameFromEmail || auth.user_id;
const displayName = getAccountDisplayName(auth);
const handleLogout = () => {
clearStoredAuth();
@@ -1,7 +1,7 @@
"use client";
import { DropletIcon, LayoutGridIcon, LayoutIcon, ListIcon, MoonIcon, PanelLeftIcon, SunIcon } from "lucide-react";
import { useMemo, type ComponentType, type SVGProps } from "react";
import { useMemo, useState, type ComponentType, type SVGProps } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
@@ -20,6 +20,8 @@ import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { getStoredAuth } from "@/core/auth";
import { migrateAuthToSession } from "@/core/auth/scoped-storage";
import { isIsolatedSession, setIsolatedSession } from "@/core/embed/embed-session";
import { enUS, isLocale, zhCN, type Locale } from "@/core/i18n";
import { useI18n } from "@/core/i18n/hooks";
import { useLocalSettings } from "@/core/settings";
@@ -64,6 +66,29 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
const cleanupWords =
citationDisplay?.cleanup_words ?? settings.display.citationCleanupWords ?? [];
// 独立登录会话(本标签页):开关切换鉴权存储 localStorage ↔ sessionStorage(见 scoped-storage)。
const [isolatedSession, setIsolatedSessionState] = useState(() => isIsolatedSession());
const handleToggleIsolatedSession = (checked: boolean) => {
if (checked) {
// 先把当前账号从 localStorage 快照搬进 sessionStorage,再翻标志,避免切换存储后被登出。
migrateAuthToSession();
setIsolatedSession(true);
setIsolatedSessionState(true);
toast.success("已开启独立登录会话", {
description:
"本标签页的登录已与其它标签页隔离:在别的窗口登录或切换其它账号都不会影响这里,你也可以在此单独登录另一个账号。该独立会话只存在于当前标签页,关闭此标签后即结束(需重新登录)。",
duration: 9000,
});
} else {
setIsolatedSession(false);
setIsolatedSessionState(false);
toast.info("已关闭独立登录会话", {
description: "本标签页恢复与其它标签页共享同一登录。如页面显示未及时同步,请刷新本页。",
duration: 6000,
});
}
};
const handleSetGlobalDefault = async (
value: "light" | "dark" | "lightblue",
) => {
@@ -395,6 +420,28 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
<Separator />
<SettingsSection
title="登录会话"
description="控制本标签页的登录身份是否与浏览器其它标签页隔离。"
>
<div className="flex items-start justify-between gap-4 rounded-lg border p-4">
<div>
<div className="text-sm font-medium">独立登录会话(本标签页)</div>
<p className="text-muted-foreground mt-1 max-w-md text-xs leading-relaxed">
开启后,本标签页的登录状态仅保存在当前标签页:在别的窗口登录或切换其它账号都不会影响这里,
你也可以在此单独登录另一个账号。关闭浏览器标签后该独立会话即结束(需重新登录)。
</p>
</div>
<Switch
checked={isolatedSession}
onCheckedChange={handleToggleIsolatedSession}
aria-label="独立登录会话"
/>
</div>
</SettingsSection>
<Separator />
<SettingsSection
title="对话体验"
description="问答过程中的辅助显示。"
@@ -0,0 +1,54 @@
"use client";
import { User } from "lucide-react";
import { useMemo } from "react";
import { getStoredAuth } from "@/core/auth";
import { useMyPosition } from "@/core/positions";
import { cn } from "@/lib/utils";
import { readUserInfo } from "@/strategy-components/lib/light-app";
/**
* 名称 + 岗位 用户标识。全量模式由 strategy-components/Header.tsx 顶栏右侧展示;
* 紧凑模式(不带全局顶栏)无处承载,故抽成共享组件,复用同一套数据来源
* (`readUserInfo().userName` 优先、回退 auth 邮箱前缀;岗位取 `useMyPosition`),
* 供页面级顶栏(如 ChatPage)右侧复用,保证两套布局一致。
*
* 配色按当前内容区前景色(foreground / muted-foreground),适配聊天页浅底顶栏,
* 而非 Header 的白字贴 banner 方案。
*/
export function UserIdentityBadge({ className }: { className?: string }) {
const auth = getStoredAuth();
const { data: myPosition } = useMyPosition();
const positionName = myPosition?.name?.trim() || "";
// 与 Header.tsx 一致:外部登录写入的真实用户名优先,缺省回退邮箱前缀。
const displayName = useMemo(() => {
const info = readUserInfo();
const name = typeof info.userName === "string" ? info.userName.trim() : "";
if (name) return name;
const email = auth?.email?.trim();
return email ? email.split("@")[0] : "用户";
}, [auth?.email]);
return (
<div
className={cn("flex shrink-0 items-center gap-2", className)}
title={positionName ? `${displayName}·${positionName}` : displayName}
>
<div className="bg-muted text-muted-foreground flex size-7 shrink-0 items-center justify-center rounded-full">
<User className="size-3.5" />
</div>
<div className="hidden min-w-0 text-left sm:block">
<p className="text-foreground truncate text-sm font-medium leading-tight">
{displayName}
</p>
{positionName && (
<p className="text-muted-foreground truncate text-[11px] leading-tight">
{positionName}
</p>
)}
</div>
</div>
);
}
+8
View File
@@ -58,6 +58,10 @@ export interface Agent {
/** 入库模板名(外部知识入库接口的 templateName)。配置后该智能体会话中的
* Markdown 产物右上角出现"发布入库"按钮。空/缺省 = 不支持入库。 */
template_name?: string | null;
/** 会商席位「技能识别强化」开关。作为会商席位运行时,是否把本智能体配置的技能
* (名称 + SKILL.md 路径 + 必须先 read_file 的硬指令) 拼进本轮任务以补偿弱模型。
* 与业务链条同名开关取 OR。null/false = 关 (默认)。 */
seat_skill_directive?: boolean | null;
tags?: Tag[];
featured_order?: number | null;
/** Whether the current user has favorited (收藏) this agent. */
@@ -91,6 +95,8 @@ export interface CreateAgentRequest {
tool_groups?: string[] | null;
common_questions?: AgentQuestion[] | null;
template_name?: string | null;
/** 会商席位「技能识别强化」开关;缺省/false = 关。 */
seat_skill_directive?: boolean | null;
}
export interface UpdateAgentRequest {
@@ -106,4 +112,6 @@ export interface UpdateAgentRequest {
common_questions?: AgentQuestion[] | null;
/** 入库模板名;传空字符串表示清除。 */
template_name?: string | null;
/** 会商席位「技能识别强化」开关;缺省/false = 关。 */
seat_skill_directive?: boolean | null;
}
@@ -0,0 +1,223 @@
/**
* 大屏绘制智能体「独立页面」的**输入 JSON** 适配 seam。
*
* 设计意图:深链 `?taskId=` 模式下,后端提供「研判情报报告」接口
* GET `{VITE_AIPI_CONSUMER_URL}/cop/selectSqReport?taskId=`
* 返回该任务的多类情报内容;本页把它**提取成干净的结构化 JSON** 交给智能体分析
* → 产出 report-json → 绘制大屏(react / html)。
*
* 接口返回结构:`{ state, msg, data: [{ id, taskId, ..., contentJson, categoryType }] }`,
* 其中 `contentJson` 是**被转义的 JSON 字符串**,`categoryType` 形如「敌情关键事件 JSON」。
* 本模块 `extractSqReport` 把每条的 `contentJson` 反序列化、按 `categoryType` 归类,
* 拼成 `{ taskId, categories: { 敌情关键事件: [...], 决心建议: {...}, ... } }` 喂给智能体。
*
* ⚠️ 真实接口现在还**请求不到**:通过 `VITE_MOCK_SQ_REPORT=true`(见 `utils/request.ts`)
* 走后端给的样例假数据(`sq-report-mock.json`),机制与 cop-task-detail 假数据一致。
* 联调通过后把该 env 置 false 即走真实接口;接口/数据若有变只需改 `extractSqReport`。
*/
import { requestCrudService } from "@/service/request-axios-service";
import { readCopTaskDetail } from "@/core/auth/task-deeplink";
/** 本页输入 JSON 暂存的 sessionStorage key(拉取一次后复用,避免重复请求)。 */
export const DASHBOARD_INPUT_STORAGE_KEY = "dashboard.inputJson";
/**
* 🧪 演示用模拟业务 JSON —— JSON 接口未就绪、也没有登录任务详情时的兜底输入。
* 让大屏页可立即跑通:智能体分析这份数据 → report-json → 渲染大屏。
* ⚠️ 接口就绪后删除本常量及其兜底引用。
*/
export const DEMO_DASHBOARD_INPUT = {
taskId: "DEMO-涉台舆情",
taskName: "2026 第一季度涉台舆情态势研判",
taskContent:
"汇总境内外多平台涉台舆情数据,研判热点叙事走势、关键行为体立场与传播渠道分布,识别风险并给出处置建议。",
overview:
"本季涉台舆情整体平稳但局部波动,'两岸交流''和平发展'类正向叙事占比上升,少数账号借军事议题制造紧张;境外智库与媒体联动放大特定框架。",
period: "2026-01-01 ~ 2026-03-31",
kpis: {
总信息量: 1284000,
日均增速: "12%",
正向占比: "58%",
负向占比: "19%",
识别风险点: 7,
覆盖平台: 12,
},
channels: [
{ platform: "微博", share: 34 },
{ platform: "境外社媒(X/FB)", share: 27 },
{ platform: "短视频", share: 18 },
{ platform: "新闻门户", share: 13 },
{ platform: "论坛/贴吧", share: 8 },
],
narratives: [
{ theme: "两岸交流与融合发展", sentiment: "正向", volume: 42, trend: "up" },
{ theme: "和平稳定·避战", sentiment: "正向", volume: 26, trend: "up" },
{ theme: "军事演训与安全", sentiment: "中性偏负", volume: 21, trend: "flat" },
{ theme: "外部势力介入", sentiment: "负向", volume: 11, trend: "down" },
],
actors: [
{ name: "主流官媒", stance: "正面引导", influence: 88, note: "议程设置与权威发布" },
{ name: "岛内民间团体", stance: "中性多元", influence: 64, note: "交流合作类内容活跃" },
{ name: "境外智库", stance: "负面框架", influence: 57, note: "联动媒体放大紧张叙事" },
{ name: "自媒体大V", stance: "立场分化", influence: 49, note: "情绪化传播、易被借势" },
],
risks: [
{ label: "军事议题被恶意剪辑放大", level: "high" },
{ label: "境外智库联动制造紧张框架", level: "high" },
{ label: "个别大V情绪化带节奏", level: "mid" },
{ label: "短视频谣言二次传播", level: "mid" },
{ label: "节假日期间信息量骤增", level: "low" },
],
timeline: [
{ phase: "数据汇聚", desc: "12 平台多源采集与清洗去重" },
{ phase: "叙事识别", desc: "聚类提炼核心叙事与情感倾向" },
{ phase: "行为体画像", desc: "关键账号立场与影响力建模" },
{ phase: "风险研判", desc: "识别高危议题与传播链路" },
{ phase: "处置建议", desc: "分级响应与正向引导预案" },
],
weeklyVolume: [
{ week: "W1", value: 86 },
{ week: "W2", value: 92 },
{ week: "W3", value: 110 },
{ week: "W4", value: 134 },
{ week: "W5", value: 121 },
{ week: "W6", value: 158 },
],
};
/** 「研判情报报告」接口完整地址:`{VITE_AIPI_CONSUMER_URL}/cop/selectSqReport`。 */
function sqReportUrl(): string {
const value = (import.meta.env as Record<string, unknown>).VITE_AIPI_CONSUMER_URL;
const base = typeof value === "string" ? value.replace(/\/+$/, "") : "";
return base ? `${base}/cop/selectSqReport` : "";
}
/** 把单条 `contentJson` 反序列化为对象/数组/原值(已是对象则原样返回)。 */
function parseContentJson(raw: unknown): unknown {
if (typeof raw !== "string") return raw ?? null;
const text = raw.trim();
if (!text) return null;
try {
return JSON.parse(text);
} catch {
return text; // 解析失败就把原始字符串透传给智能体,让它自行理解
}
}
/** 去掉 categoryType 末尾的「 JSON」后缀,作为归类键(如「敌情关键事件 JSON」→「敌情关键事件」)。 */
function categoryKey(categoryType: unknown, index: number): string {
const raw = typeof categoryType === "string" ? categoryType.trim() : "";
const cleaned = raw.replace(/\s*JSON\s*$/i, "").trim();
return cleaned || `分类${index + 1}`;
}
/**
* 把 selectSqReport 的整包响应**提取**成喂给智能体的干净结构化输入:
* `{ taskId, source, categories: { [类目]: 反序列化后的内容 } }`
* 返回 null 表示无可用内容(调用方据此回退/不开跑)。
*/
export function extractSqReport(body: unknown, taskId: string): unknown | null {
const data = (body && typeof body === "object" ? (body as { data?: unknown }).data : null) as
| Array<Record<string, unknown>>
| undefined;
if (!Array.isArray(data) || data.length === 0) return null;
const categories: Record<string, unknown> = {};
data.forEach((item, index) => {
const content = parseContentJson(item?.contentJson);
if (content == null) return;
let key = categoryKey(item?.categoryType, index);
if (key in categories) key = `${key}(${index + 1})`; // 同名类目去重保留
categories[key] = content;
});
if (Object.keys(categories).length === 0) return null;
return { taskId, source: "cop/selectSqReport", categories };
}
/**
* 输入 JSON 缓存**仅供开发(mock)使用**:`VITE_MOCK_SQ_REPORT==='true'` 时才读/写缓存,
* 避免开发反复请求样例假数据。真实接口模式(false)下不读不写缓存,**始终拉取真实数据**。
*/
function inputCacheEnabled(): boolean {
return (import.meta.env as Record<string, unknown>).VITE_MOCK_SQ_REPORT === "true";
}
/** 读取暂存的输入 JSON(仅 mock 开发模式生效,真实模式恒返回 null 以强制重新拉取)。 */
export function readDashboardInputJson(): unknown | null {
if (!inputCacheEnabled()) return null;
try {
const raw = sessionStorage.getItem(DASHBOARD_INPUT_STORAGE_KEY);
return raw ? JSON.parse(raw) : null;
} catch {
return null;
}
}
/** 暂存输入 JSON(仅 mock 开发模式生效;隐私模式/quota 异常静默失败)。 */
export function persistDashboardInputJson(data: unknown): void {
if (!inputCacheEnabled()) return;
try {
sessionStorage.setItem(DASHBOARD_INPUT_STORAGE_KEY, JSON.stringify(data));
} catch {
/* noop */
}
}
/** 用登录暂存的任务详情拼一份占位输入(接口未就绪时的回退)。 */
function placeholderFromCopTask(taskId: string): unknown | null {
const detail = readCopTaskDetail();
if (!detail) return taskId ? { taskId } : null;
return {
taskId,
taskName: detail.taskName,
taskContent: detail.taskContent,
overview: detail.overview,
taskDirection: detail.taskDirection,
_note: "占位输入(真实业务 JSON 接口未就绪)",
};
}
/**
* 取本页的输入 JSON:**先请求 selectSqReport,待其返回后再交给模型抽取**。
*
* - 真实接口模式(`VITE_MOCK_SQ_REPORT=false`):不读缓存、不兜底假数据——
* **只用接口真实返回的内容**;请求失败或返回空一律返回 `null`(页面据此提示「请求失败/无数据」,
* 绝不拿占位/演示数据去喂模型,避免「没等接口就抽取假数据」)。
* - mock 开发模式(true):走本地样例假数据(见 utils/request.ts)并缓存避免反复请求;
* 仅此模式在接口不可用时回退 copTaskDetail 占位 / DEMO 演示数据,保证开发能跑通。
*/
export async function fetchDashboardInputJson(
taskId: string,
opts?: { forceRefresh?: boolean },
): Promise<unknown | null> {
const mock = inputCacheEnabled(); // true=mock/开发;false=真实接口
// forceRefresh(重新分析/修改时):跳过缓存,强制重新请求接口拿**最新数据**(数据可能已变化)。
const cached = opts?.forceRefresh ? null : readDashboardInputJson(); // 真实模式恒 null(缓存仅开发用)
if (cached) return cached;
const url = sqReportUrl();
if (url && taskId) {
try {
// service 拦截器统一注入鉴权并返回 response.data(整包 body)。
// await 在此:必须**等接口返回**后才有 body 可 extract → 再由上层启动模型抽取。
const body = await requestCrudService.get(url, { taskId });
const extracted = extractSqReport(body, taskId);
if (extracted) {
persistDashboardInputJson(extracted); // 真实模式 no-op
return extracted;
}
} catch {
/* 请求失败:真实模式返回 null(见下),mock 模式落占位/DEMO */
}
}
// 真实接口模式:**不兜底假数据**。失败/空 → null,让页面提示而不是拿假数据喂模型。
if (!mock) return null;
// 以下兜底**仅 mock/开发模式**:copTaskDetail 占位 / DEMO 演示数据,保证开发能看效果。
const placeholder = placeholderFromCopTask(taskId);
const detail = readCopTaskDetail();
const resolved = detail ? placeholder : { ...DEMO_DASHBOARD_INPUT, taskId: taskId || DEMO_DASHBOARD_INPUT.taskId };
if (resolved) persistDashboardInputJson(resolved);
return resolved;
}
+16 -21
View File
@@ -9,6 +9,8 @@
* theme 不存(直接走 ThemeContext,避免双源)。
*/
import { authStorageGet, authStorageSet } from "@/core/auth/scoped-storage";
export const EXTERNAL_LOGIN_STORAGE_KEYS = {
ticket: "login.ticket",
userId: "login.userId",
@@ -27,32 +29,25 @@ export type ExternalLoginParams = {
/** 把外部跳转带来的三个参数写到 localStorage;隐私模式 / quota 异常时静默失败 */
export function persistExternalLoginParams(params: ExternalLoginParams): void {
try {
if (params.ticket) {
localStorage.setItem(EXTERNAL_LOGIN_STORAGE_KEYS.ticket, params.ticket);
}
if (params.userId) {
localStorage.setItem(EXTERNAL_LOGIN_STORAGE_KEYS.userId, params.userId);
}
if (params.env) {
localStorage.setItem(EXTERNAL_LOGIN_STORAGE_KEYS.env, params.env);
}
} catch {
// localStorage 不可用时不阻断登录流程
// 嵌入(iframe)态走 sessionStorage(按标签页隔离),正常态走 localStorage —— 见 scoped-storage.ts。
if (params.ticket) {
authStorageSet(EXTERNAL_LOGIN_STORAGE_KEYS.ticket, params.ticket);
}
if (params.userId) {
authStorageSet(EXTERNAL_LOGIN_STORAGE_KEYS.userId, params.userId);
}
if (params.env) {
authStorageSet(EXTERNAL_LOGIN_STORAGE_KEYS.env, params.env);
}
}
/** 读取持久化的外部登录参数;不可用时返回空字符串 */
export function readExternalLoginParams(): Required<ExternalLoginParams> {
try {
return {
ticket: localStorage.getItem(EXTERNAL_LOGIN_STORAGE_KEYS.ticket) ?? "",
userId: localStorage.getItem(EXTERNAL_LOGIN_STORAGE_KEYS.userId) ?? "",
env: localStorage.getItem(EXTERNAL_LOGIN_STORAGE_KEYS.env) ?? "",
};
} catch {
return { ticket: "", userId: "", env: "" };
}
return {
ticket: authStorageGet(EXTERNAL_LOGIN_STORAGE_KEYS.ticket) ?? "",
userId: authStorageGet(EXTERNAL_LOGIN_STORAGE_KEYS.userId) ?? "",
env: authStorageGet(EXTERNAL_LOGIN_STORAGE_KEYS.env) ?? "",
};
}
/**
+110 -94
View File
@@ -1,94 +1,110 @@
export interface LoginByUsernameResponse {
access_token: string;
token_type: string;
expires_in: number;
user_id: string;
email: string;
system_role: string;
needs_setup: boolean;
created: boolean;
}
const AUTH_STORAGE_KEY = "deerflow.auth";
function isBrowser(): boolean {
return typeof window !== "undefined";
}
export function getStoredAuth(): LoginByUsernameResponse | null {
if (!isBrowser()) {
return null;
}
const raw = window.localStorage.getItem(AUTH_STORAGE_KEY);
if (!raw) {
return null;
}
try {
return JSON.parse(raw) as LoginByUsernameResponse;
} catch {
return null;
}
}
export function setStoredAuth(auth: LoginByUsernameResponse) {
if (!isBrowser()) {
return;
}
window.localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(auth));
}
export function clearStoredAuth() {
if (!isBrowser()) {
return;
}
window.localStorage.removeItem(AUTH_STORAGE_KEY);
}
/**
* 把登录用户名写入 localStorage.userInfo.userName(顶栏用户区据此显示)。
* 仅在尚未设置时写入,避免覆盖外部登录(yUserId)从 consumer 拿到的用户名。
*/
export function setStoredUserName(name: string | null | undefined) {
if (!isBrowser()) {
return;
}
const trimmed = name?.trim();
if (!trimmed) {
return;
}
let info: Record<string, unknown> = {};
try {
const raw = window.localStorage.getItem("userInfo");
if (raw) {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") {
info = parsed as Record<string, unknown>;
}
}
} catch {
info = {};
}
if (typeof info.userName === "string" && info.userName.trim()) {
return;
}
info.userName = trimmed;
window.localStorage.setItem("userInfo", JSON.stringify(info));
}
export function getAccessToken(): string | undefined {
const auth = getStoredAuth();
const token = auth?.access_token?.trim();
return token ? token : undefined;
}
export function getAuthorizationHeaderValue(): string | undefined {
const auth = getStoredAuth();
const token = auth?.access_token?.trim();
if (!token) {
return undefined;
}
const rawType = auth?.token_type?.trim();
const tokenType = rawType ? rawType : "Bearer";
return `${tokenType} ${token}`;
}
export interface LoginByUsernameResponse {
access_token: string;
token_type: string;
expires_in: number;
user_id: string;
email: string;
system_role: string;
needs_setup: boolean;
created: boolean;
}
import {
authStorageGet,
authStorageRemove,
authStorageSet,
} from "@/core/auth/scoped-storage";
const AUTH_STORAGE_KEY = "deerflow.auth";
function isBrowser(): boolean {
return typeof window !== "undefined";
}
export function getStoredAuth(): LoginByUsernameResponse | null {
if (!isBrowser()) {
return null;
}
// 嵌入(iframe)态走 sessionStorage、正常态走 localStorage —— 隔离 iframe 登录用户与正常登录用户。
const raw = authStorageGet(AUTH_STORAGE_KEY);
if (!raw) {
return null;
}
try {
return JSON.parse(raw) as LoginByUsernameResponse;
} catch {
return null;
}
}
export function setStoredAuth(auth: LoginByUsernameResponse) {
if (!isBrowser()) {
return;
}
authStorageSet(AUTH_STORAGE_KEY, JSON.stringify(auth));
}
export function clearStoredAuth() {
if (!isBrowser()) {
return;
}
authStorageRemove(AUTH_STORAGE_KEY);
}
/** 与设置 → 个人信息页「用户名」一致:邮箱 @ 前缀,否则 user_id。 */
export function getAccountDisplayName(
auth: LoginByUsernameResponse | null = getStoredAuth(),
): string {
if (!auth) return "用户";
const usernameFromEmail = (auth.email ?? "").split("@")[0] ?? "";
return usernameFromEmail || auth.user_id || "用户";
}
/**
* 把登录用户名写入 localStorage.userInfo.userName(轻应用登录参数等场景使用)。
* 仅在尚未设置时写入,避免覆盖外部登录(yUserId)从 consumer 拿到的用户名。
*/
export function setStoredUserName(name: string | null | undefined) {
if (!isBrowser()) {
return;
}
const trimmed = name?.trim();
if (!trimmed) {
return;
}
let info: Record<string, unknown> = {};
try {
const raw = authStorageGet("userInfo");
if (raw) {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") {
info = parsed as Record<string, unknown>;
}
}
} catch {
info = {};
}
if (typeof info.userName === "string" && info.userName.trim()) {
return;
}
info.userName = trimmed;
authStorageSet("userInfo", JSON.stringify(info));
}
export function getAccessToken(): string | undefined {
const auth = getStoredAuth();
const token = auth?.access_token?.trim();
return token ? token : undefined;
}
export function getAuthorizationHeaderValue(): string | undefined {
const auth = getStoredAuth();
const token = auth?.access_token?.trim();
if (!token) {
return undefined;
}
const rawType = auth?.token_type?.trim();
const tokenType = rawType ? rawType : "Bearer";
return `${tokenType} ${token}`;
}
@@ -0,0 +1,94 @@
/**
* 鉴权 / 身份存储的「按登录态隔离」选择器。
*
* 诉求:外部系统用 iframe 套用咱们的深链问答时,**iframe 里登录的用户**要和**同浏览器正常登录
* 的用户**完全隔离——不然 iframe 里随便登一个用户,会覆盖正常标签页的登录态(甚至触发跨标签
* 账号变更提示)。
*
* 根因:同源下 `localStorage` 跨所有标签页共享,鉴权 token(`deerflow.auth`)/ 身份(`userInfo`)/
* 外部登录参数(`login.*` / `tools_token`)都存在那里,iframe 一写就污染正常页。
*
* 方案:嵌入态(`isEmbedActive()`,见 [[embed-session]])下,这些键改走 **sessionStorage**——它按
* **标签页/浏览上下文**隔离,iframe(即便同源)有自己独立的一份,写它绝不动正常标签页的
* localStorage,也不会触发正常页的 `storage` 事件(见 sync.tsx 的跨标签账号监听)。正常态仍走
* localStorage,行为零变化。
*
* 把所有受保护键的读写都收口到 `authStorage()`,保证同一标签页内读写落到同一处(嵌入态恒为
* sessionStorage、正常态恒为 localStorage;嵌入标志一进程内不翻转,故一致)。
*/
import { isEmbedActive, isIsolatedSession } from "@/core/embed/embed-session";
/**
* 返回当前应使用的鉴权存储:嵌入态(iframe)**或**独立会话态(`?isolate=1`)→ sessionStorage
* (按标签页隔离);否则 → localStorage(跨标签共享、持久)。非浏览器环境返回 null(调用方各自
* 有 SSR 守卫)。两种隔离态等价于「本标签页鉴权独立、绝不污染其它标签页登录态」,区别仅在于嵌入态
* 还会去 chrome / 强制主题,独立会话态只切换存储。
*/
export function authStorage(): Storage | null {
if (typeof window === "undefined") return null;
return isEmbedActive() || isIsolatedSession() ? window.sessionStorage : window.localStorage;
}
/** 读受保护键(嵌入态 sessionStorage / 正常态 localStorage)。 */
export function authStorageGet(key: string): string | null {
try {
return authStorage()?.getItem(key) ?? null;
} catch {
return null;
}
}
/** 写受保护键。隐私模式 / quota 异常静默失败。 */
export function authStorageSet(key: string, value: string): void {
try {
authStorage()?.setItem(key, value);
} catch {
/* noop */
}
}
/** 删受保护键。 */
export function authStorageRemove(key: string): void {
try {
authStorage()?.removeItem(key);
} catch {
/* noop */
}
}
/**
* 受 `authStorage()` 收口管理的鉴权 / 身份键:四个精确键 + `login.` 前缀(外部登录参数族
* ticket/userId/env/maxkeyOnlineToken/userDetailToken)。用于「开启独立会话」时把当前登录态从
* localStorage 快照搬进 sessionStorage,避免切换存储后被登出。
*/
const PROTECTED_AUTH_EXACT_KEYS = ["deerflow.auth", "userInfo", "userId", "tools_token"];
const PROTECTED_AUTH_PREFIX = "login.";
function isProtectedAuthKey(key: string): boolean {
return PROTECTED_AUTH_EXACT_KEYS.includes(key) || key.startsWith(PROTECTED_AUTH_PREFIX);
}
/**
* 把 localStorage 里的鉴权 / 身份键**快照复制**进 sessionStorage(覆盖式)。
*
* 「外观」设置开启独立会话时调用:此后 `authStorage()` 改读 sessionStorage,若不先搬一份当前账号
* 过去就会瞬间「未登录」。每次开启都重新快照(覆盖旧值),确保拿到的是当前 localStorage 的最新账号。
* 仅搬受保护键,不动 sessionStorage 里既有的本标签页专属态(embed.session / 任务上下文等)。
*/
export function migrateAuthToSession(): void {
if (typeof window === "undefined") return;
try {
const ls = window.localStorage;
const ss = window.sessionStorage;
for (let i = 0; i < ls.length; i++) {
const key = ls.key(i);
if (key && isProtectedAuthKey(key)) {
const value = ls.getItem(key);
if (value !== null) ss.setItem(key, value);
}
}
} catch {
/* noop */
}
}
+10
View File
@@ -4,6 +4,7 @@ import { useEffect, useRef } from "react";
import { toast } from "sonner";
import { getStoredAuth } from "@/core/auth";
import { isEmbedActive, isIsolatedSession } from "@/core/embed/embed-session";
const AUTH_STORAGE_KEY = "deerflow.auth";
const SETTLE_DELAY_MS = 1200;
@@ -21,6 +22,10 @@ export function AuthSyncWatcher() {
const lastUserIdRef = useRef<string | null>(readUserId());
useEffect(() => {
// 嵌入(iframe)态 / 独立会话态(?isolate=1):鉴权走按标签页的 sessionStorage,本就不与其它标签页
// 共享,且不应被其它标签页的 localStorage 账号变更打扰 —— 直接不挂跨标签监听。
if (isEmbedActive() || isIsolatedSession()) return;
let settleTimer: ReturnType<typeof setTimeout> | null = null;
function evaluateSettledIdentity() {
@@ -47,6 +52,11 @@ export function AuthSyncWatcher() {
}
function handleStorage(event: StorageEvent) {
// 运行时若已切到独立会话(「外观」开关在挂载后才开启):鉴权改读本标签页 sessionStorage,
// 不应再被其它标签页的 localStorage 账号变更打扰 —— 即时忽略,无需刷新页面。
if (isEmbedActive() || isIsolatedSession()) {
return;
}
// Ignore unrelated keys and localStorage.clear(). Backend session loss is
// handled centrally through 401 responses.
if (event.key !== AUTH_STORAGE_KEY) {
+261
View File
@@ -0,0 +1,261 @@
/**
* 任务工作区(任务深链 rwfx / 3qfx / xdfx,见 ``TaskFxWorkspace``)左侧栏的
* **可配置跳转按钮**。
*
* 数据源优先级:后端 ``/api/task-buttons``(全局共享、admin 整体替换)。**仅当整张表
* 为空(全新部署、从未保存过)**时回退到代码种子默认(``defaultTaskButtons``,从实时
* 任务深链配置读出 rwfx 的 4 个历史按钮,3qfx/xdfx 为空)——这样真实跳转地址通过实时
* config 进种子,避免写死;一旦保存过,后端即唯一数据源。
*
* 按钮两类(``linkType``):``url`` 外链(``window.open``,可选追加 ``?id=任务id``)/
* ``business`` 内部切换到另一业务(复用 [[task-deeplink]] 的 ``resolveTaskDeeplinkTarget``)。
*/
import {
appendQueryParam,
type TaskDeeplinkConfig,
} from "@/core/auth/task-deeplink-config";
import {
readCopTaskDetail,
resolveTaskDeeplinkTarget,
} from "@/core/auth/task-deeplink";
/** 任务工作区业务码(与路由 taskBase 一一对应)。 */
export type TaskBusiness = "rwfx" | "3qfx" | "xdfx";
/** 业务元数据:每个 = 一个任务深链页面。``goPath`` 为深链 ``?goPath=`` 值;``desc`` 给管理页说明。 */
export const TASK_BUSINESSES: {
code: TaskBusiness;
/** 页面名(tab 主标题)。 */
name: string;
/** 深链 goPath 值。 */
goPath: string;
/** 页面说明。 */
desc: string;
}[] = [
{
code: "rwfx",
name: "任务分析",
goPath: "rwfx",
desc: "完整版任务工作区(带目的树闸门),通过 ?goPath=rwfx 进入。",
},
{
code: "3qfx",
name: "三情分析",
goPath: "3qfx",
desc: "精简版工作区(无目的树闸门),通过 ?goPath=3qfx 进入。",
},
{
code: "xdfx",
name: "行动分析",
goPath: "xdfx",
desc: "精简版工作区,通过 ?goPath=xdfx 进入(深链 taskId 实为行动id)。",
},
];
/** ``url``=外链 / ``business``=切换业务 / ``purpose``=弹出任务目的树表格(无需 target)。 */
export type TaskButtonLinkType = "url" | "business" | "purpose";
/** 追加的 id 取哪种:``task``=任务id(默认)/ ``action``=行动id(仅 xdfx 二者不同)。 */
export type TaskButtonIdKind = "task" | "action";
/** ``url`` 外链打开方式:``blank``=新窗口(默认)/ ``self``=当前窗口(嵌入态即当前 iframe)。 */
export type TaskButtonOpenMode = "blank" | "self";
/** 一个可配置跳转按钮。 */
export interface TaskButton {
id: string;
business: TaskBusiness;
label: string;
linkType: TaskButtonLinkType;
/** ``url``=完整地址;``business``=目标业务码(如 ``3qfx``)。 */
target: string;
/** ``url`` 类型是否追加 id 查询参数。 */
appendTaskId: boolean;
/** 追加的查询参数名(如 ``id`` / ``task_id``);空则用 ``id``。 */
idParam: string;
/**
* ``url`` 追加 id 时取任务id 还是行动id。仅 xdfx(行动分析)二者不同:深链原始 ``?taskId=``
* 实为行动id,任务id 由 action 接口解析。其它业务两者相同。
*/
idKind: TaskButtonIdKind;
/** ``url`` 外链打开方式:``blank``=新窗口(默认)/ ``self``=当前窗口。仅 ``url`` 类型有意义。 */
openMode: TaskButtonOpenMode;
enabled: boolean;
sortOrder: number;
}
/** 内部切换可选的目标业务(``business`` 类型按钮的下拉项)。 */
export const TASK_BUSINESS_TARGETS: { code: TaskBusiness; label: string }[] = [
{ code: "3qfx", label: "三情分析" },
{ code: "rwfx", label: "任务分析" },
{ code: "xdfx", label: "行动分析" },
];
/**
* 代码种子默认按钮(仅在后端整张表为空时使用):
* - rwfx:历史 4 个按钮(编辑/下一步/3q详情,地址取自实时任务深链配置)+ 切换到三情/行动分析;
* - 3qfx / xdfx:互相切换到另外两个业务。
* 即「三个业务都带切换按钮」。已保存过则用页面「导入默认」把缺失项补进来。
*/
export function defaultTaskButtons(cfg: TaskDeeplinkConfig): TaskButton[] {
const sw = (
id: string,
business: TaskBusiness,
label: string,
target: TaskBusiness,
sortOrder: number,
): TaskButton => ({
id,
business,
label,
linkType: "business",
target,
appendTaskId: false,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder,
});
// 目的树弹框按钮(无需 target)。
const pz = (id: string, business: TaskBusiness, sortOrder: number): TaskButton => ({
id,
business,
label: "弹框查看",
linkType: "purpose",
target: "",
appendTaskId: false,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder,
});
return [
// rwfx(任务分析):外链 + 切换
{
id: "rwfx-edit",
business: "rwfx",
label: "编辑",
linkType: "url",
target: cfg.treemapEditUrl,
appendTaskId: true,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder: 0,
},
{
id: "rwfx-next",
business: "rwfx",
label: "下一步",
linkType: "url",
target: cfg.treemapNextUrl,
appendTaskId: true,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder: 1,
},
{
id: "rwfx-detail3q",
business: "rwfx",
label: "3q详情",
linkType: "url",
target: cfg.detail3qUrl,
appendTaskId: true,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder: 2,
},
sw("rwfx-switch3q", "rwfx", "切换到三情分析", "3qfx", 3),
sw("rwfx-switchxd", "rwfx", "切换到行动分析", "xdfx", 4),
pz("rwfx-purpose", "rwfx", 5),
// 3qfx(三情分析):切换到任务/行动分析
sw("3qfx-switchrw", "3qfx", "切换到任务分析", "rwfx", 0),
sw("3qfx-switchxd", "3qfx", "切换到行动分析", "xdfx", 1),
// xdfx(行动分析):切换到任务/三情分析 + 弹框查看
sw("xdfx-switchrw", "xdfx", "切换到任务分析", "rwfx", 0),
sw("xdfx-switch3q", "xdfx", "切换到三情分析", "3qfx", 1),
pz("xdfx-purpose", "xdfx", 2),
];
}
/**
* 实际生效的按钮列表:后端有任意一条记录时即以后端为准;整张表为空才回退种子默认。
* (与 [[敏感词管理]] 的种子语义一致:空=从未配置→用种子;非空=已配置→后端说了算,
* 哪怕某业务被清空也不回退。)
*/
export function resolveTaskButtons(
stored: TaskButton[],
cfg: TaskDeeplinkConfig,
): TaskButton[] {
return stored.length > 0 ? stored : defaultTaskButtons(cfg);
}
/** 取某业务下、启用的按钮,按 sortOrder 升序。 */
export function buttonsForBusiness(
buttons: TaskButton[],
business: TaskBusiness,
): TaskButton[] {
return buttons
.filter((b) => b.business === business && b.enabled)
.sort((a, b) => a.sortOrder - b.sortOrder);
}
export interface RunTaskButtonCtx {
/** 任务id(xdfx 为 action 接口解析后的真实任务id;其它业务即深链原始 id)。 */
taskId: string;
/** 行动id(xdfx 深链原始 ?taskId=;其它业务通常等于 taskId)。 */
actionId?: string;
navigate: (path: string, opts?: { state?: Record<string, unknown> }) => void;
/** 跳转/打开失败时的提示回调(默认 noop)。 */
onError?: (message: string) => void;
}
/**
* 执行一个跳转按钮:
* - ``url``:拼地址(可选追加 ``?id=``,取任务id 或行动id 视 ``idKind``)新标签打开;地址为空提示未配置。
* - ``business``:复用深链解析(会按目标业务重绑任务上下文)后 ``navigate``(始终用任务id)。
*/
export async function runTaskButton(btn: TaskButton, ctx: RunTaskButtonCtx): Promise<void> {
const fail = (m: string) => ctx.onError?.(m);
// purpose(目的树弹框)由组件层处理(需打开 React 弹框),此处不动作。
if (btn.linkType === "purpose") return;
if (btn.linkType === "url") {
const base = btn.target.trim();
if (!base) {
fail(`未配置「${btn.label}」的跳转地址`);
return;
}
// 行动分析(xdfx)可选追加行动id;否则用任务id。行动id 缺失时回退任务id。
const id = btn.idKind === "action" ? ctx.actionId || ctx.taskId : ctx.taskId;
const param = (btn.idParam || "id").trim() || "id";
const url = btn.appendTaskId && id ? appendQueryParam(base, param, id) : base;
// 打开方式:self=当前窗口(嵌入态即当前 iframe);否则 blank=新窗口(默认)。
if (btn.openMode === "self") {
window.location.assign(url);
} else {
window.open(url, "_blank", "noopener,noreferrer");
}
return;
}
// business:内部切换到另一业务
const detail = readCopTaskDetail();
if (!detail || !ctx.taskId) {
fail("缺少任务信息,无法跳转");
return;
}
try {
const target = await resolveTaskDeeplinkTarget(btn.target, detail, ctx.taskId);
if (target) ctx.navigate(target.path, { state: target.state });
else fail(`未配置「${btn.label}」对应的业务智能体`);
} catch {
fail("跳转失败,请稍后再试");
}
}
@@ -0,0 +1,120 @@
/**
* 任务深链(``goPath=rwfx``)的运行时配置:从后端公开只读接口
* ``GET /api/public/config/task-deeplink`` 读取(地址、测试开关、测试假数据全在后端
* ``config.yaml`` 的 ``task_deeplink`` 段,改完即时生效,前端无需重建)。
*
* 两种用法:
* - 命令式(登录深链流程,非 React 环境):``fetchTaskDeeplinkConfig()`` 拉取并模块级缓存;
* ``getCachedTaskDeeplinkConfig()`` 同步读缓存(拼跳转地址用)。
* - React 组件:``useTaskDeeplinkConfig()``(见 [[task-purpose]] 的面板/列表)。
*
* 拉取失败 → 用内置默认值(``test=false`` + 真实 URL)兜底,功能不整体挂掉。
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
export interface TaskDeeplinkConfig {
/** 目的树查询走假数据。 */
test: boolean;
/** 删除接口走假数据(该接口未开发完时打开)。 */
deleteTest: boolean;
/** 行动→任务解析走假数据(xdfx 行动id→任务id)。 */
actionTest: boolean;
/** 目的树查询完整 URL(调用追加 ?taskId=)。 */
purposeDetailUrl: string;
/** 删除完整 URL(调用追加 ?taskId=)。 */
deleteUrl: string;
/** B 系统树形完整编辑页 URL(跳转追加 ?id=)。 */
treemapEditUrl: string;
/** B 系统树形下一步页 URL(跳转追加 ?id=)。 */
treemapNextUrl: string;
/** 行动详情接口基址(xdfx 行动→任务):调用追加 /{actionId},返回 data.taskId 为真正任务id。 */
actionDetailUrl: string;
/** 「3q详情」详情页 URL(rwfx 目的树面板链接,跳转追加 ?id= 任务id);留空则前端提示未配置。 */
detail3qUrl: string;
/** 测试假数据:purposeDetail = 原始 {state,msg,data};delete = {message,success};
* actionDetail = 原始 {state,msg,data:{taskId,...}}。 */
mock: {
purposeDetail?: unknown;
delete?: { message?: string; success?: boolean };
actionDetail?: unknown;
};
}
/** 内置默认值(后端拿不到时兜底;真实 URL + 关闭测试)。 */
export const DEFAULT_TASK_DEEPLINK_CONFIG: TaskDeeplinkConfig = {
test: false,
deleteTest: false,
actionTest: false,
purposeDetailUrl: "https://ch1.b.uat.4.cn/consumer/taskAnalyseSearch/getTaskPurposeDetail",
deleteUrl: "https://ch1.b.uat.4.cn/consumer/taskAnalyseSearch/delete",
treemapEditUrl: "https://ch1.b.uat.4.cn/web/#/task/item-aicoh/step-mode-treemap-full-edit",
treemapNextUrl: "https://ch1.b.uat.4.cn/web/#/task/item-aicoh/step-mode-treemap-full-next",
actionDetailUrl: "https://ch1.b.uat.4.cn/consumer/plan/action",
detail3qUrl: "",
mock: {},
};
/** 后端 snake_case 响应 → 前端 camelCase;缺字段回退默认值。 */
function normalize(body: unknown): TaskDeeplinkConfig {
const o = body && typeof body === "object" ? (body as Record<string, unknown>) : {};
const d = DEFAULT_TASK_DEEPLINK_CONFIG;
const str = (v: unknown, fallback: string) =>
typeof v === "string" && v.trim() ? v : fallback;
const mock = o.mock && typeof o.mock === "object" ? (o.mock as Record<string, unknown>) : {};
return {
test: o.test === true,
deleteTest: o.delete_test === true,
actionTest: o.action_test === true,
purposeDetailUrl: str(o.purpose_detail_url, d.purposeDetailUrl),
deleteUrl: str(o.delete_url, d.deleteUrl),
treemapEditUrl: str(o.treemap_edit_url, d.treemapEditUrl),
treemapNextUrl: str(o.treemap_next_url, d.treemapNextUrl),
actionDetailUrl: str(o.action_detail_url, d.actionDetailUrl),
// detail_3q_url 允许为空(地址待定),不回退默认;只在配了非空时才生效。
detail3qUrl: typeof o.detail_3q_url === "string" ? o.detail_3q_url : d.detail3qUrl,
mock: {
purposeDetail: mock.purpose_detail,
delete:
mock.delete && typeof mock.delete === "object"
? (mock.delete as { message?: string; success?: boolean })
: undefined,
actionDetail: mock.action_detail,
},
};
}
let cached: TaskDeeplinkConfig | null = null;
let inflight: Promise<TaskDeeplinkConfig> | null = null;
/** 拉取(带模块级缓存 + 去重);失败回退默认值。 */
export async function fetchTaskDeeplinkConfig(): Promise<TaskDeeplinkConfig> {
if (cached) return cached;
if (inflight) return inflight;
inflight = (async () => {
try {
const res = await apiFetch(`${getBackendBaseURL()}/api/public/config/task-deeplink`);
if (!res.ok) throw new Error(`task-deeplink config ${res.status}`);
cached = normalize(await res.json());
} catch {
cached = { ...DEFAULT_TASK_DEEPLINK_CONFIG };
} finally {
inflight = null;
}
return cached;
})();
return inflight;
}
/** 同步读缓存(未拉取过则返回默认值)。 */
export function getCachedTaskDeeplinkConfig(): TaskDeeplinkConfig {
return cached ?? DEFAULT_TASK_DEEPLINK_CONFIG;
}
/** 在完整 URL(可能含 `#` 片段)后追加查询参数,供跳转/调用拼 id/taskId。 */
export function appendQueryParam(url: string, key: string, value: string): string {
if (!url) return "";
const sep = url.includes("?") ? "&" : "?";
return `${url}${sep}${key}=${encodeURIComponent(value)}`;
}
+162 -15
View File
@@ -16,8 +16,13 @@
*/
import { requestCrudService } from "@/service/request-axios-service";
import { clearTaskContext, persistTaskContext } from "@/core/auth/task-purpose";
import { fetchTaskDeeplinkConfig } from "@/core/auth/task-deeplink-config";
import { listBusinessMappings } from "@/strategy-components/api/business-mapping";
/** xdfx 业务码:深链传入的是「行动id」,需先调 action 接口解析出真正的「任务id」。 */
const XDFX_BUSINESS_CODE = "7BF";
/** consumer 接口返回的任务详情(data 字段)。 */
export interface CopTaskDetail {
id: string | number | null;
@@ -30,6 +35,9 @@ export interface CopTaskDetail {
/** 任务详情整包暂存的 sessionStorage key(目标页/后续可读取)。 */
export const COP_TASK_DETAIL_STORAGE_KEY = "login.copTaskDetail";
/** 行动详情整包暂存的 sessionStorage key(xdfx 行动分析:会商/单智能体读取行动名称/叙事)。 */
export const ACTION_DETAIL_STORAGE_KEY = "login.actionDetail";
/** goPath 基础码 → 业务码(配置管理 businessCode)。 */
const GOPATH_BUSINESS_CODE: Record<string, string> = {
"3qfx": "3Q", // 三情分析
@@ -69,8 +77,28 @@ function consumerBaseUrl(): string {
return typeof value === "string" ? value.replace(/\/+$/, "") : "";
}
/** 拉取任务详情;缺少 consumer 地址 / 返回不合法时返回 null。 */
/** cop-task-detail 是否走本地假数据:开关 `VITE_MOCK_COP_TASK_DETAIL=true`(真实接口未就绪时调试用)。 */
function copTaskDetailMockEnabled(): boolean {
return (import.meta.env as Record<string, unknown>).VITE_MOCK_COP_TASK_DETAIL === "true";
}
/** cop-task-detail 本地假数据(与真实 data 字段同构;mock 开关开启时返回)。 */
function mockCopTaskDetail(taskId: string): CopTaskDetail {
return {
id: taskId || "2055",
overview: "暑期文旅消费高峰期间的舆情态势综合研判与引导任务(本地假数据)。",
taskDirection: "正向引导 + 风险预警",
taskName: "任务01:暑期文旅舆情综合研判",
taskContent:
"围绕暑期文旅消费高峰,对重点城市、重点景区的公众情绪与舆情态势做综合研判,识别情绪拐点与潜在风险,提出正向引导与处置建议。",
};
}
/** 拉取任务详情;``VITE_MOCK_COP_TASK_DETAIL=true`` 走假数据;缺少 consumer 地址 / 返回不合法时返回 null。 */
export async function fetchCopTaskDetail(taskId: string): Promise<CopTaskDetail | null> {
if (copTaskDetailMockEnabled()) {
return mockCopTaskDetail(taskId);
}
const base = consumerBaseUrl();
if (!base || !taskId) return null;
// service 拦截器已统一注入 `Authorization: Bearer admin` 并返回 response.data(整包 body)。
@@ -106,17 +134,111 @@ export function readCopTaskDetail(): CopTaskDetail | null {
}
}
/** 把行动详情整包暂存到 sessionStorage(xdfx 行动分析用;隐私模式/quota 异常时静默失败)。 */
export function persistActionDetail(detail: ActionDetail): void {
try {
sessionStorage.setItem(ACTION_DETAIL_STORAGE_KEY, JSON.stringify(detail));
} catch {
/* noop */
}
}
/** 读取暂存的行动详情(会商左上角「当前行动」、单智能体行动详情卡都可读)。 */
export function readActionDetail(): ActionDetail | null {
try {
const raw = sessionStorage.getItem(ACTION_DETAIL_STORAGE_KEY);
return raw ? (JSON.parse(raw) as ActionDetail) : null;
} catch {
return null;
}
}
/** 行动详情接口 ``{action_detail_url}/{actionId}`` 返回的 ``data`` 字段(xdfx 行动分析用)。 */
export interface ActionDetail {
/** 行动id(深链 ?taskId= 传入的就是它)。 */
id: string;
/** 该行动归属的真正「任务id」。 */
taskId: string;
/** 所属目的id。 */
purposeId: string;
/** 行动名称。 */
actionName: string;
/** 行动状态码。 */
actionStatus: number | string;
/** 行动叙事 / 描述。 */
narration: string;
}
/**
* xdfx 深链:用「行动id」调行动详情接口 ``{action_detail_url}/{actionId}``,取出整包行动详情。
* ``action_test=true`` 时直接用后端配置里的假数据(接口未通时用)。
* 缺地址 / 返回不合法 → 返回 null。
*/
export async function fetchActionDetail(actionId: string): Promise<ActionDetail | null> {
if (!actionId) return null;
const cfg = await fetchTaskDeeplinkConfig();
let body: unknown;
if (cfg.actionTest) {
body = cfg.mock.actionDetail;
} else if (cfg.actionDetailUrl) {
const base = cfg.actionDetailUrl.replace(/\/+$/, "");
// service 拦截器已统一注入 Authorization: Bearer admin 并返回整包 body;行动id 走路径段。
body = await requestCrudService.get(`${base}/${encodeURIComponent(actionId)}`);
} else {
return null;
}
const data = body && typeof body === "object" ? (body as { data?: unknown }).data : null;
if (!data || typeof data !== "object") return null;
const d = data as Record<string, unknown>;
const detail: ActionDetail = {
id: d.id != null ? String(d.id) : "",
taskId: d.taskId != null ? String(d.taskId) : "",
purposeId: d.purposeId != null ? String(d.purposeId) : "",
actionName: typeof d.actionName === "string" ? d.actionName : "",
actionStatus:
typeof d.actionStatus === "number" || typeof d.actionStatus === "string" ? d.actionStatus : "",
narration: typeof d.narration === "string" ? d.narration : "",
};
// 取到即整包暂存:登录解析任务id 时(resolveDeeplinkTaskId→fetchTaskIdFromAction)就会缓存它,
// 之后会商左上角「当前行动」、单智能体行动详情卡都能直接 readActionDetail(),避免重复请求。
persistActionDetail(detail);
return detail;
}
/**
* xdfx 深链:用「行动id」解析出真正的「任务id」(取行动详情的 ``data.taskId``)。
* 缺地址 / 返回不合法 → 返回 ""(调用方据此回退)。
*/
export async function fetchTaskIdFromAction(actionId: string): Promise<string> {
return (await fetchActionDetail(actionId))?.taskId ?? "";
}
/**
* 据 goPath 把深链 URL 里的原始 id 解析成真正的「任务id」:
* - xdfx(行动分析):URL 传入的是「行动id」,调 action 接口换成 ``data.taskId``;
* 解析失败返回 ""(让调用方回退默认首页,避免拿行动id当任务id污染后续查询/绑定)。
* - 其它业务:URL 传入的本就是任务id,原样返回。
*/
export async function resolveDeeplinkTaskId(goPath: string, rawId: string): Promise<string> {
const parsed = parseGoPath(goPath);
if (parsed?.businessCode === XDFX_BUSINESS_CODE) {
return fetchTaskIdFromAction(rawId);
}
return rawId;
}
export interface TaskDeeplinkTarget {
path: string;
/** react-router navigate 的 state(多智能体会商用 roundtablePrefill)。 */
state?: Record<string, unknown>;
}
/** 用 taskName / taskContent 拼出开场信息文本。 */
function buildOpeningText(detail: CopTaskDetail): string {
/** 用 taskName / taskContent 拼出开场信息文本;末尾附上任务 id(task_id),供后端识别任务。 */
function buildOpeningText(detail: CopTaskDetail, taskId: string): string {
return [
detail.taskName ? `任务名称:${detail.taskName}` : "",
detail.taskContent ? `任务内容:${detail.taskContent}` : "",
taskId ? `任务id(task_id)为${taskId}` : "",
]
.filter(Boolean)
.join("\n");
@@ -124,22 +246,43 @@ function buildOpeningText(detail: CopTaskDetail): string {
/**
* 据 goPath + 任务详情解析跳转目标。
* - 多智能体会商:返回带 ``roundtablePrefill``(businessCode 让会商页自动选用配置的业务链条)的 state。
* - 多智能体会商:返回带 ``roundtablePrefill``(businessCode 让会商页自动选用配置的业务链条;
* taskId 让会商页按任务隔离存取草稿/聊天记录)的 state。
* - 单智能体问答:解析「配置管理」里该业务配置的智能体;把开场信息写入
* ``sessionStorage.pendingAgentMessage``(AgentChatPage 自动发出)。
* 无法识别 goPath / 未配置智能体时返回 null(调用方回退到默认首页)。
*
* @param taskId 真实任务 id(xdfx 已由 action 接口解析;其它业务即深链原始 ?taskId=)。
* 用于按任务隔离草稿/对话;与 consumer 返回的 detail.id 区分。
* @param rawId 深链 URL 的原始 ``?taskId=``(xdfx 为「行动id」)。供需追加行动id 的按钮用;
* 省略时回退 taskId。
*/
export async function resolveTaskDeeplinkTarget(
goPath: string,
detail: CopTaskDetail,
taskId: string,
rawId?: string,
): Promise<TaskDeeplinkTarget | null> {
const parsed = parseGoPath(goPath);
if (!parsed) return null;
const taskBase = BUSINESS_TASK_BASE[parsed.businessCode];
if (!taskBase) return null;
// 清掉上一次深链可能残留的任务上下文(单智能体分支会用本次任务重新写入)。
clearTaskContext();
if (parsed.roundtable) {
// 多智能体会商:嵌进对应业务的「任务管理」布局;businessCode 让会商页自动选用配置的业务链条。
// 多智能体会商:嵌进对应业务的「任务管理」布局;businessCode 让会商页自动选用配置的业务链条;
// taskId 让会商页按任务隔离存取草稿(一个 taskId 多条记录),并触发第三步自动结构化输出。
// xdfx(行动分析):根是「行动」——把行动名称随首条消息交给任务理解,左上角展示「当前行动」。
// 行动详情登录解析任务id 时已缓存(fetchActionDetail 内 persistActionDetail);这里优先读缓存。
let actionName = "";
let actionId = "";
if (parsed.businessCode === XDFX_BUSINESS_CODE && rawId) {
actionId = rawId;
const ad = readActionDetail() ?? (await fetchActionDetail(rawId));
actionName = ad?.actionName ?? "";
}
return {
path: `${taskBase}/roundtable`,
state: {
@@ -147,6 +290,9 @@ export async function resolveTaskDeeplinkTarget(
taskTitle: detail.taskName,
taskGoal: detail.taskContent,
businessCode: parsed.businessCode,
taskId: taskId || undefined,
...(actionId ? { actionId } : {}),
...(actionName ? { actionName } : {}),
autoStart: true,
},
},
@@ -162,14 +308,15 @@ export async function resolveTaskDeeplinkTarget(
}
if (!agentId) return null;
try {
sessionStorage.setItem(
"pendingAgentMessage",
JSON.stringify({ agentId, text: buildOpeningText(detail) }),
);
} catch {
/* noop */
}
// 单智能体问答:同样嵌进对应业务的「任务管理」布局。
return { path: `${taskBase}/agent/${agentId}/chats/new` };
// 单智能体问答统一走「任务工作区」(任务↔对话 1:N,按 taskId + agentId 隔离不同业务的对话列表):
// 暂存任务上下文(taskId + agentId + 开场信息),跳到 chats 索引,由工作区按 taskId 决定
// 开最新历史对话 / 新建。rwfx 在工作区里额外过「目的树闸门」;3qfx/xdfx 仅 1:N 列表,
// 新建对话直接带开场信息自动发出(见 task-purpose / AgentChatPage 的 taskGate / taskBind)。
persistTaskContext({
taskId,
agentId,
openingText: buildOpeningText(detail, taskId),
actionId: rawId || taskId,
});
return { path: `${taskBase}/agent/${agentId}/chats` };
}
+326
View File
@@ -0,0 +1,326 @@
/**
* 任务深链(``goPath=rwfx``)的「目的树闸门 + 任务↔对话绑定」支持。
*
* 角色区分:
* - **目的树数据**:B 系统里的策划结果,走 ``getTaskPurposeDetail`` / ``delete``(地址、测试
* 开关、测试假数据都来自 [[task-deeplink-config]] / 后端 config.yaml),与聊天对话无关。
* 新建对话(含首次进入)前用它做「已有数据→覆盖确认」闸门。
* - **对话(thread)**:聊天会话;通过 thread 的 ``metadata.taskId`` 标签把多个对话挂到同一个
* 任务下(1:N),列表用 useThreadsPage({ metadata:{ taskId } }) 过滤。详见 [[task-deeplink]]。
*/
import {
appendQueryParam,
fetchTaskDeeplinkConfig,
getCachedTaskDeeplinkConfig,
} from "@/core/auth/task-deeplink-config";
import { requestCrudService } from "@/service/request-axios-service";
import type {
FlowGraphData,
FlowGraphEdge,
FlowGraphNode,
FlowNodeType,
} from "@/roundtable-planning/lib/flow-graph";
/** 归一化后的目的树节点(用于展示,逐层:目的→行为体→预期行为→驱动因素→叙事)。 */
export interface PurposeTreeNode {
/** 节点类型中文标签。 */
label: string;
/** 节点主文本(目的/行为体名/预期/因素/叙事内容)。 */
text: string;
/** 推荐理由(若有)。 */
reason?: string;
children: PurposeTreeNode[];
}
/** 当前 rwfx 任务上下文(深链进入或「新建对话」时暂存,供闸门面板与绑定使用)。 */
export interface TaskContext {
taskId: string;
agentId: string;
/** 自动发出的开场信息(任务名称/内容)。 */
openingText: string;
/** 深链原始 id(xdfx 为「行动id」,需追加行动id 的按钮用;其它业务等于 taskId)。 */
actionId?: string;
}
const TASK_CONTEXT_STORAGE_KEY = "task.rwfxContext";
/* --------------------------- 目的树查询/删除 --------------------------- */
/** 逐层 dto 字段映射:key=childrenList 里出现的 *Dto 字段名。 */
const DTO_FIELD_MAP: Record<string, { label: string; textKey: string }> = {
purposeDto: { label: "目的", textKey: "zzPurpose" },
actorDto: { label: "行为体", textKey: "actorName" },
expectedBehaviorDto: { label: "预期行为", textKey: "behavior" },
drivingFactorDto: { label: "驱动因素", textKey: "drivingFactor" },
narrationDto: { label: "叙事", textKey: "narration" },
};
// 取节点主文本时跳过的字段(id/时间/标记/理由等非展示文本),保证容错。
const SKIP_TEXT_KEY = /(^id$|Id$|Time$|Flag$|Type$|Level$|recReason|createBy|updateBy|^mid$)/i;
/** 从一个 dto 里取展示文本:优先 preferredKey,否则取第一个像「内容」的字符串字段。 */
function pickDtoText(dto: Record<string, unknown>, preferredKey?: string): string {
if (preferredKey && typeof dto[preferredKey] === "string" && (dto[preferredKey] as string).trim()) {
return dto[preferredKey] as string;
}
for (const [k, v] of Object.entries(dto)) {
if (typeof v === "string" && v.trim() && !SKIP_TEXT_KEY.test(k)) return v;
}
return "";
}
/**
* 把一层节点归一化为 {label,text,reason,children}。**容错**:
* - 优先匹配已知 dto(目的/行为体/...);未知 ``*Dto`` 字段也兜底(标签取字段名去 Dto);
* - 文本字段改名也能取到(pickDtoText 兜底);
* - 完全不认识的结构仍递归 childrenList,避免整棵树丢失。
*/
function normalizeNode(raw: unknown): PurposeTreeNode | null {
if (!raw || typeof raw !== "object") return null;
const obj = raw as Record<string, unknown>;
const isObj = (k: string) => obj[k] && typeof obj[k] === "object" && !Array.isArray(obj[k]);
// 先找已知 dto,再兜底任意 `*Dto` 字段。
let dtoKey = Object.keys(DTO_FIELD_MAP).find(isObj);
if (!dtoKey) dtoKey = Object.keys(obj).find((k) => /Dto$/.test(k) && isObj(k));
const childrenRaw = Array.isArray(obj.childrenList) ? obj.childrenList : [];
const children = childrenRaw
.map(normalizeNode)
.filter((n): n is PurposeTreeNode => n !== null);
if (!dtoKey) {
// 不认识的结构:仅当有子节点时保留为占位节点,否则丢弃。
return children.length ? { label: "节点", text: "", children } : null;
}
const mapped = DTO_FIELD_MAP[dtoKey];
const dto = obj[dtoKey] as Record<string, unknown>;
const label = mapped?.label ?? dtoKey.replace(/Dto$/, "");
const text = pickDtoText(dto, mapped?.textKey);
const reason =
typeof dto.recReason === "string" && (dto.recReason as string).trim()
? (dto.recReason as string)
: undefined;
return { label, text, reason, children };
}
/** 表格行:根→叶一条路径上的各层单元格(层级数可变,做了容错)。 */
export type PurposeFlatCell = { label: string; text: string; reason?: string };
/** 把目的树拍平成「一行一条叶子路径」,供表格展示(层级缺失/变动都不崩)。 */
export function flattenPurposeTree(nodes: PurposeTreeNode[]): PurposeFlatCell[][] {
const rows: PurposeFlatCell[][] = [];
const walk = (node: PurposeTreeNode, trail: PurposeFlatCell[]) => {
const next = [...trail, { label: node.label, text: node.text, reason: node.reason }];
if (!node.children || node.children.length === 0) rows.push(next);
else node.children.forEach((c) => walk(c, next));
};
nodes.forEach((n) => walk(n, []));
return rows;
}
/* --------------------- 目的树 → 流程图(flow-graph) --------------------- */
/**
* 目的树各层级标签 → 流程图节点类型(仅决定配色,见 FLOW_NODE_TYPE_META)。
* 未知层级回退 task。层级名本身仍原样写进节点 group,画布上当小标签显示。
*/
const PURPOSE_LABEL_TO_FLOW_TYPE: Record<string, FlowNodeType> = {
目的: "stage",
行为体: "role",
预期行为: "task",
驱动因素: "decision",
叙事: "deliverable",
};
/** 目的树的一个层级(深度):层级中文名 + 对应流程图节点类型(决定配色)。 */
export interface PurposeLevel {
/** 层级中文名(目的 / 行为体 / 预期行为 / 驱动因素 / 叙事…)。 */
label: string;
/** 流程图节点类型(用于取 FLOW_NODE_TYPE_META 配色,与画布节点一致)。 */
type: FlowNodeType;
}
/**
* 按**深度**抽出目的树的有序层级(每层取该深度第一个非空层级名作代表)。
*
* 目的树每一深度的层级是一致的(深度 0 = 目的、1 = 行为体、… 直到叶子叙事),
* 故逐层 BFS、每层取一个代表标签即可得到「任务策划共几级、分别是什么」,
* 供消息列表上方的「流程示例图」按层级画彩色小图标。
*/
export function derivePurposeLevels(tree: PurposeTreeNode[]): PurposeLevel[] {
const levels: PurposeLevel[] = [];
let frontier = tree;
let depth = 0;
while (frontier.length > 0 && depth < 12) {
const label = frontier.find((n) => n.label?.trim())?.label?.trim() || `层级 ${depth + 1}`;
levels.push({ label, type: PURPOSE_LABEL_TO_FLOW_TYPE[label] ?? "task" });
frontier = frontier.flatMap((n) => n.children ?? []);
depth += 1;
}
return levels;
}
/**
* 把归一化后的目的树转换成 Step 3 流程图组件(FlowGraphPanel)认识的 FlowGraphData。
*
* - 逐层深度优先遍历,给每个节点分配稳定 id(`p1/p2/…`,按遍历顺序);
* - 父→子建一条边(from=父 id);
* - 节点主文本(`text`)作 label,层级名(`label`)作 group(画布顶部小标签),
* 推荐理由并进 detail(点节点弹窗里看)。
* - 传入 ``rootLabel`` 时,在最顶层加一个「任务」根节点,所有「目的」挂到它下面
* (与 B 系统给的「任务 → 目的 → 行为体 → …」流程一致,单一根节点);不传则保持
* 旧的「多个目的各自成根」森林(向后兼容)。
* 容错沿用 PurposeTreeNode(normalizeNode 已兜底字段/层级变动),这里不再二次判断。
*/
export function purposeTreeToFlowGraph(
tree: PurposeTreeNode[],
taskId?: string,
rootLabel?: string,
): FlowGraphData {
const nodes: FlowGraphNode[] = [];
const edges: FlowGraphEdge[] = [];
let counter = 0;
const walk = (node: PurposeTreeNode, parentId: string | null) => {
const id = `p${++counter}`;
const type = PURPOSE_LABEL_TO_FLOW_TYPE[node.label] ?? "task";
const text = node.text?.trim() || node.label || "(空)";
const detail = node.reason?.trim()
? `${text}\n理由:${node.reason.trim()}`
: node.text?.trim() || undefined;
nodes.push({ id, label: text, type, group: node.label || undefined, detail });
if (parentId) edges.push({ from: parentId, to: id });
node.children?.forEach((child) => walk(child, id));
};
// 任务为单一根节点(仅在有目的数据且传入 rootLabel 时):每个「目的」根挂到它下面。
const rootId = rootLabel && rootLabel.trim() && tree.length > 0 ? "task-root" : null;
if (rootId) {
nodes.push({ id: rootId, label: rootLabel!.trim(), type: "start", group: "任务" });
}
tree.forEach((root) => walk(root, rootId));
return {
title: taskId ? `任务目的(任务 ${taskId})` : "任务目的",
nodes,
edges,
};
}
/** 从接口/假数据的整包 body 里取出 data 数组并归一化成树。 */
function bodyToTree(body: unknown): PurposeTreeNode[] {
const data =
body && typeof body === "object" ? (body as { data?: unknown }).data : null;
const arr = Array.isArray(data) ? data : [];
return arr.map(normalizeNode).filter((n): n is PurposeTreeNode => n !== null);
}
export interface TaskPurposeResult {
tree: PurposeTreeNode[];
/** data 数组里有有效目的节点 = 已有策划数据。 */
hasData: boolean;
}
/**
* 查询任务目的树。``test=true`` 时直接用后端配置里的假数据;否则打真实接口
* (地址来自配置,``Authorization: Bearer admin`` 由 axios 拦截器统一注入)。
* 缺地址 / 返回不合法 → ``{ tree: [], hasData: false }``。
*/
export async function fetchTaskPurposeDetail(
taskId: string,
): Promise<TaskPurposeResult> {
if (!taskId) return { tree: [], hasData: false };
const cfg = await fetchTaskDeeplinkConfig();
let body: unknown;
if (cfg.test) {
body = cfg.mock.purposeDetail;
} else if (cfg.purposeDetailUrl) {
body = await requestCrudService.get(cfg.purposeDetailUrl, { taskId });
} else {
return { tree: [], hasData: false };
}
const tree = bodyToTree(body);
return { tree, hasData: tree.length > 0 };
}
export interface DeleteTaskPurposeResult {
message: string;
success: boolean;
}
/**
* 删除任务目的树(覆盖前清空 / 手动清除任务记录都走这里)。``delete_test=true`` 时
* 用后端配置里的假数据(接口未开发完时用);否则打真实接口。
*/
export async function deleteTaskPurpose(
taskId: string,
): Promise<DeleteTaskPurposeResult> {
if (!taskId) return { message: "缺少 taskId", success: false };
const cfg = await fetchTaskDeeplinkConfig();
if (cfg.deleteTest) {
const m = cfg.mock.delete ?? {};
return { message: typeof m.message === "string" ? m.message : "", success: m.success === true };
}
if (!cfg.deleteUrl) return { message: "缺少删除接口地址", success: false };
const body = await requestCrudService.get(cfg.deleteUrl, { taskId });
const obj =
body && typeof body === "object" ? (body as unknown as Record<string, unknown>) : {};
return {
message: typeof obj.message === "string" ? obj.message : "",
success: obj.success === true,
};
}
/* ----------------------------- 跳转地址 ----------------------------- */
/** B 系统「树形完整编辑」页地址(问答后「编辑」按钮,新标签打开)。用同步缓存配置。 */
export function buildTreemapEditUrl(taskId: string): string {
const url = getCachedTaskDeeplinkConfig().treemapEditUrl;
return url && taskId ? appendQueryParam(url, "id", taskId) : "";
}
/** B 系统「树形下一步」页地址(问答后「下一步」按钮,新标签打开)。 */
export function buildTreemapNextUrl(taskId: string): string {
const url = getCachedTaskDeeplinkConfig().treemapNextUrl;
return url && taskId ? appendQueryParam(url, "id", taskId) : "";
}
/** 「3q详情」详情页地址(目的树面板链接,新标签打开);追加 ?id=任务id。地址未配置时返回 ""。 */
export function buildDetail3qUrl(taskId: string): string {
const url = getCachedTaskDeeplinkConfig().detail3qUrl;
return url && taskId ? appendQueryParam(url, "id", taskId) : "";
}
/* --------------------------- 任务上下文暂存 --------------------------- */
export function persistTaskContext(ctx: TaskContext): void {
try {
sessionStorage.setItem(TASK_CONTEXT_STORAGE_KEY, JSON.stringify(ctx));
} catch {
/* noop */
}
}
export function readTaskContext(): TaskContext | null {
try {
const raw = sessionStorage.getItem(TASK_CONTEXT_STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as Partial<TaskContext>;
if (!parsed?.taskId || !parsed?.agentId) return null;
return {
taskId: String(parsed.taskId),
agentId: String(parsed.agentId),
openingText: typeof parsed.openingText === "string" ? parsed.openingText : "",
actionId: typeof parsed.actionId === "string" ? parsed.actionId : undefined,
};
} catch {
return null;
}
}
export function clearTaskContext(): void {
try {
sessionStorage.removeItem(TASK_CONTEXT_STORAGE_KEY);
} catch {
/* noop */
}
}
@@ -4,6 +4,7 @@ import {
EXTERNAL_LOGIN_STORAGE_KEYS,
persistExternalLoginParams,
} from "./external-login";
import { authStorageSet } from "@/core/auth/scoped-storage";
const AUTH_BASE_URL = (import.meta.env.VITE_AUTH_BASE_URL || "").replace(
/\/$/,
@@ -49,21 +50,14 @@ type UserDetailTokenResponse = {
};
function persistMaxkeyOnlineToken(token: string): void {
try {
localStorage.setItem(MAXKEY_ONLINE_TOKEN_STORAGE_KEY, token);
} catch {
// 静默失败,不阻断登录
}
// 嵌入(iframe)态走 sessionStorage(按标签页隔离),正常态走 localStorage。
authStorageSet(MAXKEY_ONLINE_TOKEN_STORAGE_KEY, token);
}
function persistUserDetailToken(data: UserDetailTokenPayload): void {
try {
localStorage.setItem(USER_DETAIL_TOKEN_STORAGE_KEY, JSON.stringify(data));
if (data.user_id) {
localStorage.setItem(EXTERNAL_LOGIN_STORAGE_KEYS.userId, String(data.user_id));
}
} catch {
// 静默失败
authStorageSet(USER_DETAIL_TOKEN_STORAGE_KEY, JSON.stringify(data));
if (data.user_id) {
authStorageSet(EXTERNAL_LOGIN_STORAGE_KEYS.userId, String(data.user_id));
}
}
+6 -5
View File
@@ -1,4 +1,5 @@
import { requestCrudService } from "@/service/request-axios-service";
import { authStorageGet, authStorageSet } from "@/core/auth/scoped-storage";
const CONSUMER_URL = import.meta.env.VITE_AIPI_CONSUMER_URL || "";
@@ -23,7 +24,7 @@ export async function loginByYUserId(
token?: string | null,
): Promise<void> {
if (token) {
localStorage.setItem(TOOLS_TOKEN_STORAGE_KEY, token);
authStorageSet(TOOLS_TOKEN_STORAGE_KEY, token);
}
const res = (await requestCrudService.get(
@@ -37,14 +38,14 @@ export async function loginByYUserId(
// 注意:接口也会返回 accessToken,但 XK/PG 及 source=accessToken 要用路由透传的
// access_token,故登录流程随后会用 persistAccessToken 覆盖 userInfo.accessToken。
const result = res.data ?? {};
localStorage.setItem(
authStorageSet(
EXTERNAL_USER_INFO_STORAGE_KEY,
JSON.stringify({ ...result, yUserId }),
);
}
export function persistToolsToken(token: string): void {
localStorage.setItem(TOOLS_TOKEN_STORAGE_KEY, token);
authStorageSet(TOOLS_TOKEN_STORAGE_KEY, token);
}
/**
@@ -59,7 +60,7 @@ export function persistAccessToken(token: string): void {
if (!trimmed) return;
let info: Record<string, unknown> = {};
try {
const raw = localStorage.getItem(EXTERNAL_USER_INFO_STORAGE_KEY);
const raw = authStorageGet(EXTERNAL_USER_INFO_STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") {
@@ -70,5 +71,5 @@ export function persistAccessToken(token: string): void {
info = {};
}
info.accessToken = trimmed;
localStorage.setItem(EXTERNAL_USER_INFO_STORAGE_KEY, JSON.stringify(info));
authStorageSet(EXTERNAL_USER_INFO_STORAGE_KEY, JSON.stringify(info));
}
@@ -0,0 +1,213 @@
/**
* 「外部系统 iframe 套用深链」相关的**按标签页**会话开关。承载三个相互独立的能力,多由 URL
* 路由参数开启(独立会话 `isolate` 另可由「外观」设置里的开关在运行时切换,见 `setIsolatedSession`),
* 存进同一份 sessionStorage 会话、跨登录跳转/刷新/页内导航存活:
*
* 1. `embed=1`(可带 `&theme=`)—— **嵌入模式**:去掉全局导航栏(Header)+ 侧边栏(PageSidebar),
* 并按外部主题色强制系统明/暗(离散切换)。
* 2. `hideJump=1` —— **隐藏深链底部「快捷跳转」栏**:去掉 `TaskJumpBar` 的两部分——底部的
* 「下一步」等按钮 + 右侧垂直居中的悬浮菜单(单智能体问答 / 多智能体会商深链共用该栏)。
* 3. `isolate=1` —— **独立会话登录**:本标签页的鉴权身份按标签页隔离(见 [[scoped-storage]]
* `authStorage()`,嵌入态与独立态同走 sessionStorage)。用于同一浏览器里**另开一个标签页登
* 录不同账号**而**不覆盖**当前标签页(localStorage)的登录态——`embed` 已隐含此隔离,`isolate`
* 则是把同一套隔离单独提供给**普通(带 chrome)标签页**,不去 chrome、不强制主题、不动跳转栏。
*
* 三者可单独使用,也可叠加:`hideJump` **只**隐藏跳转栏,不动 chrome / 主题;`embed` 不影响跳转栏;
* `isolate` 只切换鉴权存储,不影响 chrome / 主题 / 跳转栏。
*
* 隔离要点(核心诉求:同一浏览器另开咱们正常系统页,**绝不能**被这些开关影响):
* - 用 **sessionStorage**(按标签页隔离、绝不跨标签)持有这些 flag,而**不用** localStorage
* (跨标签共享 → 会污染正常页)。
* - 主题走 next-themes 的 `forcedTheme`(见 App.tsx `AppProviders`)——只在本标签页生效、
* 不写 localStorage `strategy-theme`;嵌入侧绝不调 `setTheme`。
* - 去 chrome / 去跳转栏均由本模块的 sessionStorage flag 驱动,不碰 `persistSidebarEnabled` 等
* localStorage 偏好。
*
* iframe 的浏览器上下文就是它自己的标签页,sessionStorage 天然「一个 iframe 一份、随关闭消失」;
* 正常页标签页里既无这些参数也无这份会话 → 所有 `isXxx()` 恒为 false,完全不受影响。
*/
const EMBED_SESSION_KEY = "embed.session";
export type EmbedTheme = "light" | "dark";
/** 本标签页的嵌入会话(按需置位的若干独立开关)。 */
export interface EmbedSession {
/** 嵌入模式:去全局 chrome + 强制主题。 */
embed: boolean;
/** 嵌入模式下强制的主题(仅 embed 为真时有意义)。 */
theme: EmbedTheme;
/** 隐藏深链底部「快捷跳转」栏(TaskJumpBar:底部按钮 + 右侧悬浮菜单)。 */
hideJump: boolean;
/** 独立会话:鉴权身份按本标签页隔离(走 sessionStorage),用于同浏览器登录不同账号互不覆盖。 */
isolate: boolean;
}
/** URL 布尔参数的三态:显式开 / 显式关 / 未带。 */
type FlagParam = "on" | "off" | null;
function toSearchParams(search: string): URLSearchParams {
return new URLSearchParams(search.startsWith("?") ? search : `?${search}`);
}
/** 读某个布尔型 query 参数的三态。`1/true/yes` → on;`0/false/no` → off;缺省/其它 → null。 */
function readFlagParam(search: string, key: string): FlagParam {
const v = (toSearchParams(search).get(key) ?? "").trim().toLowerCase();
if (!v) return null;
if (v === "1" || v === "true" || v === "yes") return "on";
if (v === "0" || v === "false" || v === "no") return "off";
return null;
}
/** 读 URL 里的 `embed` 三态。 */
export function readEmbedParam(search: string): FlagParam {
return readFlagParam(search, "embed");
}
/** 读 URL 里的 `hideJump` 三态。 */
export function readHideJumpParam(search: string): FlagParam {
return readFlagParam(search, "hideJump");
}
/** 读 URL 里的 `isolate` 三态(独立会话登录)。 */
export function readIsolateParam(search: string): FlagParam {
return readFlagParam(search, "isolate");
}
/**
* 把外部传入的主题色映射成离散明/暗。与 `resolveThemeFromQuery` 同源约定(dark-blue → 深色),
* 另外宽松接受 `dark` / 中文「深色/深蓝」直传;其余(含空)一律浅色。
*/
export function resolveEmbedThemeMode(raw: string | null | undefined): EmbedTheme {
const v = (raw ?? "").trim().toLowerCase();
if (v === "dark" || v === "dark-blue" || v === "深色" || v === "深蓝") return "dark";
return "light";
}
/** 取 URL query 里的 `theme` 值(embed 主题来源)。 */
export function readEmbedThemeParam(search: string): string {
return (toSearchParams(search).get("theme") ?? "").trim();
}
/** 读本标签页的嵌入会话;无 → null。 */
export function readEmbedSession(): EmbedSession | null {
try {
const raw = sessionStorage.getItem(EMBED_SESSION_KEY);
if (!raw) return null;
const p = JSON.parse(raw) as Partial<EmbedSession>;
return {
embed: p.embed === true,
theme: p.theme === "dark" ? "dark" : "light",
hideJump: p.hideJump === true,
isolate: p.isolate === true,
};
} catch {
return null;
}
}
/** 写会话;无任何开关置位时直接清除(保持 sessionStorage 干净)。隐私模式/quota 异常静默失败。 */
function writeEmbedSession(next: EmbedSession): void {
try {
if (!next.embed && !next.hideJump && !next.isolate) {
sessionStorage.removeItem(EMBED_SESSION_KEY);
return;
}
sessionStorage.setItem(EMBED_SESSION_KEY, JSON.stringify(next));
} catch {
/* noop */
}
}
/** 本标签页是否处于嵌入模式(驱动去全局 chrome + 强制主题)。 */
export function isEmbedActive(): boolean {
return readEmbedSession()?.embed === true;
}
/** 本标签页是否要隐藏深链底部「快捷跳转」栏(TaskJumpBar)。 */
export function isJumpBarHidden(): boolean {
return readEmbedSession()?.hideJump === true;
}
/**
* 本标签页是否处于独立会话态:鉴权身份按标签页隔离(走 sessionStorage)。
* `embed` 已隐含同样的隔离,故 `authStorage()` 取「embed || isolate」之并;这里只判 `isolate`,
* 供需要区分「纯独立会话(带 chrome)」与「嵌入态(去 chrome)」的场合使用。
*/
export function isIsolatedSession(): boolean {
return readEmbedSession()?.isolate === true;
}
/**
* 按 URL 参数同步 sessionStorage 会话(AppProviders 在每次 search 变化时调用一次)。
* **合并语义**:on 置位、off 清位、未带则沿用既有值——这样登录后跳到不带参数的干净路由时,
* 之前置位的开关不会被抹掉。
*/
export function syncEmbedSessionFromSearch(search: string): void {
const cur =
readEmbedSession() ??
{ embed: false, theme: "light" as EmbedTheme, hideJump: false, isolate: false };
const next: EmbedSession = { ...cur };
const embedParam = readEmbedParam(search);
if (embedParam === "on") {
next.embed = true;
next.theme = resolveEmbedThemeMode(readEmbedThemeParam(search));
} else if (embedParam === "off") {
next.embed = false;
}
const hideJumpParam = readHideJumpParam(search);
if (hideJumpParam === "on") next.hideJump = true;
else if (hideJumpParam === "off") next.hideJump = false;
const isolateParam = readIsolateParam(search);
if (isolateParam === "on") next.isolate = true;
else if (isolateParam === "off") next.isolate = false;
writeEmbedSession(next);
}
/**
* 从当前 HashRouter URL(`#/path?a=b`)取出 query 串。
* 供「在 React 渲染之前」同步启用嵌入会话(main.tsx)——必须早于任何鉴权写入,
* 否则首帧 LoginPage 的 effect 可能抢在 AppProviders 同步 effect 之前把登录参数写进 localStorage。
*/
function currentHashSearch(): string {
if (typeof window === "undefined") return "";
const hash = window.location.hash || "";
const i = hash.indexOf("?");
return i >= 0 ? hash.slice(i) : "";
}
/** main.tsx 在渲染前同步调用一次:据当前 URL 启用/关闭本标签页嵌入会话。 */
export function syncEmbedSessionFromCurrentUrl(): void {
syncEmbedSessionFromSearch(currentHashSearch());
}
/**
* 解析「应当强制的嵌入主题」供 `AppProviders` 的 `forcedTheme` 用:
* - URL 显式 `embed=1` → 用 URL `theme`(首帧即生效,登录页转场不闪烁);
* - URL 显式 `embed=0` → 不强制(undefined);
* - URL 未带 → 回退本标签页嵌入会话主题(仅 embed 置位时)。
* 非嵌入标签页恒返回 undefined → 完全不影响正常系统页的主题。
*/
export function resolveForcedEmbedTheme(search: string): EmbedTheme | undefined {
const param = readEmbedParam(search);
if (param === "on") return resolveEmbedThemeMode(readEmbedThemeParam(search));
if (param === "off") return undefined;
const session = readEmbedSession();
return session?.embed ? session.theme : undefined;
}
/**
* 运行时直接置位/清除本标签页的独立会话标志(供「外观」设置里的开关用,区别于 URL 参数驱动)。
* 仅切换标志;登录态的「localStorage 快照搬进 sessionStorage」由 [[scoped-storage]]
* `migrateAuthToSession()` 负责,调用顺序见 appearance 设置页。
*/
export function setIsolatedSession(on: boolean): void {
const cur =
readEmbedSession() ??
{ embed: false, theme: "light" as EmbedTheme, hideJump: false, isolate: false };
writeEmbedSession({ ...cur, isolate: on });
}
@@ -0,0 +1,119 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
applyMenuOverrides,
buildTreeFromMerged,
diffOverrides,
flattenMenu,
isDescendant,
mergeFlatNodes,
wouldExceedDepth,
type MenuOverride,
} from "./menu-overrides";
import type { MenuItem } from "./sidebar-menu";
// 极简图标占位(合并逻辑不关心图标本身)。
const I = (() => null) as unknown as MenuItem["icon"];
function sampleTree(): MenuItem[] {
return [
{
id: "a",
label: "A",
icon: I,
children: [
{ id: "a1", label: "A1", icon: I, path: "/a1" },
{
id: "a2",
label: "A2",
icon: I,
children: [{ id: "a2x", label: "A2X", icon: I, path: "/a2x" }],
},
],
},
{ id: "b", label: "B", icon: I, path: "/b" },
];
}
const ids = (items: MenuItem[]): string[] =>
items.flatMap((i) => [i.id, ...(i.children ? ids(i.children) : [])]);
test("无覆盖时原样返回", () => {
const tree = sampleTree();
assert.equal(applyMenuOverrides(tree, []), tree);
});
test("改名只改 label,不动结构", () => {
const out = applyMenuOverrides(sampleTree(), [
{ nodeId: "a1", parentId: "a", sortOrder: 0, label: "改名了", disabled: false },
]);
const a = out.find((n) => n.id === "a")!;
assert.equal(a.children![0].label, "改名了");
assert.deepEqual(ids(out), ["a", "a1", "a2", "a2x", "b"]);
});
test("停用一级菜单隐藏其整棵子树", () => {
const out = applyMenuOverrides(sampleTree(), [
{ nodeId: "a", parentId: null, sortOrder: 0, label: null, disabled: true },
]);
assert.deepEqual(ids(out), ["b"]); // a / a1 / a2 / a2x 全部隐藏
});
test("管理页 includeDisabled=true 保留停用节点", () => {
const merged = mergeFlatNodes(flattenMenu(sampleTree()), [
{ nodeId: "a2", parentId: "a", sortOrder: 1, label: null, disabled: true },
]);
const all = buildTreeFromMerged(merged, true);
assert.ok(ids(all).includes("a2"));
const sidebar = buildTreeFromMerged(merged, false);
assert.ok(!ids(sidebar).includes("a2"));
assert.ok(!ids(sidebar).includes("a2x")); // 子树同隐藏
});
test("改父级把子树一起搬走", () => {
// 把 a2(带子 a2x)移到一级 B 之后 → a2 成为一级。
const out = applyMenuOverrides(sampleTree(), [
{ nodeId: "a2", parentId: null, sortOrder: 5, label: null, disabled: false },
]);
const top = out.map((n) => n.id);
assert.ok(top.includes("a2"));
const a2 = out.find((n) => n.id === "a2")!;
assert.deepEqual(a2.children!.map((c) => c.id), ["a2x"]); // 子树跟随
});
test("wouldExceedDepth 阻止四级", () => {
const merged = mergeFlatNodes(flattenMenu(sampleTree()), []);
// a2x 是三级;把 a(高度3)移到 a2x 下 → 6 级,必拒。
assert.equal(wouldExceedDepth("a", "a2x", merged), true);
// a1(叶子,高度1)移到 a2 下 → a2 是二级,结果三级,允许。
assert.equal(wouldExceedDepth("a1", "a2", merged), false);
});
test("isDescendant 识别子树", () => {
const merged = mergeFlatNodes(flattenMenu(sampleTree()), []);
assert.equal(isDescendant("a", "a2x", merged), true);
assert.equal(isDescendant("a", "b", merged), false);
});
test("diffOverrides 只输出有变化的节点", () => {
const merged = mergeFlatNodes(flattenMenu(sampleTree()), []);
// 原样 → 无 diff
assert.deepEqual(diffOverrides(merged), []);
// 改一个 label
const renamed = merged.map((n) => (n.id === "b" ? { ...n, label: "B改" } : n));
const diff = diffOverrides(renamed);
assert.equal(diff.length, 1);
assert.equal(diff[0]!.nodeId, "b");
assert.equal(diff[0]!.label, "B改");
});
test("套覆盖再 diff 可往返", () => {
const overrides: MenuOverride[] = [
{ nodeId: "a1", parentId: "a", sortOrder: 0, label: "X", disabled: false },
];
const merged = mergeFlatNodes(flattenMenu(sampleTree()), overrides);
const diff = diffOverrides(merged);
assert.equal(diff.length, 1);
assert.equal(diff[0]!.label, "X");
});
@@ -0,0 +1,263 @@
/**
* 菜单覆盖层(overlay)合并逻辑。
*
* 静态菜单(sidebar-menu.ts)+ 注入的 iframe 轻应用 = 合并树,是结构/图标/路由的
* 唯一来源;后端只按节点 id 存「覆盖项」(改名 label / 停用 disabled / 排序
* sortOrder / 改父级 parentId)。渲染时把覆盖项套到合并树上重建。
*
* 图标与路由永不入库 —— 覆盖只动 label/可见性/位置/层级,所以新增的代码菜单、
* 新注册的 iframe 应用都会自动出现,且立即可被配置。
*
* 严格 3 级:一级 → 二级 → 三级,移动导致超过 3 级的非法布局会被
* `wouldExceedDepth` 拦截(后端 `_validate_depth` 二次校验)。
*/
import type { MenuItem } from "./sidebar-menu";
export const MAX_MENU_DEPTH = 3;
export const ROOT_PARENT_ID = "__root__";
/** 单个节点的覆盖项(与后端 MenuOverride 对应;camelCase 边界)。 */
export interface MenuOverride {
nodeId: string;
/** 生效的父节点 id;null = 一级菜单。 */
parentId: string | null;
sortOrder: number;
/** 改名;null/undefined 保留代码定义的 label。 */
label?: string | null;
disabled: boolean;
}
/** 拍平后的节点:保留原始定义 + 代码默认的父级/次序。 */
export interface FlatMenuNode {
id: string;
/** 代码默认 label(未改名时显示)。 */
defaultLabel: string;
defaultParentId: string | null;
defaultIndex: number;
/** 原始静态节点(含 icon/path/adminOnly/userPath,重建时复用)。 */
source: MenuItem;
/** 是否为注入的 iframe 轻应用节点(light-app-<appId>)。 */
isLightApp: boolean;
}
/** 把合并树拍平成有序节点列表,记录每个节点的代码默认父级与同级次序。 */
export function flattenMenu(items: MenuItem[]): FlatMenuNode[] {
const out: FlatMenuNode[] = [];
const walk = (nodes: MenuItem[], parentId: string | null) => {
nodes.forEach((node, index) => {
out.push({
id: node.id,
defaultLabel: node.label,
defaultParentId: parentId,
defaultIndex: index,
source: node,
isLightApp: node.id.startsWith("light-app-"),
});
if (node.children?.length) {
walk(node.children, node.id);
}
});
};
walk(items, null);
return out;
}
/**
* 合并视图节点:拍平节点 + 生效后的 label / parentId / order / disabled。
* 菜单管理页直接编辑这份结构(含停用项,用于灰显展示)。
*/
export interface MergedMenuNode extends FlatMenuNode {
label: string;
parentId: string | null;
order: number;
disabled: boolean;
/** 该节点是否带显式覆盖项(用于「重置该项」判断)。 */
hasOverride: boolean;
}
/** 把覆盖项套到拍平节点上,得到生效后的合并节点(不重建树)。 */
export function mergeFlatNodes(
flat: FlatMenuNode[],
overrides: MenuOverride[],
): MergedMenuNode[] {
const byId = new Map(overrides.map((o) => [o.nodeId, o]));
return flat.map((node) => {
const ov = byId.get(node.id);
return {
...node,
label: ov?.label != null && ov.label !== "" ? ov.label : node.defaultLabel,
parentId: ov ? ov.parentId : node.defaultParentId,
order: ov ? ov.sortOrder : node.defaultIndex,
disabled: ov?.disabled ?? false,
hasOverride: ov != null,
};
});
}
/**
* 把合并节点重建成菜单树。
* @param includeDisabled 渲染侧边栏时为 false(连同停用节点的整棵子树一并隐藏);
* 管理页为 true(全部展示,停用项灰显)。
*/
export function buildTreeFromMerged(
merged: MergedMenuNode[],
includeDisabled = false,
): MenuItem[] {
const parentOf = new Map(merged.map((n) => [n.id, n.parentId ?? null]));
const disabledIds = new Set(merged.filter((n) => n.disabled).map((n) => n.id));
// 停用节点本身或任一祖先被停用 → 整棵子树隐藏(渲染侧边栏时)。
const isHidden = (id: string): boolean => {
let cursor: string | null = id;
const seen = new Set<string>();
while (cursor) {
if (disabledIds.has(cursor)) return true;
if (seen.has(cursor)) break;
seen.add(cursor);
cursor = parentOf.get(cursor) ?? null;
}
return false;
};
const visible = includeDisabled ? merged : merged.filter((n) => !isHidden(n.id));
const visibleIds = new Set(visible.map((n) => n.id));
const childrenOf = new Map<string | null, MergedMenuNode[]>();
for (const node of visible) {
// parentId 指向不存在/已隐藏的节点 → 回落到一级(数据安全网,正常数据不会触发)。
const key = node.parentId != null && visibleIds.has(node.parentId) ? node.parentId : null;
const list = childrenOf.get(key) ?? [];
list.push(node);
childrenOf.set(key, list);
}
const assemble = (parentId: string | null): MenuItem[] => {
const list = (childrenOf.get(parentId) ?? [])
.slice()
.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
return list.map((node) => {
const children = assemble(node.id);
const base: MenuItem = { ...node.source, label: node.label };
if (children.length) {
base.children = children;
} else if (base.children) {
// 原本有 children 但全被过滤/移走:保留空数组以维持「分组」语义。
base.children = [];
}
return base;
});
};
return assemble(null);
}
/** 应用覆盖层并返回供侧边栏渲染的菜单树(停用项已剔除)。 */
export function applyMenuOverrides(items: MenuItem[], overrides: MenuOverride[]): MenuItem[] {
if (!overrides.length) return items;
const merged = mergeFlatNodes(flattenMenu(items), overrides);
return buildTreeFromMerged(merged, false);
}
// ── 管理页编辑辅助 ──────────────────────────────────────────────────────
/** 计算某节点在「父级映射」下的深度(1=一级)。检测到环时返回 Infinity。 */
export function depthOf(nodeId: string, parentOf: Map<string, string | null>): number {
let depth = 1;
const seen = new Set<string>([nodeId]);
let cursor = parentOf.get(nodeId) ?? null;
while (cursor) {
depth += 1;
if (seen.has(cursor)) return Infinity;
seen.add(cursor);
cursor = parentOf.get(cursor) ?? null;
}
return depth;
}
/** 某节点子树的最大相对高度(叶子=1)。用于判断移动后是否超 3 级。 */
export function subtreeHeight(nodeId: string, childrenMap: Map<string | null, string[]>): number {
const kids = childrenMap.get(nodeId) ?? [];
if (!kids.length) return 1;
return 1 + Math.max(...kids.map((k) => subtreeHeight(k, childrenMap)));
}
/**
* 把 `nodeId` 移到 `targetParentId`(null=一级)后,是否会超过 3 级。
* = 目标父级深度 + 被移动子树的高度 > MAX_MENU_DEPTH。
*/
export function wouldExceedDepth(
nodeId: string,
targetParentId: string | null,
merged: MergedMenuNode[],
): boolean {
const parentOf = new Map(merged.map((n) => [n.id, n.parentId]));
const childrenMap = new Map<string | null, string[]>();
for (const n of merged) {
const key = n.parentId ?? null;
const list = childrenMap.get(key) ?? [];
list.push(n.id);
childrenMap.set(key, list);
}
const parentDepth = targetParentId == null ? 0 : depthOf(targetParentId, parentOf);
if (parentDepth === Infinity) return true;
const height = subtreeHeight(nodeId, childrenMap);
return parentDepth + height > MAX_MENU_DEPTH;
}
/** 目标父级是否落在被移动节点自身的子树内(禁止把节点移进自己的后代)。 */
export function isDescendant(
nodeId: string,
candidateParentId: string | null,
merged: MergedMenuNode[],
): boolean {
if (candidateParentId == null) return false;
const parentOf = new Map(merged.map((n) => [n.id, n.parentId]));
let cursor: string | null = candidateParentId;
const seen = new Set<string>();
while (cursor) {
if (cursor === nodeId) return true;
if (seen.has(cursor)) break;
seen.add(cursor);
cursor = parentOf.get(cursor) ?? null;
}
return false;
}
/**
* 把当前合并节点与代码默认值求差,得到需要持久化的最小覆盖集。
* 只有「改名 / 停用 / 父级变化 / 同级次序变化」的节点才入库。
*/
export function diffOverrides(merged: MergedMenuNode[]): MenuOverride[] {
// 同级内按 order 排序后重排为紧凑索引,便于和 defaultIndex 比较。
const siblings = new Map<string | null, MergedMenuNode[]>();
for (const n of merged) {
const key = n.parentId ?? null;
const list = siblings.get(key) ?? [];
list.push(n);
siblings.set(key, list);
}
const compactIndex = new Map<string, number>();
for (const list of siblings.values()) {
list
.slice()
.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
.forEach((n, i) => compactIndex.set(n.id, i));
}
const out: MenuOverride[] = [];
for (const n of merged) {
const idx = compactIndex.get(n.id) ?? n.order;
const renamed = n.label !== n.defaultLabel;
const reparented = (n.parentId ?? null) !== (n.defaultParentId ?? null);
const reordered = idx !== n.defaultIndex;
if (!renamed && !reparented && !n.disabled && !reordered) continue;
out.push({
nodeId: n.id,
parentId: n.parentId ?? null,
sortOrder: idx,
label: renamed ? n.label : null,
disabled: n.disabled,
});
}
return out;
}
+372 -353
View File
@@ -1,353 +1,372 @@
/**
* 全局侧边栏菜单数据与权限过滤逻辑。
*
* 浅色 ``PageSidebar`` 和深色 ``PageSidebarDark`` 共用这份数据 —— 菜单结构与
* adminOnly 权限策略对两种皮肤完全一致;UI 渲染(icon 显示/折叠样式/hover flyout)
* 在各自组件里实现。
*
* 修改菜单只需改这一处,两个 sidebar 自动同步。
*/
import type { ElementType } from "react";
import {
Activity,
BookOpen,
Bot,
Brain,
Briefcase,
CalendarClock,
CircleHelp,
ClipboardList,
Database,
FileBox,
FileText,
Gauge,
Grid3X3,
HelpCircle,
History,
Layers,
Layout,
Library,
List,
ListChecks,
ListTodo,
Network,
Radar,
Settings,
Sparkles,
Target,
Trophy,
Users,
} from "lucide-react";
export type MenuItem = {
id: string;
label: string;
icon: ElementType;
path?: string;
/** 非 admin 用户使用的路由(菜单对普通用户可见时生效,与简洁模式公开排行榜一致) */
userPath?: string;
adminOnly?: boolean;
children?: MenuItem[];
};
export const sidebarMenuItems: MenuItem[] = [
{
id: "qa-center",
label: "问答管理",
icon: HelpCircle,
children: [
{ id: "general-qa", label: "通用问答", icon: CircleHelp, path: "/page/workspace/chats/new" },
{
id: "multi-agent-roundtable",
label: "多智能体会商",
icon: Users,
path: "/page/strategy/qa/multi-agent-roundtable",
},
// { id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
{
id: "qa-zzjc",
label: "JC支持",
icon: Bot,
path: "/page/strategy/qa/zzjc",
},
{ id: "qa-zzxd", label: "XD应用", icon: Layout, path: "/page/strategy/qa/zzxd" },
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
],
},
{
id: "task-management",
label: "任务管理",
icon: Target,
children: [
{
id: "xk-center-task",
label: "XK中任务",
icon: ClipboardList,
children: [
// {
// id: "xk-task-jc",
// label: "任务JC",
// icon: ListTodo,
// path: "/page/strategy/task-management/xk-task-jc",
// },
// {
// id: "xk-task-dispatch",
// label: "任务调度",
// icon: ListTodo,
// path: "/page/strategy/task-management/xk-task-dispatch",
// },
],
},
{
id: "coh-center-task",
label: "COH中任务",
icon: Activity,
children: [
// {
// id: "coh-task-3qfx",
// label: "3QFX",
// icon: ListTodo,
// path: "/page/strategy/task-management/plan-task-sentiment",
// },
// {
// id: "coh-task-fx",
// label: "任务FX",
// icon: ListTodo,
// path: "/page/strategy/task-management/plan-task/plan-task-fx",
// },
// {
// id: "coh-task-xdfx",
// label: "XDFX",
// icon: ListTodo,
// path: "/page/strategy/task-management/plan-task/plan-task-action",
// },
],
},
{
id: "pg-center-task",
label: "PG中任务",
icon: Gauge,
children: [
// {
// id: "pg-task-pg",
// label: "任务PG",
// icon: ListTodo,
// path: "/page/strategy/task-management/effect-task-pg",
// },
// {
// id: "pg-task-xdpg",
// label: "XDPG",
// icon: ListTodo,
// path: "/page/strategy/task-management/effect-action-pg",
// },
// {
// id: "pg-task-info-pg",
// label: "信息PG",
// icon: ListTodo,
// path: "/page/strategy/task-management/effect-info-pg",
// },
],
},
{
id: "ty-center-task",
label: "TY中任务",
icon: Radar,
children: [
// {
// id: "ty-task-xdty",
// label: "XDTY任务",
// icon: ListTodo,
// path: "/page/strategy/task-management/mnty-task-mechanism",
// },
// {
// id: "ty-task-plan",
// label: "方案TY任务",
// icon: ListTodo,
// path: "/page/strategy/task-management/mnty-task-plan",
// },
// {
// id: "ty-task-xxty",
// label: "XXTY任务",
// icon: ListTodo,
// path: "/page/strategy/task-management/mnty-task-zsty",
// },
],
},
],
},
{
id: "light-app-center",
label: "应用中心",
icon: Grid3X3,
children: [
{
id: "light-app-management",
label: "应用管理",
icon: Layout,
path: "/page/strategy/light-app/management",
adminOnly: true,
},
{
id: "light-app-apps",
label: "应用列表",
icon: List,
path: "/page/strategy/light-app/apps",
},
],
},
{
id: "comprehensive-management",
label: "综合管理",
icon: Settings,
children: [
{
id: "mgmt-user-leaderboard",
label: "用户排行榜",
icon: Trophy,
path: "/page/strategy/admin/user-leaderboard",
userPath: "/page/strategy/user-leaderboard",
},
{ id: "mgmt-agents", label: "智能体管理", icon: Bot, path: "/page/strategy/agents" },
{
id: "mgmt-business-chain-mapping",
label: "配置管理",
icon: Network,
path: "/page/strategy/business-chain-mapping",
},
{
id: "mgmt-business-chains",
label: "业务链条配置",
icon: Layers,
path: "/page/strategy/business-chains",
},
{ id: "mgmt-skills", label: "技能管理", icon: Sparkles, path: "/page/strategy/skills" },
{ id: "mgmt-memory", label: "记忆管理", icon: Brain, path: "/page/strategy/memory" },
{
id: "mgmt-tasks",
label: "定时任务",
icon: ListChecks,
path: "/page/strategy/scheduled/tasks",
},
{
id: "mgmt-llm-metrics",
label: "大模型调用统计",
icon: Gauge,
path: "/page/strategy/settings/llm-metrics",
adminOnly: true,
},
{
id: "mgmt-users",
label: "用户管理",
icon: Users,
path: "/page/strategy/admin/users",
adminOnly: true,
},
{
id: "mgmt-positions",
label: "岗位管理",
icon: Briefcase,
path: "/page/strategy/admin/positions",
adminOnly: true,
},
{
id: "mgmt-admin-scheduled-tasks",
label: "定时任务管理",
icon: CalendarClock,
path: "/page/strategy/admin/scheduled-tasks",
adminOnly: true,
},
{
id: "mgmt-user-activity",
label: "用户活动审计",
icon: History,
path: "/page/strategy/admin/user-activity",
adminOnly: true,
},
],
},
{
id: "resource-management",
label: "资源管理",
icon: Database,
children: [
// {
// id: "resource-network-xwt",
// label: "网络xwt资源管理",
// icon: Network,
// path: "/page/strategy/resource-management/resource-network-actor",
// },
{
id: "resource-knowledge-native",
label: "问答梳理",
icon: BookOpen,
path: "/page/workspace/knowledge",
},
{
id: "resource-knowledge-base",
label: "知识库资源管理",
icon: Library,
path: "/page/strategy/resource-management/resource-knowledge-base",
},
// {
// id: "resource-evaluation-index",
// label: "作战资源管理",
// icon: FileBox,
// path: "/page/strategy/resource-management/resource-evaluation-index",
// },
],
},
];
/** 默认展开的菜单 id 集合(浅色版可折叠交互的初始状态) */
export const defaultExpandedIds: ReadonlySet<string> = new Set([
"qa-center",
"light-app-center",
"light-app-note-management",
"task-management",
"xk-center-task",
"comprehensive-management",
]);
/** 该菜单项自身或任意后代的 path 是否匹配当前路由(支持子路径,如 /knowledge/:id) */
export function menuItemContainsPath(item: MenuItem, pathname: string): boolean {
if (item.path && (pathname === item.path || pathname.startsWith(item.path + "/"))) {
return true;
}
return item.children?.some((child) => menuItemContainsPath(child, pathname)) ?? false;
}
/**
* 在「一级 → 二级 → 三级」菜单中,取当前路由所在的「激活二级项」的三级子项。
* 浅色侧边栏据此在二级右侧展开三级列;深色顶栏据此渲染三级横条。
* 全量模式:三级仅一项时不返回(无选择必要,侧边栏保持窄栏 / 不渲染横条)。
*/
export function getActiveThirdLevelItems(
items: MenuItem[],
pathname: string,
): MenuItem[] {
const activeTop =
items.find((item) => menuItemContainsPath(item, pathname)) ?? items[0];
const secondary = activeTop?.children ?? [];
const activeSecond = secondary.find(
(item) => (item.children?.length ?? 0) > 0 && menuItemContainsPath(item, pathname),
);
const third = activeSecond?.children ?? [];
return third.length <= 1 ? [] : third;
}
/** 按 admin 角色过滤菜单:非 admin 不展示 ``adminOnly: true`` 的项;``userPath`` 替换 ``path``。 */
export function filterMenuItemsByRole(items: MenuItem[], isAdmin: boolean): MenuItem[] {
return items
.filter((item) => !item.adminOnly || isAdmin)
.map((item) => {
const children = item.children
? filterMenuItemsByRole(item.children, isAdmin)
: undefined;
const base = children ? { ...item, children } : item;
if (!isAdmin && base.userPath) {
const { userPath: _userPath, ...rest } = base;
return { ...rest, path: base.userPath };
}
return base;
});
}
/**
* 全局侧边栏菜单数据与权限过滤逻辑。
*
* 浅色 ``PageSidebar`` 和深色 ``PageSidebarDark`` 共用这份数据 —— 菜单结构与
* adminOnly 权限策略对两种皮肤完全一致;UI 渲染(icon 显示/折叠样式/hover flyout)
* 在各自组件里实现。
*
* 修改菜单只需改这一处,两个 sidebar 自动同步。
*/
import type { ElementType } from "react";
import {
Activity,
BookOpen,
Bot,
Brain,
Briefcase,
CalendarClock,
CircleHelp,
ClipboardList,
Database,
FileBox,
FileText,
Gauge,
Grid3X3,
HelpCircle,
History,
Layers,
Layout,
Library,
List,
ListChecks,
ListTodo,
Network,
Radar,
Settings,
Sparkles,
Target,
Trophy,
Users,
} from "lucide-react";
export type MenuItem = {
id: string;
label: string;
icon: ElementType;
path?: string;
/** 额外视为「当前页属于本菜单项」的路由(不在侧栏展示,仅用于高亮)。 */
aliasPaths?: string[];
/** 非 admin 用户使用的路由(菜单对普通用户可见时生效,与简洁模式公开排行榜一致) */
userPath?: string;
adminOnly?: boolean;
children?: MenuItem[];
};
export const sidebarMenuItems: MenuItem[] = [
{
id: "qa-center",
label: "问答管理",
icon: HelpCircle,
children: [
{ id: "general-qa", label: "通用问答", icon: CircleHelp, path: "/page/workspace/chats/new" },
{
id: "multi-agent-roundtable",
label: "多智能体会商",
icon: Users,
path: "/page/strategy/qa/multi-agent-roundtable",
},
{
id: "dashboard-agent",
label: "大屏绘制",
icon: Gauge,
path: "/page/strategy/dashboard-agent",
},
// { id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
{
id: "qa-zzjc",
label: "JC支持",
icon: Bot,
path: "/page/strategy/qa/zzjc",
},
{ id: "qa-zzxd", label: "XD应用", icon: Layout, path: "/page/strategy/qa/zzxd" },
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
],
},
{
id: "task-management",
label: "任务管理",
icon: Target,
children: [
{
id: "xk-center-task",
label: "XK中任务",
icon: ClipboardList,
children: [
// {
// id: "xk-task-jc",
// label: "任务JC",
// icon: ListTodo,
// path: "/page/strategy/task-management/xk-task-jc",
// },
// {
// id: "xk-task-dispatch",
// label: "任务调度",
// icon: ListTodo,
// path: "/page/strategy/task-management/xk-task-dispatch",
// },
],
},
{
id: "coh-center-task",
label: "COH中任务",
icon: Activity,
children: [
// {
// id: "coh-task-3qfx",
// label: "3QFX",
// icon: ListTodo,
// path: "/page/strategy/task-management/plan-task-sentiment",
// },
// {
// id: "coh-task-fx",
// label: "任务FX",
// icon: ListTodo,
// path: "/page/strategy/task-management/plan-task/plan-task-fx",
// },
// {
// id: "coh-task-xdfx",
// label: "XDFX",
// icon: ListTodo,
// path: "/page/strategy/task-management/plan-task/plan-task-action",
// },
],
},
{
id: "pg-center-task",
label: "PG中任务",
icon: Gauge,
children: [
// {
// id: "pg-task-pg",
// label: "任务PG",
// icon: ListTodo,
// path: "/page/strategy/task-management/effect-task-pg",
// },
// {
// id: "pg-task-xdpg",
// label: "XDPG",
// icon: ListTodo,
// path: "/page/strategy/task-management/effect-action-pg",
// },
// {
// id: "pg-task-info-pg",
// label: "信息PG",
// icon: ListTodo,
// path: "/page/strategy/task-management/effect-info-pg",
// },
],
},
{
id: "ty-center-task",
label: "TY中任务",
icon: Radar,
children: [
// {
// id: "ty-task-xdty",
// label: "XDTY任务",
// icon: ListTodo,
// path: "/page/strategy/task-management/mnty-task-mechanism",
// },
// {
// id: "ty-task-plan",
// label: "方案TY任务",
// icon: ListTodo,
// path: "/page/strategy/task-management/mnty-task-plan",
// },
// {
// id: "ty-task-xxty",
// label: "XXTY任务",
// icon: ListTodo,
// path: "/page/strategy/task-management/mnty-task-zsty",
// },
],
},
],
},
{
id: "light-app-center",
label: "应用中心",
icon: Grid3X3,
children: [
{
id: "light-app-management",
label: "应用管理",
icon: Layout,
path: "/page/strategy/light-app/management",
adminOnly: true,
},
{
id: "light-app-apps",
label: "应用列表",
icon: List,
path: "/page/strategy/light-app/apps",
},
],
},
{
id: "comprehensive-management",
label: "综合管理",
icon: Settings,
children: [
{
id: "mgmt-user-leaderboard",
label: "用户排行榜",
icon: Trophy,
path: "/page/strategy/admin/user-leaderboard",
userPath: "/page/strategy/user-leaderboard",
},
{ id: "mgmt-agents", label: "智能体管理", icon: Bot, path: "/page/strategy/agents" },
// {
// id: "mgmt-business-chain-mapping",
// label: "配置管理",
// icon: Network,
// path: "/page/strategy/business-chain-mapping",
// },
{
id: "mgmt-business-chains",
label: "业务链条配置",
icon: Layers,
path: "/page/strategy/business-chains",
aliasPaths: ["/page/strategy/business-chain-mapping"],
},
{ id: "mgmt-skills", label: "技能管理", icon: Sparkles, path: "/page/strategy/skills" },
{ id: "mgmt-memory", label: "记忆管理", icon: Brain, path: "/page/strategy/memory" },
{
id: "mgmt-tasks",
label: "定时任务",
icon: ListChecks,
path: "/page/strategy/scheduled/tasks",
},
{
id: "mgmt-llm-metrics",
label: "大模型调用统计",
icon: Gauge,
path: "/page/strategy/settings/llm-metrics",
adminOnly: true,
},
{
id: "mgmt-users",
label: "用户管理",
icon: Users,
path: "/page/strategy/admin/users",
adminOnly: true,
},
{
id: "mgmt-positions",
label: "岗位管理",
icon: Briefcase,
path: "/page/strategy/admin/positions",
adminOnly: true,
},
{
id: "mgmt-admin-scheduled-tasks",
label: "定时任务管理",
icon: CalendarClock,
path: "/page/strategy/admin/scheduled-tasks",
adminOnly: true,
},
{
id: "mgmt-user-activity",
label: "用户活动审计",
icon: History,
path: "/page/strategy/admin/user-activity",
adminOnly: true,
},
],
},
{
id: "resource-management",
label: "资源管理",
icon: Database,
children: [
// {
// id: "resource-network-xwt",
// label: "网络xwt资源管理",
// icon: Network,
// path: "/page/strategy/resource-management/resource-network-actor",
// },
{
id: "resource-knowledge-native",
label: "问答梳理",
icon: BookOpen,
path: "/page/workspace/knowledge",
},
{
id: "resource-knowledge-base",
label: "知识库资源管理",
icon: Library,
path: "/page/strategy/resource-management/resource-knowledge-base",
},
// {
// id: "resource-evaluation-index",
// label: "作战资源管理",
// icon: FileBox,
// path: "/page/strategy/resource-management/resource-evaluation-index",
// },
],
},
];
/** 默认展开的菜单 id 集合(浅色版可折叠交互的初始状态) */
export const defaultExpandedIds: ReadonlySet<string> = new Set([
"qa-center",
"light-app-center",
"light-app-note-management",
"task-management",
"xk-center-task",
"comprehensive-management",
]);
/** 单条路由是否与 pathname 精确匹配或为其子路径。 */
function routeMatchesPathname(pathname: string, route?: string): boolean {
if (!route) return false;
return pathname === route || pathname.startsWith(route + "/");
}
/** 菜单项自身 path / aliasPaths 是否匹配当前路由。 */
export function menuItemMatchesPath(item: MenuItem, pathname: string): boolean {
if (routeMatchesPathname(pathname, item.path)) return true;
return item.aliasPaths?.some((p) => routeMatchesPathname(pathname, p)) ?? false;
}
/** 该菜单项自身或任意后代的 path 是否匹配当前路由(支持子路径,如 /knowledge/:id) */
export function menuItemContainsPath(item: MenuItem, pathname: string): boolean {
if (menuItemMatchesPath(item, pathname)) return true;
return item.children?.some((child) => menuItemContainsPath(child, pathname)) ?? false;
}
/**
* 在「一级 → 二级 → 三级」菜单中,取当前路由所在的「激活二级项」的三级子项。
* 浅色侧边栏据此在二级右侧展开三级列;深色顶栏据此渲染三级横条。
* 全量模式:三级仅一项时不返回(无选择必要,侧边栏保持窄栏 / 不渲染横条)。
*/
export function getActiveThirdLevelItems(
items: MenuItem[],
pathname: string,
): MenuItem[] {
const activeTop =
items.find((item) => menuItemContainsPath(item, pathname)) ?? items[0];
const secondary = activeTop?.children ?? [];
const activeSecond = secondary.find(
(item) => (item.children?.length ?? 0) > 0 && menuItemContainsPath(item, pathname),
);
const third = activeSecond?.children ?? [];
return third.length <= 1 ? [] : third;
}
/** 按 admin 角色过滤菜单:非 admin 不展示 ``adminOnly: true`` 的项;``userPath`` 替换 ``path``。 */
export function filterMenuItemsByRole(items: MenuItem[], isAdmin: boolean): MenuItem[] {
return items
.filter((item) => !item.adminOnly || isAdmin)
.map((item) => {
const children = item.children
? filterMenuItemsByRole(item.children, isAdmin)
: undefined;
const base = children ? { ...item, children } : item;
if (!isAdmin && base.userPath) {
const { userPath: _userPath, ...rest } = base;
return { ...rest, path: base.userPath };
}
return base;
});
}
@@ -12,8 +12,12 @@ import { useLocation } from "react-router-dom";
import { Layout } from "lucide-react";
import { getStoredAuth } from "@/core/auth";
import { desensitize, makeDesensitizer } from "@/lib/desensitize";
import { useLightApps, type LightApp } from "@/strategy-components/api/light-apps";
import { useMenuOverrides } from "@/strategy-components/api/menu-overrides";
import { useSensitiveWords, wordsToMap } from "@/strategy-components/api/sensitive-words";
import { applyMenuOverrides } from "./menu-overrides";
import {
filterMenuItemsByRole,
getActiveThirdLevelItems,
@@ -31,7 +35,7 @@ function lightAppLeaf(app: LightApp): MenuItem {
}
/** 在菜单树(不可变克隆)中,把 iframe 应用按 mountLocation 注入对应父节点末尾。 */
function injectLightApps(items: MenuItem[], apps: LightApp[]): MenuItem[] {
export function injectLightApps(items: MenuItem[], apps: LightApp[]): MenuItem[] {
if (apps.length === 0) return items;
const byMount = new Map<string, LightApp[]>();
@@ -56,12 +60,43 @@ function injectLightApps(items: MenuItem[], apps: LightApp[]): MenuItem[] {
return walk(items);
}
/** 返回合并了 iframe 轻应用、并按 admin 角色过滤后的菜单。 */
/** 递归对菜单标签做脱敏(仅改 `label`,path/id/icon 不动,保证高亮与路由不受影响)。 */
function desensitizeLabels(items: MenuItem[], fn: (text: string) => string): MenuItem[] {
return items.map((node) => ({
...node,
label: fn(node.label),
children: node.children ? desensitizeLabels(node.children, fn) : node.children,
}));
}
/**
* 返回合并了 iframe 轻应用、套用了后端「菜单覆盖层」(改名/停用/排序/层级)、
* 按 admin 角色过滤、并对标签做**展示层脱敏**后的菜单。
*
* 管线顺序:静态菜单 → 注入 iframe 轻应用 → 套覆盖层(停用项被剔除)→ 角色过滤 → 标签脱敏。
* 覆盖层作用在合并后的整棵树上,所以 iframe 轻应用节点同样可被改名/停用/移层级。
*
* 脱敏直接用 `/api/sensitive-words` 查询结果构造(后台非空时用其映射,否则回退到内置种子的
* 全局 {@link desensitize}),避免依赖 {@link replaceDesensitizeMap} 的 effect 回灌时序。
*/
export function useSidebarMenuItems(isAdmin: boolean): MenuItem[] {
const { data: iframeApps = [] } = useLightApps({ appType: "iframe", enabledOnly: true });
const { data: overrides = [] } = useMenuOverrides();
const { data: words = [] } = useSensitiveWords();
const desensitizeLabel = useMemo(
() => (words.length > 0 ? makeDesensitizer(wordsToMap(words)) : desensitize),
[words],
);
return useMemo(
() => filterMenuItemsByRole(injectLightApps(sidebarMenuItems, iframeApps), isAdmin),
[iframeApps, isAdmin],
() =>
desensitizeLabels(
filterMenuItemsByRole(
applyMenuOverrides(injectLightApps(sidebarMenuItems, iframeApps), overrides),
isAdmin,
),
desensitizeLabel,
),
[iframeApps, overrides, isAdmin, desensitizeLabel],
);
}
@@ -1,5 +1,7 @@
/** Strategy 模块外部 iframe / 嵌入页链接(来自 Vite 环境变量) */
import { authStorageGet } from "@/core/auth/scoped-storage";
function trimTrailingSlash(url: string): string {
return url.replace(/\/+$/, "");
}
@@ -30,7 +32,7 @@ export function getNetworkActorIframeUrl(): string {
/** 读取并解析 localStorage 中的 userInfo(登录信息)。 */
function readUserInfo(): Record<string, unknown> {
try {
const raw = localStorage.getItem("userInfo");
const raw = authStorageGet("userInfo");
if (!raw) return {};
const parsed = JSON.parse(raw);
return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
+49 -5
View File
@@ -34,6 +34,9 @@ export type ThreadStreamOptions = {
context: LocalSettings["context"];
isMock?: boolean;
assistantId?: string;
/** 额外写到新建 thread 的 metadata(与 agent_id 合并)。
* 任务深链用 `{ taskId }` 把对话挂到任务下(1:N),列表按 metadata.taskId 过滤。 */
threadMetadata?: Record<string, unknown>;
onStart?: (threadId: string) => void;
onFinish?: (state: AgentThreadState) => void;
onToolEnd?: (event: ToolEndEvent) => void;
@@ -118,6 +121,39 @@ function getRunMetadataStorage(): {
};
}
/**
* 显式停止某会话「服务端正在跑」的 run。
*
* 注意:useStream / `thread.stop()` 只中断本地 SSE 监听,服务端 run 仍会继续跑。
* 任务流程要求「开启新对话时老对话要停止」,所以这里读出 SDK 存在 sessionStorage
* (``lg:stream:{threadId}``)里的 run id,调用 ``runs.cancel`` 真正取消后端 run,
* 再清掉本地 reconnect 记录。已结束 / 不存在的 run 取消失败时静默忽略。
*/
export async function stopThreadRun(
threadId: string | null | undefined,
): Promise<void> {
if (!threadId || typeof window === "undefined") return;
let runId: string | null = null;
try {
runId = normalizeStoredRunId(
window.sessionStorage.getItem(`lg:stream:${threadId}`),
);
} catch {
runId = null;
}
if (!runId) return;
try {
await getAPIClient().runs.cancel(threadId, runId);
} catch {
/* 已结束 / 不存在 / 网络错误等忽略 */
}
try {
window.sessionStorage.removeItem(`lg:stream:${threadId}`);
} catch {
/* noop */
}
}
function getStreamErrorMessage(error: unknown): string {
if (typeof error === "string" && error.trim()) {
return error;
@@ -200,6 +236,7 @@ export function useThreadStream({
context,
isMock,
assistantId,
threadMetadata,
onStart,
onFinish,
onToolEnd,
@@ -277,11 +314,15 @@ export function useThreadStream({
handleStreamStart(meta.thread_id);
setOnStreamThreadId(meta.thread_id);
const metadataAgentId = context.agent_id ?? context.agent_name;
if (metadataAgentId && !isMock) {
const extraMetadata =
threadMetadata && typeof threadMetadata === "object" ? threadMetadata : {};
const metadata: Record<string, unknown> = {
...(metadataAgentId ? { agent_id: metadataAgentId } : {}),
...extraMetadata,
};
if (Object.keys(metadata).length > 0 && !isMock) {
void getAPIClient()
.threads.update(meta.thread_id, {
metadata: { agent_id: metadataAgentId },
})
.threads.update(meta.thread_id, { metadata })
.catch(() => ({}));
}
},
@@ -744,7 +785,10 @@ export function useThreadStream({
} as typeof thread)
: thread;
return [mergedThread, sendMessage, isUploading] as const;
// 第 4 个返回值 `onStreamThreadId` = 底层 useStream 当前实际绑定的线程 id(新建/未保存时为 null)。
// 调用方据此判断「流是否已切到全新线程」,避免在切换会话的那一帧把消息发进上一个会话
// (submit 的 threadId 选项仅在 hook 线程为 null/undefined 时才生效)。
return [mergedThread, sendMessage, isUploading, onStreamThreadId] as const;
}
export function useThreads(
@@ -0,0 +1,98 @@
import { toast } from "sonner";
import { getStoredAuth } from "@/core/auth";
/**
* Shared helpers for re-framing LangGraph "thread not accessible" 404s around
* the current login identity.
*
* The most common cause in practice is a login session change: a thread is
* owned by the previously logged-in account, so after switching accounts the
* backend (``app/gateway/authz.py``) correctly returns
* ``HTTP 404: {"detail":"Thread <uuid> not accessible"}``. Raw-toasting that
* 404 just leaves the user staring at a scary error. Both the chat stream
* (``core/threads/hooks.ts``) and the AI-writing stream
* (``open-canvas/contexts/AIWritingContext.tsx``) funnel their stream errors
* through here so the UX is identical: detect the login-change 404 and prompt
* the user to refresh against the current identity instead of erroring out.
*/
/** Normalize an unknown stream error into a human-readable message string. */
export function getStreamErrorMessage(error: unknown): string {
if (typeof error === "string" && error.trim()) {
return error;
}
if (error instanceof Error && error.message.trim()) {
return error.message;
}
if (typeof error === "object" && error !== null) {
const message = Reflect.get(error, "message");
if (typeof message === "string" && message.trim()) {
return message;
}
const nestedError = Reflect.get(error, "error");
if (nestedError instanceof Error && nestedError.message.trim()) {
return nestedError.message;
}
if (typeof nestedError === "string" && nestedError.trim()) {
return nestedError;
}
}
return "Request failed.";
}
/**
* Detect "thread not found" / forbidden errors from the LangGraph SDK.
*
* Backend returns 404 both when a thread truly doesn't exist and when the
* currently authenticated user doesn't own it ("not found" = no row + no
* checkpoint, "not accessible" = row owned by another user / stale login
* session). Both mean the current user can't use this thread.
*/
export function isThreadNotAccessibleError(message: string): boolean {
const lowered = message.toLowerCase();
if (/thread\s+[\w-]{8,}\s+not\s+(found|accessible)/i.test(message)) {
return true;
}
// Fallback: a bare 404/403 from the threads endpoint when the SDK has
// wrapped the detail differently.
return (
(lowered.includes("http 404") || lowered.includes("http 403")) &&
lowered.includes("thread")
);
}
/** Build a label for the *current* logged-in identity (email → user_id → 未知). */
export function buildCurrentUserLabel(): string {
const auth = getStoredAuth();
if (!auth) {
return "未登录";
}
const email = auth.email?.trim();
if (email) {
return email;
}
const userId = auth.user_id?.trim();
return userId ? userId : "未知用户";
}
/**
* Re-frame a login-change 404 around the current identity and reload the page.
*
* Shows a friendly toast naming the current login, then full-reloads after a
* short delay so the toast is visible and so TanStack Query cache / context
* providers / any state captured under the previous user get rebuilt against
* the current login. Used by streams whose session id lives in component state
* (not the URL) — a plain reload lands them back on a fresh, valid page.
*/
export function notifyThreadAccessChangedAndReload(): void {
const userLabel = buildCurrentUserLabel();
toast.info(
`当前登录用户为 ${userLabel},原会话不存在或无权访问,正在为你刷新页面…`,
);
if (typeof window !== "undefined") {
window.setTimeout(() => {
window.location.reload();
}, 900);
}
}
@@ -0,0 +1,37 @@
/**
* 「一个任务挂多个对话」(1:N):按 thread 的 ``metadata.taskId`` 过滤出某任务下的对话列表。
*
* 新建对话时由 [[task-purpose]] 流程给 thread 打 ``metadata.taskId`` 标签
* (见 useThreadStream 的 ``threadMetadata``);这里复用服务端分页搜索按该标签过滤,
* 后端默认按 ``updated_at desc`` 排序,所以 ``threads[0]`` 即最新一条。
*
* 同一个 taskId 可能挂在多条业务链上(rwfx / 3qfx / xdfx 共用任务 id),每条业务用各自的
* 智能体。传入 ``agentId`` 时额外按 ``metadata.agent_id`` 过滤(后端 metadata 过滤是 AND/子集
* 匹配),把不同业务的对话列表隔离开——否则三种业务的对话会混在一起。
*/
import { useThreadsPage } from "@/core/threads/hooks";
import type { AgentThread } from "@/core/threads/types";
export function useTaskThreads(
taskId: string | null | undefined,
agentId?: string | null | undefined,
) {
const enabled = !!taskId;
// 任务工作区只在有 taskId 时渲染;无 taskId 时传一个不可能命中的过滤,返回空列表。
const metadata = enabled
? agentId
? { taskId, agent_id: agentId }
: { taskId }
: { taskId: "__none__" };
const query = useThreadsPage({ page: 1, pageSize: 100, metadata });
const threads: AgentThread[] = enabled ? (query.data?.threads ?? []) : [];
return {
...query,
threads,
/** 最新对话(按 updated_at desc,列表第一条)。 */
latestThreadId: threads[0]?.thread_id ?? null,
/** 是否已有历史对话(决定深链进入后默认开最新还是走新建闸门)。 */
hasThreads: threads.length > 0,
};
}
+52 -3
View File
@@ -1,9 +1,20 @@
/**
* 脱敏词映射表
* 脱敏词「种子」映射表(前端内置)。
* key: 原始词(支持正则特殊字符,会被转义)
* value: 脱敏后替换词
*
* 这份常量是**部署种子**:新机器首次启动、后台还没有任何敏感词时,运行时直接用它;
* 管理员也可在「敏感词管理」页一键「导入种子词」把它写入后台。线上以后台配置为准
* (见 {@link replaceDesensitizeMap}),后台为空时回退到这份种子。
*
* 注意:请勿在运行时修改本对象——它要保持与「出厂种子」一致。运行时可变映射见
* {@link DESENSITIZE_MAP}。
*/
export const DESENSITIZE_MAP: Record<string, string> = {
export const SEED_DESENSITIZE_MAP: Readonly<Record<string, string>> = Object.freeze({
// 任务工作区业务名 → 业务码(脱敏展示)。整词在前,优先于下面更短的「任务」「行动」匹配。
任务分析: "rwfx",
三情分析: "3qfx",
行动分析: "xdfx",
方案: "FA",
设计: "SJ",
任务: "RW",
@@ -44,8 +55,15 @@ export const DESENSITIZE_MAP: Record<string, string> = {
军: "J",
美军: "MJ",
台军: "TJ",
});
};
/**
* 运行时实际生效的脱敏词映射表(可变)。
*
* 初始为 {@link SEED_DESENSITIZE_MAP} 的浅拷贝(保证后台数据加载前 `desensitize`
* 立即可用);应用启动后由 {@link replaceDesensitizeMap} 用后台配置整体替换。
*/
export const DESENSITIZE_MAP: Record<string, string> = { ...SEED_DESENSITIZE_MAP };
/**
* 将 DESENSITIZE_MAP 编译为单个正则,避免多次遍历字符串。
@@ -75,6 +93,22 @@ export function desensitize(text: string): string {
return text.replace(_regex, (matched) => DESENSITIZE_MAP[matched] ?? matched);
}
/**
* 用**指定映射**(而非全局 {@link DESENSITIZE_MAP})构造一个脱敏函数。
*
* 适用于「数据加载完就要立即用其结果脱敏、不能依赖全局 map 的异步回灌时序」的场景
* (如侧边栏/导航栏菜单:直接用 `/api/sensitive-words` 查询结果计算标签,避免与
* {@link replaceDesensitizeMap} 的 effect 时序竞态)。正则在构造时编译一次,可缓存复用。
*
* @param map 原始词 → 替换词
* @returns `(text) => 脱敏后文本`;map 为空时返回恒等函数
*/
export function makeDesensitizer(map: Record<string, string>): (text: string) => string {
const regex = buildRegex(map);
if (!regex) return (text) => text;
return (text) => text.replace(regex, (matched) => map[matched] ?? matched);
}
/**
* 深度脱敏:递归遍历对象 / 数组,对其中所有字符串值做 {@link desensitize},
* 其余类型原样保留。返回**新值**(不修改入参),用于对结构化数据(如大屏 report-json
@@ -107,3 +141,18 @@ export function addDesensitizeEntries(entries: Record<string, string>): void {
Object.assign(DESENSITIZE_MAP, entries);
_regex = buildRegex(DESENSITIZE_MAP);
}
/**
* 用后台配置**整体替换**运行时脱敏词映射表,替换后自动重编译正则。
*
* 与 {@link addDesensitizeEntries} 不同,本函数会先清空现有词条,因此后台里被
* 删除的词不会因为还残留在种子里而继续生效。应用启动时拉取
* `/api/sensitive-words` 后调用;若后台为空则不调用,保持使用种子。
*
* @param entries 后台返回的「启用」词条,格式同 {@link DESENSITIZE_MAP}
*/
export function replaceDesensitizeMap(entries: Record<string, string>): void {
for (const key of Object.keys(DESENSITIZE_MAP)) delete DESENSITIZE_MAP[key];
Object.assign(DESENSITIZE_MAP, entries);
_regex = buildRegex(DESENSITIZE_MAP);
}
+12 -7
View File
@@ -1,15 +1,20 @@
import "@fontsource/noto-sans-sc/chinese-simplified-400.css";
import "@fontsource/noto-sans-sc/chinese-simplified-500.css";
import "@fontsource/noto-sans-sc/chinese-simplified-600.css";
import "@fontsource/noto-sans-sc/chinese-simplified-700.css";
import "./styles/globals.css";
import "tdesign-react/es/style/index.css";
import "katex/dist/katex.min.css";
import "@fontsource/noto-sans-sc/chinese-simplified-400.css";
import "@fontsource/noto-sans-sc/chinese-simplified-500.css";
import "@fontsource/noto-sans-sc/chinese-simplified-600.css";
import "@fontsource/noto-sans-sc/chinese-simplified-700.css";
import "./styles/globals.css";
import "tdesign-react/es/style/index.css";
import "katex/dist/katex.min.css";
import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./App";
import { syncEmbedSessionFromCurrentUrl } from "@/core/embed/embed-session";
// 渲染前同步启用「iframe 嵌入会话」(按标签页 sessionStorage):必须早于任何鉴权写入,
// 使 iframe 嵌入态的登录走 sessionStorage、与同浏览器正常登录(localStorage)完全隔离。
syncEmbedSessionFromCurrentUrl();
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
@@ -87,6 +87,50 @@ export async function deleteAIWritingSession(id: string): Promise<void> {
if (!resp.ok) throw new Error(`删除失败: ${resp.status}`);
}
/**
* 把一篇写作转入「后台挂起」:后端自动驱动剩余流程到定稿(离页/刷新/切号不打断)。
*
* 幂等——同一会话已在后台跑则后端直接返回 ``started:false``。
*/
export async function suspendAIWritingToBackground(
id: string,
): Promise<{ started: boolean; status: string }> {
const resp = await apiFetch(`${BASE()}/${id}/background`, { method: 'POST' });
if (!resp.ok) throw new Error(`后台挂起失败: ${resp.status}`);
return resp.json();
}
/** 一篇写作的实际进度(供「查看进度」流程图弹窗轮询)。 */
export interface AIWritingProgress {
sessionStatus: string;
/** 规范化阶段 key(与流程图阶段一一对应);null = 还没建 checkpoint。 */
stage: string | null;
note: string | null;
revisionCount: number;
maxRevisions: number;
reviewVerdict: string | null;
isRunning: boolean;
}
export async function getAIWritingProgress(id: string): Promise<AIWritingProgress> {
const resp = await apiFetch(`${BASE()}/${id}/progress`);
if (!resp.ok) throw new Error(`获取进度失败: ${resp.status}`);
return resp.json();
}
/**
* beforeunload 兜底:离开/刷新页面时用 keepalive 发起后台挂起,
* 保证浏览器卸载页面后请求仍能发完。fire-and-forget,不读响应;
* 重复触发由后端「同会话已在后台跑」幂等兜住。
*/
export function suspendAIWritingToBackgroundKeepalive(id: string): void {
try {
void apiFetch(`${BASE()}/${id}/background`, { method: 'POST', keepalive: true }).catch(() => {});
} catch {
/* 卸载阶段尽力而为,忽略一切异常 */
}
}
/**
* 保存会话的完整对话时间线,供历史回显出与实时对话一致的富时间线。
*
@@ -0,0 +1,138 @@
/**
* AI 写作流程图(竖向固定流水线)。
*
* 写作流程是固定线性流水线:意图理解 → 素材搜集 → 素材确认 → 大纲规划 → 大纲确认 →
* 写作 → 草稿确认 → 编辑审核 → 定稿。按传入的 ``activeKey``(后端从 graph checkpoint
* 推导的当前阶段 key)点亮:已过=done 打钩、当前=active 转圈、未到=灰。
*
* 纯展示组件,无弹窗/无窗口 chrome —— 由 ``AIWritingFlowDialog`` 套在弹窗里使用。
*/
import { CheckIcon, Loader2Icon } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface FlowStage {
key: string;
label: string;
emoji: string;
}
/** 固定流水线阶段(key 与后端 ai_writing_job_executor 的 stage key 一致)。 */
export const FLOW_STAGES: readonly FlowStage[] = [
{ key: 'intent', label: '意图理解', emoji: '🧭' },
{ key: 'research', label: '素材搜集', emoji: '🔍' },
{ key: 'material_confirm', label: '素材确认', emoji: '📚' },
{ key: 'outline', label: '大纲规划', emoji: '🗂️' },
{ key: 'outline_confirm', label: '大纲确认', emoji: '🧩' },
{ key: 'draft', label: '写作', emoji: '✍️' },
{ key: 'draft_confirm', label: '草稿确认', emoji: '📝' },
{ key: 'review', label: '编辑审核', emoji: '🧐' },
{ key: 'done', label: '定稿', emoji: '🏁' },
];
export const FLOW_STAGE_LABEL: Record<string, string> = Object.fromEntries(
FLOW_STAGES.map((s) => [s.key, s.label]),
);
type StageState = 'pending' | 'active' | 'done' | 'error';
const LINE = 'bg-slate-300 dark:bg-border';
function StageNode({
label,
emoji,
state,
note,
}: {
label: string;
emoji: string;
state: StageState;
note?: string | null;
}) {
return (
<div className="flex shrink-0 flex-col items-center gap-1 px-0.5 text-center">
<div className="relative flex size-11 items-center justify-center">
{state === 'active' && <span className="absolute inset-0 animate-ping rounded-full bg-primary/25" />}
<span
className={cn(
'relative flex size-11 items-center justify-center rounded-full border-2 bg-white text-lg transition-all dark:bg-card',
state === 'active' && 'border-primary shadow-[0_0_0_3px_rgba(22,119,255,0.12)]',
state === 'done' && 'border-emerald-400/70',
state === 'error' && 'border-destructive',
state === 'pending' && 'border-border opacity-45 grayscale',
)}
>
{emoji}
{state === 'done' && (
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-emerald-500 text-white shadow">
<CheckIcon className="size-2.5" />
</span>
)}
{state === 'active' && (
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-primary text-primary-foreground shadow">
<Loader2Icon className="size-2.5 animate-spin" />
</span>
)}
</span>
</div>
<span
className={cn(
'whitespace-nowrap rounded border px-1 py-px text-[10px] font-medium leading-tight',
state === 'active' && 'border-primary/40 bg-primary/10 text-primary',
state === 'done' && 'border-emerald-400/40 bg-emerald-50 text-emerald-600 dark:bg-emerald-950/30',
state === 'error' && 'border-destructive/40 bg-destructive/10 text-destructive',
state === 'pending' && 'border-border bg-muted text-muted-foreground',
)}
title={label}
>
{label}
</span>
{note && state === 'active' && (
<span className="rounded bg-amber-100 px-1 py-px text-[9px] font-medium text-amber-600 dark:bg-amber-950/30">
{note}
</span>
)}
</div>
);
}
export function AIWritingFlowChart({
activeKey,
isError = false,
note,
className,
}: {
/** 当前阶段 key(null = 还没开始 / 准备中,全部置灰)。 */
activeKey: string | null;
isError?: boolean;
note?: string | null;
className?: string;
}) {
const allDone = activeKey === 'done';
const activeIdx = activeKey ? FLOW_STAGES.findIndex((s) => s.key === activeKey) : -1;
const stateOf = (idx: number): StageState => {
if (allDone) return 'done';
if (activeIdx < 0) return 'pending';
if (idx < activeIdx) return 'done';
if (idx === activeIdx) return isError ? 'error' : 'active';
return 'pending';
};
return (
// 横向流水线:左→右排列,节点间用横向连线(对齐到圆形头像竖直中心 ≈ 22px)。
// w-max 保持内容固有宽度,由外层 overflow-x-auto 在放不下时横向滚动。
<div className={cn('flex w-max flex-row items-start', className)}>
{FLOW_STAGES.map((stage, idx) => (
<div className="contents" key={stage.key}>
{idx > 0 && <div className={cn('mt-[22px] h-px w-5 shrink-0', LINE)} />}
<StageNode
label={stage.label}
emoji={stage.emoji}
state={stateOf(idx)}
note={stage.key === activeKey ? note : undefined}
/>
</div>
))}
</div>
);
}
@@ -0,0 +1,124 @@
/**
* 「查看进度」流程图弹窗。
*
* 在历史记录里点击一条**后台挂起中**的写作 → 弹出本弹窗,里面是写作流程图,
* 实时(轮询)反映该会话后端的实际推进位置,让用户看到「跑到哪一步了」。
*/
import { useEffect, useRef, useState } from 'react';
import { Loader2 } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
getAIWritingProgress,
type AIWritingProgress,
type AIWritingSessionSummary,
} from '../../api/ai-writing-sessions';
import { AIWritingFlowChart, FLOW_STAGE_LABEL } from './AIWritingFlowChart';
const POLL_MS = 2500;
function isTerminal(p: AIWritingProgress | null): boolean {
if (!p) return false;
return p.sessionStatus === 'done' || p.sessionStatus === 'error' || p.stage === 'done';
}
export function AIWritingFlowDialog({
session,
open,
onOpenChange,
}: {
session: AIWritingSessionSummary | null;
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const [progress, setProgress] = useState<AIWritingProgress | null>(null);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
if (!open || !session) return;
let cancelled = false;
setProgress(null);
setFetchError(false);
setLoading(true);
const tick = async () => {
try {
const p = await getAIWritingProgress(session.id);
if (cancelled) return;
setProgress(p);
setFetchError(false);
setLoading(false);
// 终态停止轮询,否则继续。
if (!isTerminal(p)) {
timerRef.current = setTimeout(tick, POLL_MS);
}
} catch {
if (cancelled) return;
setFetchError(true);
setLoading(false);
timerRef.current = setTimeout(tick, POLL_MS);
}
};
void tick();
return () => {
cancelled = true;
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = null;
};
}, [open, session]);
const terminal = isTerminal(progress);
const isError = progress?.sessionStatus === 'error';
const stage = progress?.stage ?? null;
let caption: string;
if (loading && !progress) {
caption = '加载进度中…';
} else if (isError) {
caption = '后台执行出错,请重新发起写作';
} else if (progress?.sessionStatus === 'done' || stage === 'done') {
caption = '✓ 写作已完成,点开这条记录即可查看成稿';
} else {
const stageLabel = stage ? (FLOW_STAGE_LABEL[stage] ?? '准备中') : '准备中';
let text = `后台运行中 · 当前:${stageLabel}`;
if (progress?.note) text += `(${progress.note})`;
if (stage === 'review' && (progress?.revisionCount ?? 0) > 0) {
text += ` · 第 ${progress!.revisionCount}/${progress!.maxRevisions} 轮修改`;
}
caption = text;
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle className="truncate pr-6 text-sm" title={session?.title}>
写作进度 · {session?.draft_title || session?.title || '后台写作'}
</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center gap-3 py-1">
<div className="w-full overflow-x-auto py-2">
<AIWritingFlowChart className="mx-auto" activeKey={stage} isError={isError} note={progress?.note} />
</div>
<div className="flex items-center justify-center gap-1.5 text-center text-xs text-muted-foreground">
{!terminal && !isError && <Loader2 className="size-3 shrink-0 animate-spin text-sky-500" />}
<span className={fetchError ? 'text-amber-500' : undefined}>
{fetchError ? '获取进度失败,重试中…' : caption}
</span>
</div>
</div>
</DialogContent>
</Dialog>
);
}
@@ -1,5 +1,5 @@
import { useState, useRef, useEffect } from 'react';
import { History, Trash2, Check, X, RefreshCw } from 'lucide-react';
import { History, Trash2, Check, X, RefreshCw, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
@@ -7,6 +7,8 @@ import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions';
export const STATUS_LABELS: Record<string, { label: string; color: string }> = {
in_progress: { label: '进行中', color: 'text-blue-500' },
// 后台挂起中:后端正自动驱动到定稿(离页/刷新/切号不打断)。
background: { label: '挂起中', color: 'text-sky-500' },
draft_ready: { label: '草稿', color: 'text-amber-500' },
review_ready: { label: '审核', color: 'text-purple-500' },
done: { label: '完成', color: 'text-green-500' },
@@ -29,11 +31,15 @@ export interface SessionItemProps {
session: AIWritingSessionSummary;
isSelected: boolean;
onSelect: () => void;
/** 「挂起中」记录点击时改为查看进度(流程图弹窗),不直接打开会话。 */
onShowProgress?: () => void;
onDelete: () => void;
onRename: (title: string) => void;
}
export function SessionItem({ session, isSelected, onSelect, onDelete, onRename }: SessionItemProps) {
export function SessionItem({ session, isSelected, onSelect, onShowProgress, onDelete, onRename }: SessionItemProps) {
const isBackground = session.status === 'background';
const handleRowClick = isBackground && onShowProgress ? onShowProgress : onSelect;
const [editing, setEditing] = useState(false);
const [editValue, setEditValue] = useState(session.title);
const inputRef = useRef<HTMLInputElement>(null);
@@ -60,7 +66,7 @@ export function SessionItem({ session, isSelected, onSelect, onDelete, onRename
'group relative flex items-start gap-2 px-3 py-2.5 cursor-pointer transition-colors',
isSelected ? 'bg-accent' : 'hover:bg-accent/60',
)}
onClick={!editing ? onSelect : undefined}
onClick={!editing ? handleRowClick : undefined}
>
<div className="flex-1 min-w-0">
{editing ? (
@@ -89,7 +95,10 @@ export function SessionItem({ session, isSelected, onSelect, onDelete, onRename
</p>
)}
<div className="flex items-center gap-1.5 mt-0.5">
<span className={cn('text-[10px] font-medium', color)}>{label}</span>
<span className={cn('flex items-center gap-0.5 text-[10px] font-medium', color)}>
{session.status === 'background' && <Loader2 className="w-2.5 h-2.5 animate-spin" />}
{label}
</span>
<span className="text-[10px] text-muted-foreground">·</span>
<span className="text-[10px] text-muted-foreground">{formatRelative(session.updated_at)}</span>
</div>
@@ -114,6 +123,8 @@ interface AIWritingHistoryDropdownProps {
selectedId: string | null;
loading: boolean;
onSelect: (session: AIWritingSessionSummary) => void;
/** 点击「挂起中」记录时查看进度(流程图弹窗),不直接打开会话。 */
onShowProgress?: (session: AIWritingSessionSummary) => void;
onDelete: (id: string) => void;
onRename: (id: string, title: string) => void;
onRefresh: () => void;
@@ -124,6 +135,7 @@ export function AIWritingHistoryDropdown({
selectedId,
loading,
onSelect,
onShowProgress,
onDelete,
onRename,
onRefresh,
@@ -189,6 +201,7 @@ export function AIWritingHistoryDropdown({
session={s}
isSelected={s.id === selectedId}
onSelect={() => { onSelect(s); setOpen(false); }}
onShowProgress={onShowProgress ? () => { onShowProgress(s); setOpen(false); } : undefined}
onDelete={() => onDelete(s.id)}
onRename={(title) => onRename(s.id, title)}
/>
@@ -1,8 +1,34 @@
import { useMemo } from 'react';
import { CheckCircle2, ChevronRight, FileText, Search, PenLine, ClipboardEdit, Star } from 'lucide-react';
import type { AIWritingSessionSummary, CompletedInterventionRecord } from '../../api/ai-writing-sessions';
import {
normalizeProgressDict,
normalizeMaterial,
normalizeOutline,
normalizeReviewResult,
} from '../../hooks/useAIWritingStream';
import type { CompletedIntervention } from '../../types/ai-writing';
import { AIWritingTimeline } from './AIWritingTimeline';
/**
* 归一化一条 completedIntervention(后台挂起重建的干预记录里素材/大纲/审核数据是
* snake_case,前端干预卡期望 camelCase)。对前端实时存的 camelCase 记录幂等。
*/
function normalizeCompletedIntervention(rec: Record<string, unknown>): CompletedIntervention {
const out: Record<string, unknown> = { ...rec };
out.pausePoint = rec.pausePoint ?? rec.pause_point;
if (Array.isArray(rec.materials)) {
out.materials = (rec.materials as Record<string, unknown>[]).map(normalizeMaterial);
}
if (rec.outline) out.outline = normalizeOutline(rec.outline);
const rr = rec.reviewResult ?? rec.review_result;
if (rr) out.reviewResult = normalizeReviewResult(rr);
if (out.draftTitle == null && rec.draft_title != null) out.draftTitle = rec.draft_title;
if (out.draftWordCount == null && rec.draft_word_count != null) out.draftWordCount = rec.draft_word_count;
return out as unknown as CompletedIntervention;
}
const PAUSE_LABELS: Record<string, string> = {
material_confirm: '素材确认',
outline_confirm: '大纲确认',
@@ -67,6 +93,22 @@ export function AIWritingHistoryView({ session }: AIWritingHistoryViewProps) {
const transcript = session.transcript;
// 有完整时间线快照时,复用实时对话的 AIWritingTimeline 渲染,保证回显与实时一致
const hasTranscript = !!transcript && (transcript.progressEvents?.length ?? 0) > 0;
// 归一化 transcript 事件:后台挂起跑出的事件是 raw(snake_case),前端实时存的是
// camelCase——统一过一遍 normalizeProgressDict(幂等),两种来源回显都正确一致。
const normalizedEvents = useMemo(
() => (transcript?.progressEvents ?? []).map(
(e) => normalizeProgressDict(e as unknown as Record<string, unknown>, session.id),
),
[transcript, session.id],
);
// 干预记录同样归一化(后台重建的素材/大纲/审核数据为 snake_case;前端实时记录已是
// camelCase,归一化幂等),保证素材列表/大纲/编辑审核卡片正确渲染。
const normalizedInterventions = useMemo(
() => (transcript?.completedInterventions ?? []).map(
(rec) => normalizeCompletedIntervention(rec as unknown as Record<string, unknown>),
),
[transcript],
);
const createdAt = session.created_at
? new Date(session.created_at).toLocaleString('zh-CN', {
year: 'numeric', month: 'short', day: 'numeric',
@@ -94,8 +136,8 @@ export function AIWritingHistoryView({ session }: AIWritingHistoryViewProps) {
{hasTranscript ? (
/* 完整对话时间线回显 */
<AIWritingTimeline
events={transcript!.progressEvents}
completedInterventions={transcript!.completedInterventions ?? []}
events={normalizedEvents}
completedInterventions={normalizedInterventions}
currentPause={null}
/>
) : (
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { ChevronsDown, PanelRightClose, Play, Plus, RotateCcw, Settings2, Square, Trash2 } from 'lucide-react';
import { ChevronsDown, CloudUpload, PanelRightClose, Play, Plus, RotateCcw, Settings2, Square, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
@@ -17,7 +17,12 @@ import { useAIWriting } from '../../contexts/AIWritingContext';
import { useAIWritingHistory } from '../../contexts/AIWritingHistoryContext';
import { useWritingFormOptional } from '../../contexts/WritingFormContext';
import { useAIWritingSessions } from '../../hooks/useAIWritingSessions';
import { adminCleanupAIWritingSessions, getAIWritingSession } from '../../api/ai-writing-sessions';
import {
adminCleanupAIWritingSessions,
getAIWritingSession,
suspendAIWritingToBackground,
suspendAIWritingToBackgroundKeepalive,
} from '../../api/ai-writing-sessions';
/**
* 暂停 / 继续功能开关(默认 false = 关)。
@@ -51,6 +56,7 @@ import { ReviewStreamingView } from './ReviewStreamingView';
import { RevisionSummaryCard } from './RevisionSummaryCard';
import { AIWritingHistoryDropdown } from './AIWritingHistoryDropdown';
import { AIWritingHistoryView } from './AIWritingHistoryView';
import { AIWritingFlowDialog } from './AIWritingFlowDialog';
import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions';
const STATUS_LABEL: Record<string, string> = {
@@ -91,6 +97,8 @@ export function AIWritingPanel({
useEffect(() => { refreshArticleTypes(); }, [refreshArticleTypes]);
const [reqDialogOpen, setReqDialogOpen] = useState(false);
// 「查看进度」流程图弹窗当前展示的会话(点击历史里的「挂起中」记录时打开)。
const [progressSession, setProgressSession] = useState<AIWritingSessionSummary | null>(null);
const isIdle = state.status === 'idle';
const isDone = state.status === 'done';
@@ -188,11 +196,57 @@ export function AIWritingPanel({
void openHistory(session);
}, [openHistory]);
// 点击历史里的「挂起中」记录 → 打开流程图弹窗看实际进度(而非直接打开会话)。
const handleShowProgress = useCallback((session: AIWritingSessionSummary) => {
setProgressSession(session);
}, []);
const handleNewSession = useCallback(() => {
closeHistory();
reset();
}, [closeHistory, reset]);
// ── 后台挂起:把当前写作转后台,后端自动驱动到定稿(离页/刷新/切号不打断) ──
const handleBackgroundSuspend = useCallback(async () => {
const sid = state.sessionId;
if (!sid) {
toast.error('当前没有可挂起的写作会话');
return;
}
try {
await suspendAIWritingToBackground(sid);
} catch (e) {
toast.error(e instanceof Error ? e.message : '后台挂起失败');
return;
}
toast.success('已转入后台自动完成,稍后可在「历史记录」查看进度与结果');
// reset() 会 stop 客户端 SSE 订阅并回到 idle —— 后端驱动器接管续跑,不冲突。
reset();
// 刷新历史列表,让「挂起中」徽标立刻出现。
refresh();
}, [state.sessionId, reset, refresh]);
// 离页 / 刷新 / 关标签页时,若写作仍在进行中则自动转后台(与圆桌「自动挂起」一致)。
// 用 ref 持有最新的「是否在跑 + 会话 id」,让卸载/卸载前回调读到即时值。
const suspendRef = useRef<{ running: boolean; sid: string | null }>({ running: false, sid: null });
useEffect(() => {
suspendRef.current = { running: isRunning, sid: state.sessionId ?? null };
}, [isRunning, state.sessionId]);
useEffect(() => {
const onBeforeUnload = () => {
const { running, sid } = suspendRef.current;
if (running && sid) suspendAIWritingToBackgroundKeepalive(sid);
};
window.addEventListener('beforeunload', onBeforeUnload);
return () => {
window.removeEventListener('beforeunload', onBeforeUnload);
// 组件卸载(路由离开本页 / 切换工作区标签):写作未完成则自动转后台。
const { running, sid } = suspendRef.current;
if (running && sid) suspendAIWritingToBackgroundKeepalive(sid);
};
}, []);
// ── 侧边栏"最近写作"通信:两种路径 ────────────────────────────────────────
// 用 ref 包住 handler,保证事件监听器始终能拿到最新版本
const handleSelectHistoryRef = useRef(handleSelectHistory);
@@ -299,6 +353,19 @@ export function AIWritingPanel({
新建
</Button>
)}
{/* 后台挂起:写作进行中(含等待干预)时出现,点击后由后端自动跑完剩余流程 */}
{isRunning && !isHistoryMode && state.sessionId && (
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-xs gap-1 text-sky-500 hover:text-sky-600 hover:bg-sky-50 dark:hover:bg-sky-950/30"
onClick={handleBackgroundSuspend}
title="转入后台:自动确认素材/大纲、写作、编辑审核直至定稿,离开页面也不中断"
>
<CloudUpload className="size-3" />
后台挂起
</Button>
)}
{/* ⏸️/▶️ "停止 / 继续" 由 ENABLE_PAUSE_RESUME_UI 控制(默认 false 隐藏)。
后期把 flag 翻成 true 即可恢复,UI / hook 全套代码都已就位。 */}
{ENABLE_PAUSE_RESUME_UI && isRunning && !state.isPaused && (
@@ -340,6 +407,7 @@ export function AIWritingPanel({
selectedId={historySession?.id ?? null}
loading={sessionsLoading}
onSelect={handleSelectHistory}
onShowProgress={handleShowProgress}
onDelete={remove}
onRename={rename}
onRefresh={refresh}
@@ -455,9 +523,15 @@ export function AIWritingPanel({
/>
)}
{/* 技能检索 pending:用户点击瞬间到 awaiting 之间,始终显示 SkillStepsCard 占位
steps.length === 0 时 SkillStepsCard 内部会渲染骨架行,不让用户干等空白 */}
{state.skillSearchPending && (
{/* 技能检索过程实时展示:
① skillSearchPending —— PAUSE-1 用户点"重新搜索/按输入追加"瞬间到 awaiting
之间的占位(steps 为空时 SkillStepsCard 内部渲染骨架行,不让用户干等空白);
② 首次素材收集(researching 且已有 skill_search_step)—— 让"调用了哪个技能 /
检索到多少条 / 检索完成"像智能体问答一样边搜边显示,而不是搜完才在素材确认
卡里一次性看到。素材确认(awaiting_material_confirm)时由 InterventionCard
接管展示同一份 steps,这里 researching 条件自动失效,不会重复。 */}
{(state.skillSearchPending
|| (state.status === 'researching' && state.skillSearchSteps.length > 0)) && (
<div className="px-4 pb-2">
<SkillStepsCard steps={state.skillSearchSteps} inProgress />
</div>
@@ -467,8 +541,11 @@ export function AIWritingPanel({
state.status !== 'writing_draft' &&
!(state.status === 'writing_outline' && (state.outlineStreamingText || state.outlineThinkingText)) &&
!(state.status === 'reviewing' && state.streamingReviewItems.length > 0) &&
/* 技能检索占位卡 / 选择打字机 已经在流式展示,不再叠加 skeleton */
/* 技能检索占位卡 / 选择打字机 / 已流式的技能步骤 已经在展示,不再叠加 skeleton。
(研究阶段一旦有 skill_search_step,就改由上面的 SkillStepsCard 实时呈现进度,
研究词生成阶段 steps 还为空时仍走 skeleton 透传 researchProgress 文案。) */
!state.skillSearchPending &&
!(state.status === 'researching' && state.skillSearchSteps.length > 0) &&
!(state.status === 'researching' && (state.skillSelectStreamingText || state.skillSelectThinkingText)) &&
/* 意图解析流式过程中(LLM 还在吐 JSON)不要显示 skeleton */
!state.intentStreamingText && !state.intentThinkingText && (
@@ -524,6 +601,13 @@ export function AIWritingPanel({
</div>
)}
{/* 查看进度流程图弹窗:点击历史里的「挂起中」记录时打开 */}
<AIWritingFlowDialog
session={progressSession}
open={progressSession !== null}
onOpenChange={(o) => { if (!o) setProgressSession(null); }}
/>
{/* 写作参数查看弹窗 */}
{state.request && (
<Dialog open={reqDialogOpen} onOpenChange={setReqDialogOpen}>
@@ -1,7 +1,22 @@
"use client";
import { BookOpen, FileText, LayoutGrid, Loader2, Plus, Settings2 } from "lucide-react";
import { useEffect, useState } from "react";
import {
BarChart3,
BookOpen,
FileText,
Globe2,
LayoutGrid,
Loader2,
Newspaper,
Plus,
Search,
Settings2,
SlidersHorizontal,
Sparkles,
TrendingUp,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
@@ -22,23 +37,62 @@ import type { ResearchTemplate } from "../../api/ai-writing-research-templates";
import { useWritingForm } from "../../contexts/WritingFormContext";
import { useAIWriting } from "../../contexts/AIWritingContext";
/**
* 课题研究左栏(需求 0616 #5)。
* - 上半「研究模板」= 研究模板实体(``useResearchTemplates``);点击一键预填整张写作表单
* (文章类型 / 大纲 / 搜索来源 / 字数 / 受众 / 严格模式 / 主题)并展开配置。顶部「配置」
* 入口进入模板配置页维护这些模板。
* - 下半「笔记本」= 我的空间(``useStudioNotebooks``);点击在右侧内嵌打开该笔记本页。
*/
type TemplateVisual = {
Icon: LucideIcon;
iconClass: string;
accentClass: string;
};
const TEMPLATE_VISUALS: TemplateVisual[] = [
{
Icon: Globe2,
iconClass: "bg-blue-50 text-blue-600",
accentClass: "bg-blue-500",
},
{
Icon: Newspaper,
iconClass: "bg-amber-50 text-amber-600",
accentClass: "bg-amber-500",
},
{
Icon: Sparkles,
iconClass: "bg-violet-50 text-violet-600",
accentClass: "bg-violet-500",
},
{
Icon: TrendingUp,
iconClass: "bg-rose-50 text-rose-600",
accentClass: "bg-rose-500",
},
{
Icon: BookOpen,
iconClass: "bg-emerald-50 text-emerald-600",
accentClass: "bg-emerald-500",
},
{
Icon: BarChart3,
iconClass: "bg-cyan-50 text-cyan-600",
accentClass: "bg-cyan-500",
},
];
function getTemplateVisual(tpl: ResearchTemplate, index: number): TemplateVisual {
const text = `${tpl.name} ${tpl.description ?? ""} ${tpl.article_type_key ?? ""}`;
if (/网摘|网络|热点|摘/.test(text)) return TEMPLATE_VISUALS[0];
if (/周报|周刊|日报|月报/.test(text)) return TEMPLATE_VISUALS[1];
if (/要讯|资讯|快讯|简报/.test(text)) return TEMPLATE_VISUALS[2];
if (/行业|分析|市场|竞争/.test(text)) return TEMPLATE_VISUALS[3];
if (/政策|解读|法规/.test(text)) return TEMPLATE_VISUALS[4];
return TEMPLATE_VISUALS[index % TEMPLATE_VISUALS.length];
}
export function ResearchSidebar({
viewingNotebookId,
onOpenNotebook,
onOpenAllSpaces,
}: {
/** 当前在右侧查看的笔记本 id(高亮用)。 */
viewingNotebookId?: number | null;
/** 点击笔记本 → 在右侧内嵌打开该笔记本页(替换右侧内容)。 */
onOpenNotebook: (notebookId: number) => void;
/** 点击「所有空间」→ 在右侧内嵌打开空间列表页。 */
onOpenAllSpaces: () => void;
}) {
const navigate = useNavigate();
@@ -62,7 +116,7 @@ export function ResearchSidebar({
} = useWritingForm();
const queryClient = useQueryClient();
// 新建空间弹窗(与 workspace-nav-studio 同款)。
const [templateSearch, setTemplateSearch] = useState("");
const [createOpen, setCreateOpen] = useState(false);
const [name, setName] = useState("");
const [creating, setCreating] = useState(false);
@@ -72,6 +126,16 @@ export function ResearchSidebar({
void refresh();
}, [refresh]);
const filteredTemplates = useMemo(() => {
const keyword = templateSearch.trim().toLowerCase();
if (!keyword) return templates;
return templates.filter((tpl) =>
[tpl.name, tpl.description, tpl.article_type_key]
.filter(Boolean)
.some((value) => String(value).toLowerCase().includes(keyword)),
);
}, [templates, templateSearch]);
const handleCreate = async () => {
const trimmed = name.trim();
if (!trimmed) return;
@@ -92,8 +156,6 @@ export function ResearchSidebar({
}
};
// 点击研究模板 → ①回填整张写作表单(保持写作态左栏显示与运行配置一致)
// ②直接以模板预设进入 AI 写作流程(startWriting)。
const handleTemplateClick = (tpl: ResearchTemplate) => {
const intent = tpl.topic?.trim() ?? "";
const articleType = tpl.article_type_key || "analysis";
@@ -102,7 +164,6 @@ export function ResearchSidebar({
const wordCount = tpl.word_count > 0 ? tpl.word_count : 800;
const writingMode = tpl.strict_mode ? "strict" : "loose";
// 回填表单上下文(写作态左栏据此展示)。
if (intent) setIntent(intent);
if (tpl.article_type_key) setArticleType(tpl.article_type_key);
if (outline) {
@@ -115,7 +176,6 @@ export function ResearchSidebar({
setStrictMode(tpl.strict_mode);
setFormExpanded(true);
// 无主题/意图无法发起写作 → 仅回填表单,由用户补充后手动开始。
if (!intent) return;
void startWriting({
userIntent: intent,
@@ -130,116 +190,191 @@ export function ResearchSidebar({
};
return (
<aside className="flex h-full w-64 shrink-0 flex-col overflow-hidden border-r border-border/70 bg-card/60 backdrop-blur-sm">
{/* 上半:研究模板 */}
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-2 py-3">
<div className="px-2 mb-1.5 flex items-center justify-between">
<h2 className="text-muted-foreground/70 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
研究模板
</h2>
<button
type="button"
onClick={() => navigate("/page/canvas/research-templates")}
title="配置研究模板"
aria-label="配置研究模板"
className="text-muted-foreground/70 hover:text-foreground rounded p-0.5 transition-colors"
>
<Settings2 className="size-3.5" />
</button>
</div>
{templates.length === 0 ? (
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">
暂无研究模板,点右上角配置
</p>
) : (
<div className="flex flex-col gap-1">
{templates.map((tpl) => (
<button
key={tpl.id}
type="button"
onClick={() => handleTemplateClick(tpl)}
title={tpl.description ?? tpl.name}
className="flex items-start gap-2 rounded-lg px-2.5 py-1.5 text-left text-muted-foreground transition-colors hover:bg-sidebar-accent/60 hover:text-foreground"
>
<FileText className="mt-0.5 size-3.5 shrink-0 text-muted-foreground/70" />
<span className="min-w-0">
<span className="block truncate text-[13px] font-medium">{tpl.name}</span>
{tpl.description && (
<span className="text-muted-foreground/70 line-clamp-1 block text-[11px]">
{tpl.description}
</span>
)}
</span>
</button>
))}
<aside className="ai-research-sidebar flex h-full w-[320px] shrink-0 flex-col overflow-hidden border-r border-slate-100 bg-white text-slate-700 shadow-[1px_0_18px_rgba(15,23,42,0.03)]">
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden px-3 py-4">
<section className="mb-5">
<div className="mb-3 flex items-center justify-between gap-3 px-1">
<button
type="button"
onClick={() => navigate("/page/canvas/research-templates")}
title="配置研究模板"
aria-label="配置研究模板"
className="group flex items-center gap-2 rounded-lg text-[16px] font-bold text-slate-500 transition-colors hover:text-slate-800"
>
<SlidersHorizontal className="size-4 text-slate-400" />
<span>研究模板</span>
<Settings2 className="size-3.5 text-slate-300 opacity-0 transition-opacity group-hover:opacity-100" />
</button>
<div className="relative w-[150px]">
<Search className="pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-slate-400" />
<input
type="text"
value={templateSearch}
onChange={(event) => setTemplateSearch(event.target.value)}
placeholder="搜索写作模板..."
className="h-8 w-full rounded-lg border border-slate-200 bg-slate-50/80 pl-8 pr-3 text-[12px] text-slate-600 outline-none transition focus:border-blue-200 focus:bg-white focus:ring-2 focus:ring-blue-100"
/>
</div>
</div>
)}
</div>
{/* 下半:笔记本(我的空间) */}
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto border-t border-border/60 px-2 py-3">
<h2 className="text-muted-foreground/70 px-2 mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
笔记本
</h2>
<div className="flex flex-col gap-0.5">
{/* 新建空间 */}
<button
type="button"
onClick={() => {
setName("");
setCreateError("");
setCreateOpen(true);
}}
className="flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] text-muted-foreground transition-colors hover:bg-sidebar-accent/60 hover:text-foreground"
>
<Plus className="size-3.5 shrink-0 text-muted-foreground/70" />
<span>新建空间</span>
</button>
{notebooksLoading ? (
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">加载中…</p>
) : notebooksError ? (
<p className="px-2 py-1.5 text-xs text-amber-600">
笔记本服务暂不可用(检查空间服务地址 / 账号)
{templates.length === 0 ? (
<p className="rounded-xl border border-dashed border-slate-200 px-3 py-5 text-center text-xs text-slate-400">
暂无研究模板,点击标题配置
</p>
) : filteredTemplates.length === 0 ? (
<p className="rounded-xl border border-dashed border-slate-200 px-3 py-5 text-center text-xs text-slate-400">
暂无匹配模板
</p>
) : notebooks.length === 0 ? (
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">暂无笔记本</p>
) : (
notebooks.map((nb) => {
const active = viewingNotebookId === nb.id;
return (
<button
key={nb.id}
type="button"
onClick={() => onOpenNotebook(nb.id)}
title={nb.description || nb.name}
className={cn(
"flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] transition-colors",
active
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
)}
>
<BookOpen className="size-3.5 shrink-0 text-muted-foreground/70" />
<span className="truncate">{nb.name}</span>
</button>
);
})
<div className="space-y-3">
{filteredTemplates.map((tpl, index) => {
const visual = getTemplateVisual(tpl, index);
const Icon = visual.Icon;
return (
<button
key={tpl.id}
type="button"
onClick={() => handleTemplateClick(tpl)}
title={tpl.description ?? tpl.name}
className="group relative flex w-full items-start gap-3 overflow-hidden rounded-[5px] bg-white px-4 py-4 text-left shadow-[0_8px_24px_rgba(15,23,42,0.04)] transition-all hover:-translate-y-0.5 hover:shadow-[0_14px_30px_rgba(30,64,175,0.08)] active:translate-y-0"
>
<span
className={cn(
"flex size-12 shrink-0 items-center justify-center rounded-xl transition-colors",
visual.iconClass,
)}
>
<Icon className="size-6 stroke-[2.2]" />
</span>
<span className="min-w-0 flex-1 pt-0.5">
<span className="block truncate text-[16px] font-bold leading-5 text-slate-900 transition-colors group-hover:text-blue-700">
{tpl.name}
</span>
{tpl.description && (
<span
className="mt-1.5 overflow-hidden text-[13px] leading-6 text-slate-500"
style={{
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 2,
}}
>
{tpl.description}
</span>
)}
</span>
<span
className={cn(
"absolute bottom-4 left-0 top-4 w-1 rounded-r-full opacity-0 transition-opacity group-hover:opacity-100",
visual.accentClass,
)}
/>
</button>
);
})}
</div>
)}
</section>
{/* 所有空间 */}
<button
type="button"
onClick={onOpenAllSpaces}
className="flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] text-muted-foreground transition-colors hover:bg-sidebar-accent/60 hover:text-foreground"
>
<LayoutGrid className="size-3.5 shrink-0 text-muted-foreground/70" />
<span>所有空间</span>
</button>
</div>
<section className="flex min-h-0 flex-1 flex-col border-t border-slate-100 pt-5">
<div className="mb-3 flex items-center justify-between px-2">
<h2 className="text-[15px] font-bold tracking-wide text-slate-400">
笔记本
</h2>
<button
type="button"
onClick={() => {
setName("");
setCreateError("");
setCreateOpen(true);
}}
title="新建写作空间"
aria-label="新建写作空间"
className="rounded-md p-1 text-slate-400 transition-colors hover:bg-rose-50 hover:text-rose-600"
>
<Plus className="size-4 stroke-[2.5]" />
</button>
</div>
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto px-1 pb-3">
{notebooksLoading ? (
<p className="px-3 py-2 text-xs text-slate-400">加载中...</p>
) : notebooksError ? (
<p className="rounded-xl bg-amber-50 px-3 py-2 text-xs leading-5 text-amber-700">
笔记本服务暂不可用,请检查空间服务地址或账号
</p>
) : notebooks.length === 0 ? (
<p className="px-3 py-2 text-xs text-slate-400">暂无笔记本</p>
) : (
notebooks.map((nb) => {
const active = viewingNotebookId === nb.id;
const sourceCount = Math.max(0, nb.source_count ?? 0);
return (
<button
key={nb.id}
type="button"
onClick={() => onOpenNotebook(nb.id)}
title={nb.description || nb.name}
className={cn(
"group relative flex min-h-14 w-full items-center gap-3 rounded-xl border bg-white px-3 py-2 text-left transition-all",
active
? "border-rose-100 bg-rose-50/35 text-slate-900 shadow-[0_6px_18px_rgba(244,63,94,0.06)]"
: "border-slate-100/80 text-slate-600 hover:border-slate-200 hover:bg-slate-50/70",
)}
>
{active && (
<span className="absolute bottom-4 left-0 top-4 w-1 rounded-r-full bg-rose-500" />
)}
<span
className={cn(
"flex size-8 shrink-0 items-center justify-center rounded-lg",
active ? "bg-rose-50 text-rose-600" : "bg-slate-100 text-slate-500",
)}
>
<BookOpen className="size-4 stroke-[2.2]" />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium leading-5">
{nb.name}
</span>
{sourceCount > 0 && (
<span className="mt-1 flex items-center gap-1 text-[11px] text-slate-400">
<FileText className="size-3" />
已有 {sourceCount} 篇排版
</span>
)}
</span>
{sourceCount > 0 && (
<span
className={cn(
"flex size-7 shrink-0 items-center justify-center rounded-full border text-[12px] font-semibold",
active
? "border-rose-100 bg-rose-50 text-rose-600"
: "border-slate-100 bg-slate-50 text-slate-400",
)}
>
{sourceCount}
</span>
)}
</button>
);
})
)}
</div>
<div className="border-t border-slate-100 px-1 pt-3">
<button
type="button"
onClick={onOpenAllSpaces}
className="flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left text-[14px] font-bold text-slate-700 transition-colors hover:bg-slate-50 hover:text-slate-950"
>
<LayoutGrid className="size-4 text-rose-500 stroke-[2.3]" />
<span>所有空间</span>
</button>
</div>
</section>
</div>
{/* 新建空间弹窗 */}
<Dialog open={createOpen} onOpenChange={(v) => !creating && setCreateOpen(v)}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
@@ -15,6 +15,11 @@ import {
import { useStream } from '@langchain/langgraph-sdk/react';
import { getAPIClient } from '@/core/api';
import {
getStreamErrorMessage,
isThreadNotAccessibleError,
notifyThreadAccessChangedAndReload,
} from '@/core/threads/thread-access-error';
import { useCanvasGraphContext } from '../contexts/CanvasGraphContext';
import { saveAIWritingTranscript } from '../api/ai-writing-sessions';
@@ -186,10 +191,18 @@ const AIWritingStreamHost = memo(function AIWritingStreamHost({
},
onError(err: unknown) {
eventBatcherRef.current?.cancel();
dispatchRef.current?.({
type: 'set_error',
message: err instanceof Error ? err.message : String(err),
});
const message = getStreamErrorMessage(err);
// A "thread not accessible/not found" 404 almost always means the writing
// thread belongs to a previous login session — the user switched accounts
// (or this tab outlived a re-login), so the current account legitimately
// can't access the old thread. Instead of dumping the raw HTTP 404 into
// the panel, re-frame it around the current identity and reload — same UX
// the chat stream gives (see core/threads/hooks.ts).
if (isThreadNotAccessibleError(message)) {
notifyThreadAccessChangedAndReload();
return;
}
dispatchRef.current?.({ type: 'set_error', message });
},
onFinish(finishState) {
eventBatcherRef.current?.cancel();
@@ -291,7 +304,12 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
},
);
} catch (err) {
dispatch({ type: 'set_error', message: err instanceof Error ? err.message : String(err) });
const message = getStreamErrorMessage(err);
if (isThreadNotAccessibleError(message)) {
notifyThreadAccessChangedAndReload();
return;
}
dispatch({ type: 'set_error', message });
}
}, [state.status]);
@@ -367,12 +385,24 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
dispatch({ type: 'intervention_submitted', record, nextStatus, pendingRevisionContext });
try {
// resume 是新 invocation,其 config 默认不带最初的 model_name;而写作/审核节点
// 在 resume 后才运行,若首轮 intent 未把模型存进 state(历史会话 / 捕获为空),
// 后端就只能回退默认模型。这里把表单选定的模型随每次 resume 一并回传,
// 让后端(get_writing_model / resolve_agent_model_name 的 configurable 兜底)
// 始终用上用户真正选的模型。
const resumeModelName = state.request?.modelName;
await stream.submit(undefined, {
command: { resume: resumePayload },
streamMode: ['values', 'updates', 'custom', 'messages-tuple'],
...(resumeModelName ? { config: { configurable: { model_name: resumeModelName } } } : {}),
});
} catch (err) {
dispatch({ type: 'set_error', message: err instanceof Error ? err.message : String(err) });
const message = getStreamErrorMessage(err);
if (isThreadNotAccessibleError(message)) {
notifyThreadAccessChangedAndReload();
return;
}
dispatch({ type: 'set_error', message });
}
}, [state.sessionId, state.currentPause, state.materials, state.outline,
state.currentDraftTitle, state.currentDraftMarkdown, state.reviewResult,
@@ -395,7 +395,7 @@ function handleEvent(prev: AIWritingState, event: ProgressEvent): AIWritingState
// ── snake_case ↔ camelCase 归一化(custom 通道事件 + interrupt payload) ──────
function normalizeMaterial(m: Record<string, unknown>): AIMaterial {
export function normalizeMaterial(m: Record<string, unknown>): AIMaterial {
const extra = (m.extra_metadata ?? m.extraMetadata) as Record<string, unknown> | undefined;
return {
id: String(m.id ?? ''),
@@ -430,7 +430,7 @@ function normalizeOutlineSection(s: Record<string, unknown>) {
};
}
function normalizeOutline(o: unknown): AIOutline | null {
export function normalizeOutline(o: unknown): AIOutline | null {
if (!o || typeof o !== 'object') return null;
const obj = o as Record<string, unknown>;
return {
@@ -449,7 +449,7 @@ function normalizeReviewIssue(i: Record<string, unknown>): ReviewIssue {
};
}
function normalizeReviewResult(r: unknown): ReviewResult | null {
export function normalizeReviewResult(r: unknown): ReviewResult | null {
if (!r || typeof r !== 'object') return null;
const o = r as Record<string, unknown>;
return {
@@ -472,8 +472,12 @@ function normalizeBlockedSection(b: Record<string, unknown>): BlockedSection {
};
}
/** 把后端节点 ``progress_events`` 数组里的一条 dict 翻译成前端 ProgressEvent。 */
function normalizeProgressDict(parsed: Record<string, unknown>, sessionId: string): ProgressEvent {
/** 把后端节点 ``progress_events`` 数组里的一条 dict 翻译成前端 ProgressEvent。
*
* 幂等:对已是 camelCase 的前端事件再跑一遍基本不变(snake_case 键不存在即跳过),
* 所以历史回显时可无脑对**整条** transcript 跑一遍——既归一后台存的 raw 事件,又
* 不破坏前端实时存的事件。 */
export function normalizeProgressDict(parsed: Record<string, unknown>, sessionId: string): ProgressEvent {
const out: Record<string, unknown> = { ...parsed, sessionId };
if ('agent_name' in out) out.agentName = out.agent_name;
+116 -2
View File
@@ -2,11 +2,13 @@
import { BotIcon, PlusSquare } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useLocation } from "react-router-dom";
import { useRouteBase } from "@/core/route-base";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
import { Button } from "@/components/ui/button";
import { AgentChatSidebar } from "@/components/workspace/agents/agent-chat-sidebar";
import { AgentDetailPanel } from "@/components/workspace/agents/agent-detail-panel";
import { AgentQuestionChips } from "@/components/workspace/agents/agent-question-chips";
import { AgentWelcome } from "@/components/workspace/agent-welcome";
@@ -26,14 +28,20 @@ import { useI18n } from "@/core/i18n/hooks";
import { useModels } from "@/core/models/hooks";
import { useNotification } from "@/core/notification/hooks";
import { saveLastAgentId, useThreadSettings } from "@/core/settings";
import { useThreadStream } from "@/core/threads/hooks";
import { stopThreadRun, useThreadStream } from "@/core/threads/hooks";
import { textOfMessage } from "@/core/threads/utils";
import { env } from "@/env";
import { readTaskContext } from "@/core/auth/task-purpose";
import { TaskPurposePanel } from "@/strategy-components/components/task-components/TaskPurposePanel";
import { desensitize } from "@/lib/desensitize";
export default function AgentChatPage({
embeddedAgentId,
chatBasePath,
taskGate,
taskBind,
autoStartWhenPurposeEmpty,
showAgentList,
}: {
/** 当作为「通用问答右侧嵌入」渲染时由父组件传入的 agent id(替代路由参数)。
* 传入即视为嵌入态:路由仍停留在 /chats/new,仅右侧问答区换成该智能体的对话。 */
@@ -43,6 +51,17 @@ export default function AgentChatPage({
* 传入如 `/page/strategy/task-management/plan-task-sentiment/agent/${id}/chats`,
* 使开新会话 / 首条消息后的 URL 改写都停留在任务管理上下文(侧边栏保持对应业务高亮)。 */
chatBasePath?: string;
/** rwfx 任务深链闸门:新建对话时顶部展示目的树面板(覆盖确认后才开始问答),
* 并给新建 thread 打 `metadata.taskId` 标签(任务↔对话 1:N)。见 task-purpose。 */
taskGate?: boolean;
/** 3qfx / xdfx 任务深链:仅做任务↔对话 1:N 绑定(打 `metadata.taskId` 标签 + 切换会话停旧 run),
* 不展示目的树闸门;新建对话直接把任务开场信息自动发出。与 `taskGate` 互斥使用。 */
taskBind?: boolean;
/** rwfx:查询任务目的为空数据时,自动开始第一次问答(跳过手动点「开始问答」)。 */
autoStartWhenPurposeEmpty?: boolean;
/** 是否在最左侧展示「智能体列表」栏(顶部下拉切换 我的/广场,点击进入该智能体对话)。
* 仅独立的智能体问答整页开启;任务工作区 / 模块页 / 嵌入态不传(各有自己的左栏)。 */
showAgentList?: boolean;
} = {}) {
const routeBase = useRouteBase();
const { t } = useI18n();
@@ -57,6 +76,29 @@ export default function AgentChatPage({
// 对话路由前缀:调用方可覆盖(任务深链嵌入态),否则用当前 routeBase 下的独立智能体对话路径。
const agentChatsBase = chatBasePath ?? `${routeBase}/agents/${agent_id}/chats`;
// 任务深链上下文(taskId + 开场信息):闸门(rwfx)与纯绑定(3qfx/xdfx)都要读取。
const taskCtxOn = !!(taskGate || taskBind);
const taskContext = useMemo(
() => (taskCtxOn ? readTaskContext() : null),
[taskCtxOn],
);
const taskId =
taskCtxOn && taskContext && taskContext.agentId === agent_id
? taskContext.taskId
: "";
// 纯绑定(taskBind,无闸门,3qfx/xdfx):新建对话进问答页后,右上角「开始回答」按钮点击时
// 发出的任务开场信息。不再自动发(避免新建对话竞态重复发送),改由用户手动点按钮触发。
// rwfx 走目的树闸门「开始问答」,不在此列。
const taskStartText =
taskBind && !taskGate && taskContext && taskContext.agentId === agent_id
? (taskContext.openingText?.trim() ?? "")
: "";
// 「首次进入且该任务无历史」信号:由 TaskFxIndexResolver 在「无聊天对话 → /new」时注入
// (用户主动点「新建对话」不带)。3qfx/xdfx 据此自动发出开场词、跳过「开始回答」按钮;
// rwfx 据此决定目的树为空时是否自动开始(仍由 TaskPurposePanel 在有数据时弹覆盖确认)。
const location = useLocation();
const taskAutoStart = !!(location.state as { taskAutoStart?: boolean } | null)?.taskAutoStart;
// If ChatPage stashed an opening message for this agent, skip the landing
// screen on first render so the user doesn't see a flash of the welcome UI
// before the auto-sent message takes over.
@@ -72,7 +114,7 @@ export default function AgentChatPage({
}
};
const [hasStartedConversation, setHasStartedConversation] = useState(
hasPendingForThisAgent,
() => hasPendingForThisAgent(),
);
const { agent, isLoading: isAgentLoading } = useAgent(agent_id);
@@ -101,6 +143,8 @@ export default function AgentChatPage({
threadId: isNewThread ? undefined : threadId,
assistantId: agent_id,
context: { ...settings.context, agent_id },
// 任务闸门:新建 thread 打 metadata.taskId 标签,供任务对话列表(1:N)按任务过滤。
threadMetadata: taskId ? { taskId } : undefined,
onStart: (createdThreadId) => {
setThreadId(createdThreadId);
setIsNewThread(false);
@@ -143,6 +187,30 @@ export default function AgentChatPage({
[sendMessage, threadId, agent_id],
);
// 任务流程:切换 / 新建会话时,停掉「上一会话服务端在跑」的 run(老对话要停止)。
// 任务工作区(rwfx 闸门 + 3qfx/xdfx 纯绑定)启用——普通问答页保留后台续跑行为不变。
const prevTaskThreadRef = useRef<string | null>(null);
useEffect(() => {
if (!taskCtxOn) return;
const prev = prevTaskThreadRef.current;
if (prev && prev !== threadId) void stopThreadRun(prev);
prevTaskThreadRef.current = threadId ?? null;
}, [taskCtxOn, threadId]);
useEffect(() => {
// 离开任务问答页(卸载)时也停掉当前会话的服务端 run。
return () => {
if (taskCtxOn) void stopThreadRun(prevTaskThreadRef.current);
};
}, [taskCtxOn]);
// 任务闸门通过(无目的数据 / 覆盖成功):发出开场信息开始问答;无开场信息则
// 仅切到对话态(隐藏面板),让用户手动输入。
const handleGateStart = useCallback(() => {
const text = taskContext?.openingText?.trim();
if (text) handleSubmit({ text, files: [] });
else setHasStartedConversation(true);
}, [handleSubmit, taskContext]);
// ChatPage stashes the opening message in sessionStorage when the user picks
// an agent on the landing screen, then redirects here. Replay it once so the
// user doesn't have to re-type the question on the agent chat page.
@@ -168,6 +236,24 @@ export default function AgentChatPage({
handleSubmit({ text: pending.text, files: [] });
}, [agent_id, threadId, isNewThread, handleSubmit]);
// 纯绑定任务深链(3qfx/xdfx):用户主动「新建对话」进 landing 后,由 header 右上角「开始回答」
// 按钮手动触发发出开场信息(见下方 header)。手动场景不自动发,避免新建对话竞态导致的重复发送。
const handleTaskStart = useCallback(() => {
if (taskStartText) handleSubmit({ text: taskStartText, files: [] });
}, [handleSubmit, taskStartText]);
// 首次进入且该任务无历史(taskAutoStart):3qfx/xdfx 直接自动发出开场信息,无需手动点「开始回答」。
// autoStartedRef 一次性、不随 threadId 抖动重置,故只发一次(首次进入是干净 mount,无上一会话之忧)。
const autoStartedRef = useRef(false);
useEffect(() => {
if (!taskAutoStart) return;
if (!taskStartText) return;
if (!isNewThread) return;
if (autoStartedRef.current) return;
autoStartedRef.current = true;
handleSubmit({ text: taskStartText, files: [] });
}, [taskAutoStart, taskStartText, isNewThread, handleSubmit]);
const handleClarificationSubmit = useCallback(
(answer: string) => {
setHasStartedConversation(true);
@@ -181,6 +267,9 @@ export default function AgentChatPage({
}, [thread]);
const isLandingState = isNewThread && !hasStartedConversation;
// 任务闸门面板:仅 rwfx(taskGate)在新建对话且尚未开始时,于问答页顶部展示目的树 + 覆盖确认。
// 3qfx/xdfx(taskBind)不展示闸门,新建对话进问答页后由右上角「开始回答」按钮手动发出开场信息。
const showTaskGate = !!taskGate && !!taskId && isNewThread && !hasStartedConversation;
const isDemoMode = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
const status = thread.error
@@ -197,6 +286,8 @@ export default function AgentChatPage({
always opens between the chat and the detail panel — the detail
panel stays rightmost. */}
<div className="flex size-full min-h-0 overflow-hidden workspace-chat-bg">
{/* 最左:智能体列表栏(仅独立整页问答开启)。顶部下拉切换 我的/广场。 */}
{showAgentList && <AgentChatSidebar activeAgentId={agent_id} />}
<div className="min-h-0 min-w-0 flex-1">
<ChatBox threadId={threadId}>
{/* Main conversation column. `relative` hosts the floating
@@ -219,6 +310,18 @@ export default function AgentChatPage({
</div>
<div className="flex items-center">
{/* 3qfx/xdfx 任务深链:用户主动「新建对话」进问答页后,点此发出任务开场信息开始问答。
首次进入且无历史(taskAutoStart)会自动发,不显示此按钮。 */}
{taskStartText && isLandingState && !taskAutoStart && (
<Button
size="sm"
className="mr-1 bg-[var(--color-main)] text-white shadow-sm hover:bg-[var(--brand-950)]"
onClick={handleTaskStart}
disabled={isDemoMode}
>
开始回答
</Button>
)}
<Tooltip content={t.agents.newChat}>
<Button
size="sm"
@@ -245,6 +348,16 @@ export default function AgentChatPage({
</div>
</header>
{showTaskGate && (
<TaskPurposePanel
taskId={taskId}
onStart={handleGateStart}
// rwfx:仅「首次进入且无聊天对话历史」(taskAutoStart) 时,目的树为空才自动开始;
// 用户主动新建对话则需手动点「开始问答」。目的树有数据始终弹「覆盖并开始问答」确认。
autoStartWhenEmpty={!!autoStartWhenPurposeEmpty && taskAutoStart}
/>
)}
{isLandingState ? (
/* Home: centered hero, suggested questions, and input.
Everything lives inside the scrollable main column. No fixed,
@@ -355,6 +468,7 @@ export default function AgentChatPage({
agentName={agentDisplayName}
disabled={thread.isLoading || isDemoMode}
onAskQuestion={(text) => handleSubmit({ text, files: [] })}
defaultCollapsed={taskCtxOn}
/>
</div>
</ThreadContext.Provider>
+3 -1
View File
@@ -75,7 +75,9 @@ function ModuleChatShell({ module }: { module: AgentModuleConfig }) {
const [settingsOpen, setSettingsOpen] = useState(false);
return (
<div className="flex size-full min-h-0 overflow-hidden">
// 外壳挂 workspace-chat-bg:深色下整片用同一张深蓝主题底图(fixed),作为左栏半透明
// 玻璃面板透出的「底色」;浅色透明无影响。右侧对话区自带同款底图,左右底色一致。
<div className="workspace-chat-bg flex size-full min-h-0 overflow-hidden">
<AgentModuleSidebar
moduleKey={module.key}
activeAgentId={agent_id}
@@ -9,6 +9,7 @@ import { motion } from "motion/react";
import { Select } from "tdesign-react";
import {
AlertCircle,
ArrowLeft,
HelpCircle,
Info,
Link2,
@@ -21,6 +22,7 @@ import {
import { toast } from "sonner";
import { useTheme } from "@/contexts/ThemeContext";
import { useRouteNavigate } from "@/core/route-base";
import { listAgents } from "@/core/agents/api";
import type { Agent } from "@/core/agents/types";
import { listChains } from "@/roundtable-planning/api/chains";
@@ -34,6 +36,7 @@ import { cn } from "@/lib/utils";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
export default function BusinessChainMappingPage() {
const navigate = useRouteNavigate();
const { theme } = useTheme();
const isDark = theme === "dark";
// 整片脱敏:业务链条映射页展示文本(链条名/描述/席位名/标题)。输入框 Hook 自动跳过。
@@ -142,8 +145,8 @@ export default function BusinessChainMappingPage() {
/* ── 样式 ── */
const shellClass = isDark
? "h-full overflow-y-auto text-slate-100 workspace-chat-bg"
: "h-full overflow-y-auto bg-white text-[#222]";
? "size-full min-h-0 overflow-y-auto text-slate-100 workspace-chat-bg"
: "size-full min-h-0 overflow-y-auto bg-white text-[#222]";
// 卡片:无边框,纯阴影
const cardClass = isDark
@@ -233,6 +236,20 @@ export default function BusinessChainMappingPage() {
</span>
</div>
</div>
<button
type="button"
onClick={() => navigate("/page/strategy/business-chains")}
className={cn(
"relative z-10 inline-flex shrink-0 items-center gap-1.5 rounded-[5px] border px-3.5 py-2 text-xs font-semibold transition-all active:scale-95",
isDark
? "border-white/10 bg-white/5 text-slate-300 hover:bg-white/10 hover:text-slate-100"
: "border-slate-200 bg-white text-slate-600 hover:bg-slate-50 hover:text-slate-900",
)}
>
<ArrowLeft className="size-3.5" />
返回业务链条
</button>
</motion.div>
{/* ── 表格区 ── */}
+12
View File
@@ -27,6 +27,7 @@ import { QuestionNavigator } from "@/components/workspace/question-navigator";
import { ThreadTitle } from "@/components/workspace/thread-title";
import { TodoList } from "@/components/workspace/todo-list";
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
import { UserIdentityBadge } from "@/components/workspace/user-identity-badge";
import { Welcome } from "@/components/workspace/welcome";
import { CompactWelcome } from "@/components/workspace/compact-welcome";
import { readSidebarEnabled } from "@/core/page-layout/sidebar-enabled";
@@ -481,6 +482,17 @@ export default function ChatPage() {
<ExportTrigger threadId={threadId} />
<KnowledgeSaveTrigger threadId={threadId} />
<ArtifactTrigger />
{/* 不带全局顶栏(紧凑模式)时,名称+岗位回落到聊天页顶栏右侧,
与全量模式 Header 右上角保持一致。全量模式已有顶栏则不重复展示。 */}
{!compactChrome && (
<>
<div
className="bg-border/70 mx-1 h-6 w-px shrink-0"
aria-hidden
/>
<UserIdentityBadge />
</>
)}
</div>
</header>
<main className="flex min-h-0 max-w-full grow flex-col">
@@ -3,13 +3,16 @@
*
* 深蓝主题适配见 `./light-app-management.css`(《深蓝色 UI 规范》tokens.css)。
*/
import { useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import {
AlertCircle,
AlignLeft,
ArrowDown,
ArrowUp,
ChevronDown,
ChevronUp,
Copy,
GripVertical,
ExternalLink,
FolderTree,
Globe,
@@ -239,6 +242,68 @@ export default function LightAppManagementPage() {
[apps, categoryFilter, mountFilter],
);
// ── 排序调整:仅当「iframe 嵌套 + 指定某个挂载菜单」时开启 ──
// 同一菜单下的多个 iframe 子项可拖拽 / 上下移调整顺序;调整即写回各应用的 sortOrder,
// 侧栏(use-sidebar-menu 按列表顺序注入,后端按 sort_order 升序返回)随之同步。
const reorderable = categoryFilter === "iframe" && !!mountFilter && viewMode === "table";
// 乐观顺序覆盖(保存期间稳定显示,刷新回来与服务端一致);切换筛选/搜索即清空,回落服务端顺序。
const [orderIds, setOrderIds] = useState<string[] | null>(null);
const [reordering, setReordering] = useState(false);
const dragIndexRef = useRef<number | null>(null);
useEffect(() => {
setOrderIds(null);
}, [categoryFilter, mountFilter, search]);
const displayApps = useMemo(() => {
if (!reorderable || !orderIds) return tableApps;
const pos = new Map(orderIds.map((id, i) => [id, i] as const));
return [...tableApps].sort(
(a, b) => (pos.get(a.appId) ?? 1e9) - (pos.get(b.appId) ?? 1e9),
);
}, [reorderable, orderIds, tableApps]);
// 把整组按新顺序重排 sortOrder(组内 0-based;只 PUT 顺序变了的项),乐观先行。
const persistOrder = async (ordered: LightApp[]) => {
setOrderIds(ordered.map((a) => a.appId));
const changed = ordered.filter((a, i) => a.sortOrder !== i);
if (changed.length === 0) return;
setReordering(true);
try {
await Promise.all(
ordered.map((a, i) =>
a.sortOrder === i
? Promise.resolve()
: actions.update.mutateAsync({ appId: a.appId, patch: { sortOrder: i } }),
),
);
} catch (err) {
toast.error((err as Error).message || "排序保存失败");
setOrderIds(null);
} finally {
setReordering(false);
}
};
const moveApp = (index: number, dir: -1 | 1) => {
if (reordering) return;
const target = index + dir;
if (target < 0 || target >= displayApps.length) return;
const next = [...displayApps];
[next[index], next[target]] = [next[target]!, next[index]!];
void persistOrder(next);
};
const handleRowDrop = (toIndex: number) => {
const from = dragIndexRef.current;
dragIndexRef.current = null;
if (from === null || from === toIndex || reordering) return;
const next = [...displayApps];
const [moved] = next.splice(from, 1);
if (!moved) return;
next.splice(toIndex, 0, moved);
void persistOrder(next);
};
return (
<div className="light-app-management-page h-full overflow-y-auto bg-neutral-50 dark:bg-[#0C1836] dark:text-[#C5CFE0]">
<div className="mx-auto flex min-h-full w-full max-w-7xl flex-col space-y-7 px-8 py-8">
@@ -349,9 +414,18 @@ export default function LightAppManagementPage() {
</div>
<div className="space-y-4">
<div className="lam-count text-xs font-medium text-neutral-500">
搜寻到 <strong className="font-bold text-[#F5222D]">{tableApps.length}</strong>{" "}
个注册完成的子模块轻应用
<div className="lam-count flex flex-wrap items-center gap-x-3 gap-y-1 text-xs font-medium text-neutral-500">
<span>
搜寻到 <strong className="font-bold text-[#F5222D]">{tableApps.length}</strong>{" "}
个注册完成的子模块轻应用
</span>
{reorderable && (
<span className="inline-flex items-center gap-1 text-[11px] text-sky-600">
<GripVertical className="h-3.5 w-3.5" />
拖拽行或用上 / 下按钮调整「{mountLabel(mountFilter)}」下的菜单顺序,调整即生效
{reordering && <span className="text-neutral-400">· 保存中…</span>}
</span>
)}
</div>
{viewMode === "table" ? (
@@ -359,6 +433,7 @@ export default function LightAppManagementPage() {
<table className="lam-table w-full table-fixed border-collapse text-left">
<thead>
<tr className="select-none border-b border-neutral-100/80 bg-neutral-50/40 text-[12.5px] font-semibold text-neutral-500">
{reorderable && <th className="w-[44px] px-2 py-4" aria-label="拖拽排序" />}
<th className="w-[15%] px-6 py-4">名称</th>
<th className="w-[14%] px-4 py-4">类型</th>
<th className="w-[27%] px-4 py-4">地址</th>
@@ -369,8 +444,32 @@ export default function LightAppManagementPage() {
</tr>
</thead>
<tbody className="divide-y divide-neutral-100">
{tableApps.map((app) => (
<tr key={app.appId} className="group align-middle transition-colors hover:bg-neutral-50/40">
{displayApps.map((app, index) => (
<tr
key={app.appId}
className={`group align-middle transition-colors hover:bg-neutral-50/40 ${
reorderable ? "lam-reorder-row" : ""
}`}
draggable={reorderable}
onDragStart={
reorderable
? (e) => {
dragIndexRef.current = index;
e.dataTransfer.effectAllowed = "move";
}
: undefined
}
onDragOver={reorderable ? (e) => e.preventDefault() : undefined}
onDrop={reorderable ? () => handleRowDrop(index) : undefined}
>
{reorderable && (
<td className="px-2 py-[18px] text-center">
<GripVertical
className="lam-drag-handle mx-auto h-4 w-4 cursor-grab text-neutral-300"
aria-hidden
/>
</td>
)}
<td className="px-6 py-[18px]">
<span className="lam-row-name text-[14px] font-bold text-neutral-800 transition-colors group-hover:text-[#F5222D]">
{app.name}
@@ -505,6 +604,29 @@ export default function LightAppManagementPage() {
<td className="px-4 py-[18px] pr-6 text-center">
<div className="flex items-center justify-center space-x-1">
{reorderable && (
<>
<button
type="button"
disabled={index === 0 || reordering}
onClick={() => moveApp(index, -1)}
className="lam-icon-btn cursor-pointer rounded-[5px] p-1 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-[#F5222D] disabled:cursor-not-allowed disabled:opacity-30"
title="上移"
>
<ArrowUp className="h-3.5 w-3.5" />
</button>
<button
type="button"
disabled={index === displayApps.length - 1 || reordering}
onClick={() => moveApp(index, 1)}
className="lam-icon-btn cursor-pointer rounded-[5px] p-1 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-[#F5222D] disabled:cursor-not-allowed disabled:opacity-30"
title="下移"
>
<ArrowDown className="h-3.5 w-3.5" />
</button>
<span className="mx-0.5 h-4 w-px shrink-0 bg-neutral-200" />
</>
)}
<button
onClick={() => openEdit(app)}
className="lam-icon-btn cursor-pointer rounded-[5px] p-1.5 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-emerald-600"
@@ -524,9 +646,9 @@ export default function LightAppManagementPage() {
</tr>
))}
{tableApps.length === 0 && (
{displayApps.length === 0 && (
<tr>
<td colSpan={7} className="py-12 text-center">
<td colSpan={reorderable ? 8 : 7} className="py-12 text-center">
<div className="flex flex-col items-center justify-center space-y-3">
<div className="lam-empty-icon flex h-12 w-12 items-center justify-center rounded-full bg-neutral-100 text-neutral-300">
<Info className="h-6 w-6" />
+13 -8
View File
@@ -14,6 +14,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ToolMetricsPanel } from "@/components/workspace/admin/tool-metrics-panel";
import {
@@ -494,14 +495,18 @@ function Td({
export default function LlmMetricsPage() {
const [tab, setTab] = useState<"llm" | "tool">("llm");
return (
<div className="mx-auto flex w-full max-w-6xl flex-col gap-4 px-6 py-8">
<Tabs value={tab} onValueChange={(v) => setTab(v as "llm" | "tool")}>
<TabsList>
<TabsTrigger value="llm">大模型调用</TabsTrigger>
<TabsTrigger value="tool">工具调用</TabsTrigger>
</TabsList>
</Tabs>
{tab === "llm" ? <LlmMetricsPanel /> : <ToolMetricsPanel />}
<div className="flex size-full min-h-0 w-full">
<ScrollArea className="min-h-0 flex-1">
<div className="mx-auto flex w-full max-w-6xl flex-col gap-4 px-6 py-8">
<Tabs value={tab} onValueChange={(v) => setTab(v as "llm" | "tool")}>
<TabsList>
<TabsTrigger value="llm">大模型调用</TabsTrigger>
<TabsTrigger value="tool">工具调用</TabsTrigger>
</TabsList>
</Tabs>
{tab === "llm" ? <LlmMetricsPanel /> : <ToolMetricsPanel />}
</div>
</ScrollArea>
</div>
);
}
+22 -4
View File
@@ -15,10 +15,12 @@ import {
import {
fetchCopTaskDetail,
persistCopTaskDetail,
resolveDeeplinkTaskId,
resolveTaskDeeplinkTarget,
} from '@/core/auth/task-deeplink';
import { resolveUsernameByOnlineTicket } from '@/core/auth/wujie-ticket-login';
import { isWujieEnv, useWujieProps } from '@/core/embed/wujie';
import { readEmbedParam } from '@/core/embed/embed-session';
import {
GENERAL_QA_ROUTE,
loginByYUserId,
@@ -47,6 +49,13 @@ export default function LoginPage() {
() => isSidebarEnabledFromSearch(searchParams.toString()),
[searchParams],
);
// iframe 嵌入模式(外部系统 `&embed=1`):去 chrome + 按标签页强制主题。嵌入侧**不**走
// setTheme / persistSidebarEnabled(那俩落 localStorage、会跨标签污染正常系统页),改用
// sessionStorage 嵌入会话(见 embed-session.ts)。`embed=0` 显式关闭。
const isEmbed = useMemo(
() => readEmbedParam(searchParams.toString()) === 'on',
[searchParams],
);
const redirectPath = useMemo(
() =>
searchParams.get('from') === IFRAME_LOGIN_SOURCE
@@ -104,11 +113,14 @@ export default function LoginPage() {
// 主题切换:无界 props.theme 优先,其次 URL query theme。两者取值约定一致
// (dark-blue → 深色;red → 浅色;blue 暂无该主题,先用浅色代替),统一走 resolveThemeFromQuery。
// **嵌入模式跳过**:setTheme 会写 localStorage `strategy-theme`,跨标签污染正常系统页;
// 嵌入主题改由 forcedTheme(按标签页、不持久化)接管。
useEffect(() => {
if (isEmbed) return;
const themeValue = wujieProps.theme || externalParams.theme;
if (!themeValue) return;
setTheme(resolveThemeFromQuery(themeValue));
}, [wujieProps.theme, externalParams.theme, setTheme]);
}, [isEmbed, wujieProps.theme, externalParams.theme, setTheme]);
// ticket / userId / env 持久化(与 login 请求并行做,互不阻塞)
useEffect(() => {
@@ -153,18 +165,23 @@ export default function LoginPage() {
// 内网透传的 access_token 合并进 userInfo(在 loginByYUserId 覆盖之后),
// XK/PG 中任务 iframe 据此取 accessToken
persistAccessToken(accessToken);
persistSidebarEnabled(sidebarEnabled);
// 嵌入模式不写 sidebarEnabled(localStorage 的「简洁/全量」偏好会跨标签污染正常页);
// 去 chrome 由按标签页的嵌入会话(isEmbedActive)驱动,见 PageLayout。
if (!isEmbed) persistSidebarEnabled(sidebarEnabled);
setStatus('success');
// 任务深链:带 taskId + goPath 时拉任务详情并直送对应问答/会商页;
// 任一环节失败(无地址/拉取失败/未配置智能体/goPath 无法识别)都回退默认首页。
if (taskId && goPath) {
try {
const detail = await fetchCopTaskDetail(taskId);
// xdfx 深链 ?taskId= 传入的是「行动id」,先换成真正的「任务id」;其它业务原样。
const realTaskId = await resolveDeeplinkTaskId(goPath, taskId);
if (cancelled) return;
const detail = await fetchCopTaskDetail(realTaskId);
if (cancelled) return;
if (detail) {
persistCopTaskDetail(detail);
const target = await resolveTaskDeeplinkTarget(goPath, detail);
const target = await resolveTaskDeeplinkTarget(goPath, detail, realTaskId, taskId);
if (cancelled) return;
if (target) {
navigate(target.path, { replace: true, state: target.state });
@@ -205,6 +222,7 @@ export default function LoginPage() {
gatePassword,
taskId,
goPath,
isEmbed,
]);
return (
+1 -1
View File
@@ -2,7 +2,7 @@ import { MemorySettingsPage } from "@/components/workspace/settings/memory-setti
export default function MemoryPage() {
return (
<div className="flex flex-col h-full overflow-auto p-6">
<div className="flex size-full min-h-0 flex-col overflow-auto p-6">
<MemorySettingsPage />
</div>
);
@@ -0,0 +1,895 @@
/**
* 菜单管理页(仅管理员)。
*
* 管理整棵侧边栏菜单(一级 / 二级 / 三级),含通过「应用管理」注入的 iframe 轻应用节点。
* 编辑结果以「覆盖层」形式保存到后端 `/api/menu-overrides`,不改动代码里的静态菜单。
*
* 支持:
* - 改名 / 停用 / 启用(编辑弹窗)
* - 同级上下移动(↑ ↓ 箭头)
* - 拖拽调整顺序 + 跨层级移动(横向拖动改变层级,严格 ≤ 3 级)
* - 「移动到」父级选择器(拖拽之外的第二种调层级方式,键盘可达)
* - 保存 / 重置全部
*/
import { useEffect, useMemo, useState } from "react";
import { Navigate } from "react-router-dom";
import {
DndContext,
DragOverlay,
PointerSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
type DragMoveEvent,
type DragStartEvent,
} from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
ChevronDown,
ChevronRight,
ChevronsLeft,
ChevronsRight,
ChevronUp,
GripVertical,
Info,
Menu,
Pencil,
RotateCcw,
Save,
Search,
Sparkles,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { getStoredAuth } from "@/core/auth";
import {
MAX_MENU_DEPTH,
diffOverrides,
flattenMenu,
isDescendant,
mergeFlatNodes,
wouldExceedDepth,
type MenuOverride,
type MergedMenuNode,
} from "@/core/page-layout/menu-overrides";
import { sidebarMenuItems, type MenuItem } from "@/core/page-layout/sidebar-menu";
import { injectLightApps } from "@/core/page-layout/use-sidebar-menu";
import { useLightApps } from "@/strategy-components/api/light-apps";
import {
useMenuOverrideActions,
useMenuOverrides,
} from "@/strategy-components/api/menu-overrides";
const INDENT = 22;
/** 编辑器内部的扁平行(数组顺序 = DFS 显示顺序,同级连续)。 */
interface FlatRow {
id: string;
parentId: string | null;
label: string;
disabled: boolean;
source: MenuItem;
defaultLabel: string;
defaultParentId: string | null;
defaultIndex: number;
isLightApp: boolean;
}
// ── 扁平行工具 ───────────────────────────────────────────────────────────
/** 按 parentId 分组、DFS 重排,使每个节点的子节点紧跟其后(同级保持相遇顺序)。 */
function normalizeDfs(list: FlatRow[]): FlatRow[] {
const childrenOf = new Map<string | null, FlatRow[]>();
for (const r of list) {
const key = r.parentId ?? null;
const arr = childrenOf.get(key) ?? [];
arr.push(r);
childrenOf.set(key, arr);
}
const out: FlatRow[] = [];
const walk = (pid: string | null) => {
for (const node of childrenOf.get(pid) ?? []) {
out.push(node);
walk(node.id);
}
};
walk(null);
return out;
}
function mergedToRows(merged: MergedMenuNode[]): FlatRow[] {
const childrenOf = new Map<string | null, MergedMenuNode[]>();
for (const n of merged) {
const key = n.parentId ?? null;
const arr = childrenOf.get(key) ?? [];
arr.push(n);
childrenOf.set(key, arr);
}
const rows: FlatRow[] = [];
const walk = (pid: string | null) => {
(childrenOf.get(pid) ?? [])
.slice()
.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
.forEach((n) => {
rows.push({
id: n.id,
parentId: n.parentId ?? null,
label: n.label,
disabled: n.disabled,
source: n.source,
defaultLabel: n.defaultLabel,
defaultParentId: n.defaultParentId,
defaultIndex: n.defaultIndex,
isLightApp: n.isLightApp,
});
walk(n.id);
});
};
walk(null);
return rows;
}
/** 扁平行 → 合并节点(order = 同级内位置),供 diff / 深度校验复用。 */
function rowsToMerged(rows: FlatRow[]): MergedMenuNode[] {
const counter = new Map<string | null, number>();
return rows.map((r) => {
const key = r.parentId ?? null;
const order = counter.get(key) ?? 0;
counter.set(key, order + 1);
return {
id: r.id,
defaultLabel: r.defaultLabel,
defaultParentId: r.defaultParentId,
defaultIndex: r.defaultIndex,
source: r.source,
isLightApp: r.isLightApp,
label: r.label,
parentId: r.parentId ?? null,
order,
disabled: r.disabled,
hasOverride: false,
};
});
}
function depthByIdOf(rows: FlatRow[]): Map<string, number> {
const parentOf = new Map(rows.map((r) => [r.id, r.parentId]));
const cache = new Map<string, number>();
const compute = (id: string): number => {
if (cache.has(id)) return cache.get(id)!;
const pid = parentOf.get(id) ?? null;
const d = pid == null ? 1 : compute(pid) + 1;
cache.set(id, d);
return d;
};
for (const r of rows) compute(r.id);
return cache;
}
// ── 可排序行 ─────────────────────────────────────────────────────────────
interface SortableRowProps {
row: FlatRow;
depth: number;
canUp: boolean;
canDown: boolean;
canIndent: boolean;
canOutdent: boolean;
dragEnabled: boolean;
onUp: () => void;
onDown: () => void;
onIndent: () => void;
onOutdent: () => void;
onToggle: () => void;
onEdit: () => void;
}
/** 一级 / 二级 / 三级 的层级色标。 */
const LEVEL_BADGE = [
"bg-blue-50 text-blue-600 border border-blue-100",
"bg-purple-50 text-purple-600 border border-purple-100",
"bg-indigo-50 text-indigo-600 border border-indigo-100",
];
function SortableRow({
row,
depth,
canUp,
canDown,
canIndent,
canOutdent,
dragEnabled,
onUp,
onDown,
onIndent,
onOutdent,
onToggle,
onEdit,
}: SortableRowProps) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: row.id,
});
const Icon = row.source.icon;
const levelLabel = ["一级", "二级", "三级"][depth - 1] ?? `${depth}级`;
const typeLabel = row.isLightApp ? "应用" : "内置";
return (
<div
ref={setNodeRef}
style={{
transform: CSS.Transform.toString(transform),
transition,
marginLeft: (depth - 1) * INDENT,
opacity: isDragging ? 0.4 : 1,
}}
className={`group relative flex flex-col gap-3 rounded-2xl border p-3.5 transition-all md:flex-row md:items-center md:justify-between ${
row.disabled
? "border-slate-100 bg-slate-50/40"
: "border-slate-200/70 bg-white shadow-[0_1px_4px_-1px_rgba(0,0,0,0.04)] hover:border-slate-300 hover:shadow-[0_4px_16px_-4px_rgba(0,0,0,0.08)]"
}`}
>
{/* 左侧:拖拽柄 + 图标 + 名称/路径 */}
<div className="flex min-w-0 items-center gap-3">
<button
type="button"
className={`shrink-0 rounded p-1 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600 ${
dragEnabled ? "cursor-grab touch-none active:cursor-grabbing" : "cursor-not-allowed opacity-40"
}`}
title={dragEnabled ? "拖动调整顺序与层级" : "筛选状态下不可拖动"}
{...(dragEnabled ? attributes : {})}
{...(dragEnabled ? listeners : {})}
>
<GripVertical className="size-4" />
</button>
{depth > 1 && (
<ChevronRight className="hidden size-3.5 shrink-0 stroke-[2.5] text-slate-300 sm:block" />
)}
<button
type="button"
onClick={onEdit}
className={`shrink-0 rounded-xl p-2.5 transition-all ${
row.disabled
? "bg-slate-100 text-slate-400"
: "bg-red-50 text-red-600 hover:scale-105 hover:bg-red-100"
}`}
title="点击修改菜单详情"
>
<Icon className="size-[18px]" />
</button>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<button
type="button"
onClick={onEdit}
className={`truncate text-sm font-semibold transition-colors hover:text-red-600 ${
row.disabled ? "text-slate-400 line-through" : "text-slate-800"
}`}
>
{row.label}
</button>
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${LEVEL_BADGE[depth - 1] ?? LEVEL_BADGE[2]}`}
>
{levelLabel}
</span>
<span className="rounded border border-slate-200/60 bg-slate-100 px-1.5 py-0.5 font-mono text-[10px] font-medium text-slate-500">
{typeLabel}
</span>
</div>
</div>
{/* 右侧:层级/排序按钮组 + 状态 + 编辑 */}
<div className="flex items-center justify-between gap-2.5 border-t border-slate-100 pt-2.5 md:justify-end md:border-t-0 md:pt-0">
<div className="flex items-center rounded-xl border border-slate-200/70 bg-slate-50/80 p-0.5 text-slate-500">
<button
type="button"
onClick={onOutdent}
disabled={!canOutdent}
className="rounded-lg p-1.5 transition-colors hover:bg-white hover:text-slate-800 disabled:opacity-20 disabled:hover:bg-transparent"
title="升一级"
>
<ChevronsLeft className="size-3.5" />
</button>
<button
type="button"
onClick={onIndent}
disabled={!canIndent}
className="rounded-lg p-1.5 transition-colors hover:bg-white hover:text-slate-800 disabled:opacity-20 disabled:hover:bg-transparent"
title="降一级"
>
<ChevronsRight className="size-3.5" />
</button>
<div className="mx-1 h-4 w-px bg-slate-200" />
<button
type="button"
onClick={onUp}
disabled={!canUp}
className="rounded-lg p-1.5 transition-colors hover:bg-white hover:text-slate-800 disabled:opacity-20 disabled:hover:bg-transparent"
title="上移"
>
<ChevronUp className="size-3.5" />
</button>
<button
type="button"
onClick={onDown}
disabled={!canDown}
className="rounded-lg p-1.5 transition-colors hover:bg-white hover:text-slate-800 disabled:opacity-20 disabled:hover:bg-transparent"
title="下移"
>
<ChevronDown className="size-3.5" />
</button>
</div>
<button
type="button"
onClick={onToggle}
className={`inline-flex select-none items-center gap-1.5 rounded-xl px-3 py-1.5 text-xs font-semibold transition-all ${
row.disabled
? "bg-slate-100 text-slate-400 hover:bg-slate-200 hover:text-slate-600"
: "border border-emerald-200/50 bg-emerald-50 text-emerald-600 hover:bg-emerald-100"
}`}
title="点击切换启用 / 停用"
>
<span className={`size-1.5 shrink-0 rounded-full ${row.disabled ? "bg-slate-400" : "bg-emerald-500"}`} />
{row.disabled ? "停用中" : "启用中"}
</button>
<button
type="button"
onClick={onEdit}
className="rounded-lg p-1.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-700"
title="编辑"
>
<Pencil className="size-4" />
</button>
</div>
</div>
);
}
// ── 主页面 ───────────────────────────────────────────────────────────────
export default function MenuManagementPage() {
const isAdmin = getStoredAuth()?.system_role === "admin";
// 与侧边栏一致:只取「启用的 iframe 轻应用」作为合并基树,避免管理树与实际渲染脱节。
const { data: iframeApps = [] } = useLightApps({ appType: "iframe", enabledOnly: true });
const { data: overrides = [], isLoading } = useMenuOverrides();
const { save } = useMenuOverrideActions();
const baseTree = useMemo(() => injectLightApps(sidebarMenuItems, iframeApps), [iframeApps]);
// 初始扁平行(套用已保存覆盖层,含停用项)。
const initialRows = useMemo(
() => mergedToRows(mergeFlatNodes(flattenMenu(baseTree), overrides)),
[baseTree, overrides],
);
const [rows, setRows] = useState<FlatRow[]>(initialRows);
const [loadedKey, setLoadedKey] = useState("");
const [editId, setEditId] = useState<string | null>(null);
const [activeId, setActiveId] = useState<string | null>(null);
const [offsetX, setOffsetX] = useState(0);
const [query, setQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<"all" | "active" | "inactive">("all");
// 数据首次/变化加载时,用服务端值重置工作副本(避免覆盖用户未保存的编辑:以来源 key 判定)。
const sourceKey = useMemo(
() => JSON.stringify({ a: iframeApps.map((x) => x.appId), o: overrides }),
[iframeApps, overrides],
);
useEffect(() => {
if (sourceKey !== loadedKey) {
setRows(initialRows);
setLoadedKey(sourceKey);
}
}, [sourceKey, loadedKey, initialRows]);
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
const depthById = useMemo(() => depthByIdOf(rows), [rows]);
const mergedNow = useMemo(() => rowsToMerged(rows), [rows]);
const currentOverrides = useMemo(() => diffOverrides(mergedNow), [mergedNow]);
const dirty = useMemo(() => {
const norm = (list: MenuOverride[]) =>
JSON.stringify(
list
.map((o) => ({ ...o, label: o.label ?? null, parentId: o.parentId ?? null }))
.sort((a, b) => a.nodeId.localeCompare(b.nodeId)),
);
return norm(currentOverrides) !== norm(overrides);
}, [currentOverrides, overrides]);
const editingRow = rows.find((r) => r.id === editId) ?? null;
const isFiltering = query.trim() !== "" || statusFilter !== "all";
const visibleRows = useMemo(() => {
const q = query.trim().toLowerCase();
return rows.filter((r) => {
const matchQ = !q || r.label.toLowerCase().includes(q);
const matchS =
statusFilter === "all" ||
(statusFilter === "active" && !r.disabled) ||
(statusFilter === "inactive" && r.disabled);
return matchQ && matchS;
});
}, [rows, query, statusFilter]);
// ── 行操作 ──
const siblingsOf = (parentId: string | null) => rows.filter((r) => (r.parentId ?? null) === (parentId ?? null));
const reorderBefore = (moveId: string, beforeId: string) => {
setRows((prev) => {
const from = prev.findIndex((r) => r.id === moveId);
const to = prev.findIndex((r) => r.id === beforeId);
if (from < 0 || to < 0) return prev;
return normalizeDfs(arrayMove(prev, from, to));
});
};
const moveUp = (row: FlatRow) => {
const sibs = siblingsOf(row.parentId);
const i = sibs.findIndex((s) => s.id === row.id);
if (i > 0) reorderBefore(row.id, sibs[i - 1].id);
};
const moveDown = (row: FlatRow) => {
const sibs = siblingsOf(row.parentId);
const i = sibs.findIndex((s) => s.id === row.id);
if (i >= 0 && i < sibs.length - 1) reorderBefore(sibs[i + 1].id, row.id);
};
/** 降一级(缩进):成为「上一个同级兄弟」的末位子节点。 */
const indentRow = (row: FlatRow) => {
const sibs = siblingsOf(row.parentId);
const i = sibs.findIndex((s) => s.id === row.id);
if (i <= 0) return;
const newParent = sibs[i - 1].id;
if (wouldExceedDepth(row.id, newParent, mergedNow)) {
toast.error(`移动后将超过 ${MAX_MENU_DEPTH} 级,已阻止`);
return;
}
setRows((prev) => {
const next = prev.map((r) => (r.id === row.id ? { ...r, parentId: newParent } : r));
const idx = next.findIndex((r) => r.id === row.id);
const [moved] = next.splice(idx, 1);
next.push(moved);
return normalizeDfs(next);
});
};
/** 升一级(移位):移动到「父级的父级」下,紧跟原父级之后。 */
const outdentRow = (row: FlatRow) => {
if (row.parentId == null) return;
const parentRow = rows.find((r) => r.id === row.parentId);
if (!parentRow) return;
const newParent = parentRow.parentId ?? null;
setRows((prev) => {
const next = prev.map((r) => (r.id === row.id ? { ...r, parentId: newParent } : r));
const idx = next.findIndex((r) => r.id === row.id);
const [moved] = next.splice(idx, 1);
const pIdx = next.findIndex((r) => r.id === parentRow.id);
next.splice(pIdx + 1, 0, moved);
return normalizeDfs(next);
});
};
const toggleRow = (row: FlatRow) =>
setRows((prev) => prev.map((r) => (r.id === row.id ? { ...r, disabled: !r.disabled } : r)));
const applyEdit = (label: string, disabled: boolean, newParentId: string | null) => {
if (!editingRow) return;
const id = editingRow.id;
if ((newParentId ?? null) !== (editingRow.parentId ?? null)) {
if (newParentId && (newParentId === id || isDescendant(id, newParentId, mergedNow))) {
toast.error("不能移动到自身或其子菜单下");
return;
}
if (wouldExceedDepth(id, newParentId ?? null, mergedNow)) {
toast.error(`移动后将超过 ${MAX_MENU_DEPTH} 级,已阻止`);
return;
}
}
setRows((prev) => {
let next = prev.map((r) =>
r.id === id ? { ...r, label, disabled, parentId: newParentId ?? null } : r,
);
// 改了父级:把该行挪到数组末尾,规范化后成为新父级的末位子节点。
if ((newParentId ?? null) !== (editingRow.parentId ?? null)) {
const idx = next.findIndex((r) => r.id === id);
const [moved] = next.splice(idx, 1);
next.push(moved);
}
return normalizeDfs(next);
});
setEditId(null);
};
// ── 拖拽 ──
const flattenedDepths = depthById;
const computeProjection = (overId: string) => {
const activeIndex = rows.findIndex((r) => r.id === activeId);
const overIndex = rows.findIndex((r) => r.id === overId);
if (activeIndex < 0 || overIndex < 0) return null;
const moved = arrayMove(rows, activeIndex, overIndex);
const prev = moved[overIndex - 1];
const next = moved[overIndex + 1];
const activeDepth = flattenedDepths.get(activeId!) ?? 1;
const dragDepth = Math.round(offsetX / INDENT);
const projected = activeDepth + dragDepth;
// 被移动子树的高度 → 其根可落的最大深度。
const childrenMap = new Map<string | null, string[]>();
for (const r of rows) {
const k = r.parentId ?? null;
const arr = childrenMap.get(k) ?? [];
arr.push(r.id);
childrenMap.set(k, arr);
}
const heightOf = (id: string): number => {
const kids = childrenMap.get(id) ?? [];
return kids.length ? 1 + Math.max(...kids.map(heightOf)) : 1;
};
const activeCap = MAX_MENU_DEPTH - (heightOf(activeId!) - 1);
const maxDepth = Math.min(prev ? (flattenedDepths.get(prev.id) ?? 1) + 1 : 1, activeCap);
const minDepth = next ? flattenedDepths.get(next.id) ?? 1 : 1;
let depth = Math.max(minDepth, Math.min(projected, maxDepth));
depth = Math.max(1, depth);
const parentId = (() => {
if (depth <= 1 || !prev) return null;
const prevDepth = flattenedDepths.get(prev.id) ?? 1;
if (depth === prevDepth) return prev.parentId ?? null;
if (depth > prevDepth) return prev.id;
const back = moved
.slice(0, overIndex)
.reverse()
.find((r) => (flattenedDepths.get(r.id) ?? 1) === depth);
return back ? back.parentId ?? null : null;
})();
return { depth, parentId };
};
const onDragStart = (e: DragStartEvent) => {
setActiveId(String(e.active.id));
setOffsetX(0);
};
const onDragMove = (e: DragMoveEvent) => {
setOffsetX(e.delta.x);
};
const onDragEnd = (e: DragEndEvent) => {
const aId = activeId;
setActiveId(null);
setOffsetX(0);
const overId = e.over ? String(e.over.id) : null;
if (!aId || !overId) return;
const proj = computeProjection(overId);
if (!proj) return;
const parentId = proj.parentId;
if (parentId && (parentId === aId || isDescendant(aId, parentId, mergedNow))) {
return; // 落到自身子树,忽略
}
if (wouldExceedDepth(aId, parentId, mergedNow)) {
toast.error(`移动后将超过 ${MAX_MENU_DEPTH} 级,已阻止`);
return;
}
setRows((prev) => {
const activeIndex = prev.findIndex((r) => r.id === aId);
const overIndex = prev.findIndex((r) => r.id === overId);
if (activeIndex < 0 || overIndex < 0) return prev;
const clone = prev.map((r) => ({ ...r }));
clone[activeIndex].parentId = parentId;
return normalizeDfs(arrayMove(clone, activeIndex, overIndex));
});
};
const handleSave = async () => {
try {
await save.mutateAsync(currentOverrides);
toast.success("菜单配置已保存");
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存失败");
}
};
const handleReset = () => {
if (!confirm("确定要重置全部菜单为默认布局吗?保存后将清除所有自定义配置。")) return;
setRows(mergedToRows(mergeFlatNodes(flattenMenu(baseTree), [])));
};
if (!isAdmin) return <Navigate to="/page/workspace/chats/new" replace />;
return (
<div className="h-full overflow-auto bg-slate-50/60 px-4 py-6 sm:px-6 lg:px-8">
<div className="mx-auto max-w-4xl">
{/* 顶部信息卡 */}
<div className="relative mb-6 overflow-hidden rounded-3xl border border-slate-200/60 bg-white p-6 shadow-sm md:p-8">
<div className="pointer-events-none absolute right-0 top-0 select-none p-8 opacity-[0.03]">
<Menu className="size-44 text-slate-900" />
</div>
<div className="relative">
<div className="mb-4 flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div>
<span className="mb-3 inline-flex select-none items-center gap-1.5 rounded-full border border-red-100 bg-red-50 px-3 py-1 text-xs font-semibold text-red-600">
<Sparkles className="size-3" />
系统集成版
</span>
<h1 className="flex items-center gap-3 text-2xl font-bold tracking-tight text-slate-800 md:text-3xl">
菜单管理
<span className="rounded-lg border border-slate-200/60 bg-slate-100 px-2.5 py-0.5 font-mono text-xs font-medium text-slate-500">
{rows.length} 个项目
</span>
</h1>
</div>
<div className="flex items-center gap-2.5">
<button
type="button"
onClick={handleReset}
className="inline-flex cursor-pointer items-center gap-2 rounded-xl border border-slate-200 bg-white px-3.5 py-2 text-sm font-semibold text-slate-600 shadow-sm transition-all hover:border-slate-300 hover:bg-slate-50 hover:text-slate-800"
title="恢复为默认菜单布局"
>
<RotateCcw className="size-[15px]" />
重置全部
</button>
<button
type="button"
onClick={handleSave}
disabled={!dirty || save.isPending}
className="inline-flex cursor-pointer items-center gap-2 rounded-xl border border-red-600 bg-red-600 px-5 py-2 text-sm font-semibold text-white shadow-sm transition-all hover:bg-red-700 active:scale-95 disabled:cursor-not-allowed disabled:opacity-50"
>
{save.isPending ? (
<>
<div className="size-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
保存中…
</>
) : (
<>
<Save className="size-[15px]" />
保存修改
</>
)}
</button>
</div>
</div>
<p className="flex max-w-2xl items-start gap-2.5 rounded-2xl border border-slate-200/50 bg-slate-50/70 p-3.5 text-sm leading-relaxed text-slate-600">
<Info className="mt-0.5 size-4 shrink-0 text-slate-400" />
<span>
<strong>拖拽调整</strong> 菜单顺序与层级(按住拖拽地标 <span className="font-mono">::</span>{" "}
上下排序,横向拖动改变层级);也可点击卡片上的<strong> 缩进 / 移位按钮 </strong>
精确调整层级(最多 {MAX_MENU_DEPTH} 级)、启停与编辑。
</span>
</p>
</div>
</div>
{/* 搜索 + 状态筛选栏 */}
<div className="mb-6 flex flex-col items-center justify-between gap-4 rounded-2xl border border-slate-200/60 bg-white p-4 shadow-sm md:flex-row md:p-5">
<div className="relative w-full md:w-80">
<Search className="absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="搜索菜单名称…"
value={query}
onChange={(e) => setQuery(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-slate-50/50 py-2 pl-10 pr-4 text-sm transition-all hover:border-slate-300 focus:border-red-500 focus:outline-none focus:ring-4 focus:ring-red-500/5"
/>
</div>
<div className="inline-flex items-center rounded-xl border border-slate-200/40 bg-slate-100/80 p-1 text-xs font-medium">
{(
[
["all", "全部"],
["active", "已启用"],
["inactive", "已停用"],
] as const
).map(([key, label]) => (
<button
key={key}
type="button"
onClick={() => setStatusFilter(key)}
className={`cursor-pointer rounded-lg px-3.5 py-1.5 transition-all ${
statusFilter === key
? "bg-white font-semibold text-slate-800 shadow-sm"
: "text-slate-500 hover:text-slate-800"
}`}
>
{label}
</button>
))}
</div>
</div>
{/* 菜单列表卡 */}
<div className="min-h-[400px] rounded-3xl border border-slate-200/60 bg-white p-4 shadow-sm md:p-6">
{isLoading ? (
<p className="py-20 text-center text-sm text-slate-400">加载中…</p>
) : visibleRows.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20 text-center">
<div className="mb-4 rounded-full bg-slate-100 p-4 text-slate-400">
<Menu className="size-8" />
</div>
<h4 className="mb-1 text-base font-semibold text-slate-700">无符合条件的菜单项</h4>
<p className="max-w-xs text-sm text-slate-400">尝试清空搜索或筛选条件以查看全部菜单。</p>
</div>
) : (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={onDragStart}
onDragMove={onDragMove}
onDragEnd={onDragEnd}
onDragCancel={() => {
setActiveId(null);
setOffsetX(0);
}}
>
<SortableContext
items={visibleRows.map((r) => r.id)}
strategy={verticalListSortingStrategy}
>
<div className="flex flex-col gap-3">
{visibleRows.map((row) => {
const sibs = siblingsOf(row.parentId);
const i = sibs.findIndex((s) => s.id === row.id);
const canIndent = i > 0 && !wouldExceedDepth(row.id, sibs[i - 1].id, mergedNow);
return (
<SortableRow
key={row.id}
row={row}
depth={depthById.get(row.id) ?? 1}
canUp={i > 0}
canDown={i >= 0 && i < sibs.length - 1}
canIndent={canIndent}
canOutdent={row.parentId != null}
dragEnabled={!isFiltering}
onUp={() => moveUp(row)}
onDown={() => moveDown(row)}
onIndent={() => indentRow(row)}
onOutdent={() => outdentRow(row)}
onToggle={() => toggleRow(row)}
onEdit={() => setEditId(row.id)}
/>
);
})}
</div>
</SortableContext>
<DragOverlay>
{activeId ? (
<div className="rounded-2xl border border-red-200 bg-white px-3.5 py-2 text-sm font-semibold text-slate-800 shadow-lg">
{rows.find((r) => r.id === activeId)?.label}
</div>
) : null}
</DragOverlay>
</DndContext>
)}
</div>
</div>
{editingRow && (
<EditMenuDialog
key={editingRow.id}
row={editingRow}
rows={rows}
merged={mergedNow}
depthById={depthById}
onClose={() => setEditId(null)}
onApply={applyEdit}
/>
)}
</div>
);
}
// ── 编辑弹窗 ─────────────────────────────────────────────────────────────
interface EditMenuDialogProps {
row: FlatRow;
rows: FlatRow[];
merged: MergedMenuNode[];
depthById: Map<string, number>;
onClose: () => void;
onApply: (label: string, disabled: boolean, parentId: string | null) => void;
}
const ROOT_OPTION = "__root__";
function EditMenuDialog({ row, rows, merged, depthById, onClose, onApply }: EditMenuDialogProps) {
const [label, setLabel] = useState(row.label);
const [disabled, setDisabled] = useState(row.disabled);
const [parentValue, setParentValue] = useState(row.parentId ?? ROOT_OPTION);
// 合法的「移动到」父级:非自身、非自身子树、移动后不超 3 级。
const parentOptions = useMemo(() => {
const opts: { value: string; label: string }[] = [{ value: ROOT_OPTION, label: "(设为一级菜单)" }];
for (const r of rows) {
if (r.id === row.id) continue;
if (isDescendant(row.id, r.id, merged)) continue;
if (wouldExceedDepth(row.id, r.id, merged)) continue;
const depth = depthById.get(r.id) ?? 1;
opts.push({ value: r.id, label: `${" ".repeat(depth - 1)}${r.label}` });
}
return opts;
}, [row.id, rows, merged, depthById]);
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>编辑菜单</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4 py-2">
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium">名称</label>
<Input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="菜单显示名称" />
</div>
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">启用</p>
<p className="text-xs text-muted-foreground">停用后该菜单(及其子菜单)对所有用户隐藏</p>
</div>
<Switch checked={!disabled} onCheckedChange={(v) => setDisabled(!v)} />
</div>
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium">移动到(父级)</label>
<Select value={parentValue} onValueChange={setParentValue}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent className="max-h-72">
{parentOptions.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">选择目标父级即可调整层级(拖拽之外的方式),最多 {MAX_MENU_DEPTH} 级。</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
取消
</Button>
<Button
onClick={() =>
onApply(label.trim() || row.label, disabled, parentValue === ROOT_OPTION ? null : parentValue)
}
>
确定
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+5
View File
@@ -83,6 +83,8 @@ export default function NewAgentPage() {
const [modelInput, setModelInput] = useState<string>("");
const [chatModelInput, setChatModelInput] = useState<string>("");
const [templateNameInput, setTemplateNameInput] = useState("");
// 会商席位「技能识别强化」开关(弱模型补偿)。默认关。
const [seatSkillDirectiveInput, setSeatSkillDirectiveInput] = useState(false);
const [formError, setFormError] = useState("");
const [agentId, setAgentId] = useState("");
const [agent, setAgent] = useState<Agent | null>(null);
@@ -230,6 +232,7 @@ export default function NewAgentPage() {
skills: selectedSkills,
model: modelOverride,
template_name: templateNameInput.trim(),
seat_skill_directive: seatSkillDirectiveInput,
});
setAgent(updated);
return updated;
@@ -251,6 +254,7 @@ export default function NewAgentPage() {
skills: selectedSkills,
model: modelOverride,
template_name: templateNameInput.trim(),
seat_skill_directive: seatSkillDirectiveInput,
});
setAgentId(created.id);
setAgent(created);
@@ -281,6 +285,7 @@ export default function NewAgentPage() {
selectedSkills,
soulInput,
templateNameInput,
seatSkillDirectiveInput,
t.agents.nameStepCheckError,
t.agents.nameStepNetworkError,
validateForm,
+8 -1
View File
@@ -6,6 +6,7 @@ import { PageSidebarDark } from "@/components/page-sidebar-dark";
import { isChatsIframeWorkspacePath } from "@/core/page-layout/chats-iframe-route";
import { readSidebarEnabled } from "@/core/page-layout/sidebar-enabled";
import { isWujieEnv } from "@/core/embed/wujie";
import { isEmbedActive, readEmbedParam } from "@/core/embed/embed-session";
import { useTheme } from "@/contexts/ThemeContext";
import { useLocation } from "react-router-dom";
import { useActiveThirdLevel } from "@/core/page-layout/use-sidebar-menu";
@@ -37,8 +38,14 @@ function PageLayout() {
const [layoutMode] = useLayoutMode();
const chromeByPreference =
layoutMode === "full" ? true : layoutMode === "compact" ? false : sidebarEnabled;
// iframe 嵌入模式(外部系统 `&embed=1`,按标签页 sessionStorage):去掉全局导航栏 + 侧边栏,
// 只留问答/会商工作区本体。按 location 重算以跟随页内导航;非嵌入标签页恒为 false,不受影响。
const embedActive = useMemo(
() => isEmbedActive() || readEmbedParam(location.search) === "on",
[location.pathname, location.search],
);
const pageSidebarAllowed =
chromeByPreference && !isChatsIframeWorkspacePath(location.pathname);
chromeByPreference && !isChatsIframeWorkspacePath(location.pathname) && !embedActive;
// h-full(100%)而非 h-screen(100vh):配合 globals.css 的 html/body/#root height:100%
// 高度链,根布局跟随容器高度。全屏下 100% 解析到视口,与 h-screen 等价;无界等嵌套
@@ -34,6 +34,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Pagination } from "@/components/ui/pagination";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type {
AdminLeaderboardDimension,
@@ -225,7 +226,11 @@ export default function PublicLeaderboardPage() {
}, [userPageCount]);
return (
<div className="min-h-screen w-full bg-[#FFF7F7] text-[#231815] dark:bg-[#011226] dark:text-white" style={pageBg}>
<div
className="flex size-full min-h-0 w-full bg-[#FFF7F7] text-[#231815] dark:bg-[#011226] dark:text-white"
style={pageBg}
>
<ScrollArea className="min-h-0 flex-1">
<div className="mx-auto w-full max-w-6xl px-4 py-8 sm:px-6 sm:py-10">
{/* 标题区:仅展示,不含任何操作按钮 */}
<header className="mb-6">
@@ -372,6 +377,7 @@ export default function PublicLeaderboardPage() {
{data?.generated_at ? `数据生成于 ${fmtDate(data.generated_at)}` : "仅供查看"}
</footer>
</div>
</ScrollArea>
</div>
);
}
@@ -0,0 +1,333 @@
"use client";
/**
* 会商诊断日志(仅 admin):展示多智能体会商全流程(第一步意图 / 第二步研讨 /
* 第三步报告 + 后台挂起执行器 / 进程内网关)各处的报错与关键事件,支持按
* scope(前台/后台)、阶段、级别、事件码、作业/任务/草稿 id、关键词筛选 + 分页。
*
* 数据源:`GET /api/roundtable-diagnostics`(admin-gated)。入口:多智能体会商页右上角
* 设置按钮(admin)。见 [[roundtable-diagnostics]]。
*/
import { useMemo, useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import { ArrowLeft, RefreshCw, Search } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Pagination } from "@/components/ui/pagination";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { getStoredAuth } from "@/core/auth";
import {
type DiagnosticFilters,
type DiagnosticItem,
useRoundtableDiagnosticFacets,
useRoundtableDiagnostics,
} from "@/strategy-components/api/roundtable-diagnostics";
const PAGE_SIZE = 50;
const ALL = "__all__";
// 阶段中文名(已知集合;未知阶段原样显示)。
const STAGE_LABELS: Record<string, string> = {
step1_intent: "第一步 · 意图",
step2_init: "第二步 · 初始化",
step2_leader: "第二步 · 总控",
step2_seat: "第二步 · 席位",
step2_recommend: "第二步 · 推荐",
step2_orchestration: "第二步 · 编排",
step3_summary: "第三步 · 总结报告",
step3_report: "第三步 · 结果绘制",
step3_dashboard: "第三步 · 大屏数据",
step3_structure: "第三步 · 数据入库",
upstream: "回环代理",
job: "后台作业",
};
const SCOPE_LABELS: Record<string, string> = {
background: "后台挂起",
foreground: "前台实时(服务端)",
client: "前端上报",
};
// 范围切换:后台挂起(background) / 前台调用(foreground 服务端观测 + client 前端上报)。
type ScopeCategory = "background" | "frontend";
// 每个范围下可选的阶段(按用户要求:后台挂起只到第二/三步;前台调用含第一步)。
const STAGE_OPTIONS: Record<ScopeCategory, string[]> = {
background: [
"step2_init",
"step2_leader",
"step2_seat",
"step2_orchestration",
"step3_summary",
"step3_report",
"step3_dashboard",
"step3_structure",
"job",
],
frontend: [
"step1_intent",
"step2_init",
"step2_leader",
"step2_seat",
"step2_recommend",
"step3_summary",
"step3_report",
"step3_dashboard",
"step3_structure",
],
};
const LEVEL_STYLES: Record<string, string> = {
error: "bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300",
warning: "bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300",
info: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300",
};
function stageLabel(stage: string): string {
return STAGE_LABELS[stage] ?? stage;
}
function fmtTime(iso: string | null): string {
if (!iso) return "";
try {
const d = new Date(iso);
return d.toLocaleString("zh-CN", { hour12: false });
} catch {
return iso;
}
}
function DiagnosticRow({ item }: { item: DiagnosticItem }) {
const [open, setOpen] = useState(false);
const hasDetail = item.detail != null && Object.keys(item.detail as object).length > 0;
return (
<div className="rounded-lg border border-slate-200 dark:border-border bg-white dark:bg-card px-3 py-2 text-sm">
<div className="flex items-start gap-2">
<span
className={cn(
"shrink-0 rounded px-1.5 py-0.5 text-xs font-medium uppercase",
LEVEL_STYLES[item.level] ?? LEVEL_STYLES.info,
)}
>
{item.level}
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<Badge variant="secondary" className="text-xs">
{stageLabel(item.stage)}
</Badge>
<code className="text-xs text-slate-500 dark:text-muted-foreground">{item.event}</code>
{item.agentName ? (
<span className="text-xs text-slate-500 dark:text-muted-foreground">· {item.agentName}</span>
) : null}
{item.userName ? (
<span className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300">
👤 {item.userName}
</span>
) : null}
<span className="ml-auto text-xs text-slate-400 dark:text-muted-foreground">{fmtTime(item.createdAt)}</span>
</div>
<p className="mt-1 whitespace-pre-wrap break-words text-slate-700 dark:text-foreground">
{item.message || <span className="text-slate-400">(无说明)</span>}
</p>
<div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-slate-400 dark:text-muted-foreground">
<span>{SCOPE_LABELS[item.scope] ?? item.scope}</span>
{item.jobId ? <span>job: {item.jobId.slice(0, 8)}</span> : null}
{item.taskId ? <span>task: {item.taskId}</span> : null}
{item.draftId ? <span>draft: {item.draftId.slice(0, 8)}</span> : null}
{item.cycle != null ? <span>cycle: {item.cycle}</span> : null}
{hasDetail ? (
<button type="button" className="text-blue-500 hover:underline" onClick={() => setOpen((v) => !v)}>
{open ? "收起详情" : "展开详情"}
</button>
) : null}
</div>
{open && hasDetail ? (
<pre className="mt-2 max-h-64 overflow-auto rounded bg-slate-50 dark:bg-muted p-2 text-xs text-slate-600 dark:text-muted-foreground">
{JSON.stringify(item.detail, null, 2)}
</pre>
) : null}
</div>
</div>
</div>
);
}
export default function RoundtableDiagnosticsPage() {
const isAdmin = getStoredAuth()?.system_role === "admin";
const navigate = useNavigate();
const [scopeCategory, setScopeCategory] = useState<ScopeCategory>("background");
const [stage, setStage] = useState<string>(ALL);
const [level, setLevel] = useState<string>(ALL);
const [event, setEvent] = useState<string>(ALL);
const [qInput, setQInput] = useState("");
const [q, setQ] = useState("");
const [page, setPage] = useState(1);
// 「前台调用」= 服务端观测(foreground) + 前端上报(client) 两种 scope 合并查(后端按逗号分隔多值)。
const scopeParam = scopeCategory === "background" ? "background" : "foreground,client";
const filters: DiagnosticFilters = useMemo(
() => ({
scope: scopeParam,
stage: stage === ALL ? undefined : stage,
level: level === ALL ? undefined : level,
event: event === ALL ? undefined : event,
q: q || undefined,
limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE,
}),
[scopeParam, stage, level, event, q, page],
);
const { data, isLoading, isFetching, refetch } = useRoundtableDiagnostics(filters, isAdmin);
const { data: facets } = useRoundtableDiagnosticFacets(isAdmin);
if (!isAdmin) {
return <Navigate to="/page/workspace/chats/new" replace />;
}
const items = data?.items ?? [];
const total = data?.total ?? 0;
const resetPageAnd = (fn: () => void) => {
fn();
setPage(1);
};
// 切换范围时清空阶段筛选(两种范围的阶段选项不同)+ 回到第一页。
const switchScope = (next: ScopeCategory) => {
setScopeCategory(next);
setStage(ALL);
setPage(1);
};
const applySearch = () => resetPageAnd(() => setQ(qInput.trim()));
return (
<div className="flex h-full flex-col bg-slate-50 dark:bg-background">
{/* Header */}
<header className="flex items-center gap-3 border-b border-slate-200 dark:border-border bg-white dark:bg-card px-4 py-3">
<Button variant="ghost" size="sm" onClick={() => navigate(-1)} className="gap-1">
<ArrowLeft className="h-4 w-4" />
返回
</Button>
<div>
<h1 className="text-base font-semibold text-slate-800 dark:text-foreground">会商诊断日志</h1>
<p className="text-xs text-slate-400 dark:text-muted-foreground">
多智能体会商全流程报错与关键事件(含后台挂起卡死、超时、产物缺失等)
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => refetch()}
className="ml-auto gap-1"
disabled={isFetching}
>
<RefreshCw className={cn("h-4 w-4", isFetching && "animate-spin")} />
刷新
</Button>
</header>
{/* Filters */}
<div className="flex flex-wrap items-center gap-2 border-b border-slate-200 dark:border-border bg-white dark:bg-card px-4 py-2">
{/* 范围切换:后台挂起 / 前台调用 */}
<div className="inline-flex rounded-lg border border-slate-200 dark:border-border p-0.5">
{(["background", "frontend"] as ScopeCategory[]).map((c) => (
<button
key={c}
type="button"
onClick={() => switchScope(c)}
className={cn(
"rounded-md px-3 py-1 text-xs font-medium transition-colors",
scopeCategory === c
? "bg-slate-800 text-white dark:bg-primary dark:text-primary-foreground"
: "text-slate-500 hover:text-slate-700 dark:text-muted-foreground dark:hover:text-foreground",
)}
>
{c === "background" ? "后台挂起" : "前台调用"}
</button>
))}
</div>
<FilterSelect label="阶段" value={stage} onChange={(v) => resetPageAnd(() => setStage(v))}
options={STAGE_OPTIONS[scopeCategory]} labels={STAGE_LABELS} />
<FilterSelect label="级别" value={level} onChange={(v) => resetPageAnd(() => setLevel(v))}
options={facets?.level ?? []} />
<FilterSelect label="事件" value={event} onChange={(v) => resetPageAnd(() => setEvent(v))}
options={facets?.event ?? []} />
<div className="flex items-center gap-1">
<Input
value={qInput}
onChange={(e) => setQInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && applySearch()}
placeholder="搜索报错说明…"
className="h-8 w-48"
/>
<Button variant="secondary" size="sm" onClick={applySearch} className="gap-1">
<Search className="h-4 w-4" />
</Button>
</div>
<span className="ml-auto text-xs text-slate-400 dark:text-muted-foreground">共 {total} 条</span>
</div>
{/* List */}
<div className="flex-1 overflow-auto px-4 py-3">
{isLoading ? (
<p className="py-10 text-center text-sm text-slate-400">加载中…</p>
) : items.length === 0 ? (
<p className="py-10 text-center text-sm text-slate-400">暂无诊断记录</p>
) : (
<div className="flex flex-col gap-2">
{items.map((it) => (
<DiagnosticRow key={it.id} item={it} />
))}
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} className="pt-2" />
</div>
)}
</div>
</div>
);
}
function FilterSelect({
label,
value,
onChange,
options,
labels,
}: {
label: string;
value: string;
onChange: (v: string) => void;
options: string[];
labels?: Record<string, string>;
}) {
return (
<Select value={value} onValueChange={onChange}>
<SelectTrigger className="h-8 w-auto min-w-[120px] text-xs">
<SelectValue placeholder={label} />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>{label}:全部</SelectItem>
{options.map((o) => (
<SelectItem key={o} value={o}>
{labels?.[o] ?? o}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
@@ -0,0 +1,273 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { Navigate } from "react-router-dom";
import { Download, Info, Plus, Save, Search, ShieldAlert, Sparkles, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Switch } from "@/components/ui/switch";
import { getAccountDisplayName } from "@/core/auth";
import { SEED_DESENSITIZE_MAP } from "@/lib/desensitize";
import {
type SensitiveWord,
useSensitiveWordActions,
useSensitiveWords,
} from "@/strategy-components/api/sensitive-words";
interface EditRow {
/** 稳定的行 key(编辑原始词时不丢焦点) */
key: number;
word: string;
replacement: string;
enabled: boolean;
}
let _seq = 1;
const nextKey = () => _seq++;
function toRows(words: SensitiveWord[]): EditRow[] {
return words.map((w) => ({ key: nextKey(), word: w.word, replacement: w.replacement, enabled: w.enabled }));
}
/** 归一化用于「脏」判断与重复检测(按原始词去空白后比较)。 */
function serialize(rows: { word: string; replacement: string; enabled: boolean }[]): string {
return JSON.stringify(
rows
.map((r) => ({ w: r.word.trim(), r: r.replacement, e: r.enabled }))
.filter((r) => r.w !== "")
.sort((a, b) => a.w.localeCompare(b.w)),
);
}
export default function SensitiveWordsPage() {
// 仅用户名为 lqq 的账号可访问(用户名 = 设置→个人信息页展示名)。
const canManage = getAccountDisplayName().toLowerCase() === "lqq";
const { data: serverWords = [], isLoading } = useSensitiveWords();
const { save } = useSensitiveWordActions();
const [rows, setRows] = useState<EditRow[]>([]);
const [loadedKey, setLoadedKey] = useState<string | null>(null);
const [query, setQuery] = useState("");
// 服务端数据首次/变化时回填工作副本(以序列化值判定,避免覆盖未保存编辑)。
const sourceKey = useMemo(() => serialize(serverWords), [serverWords]);
useEffect(() => {
if (sourceKey !== loadedKey) {
setRows(toRows(serverWords));
setLoadedKey(sourceKey);
}
}, [sourceKey, loadedKey, serverWords]);
const dirty = useMemo(() => serialize(rows) !== serialize(serverWords), [rows, serverWords]);
const q = query.trim().toLowerCase();
const visibleRows = useMemo(
() =>
!q
? rows
: rows.filter(
(r) => r.word.toLowerCase().includes(q) || r.replacement.toLowerCase().includes(q),
),
[rows, q],
);
const enabledCount = rows.filter((r) => r.enabled && r.word.trim()).length;
// ── 行操作 ──
const patchRow = (key: number, patch: Partial<EditRow>) =>
setRows((prev) => prev.map((r) => (r.key === key ? { ...r, ...patch } : r)));
const removeRow = (key: number) => setRows((prev) => prev.filter((r) => r.key !== key));
const addRow = () => setRows((prev) => [{ key: nextKey(), word: "", replacement: "", enabled: true }, ...prev]);
/** 用前端内置种子补齐当前没有的词(已存在的词不动)。 */
const importSeed = () => {
const have = new Set(rows.map((r) => r.word.trim()).filter(Boolean));
const added: EditRow[] = [];
for (const [word, replacement] of Object.entries(SEED_DESENSITIZE_MAP)) {
if (!have.has(word)) added.push({ key: nextKey(), word, replacement, enabled: true });
}
if (added.length === 0) {
toast.info("种子词已全部存在,无需导入");
return;
}
setRows((prev) => [...added, ...prev]);
toast.success(`已导入 ${added.length} 个种子词(保存后生效)`);
};
const handleSave = async () => {
// 校验:去空白、丢弃空原始词、检测重复。
const cleaned = rows
.map((r) => ({ ...r, word: r.word.trim() }))
.filter((r) => r.word !== "");
const seen = new Set<string>();
for (const r of cleaned) {
if (seen.has(r.word)) {
toast.error(`原始词「${r.word}」重复,请合并后再保存`);
return;
}
seen.add(r.word);
}
const payload: SensitiveWord[] = cleaned.map((r, i) => ({
word: r.word,
replacement: r.replacement,
enabled: r.enabled,
sortOrder: i,
}));
try {
await save.mutateAsync(payload);
toast.success("敏感词已保存");
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存失败");
}
};
if (!canManage) return <Navigate to="/page/workspace/chats/new" replace />;
return (
<div className="h-full overflow-auto bg-slate-50/60 px-4 py-6 sm:px-6 lg:px-8">
<div className="mx-auto max-w-4xl">
{/* 顶部信息卡 */}
<div className="relative mb-6 overflow-hidden rounded-3xl border border-slate-200/60 bg-white p-6 shadow-sm md:p-8">
<div className="pointer-events-none absolute right-0 top-0 select-none p-8 opacity-[0.03]">
<ShieldAlert className="size-44 text-slate-900" />
</div>
<div className="relative">
<div className="mb-4 flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div>
<span className="mb-3 inline-flex select-none items-center gap-1.5 rounded-full border border-red-100 bg-red-50 px-3 py-1 text-xs font-semibold text-red-600">
<Sparkles className="size-3" />
系统集成版
</span>
<h1 className="flex items-center gap-3 text-2xl font-bold tracking-tight text-slate-800 md:text-3xl">
敏感词管理
<span className="rounded-lg border border-slate-200/60 bg-slate-100 px-2.5 py-0.5 font-mono text-xs font-medium text-slate-500">
{rows.length} 词 / {enabledCount} 启用
</span>
</h1>
</div>
<div className="flex items-center gap-2.5">
<button
type="button"
onClick={importSeed}
className="inline-flex cursor-pointer items-center gap-2 rounded-xl border border-slate-200 bg-white px-3.5 py-2 text-sm font-semibold text-slate-600 shadow-sm transition-all hover:border-slate-300 hover:bg-slate-50 hover:text-slate-800"
title="用前端内置种子词补齐当前缺失的词"
>
<Download className="size-[15px]" />
导入种子词
</button>
<button
type="button"
onClick={handleSave}
disabled={!dirty || save.isPending}
className="inline-flex cursor-pointer items-center gap-2 rounded-xl border border-red-600 bg-red-600 px-5 py-2 text-sm font-semibold text-white shadow-sm transition-all hover:bg-red-700 active:scale-95 disabled:cursor-not-allowed disabled:opacity-50"
>
{save.isPending ? (
<>
<div className="size-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
保存中…
</>
) : (
<>
<Save className="size-[15px]" />
保存修改
</>
)}
</button>
</div>
</div>
<p className="flex max-w-2xl items-start gap-2.5 rounded-2xl border border-slate-200/50 bg-slate-50/70 p-3.5 text-sm leading-relaxed text-slate-600">
<Info className="mt-0.5 size-4 shrink-0 text-slate-400" />
<span>
配置展示层<strong> 脱敏词映射</strong>(原始词 → 替换词)。保存后全站脱敏即时生效;
<strong> 停用 </strong>的词会保留但不参与替换。前端内置的种子词仅用于全新机器首次部署,
可用<strong>「导入种子词」</strong>一键写入后台。
</span>
</p>
</div>
</div>
{/* 搜索 + 新增栏 */}
<div className="mb-6 flex flex-col items-center justify-between gap-4 rounded-2xl border border-slate-200/60 bg-white p-4 shadow-sm md:flex-row md:p-5">
<div className="relative w-full md:w-80">
<Search className="absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="搜索原始词 / 替换词…"
value={query}
onChange={(e) => setQuery(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-slate-50/50 py-2 pl-10 pr-4 text-sm transition-all hover:border-slate-300 focus:border-red-500 focus:outline-none focus:ring-4 focus:ring-red-500/5"
/>
</div>
<button
type="button"
onClick={addRow}
className="inline-flex w-full cursor-pointer items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:border-red-300 hover:bg-red-50 hover:text-red-600 md:w-auto"
>
<Plus className="size-[15px]" />
新增敏感词
</button>
</div>
{/* 列表 */}
<div className="overflow-hidden rounded-2xl border border-slate-200/60 bg-white shadow-sm">
<div className="grid grid-cols-[1fr_1fr_auto_auto] items-center gap-3 border-b border-slate-200/60 bg-slate-50/70 px-4 py-2.5 text-xs font-semibold text-slate-500">
<span>原始词</span>
<span>替换词</span>
<span className="px-1 text-center">启用</span>
<span className="w-8" />
</div>
{isLoading ? (
<div className="px-4 py-12 text-center text-sm text-slate-400">加载中…</div>
) : visibleRows.length === 0 ? (
<div className="px-4 py-12 text-center text-sm text-slate-400">
{rows.length === 0 ? "暂无敏感词,点击「新增」或「导入种子词」开始配置" : "没有匹配的词"}
</div>
) : (
<ul className="divide-y divide-slate-100">
{visibleRows.map((row) => (
<li
key={row.key}
className={`grid grid-cols-[1fr_1fr_auto_auto] items-center gap-3 px-4 py-2.5 transition-colors hover:bg-slate-50/60 ${
row.enabled ? "" : "opacity-55"
}`}
>
<input
type="text"
value={row.word}
placeholder="原始词"
onChange={(e) => patchRow(row.key, { word: e.target.value })}
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm transition-all focus:border-red-500 focus:outline-none focus:ring-2 focus:ring-red-500/10"
/>
<input
type="text"
value={row.replacement}
placeholder="替换词"
onChange={(e) => patchRow(row.key, { replacement: e.target.value })}
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm transition-all focus:border-red-500 focus:outline-none focus:ring-2 focus:ring-red-500/10"
/>
<div className="px-1">
<Switch
checked={row.enabled}
onCheckedChange={(v) => patchRow(row.key, { enabled: v })}
/>
</div>
<button
type="button"
onClick={() => removeRow(row.key)}
title="删除"
className="flex size-8 items-center justify-center rounded-lg text-slate-400 transition-colors hover:bg-red-50 hover:text-red-600"
>
<Trash2 className="size-4" />
</button>
</li>
))}
</ul>
)}
</div>
</div>
</div>
);
}
@@ -2,7 +2,7 @@ import { SkillEvolutionPanel } from "@/components/workspace/skills/skill-evoluti
export default function SkillEvolutionPage() {
return (
<div className="flex h-full flex-col overflow-auto p-6">
<div className="flex size-full min-h-0 flex-col overflow-auto p-6">
<SkillEvolutionPanel />
</div>
);
+1 -1
View File
@@ -2,7 +2,7 @@ import { SkillSettingsPage } from "@/components/workspace/settings/skill-setting
export default function SkillsPage() {
return (
<div className="flex flex-col h-full overflow-auto p-6">
<div className="flex size-full min-h-0 flex-col overflow-auto p-6">
<SkillSettingsPage />
</div>
);
+120 -26
View File
@@ -1,8 +1,8 @@
import { Navigate, Route, Routes, useParams } from "react-router-dom";
import { Navigate, Route, Routes } from "react-router-dom";
import { Toaster } from "sonner";
import { SidebarProvider } from "@/components/ui/sidebar";
import { getStoredAuth } from "@/core/auth";
import { getAccountDisplayName, getStoredAuth } from "@/core/auth";
import { RouteBaseProvider } from "@/core/route-base";
import GeneralQA from "@/strategy-components/components/chat-qa/GeneralQA";
import SentimentAnalyzes from "@/strategy-components/components/task-components/SentimentAnalyzes";
@@ -11,10 +11,17 @@ import TaskPgFrom from "@/strategy-components/components/task-components/TaskPgF
import TaskTyFrom from "@/strategy-components/components/task-components/TaskTyFrom";
import TaskXkFrom from "@/strategy-components/components/task-components/TaskXkFrom";
import TaskAnalyzes from "@/strategy-components/components/task-components/TaskAnalyzes";
import {
TaskBindChat,
TaskFxChat,
TaskFxIndexResolver,
TaskFxWorkspace,
} from "@/strategy-components/components/task-components/TaskFxWorkspace";
import { ActionAnalyzes } from "@/strategy-components/components/task-components/ActionAnalyzes";
import KnowledgeBaseResourceManagement from "@/strategy-components/components/resource-management/KnowledgeBaseResourceManagement";
import NetworkActorResourceManagement from "@/strategy-components/components/resource-management/NetworkActorResourceManagement";
import RoundtablePlanningPage from "@/roundtable-planning/pages/RoundtablePlanningPage";
import DashboardAgentPage from "@/roundtable-planning/pages/DashboardAgentPage";
import BusinessChainListPage from "@/roundtable-planning/pages/BusinessChainListPage";
import BusinessChainEditorPage from "@/roundtable-planning/pages/BusinessChainEditorPage";
import "@/roundtable-planning/styles/roundtable-planning.css";
@@ -31,6 +38,10 @@ import PublicLeaderboardPage from "./PublicLeaderboardPage";
import LightAppIframeView from "./LightAppIframeView";
import LightAppListPage from "./LightAppListPage";
import LightAppManagementPage from "./LightAppManagementPage";
import MenuManagementPage from "./MenuManagementPage";
import SensitiveWordsPage from "./SensitiveWordsPage";
import TaskButtonsPage from "./TaskButtonsPage";
import RoundtableDiagnosticsPage from "./RoundtableDiagnosticsPage";
import LightAppNewNotePage from "./LightAppNewNotePage";
import LightAppNoteListPage from "./LightAppNoteListPage";
import LightAppNoteQAPage from "./LightAppNoteQAPage";
@@ -51,20 +62,6 @@ import AdminScheduledTasksPage from "./AdminScheduledTasksPage";
import AdminUserActivityPage from "./AdminUserActivityPage";
import { ChatRuntime } from "./WorkspaceRoutes";
/**
* 任务深链:把智能体问答嵌进「任务管理」布局。读路由参数 agent_id,给 AgentChatPage
* 传入以 taskBase 为前缀的对话路由(开新会话 / URL 改写都停留在任务管理上下文,
* 侧边栏保持对应业务高亮)。
*/
function TaskEmbeddedAgentChat({ taskBase }: { taskBase: string }) {
const { agent_id } = useParams<{ agent_id: string }>();
return (
<ChatRuntime>
<AgentChatPage chatBasePath={`${taskBase}/agent/${agent_id}/chats`} />
</ChatRuntime>
);
}
export default function StrategyRoutes() {
return (
<RouteBaseProvider value="/page/strategy">
@@ -92,6 +89,16 @@ export default function StrategyRoutes() {
}
/>
{/* 大屏绘制智能体独立页面(按 taskId 存取;ChatRuntime 提供 ArtifactsProvider 给沙箱预览) */}
<Route
path="dashboard-agent"
element={
<ChatRuntime>
<DashboardAgentPage />
</ChatRuntime>
}
/>
{/* 需求 0616 #3/#4:zzJC / zzXD 「按类型聚合」模块页(重做,独立路由)。 */}
<Route path="qa/zzjc/*" element={<AgentModuleRoutes module={AGENT_MODULES.zzjc} />} />
<Route path="qa/zzxd/*" element={<AgentModuleRoutes module={AGENT_MODULES.zzxd} />} />
@@ -137,12 +144,26 @@ export default function StrategyRoutes() {
</ChatRuntime>
}
/>
{/* 三情分析:任务工作区(左对话列表 1:N,无目的树闸门;新建对话直接带开场信息)。 */}
<Route
path="plan-task-sentiment/agent/:agent_id/chats/:thread_id"
path="plan-task-sentiment/agent/:agent_id/chats"
element={
<TaskEmbeddedAgentChat taskBase="/page/strategy/task-management/plan-task-sentiment" />
<TaskFxWorkspace taskBase="/page/strategy/task-management/plan-task-sentiment" business="3qfx" lite />
}
/>
>
<Route
index
element={
<TaskFxIndexResolver taskBase="/page/strategy/task-management/plan-task-sentiment" />
}
/>
<Route
path=":thread_id"
element={
<TaskBindChat taskBase="/page/strategy/task-management/plan-task-sentiment" />
}
/>
</Route>
<Route
path="plan-task/plan-task-fx"
element={
@@ -162,12 +183,29 @@ export default function StrategyRoutes() {
</ChatRuntime>
}
/>
{/* 任务FX:任务工作区(左对话列表 1:N + 右问答;新建对话顶部目的树闸门)。 */}
<Route
path="plan-task/plan-task-fx/agent/:agent_id/chats/:thread_id"
path="plan-task/plan-task-fx/agent/:agent_id/chats"
element={
<TaskEmbeddedAgentChat taskBase="/page/strategy/task-management/plan-task/plan-task-fx" />
<TaskFxWorkspace taskBase="/page/strategy/task-management/plan-task/plan-task-fx" business="rwfx" />
}
/>
>
<Route
index
element={
<TaskFxIndexResolver taskBase="/page/strategy/task-management/plan-task/plan-task-fx" />
}
/>
<Route
path=":thread_id"
element={
<TaskFxChat
taskBase="/page/strategy/task-management/plan-task/plan-task-fx"
autoStartWhenPurposeEmpty
/>
}
/>
</Route>
<Route
path="plan-task/plan-task-action"
element={
@@ -187,12 +225,28 @@ export default function StrategyRoutes() {
</ChatRuntime>
}
/>
{/* 行动分析:任务工作区(左对话列表 1:N 精简版 + 左上行动详情卡片;直接问答,
右上角「开始回答」按钮手动发出开场信息,不走目的树闸门/覆盖确认)。
注意:xdfx 深链传入的是「行动id」,登录时已先经 resolveDeeplinkTaskId 换成任务id。 */}
<Route
path="plan-task/plan-task-action/agent/:agent_id/chats/:thread_id"
path="plan-task/plan-task-action/agent/:agent_id/chats"
element={
<TaskEmbeddedAgentChat taskBase="/page/strategy/task-management/plan-task/plan-task-action" />
<TaskFxWorkspace taskBase="/page/strategy/task-management/plan-task/plan-task-action" business="xdfx" lite />
}
/>
>
<Route
index
element={
<TaskFxIndexResolver taskBase="/page/strategy/task-management/plan-task/plan-task-action" />
}
/>
<Route
path=":thread_id"
element={
<TaskBindChat taskBase="/page/strategy/task-management/plan-task/plan-task-action" />
}
/>
</Route>
<Route path="mnty-task-mechanism" element={<TaskTyFrom defaultPage="iframeXdty" title="XDTY任务" />} />
<Route path="mnty-task-plan" element={<TaskTyFrom defaultPage="iframeFaty" title="方案TY任务" />} />
<Route path="mnty-task-zsty" element={<TaskTyFrom defaultPage="iframeSysystem" title="XXTY任务" />} />
@@ -238,7 +292,7 @@ export default function StrategyRoutes() {
path="agents/:agent_id/chats/:thread_id"
element={
<ChatRuntime>
<AgentChatPage />
<AgentChatPage showAgentList />
</ChatRuntime>
}
/>
@@ -310,6 +364,46 @@ export default function StrategyRoutes() {
)
}
/>
<Route
path="admin/menu-management"
element={
getStoredAuth()?.system_role === "admin" ? (
<MenuManagementPage />
) : (
<Navigate to="/page/workspace/chats/new" replace />
)
}
/>
<Route
path="admin/sensitive-words"
element={
getAccountDisplayName().toLowerCase() === "lqq" ? (
<SensitiveWordsPage />
) : (
<Navigate to="/page/workspace/chats/new" replace />
)
}
/>
<Route
path="admin/task-buttons"
element={
getStoredAuth()?.system_role === "admin" ? (
<TaskButtonsPage />
) : (
<Navigate to="/page/workspace/chats/new" replace />
)
}
/>
<Route
path="admin/roundtable-diagnostics"
element={
getStoredAuth()?.system_role === "admin" ? (
<RoundtableDiagnosticsPage />
) : (
<Navigate to="/page/workspace/chats/new" replace />
)
}
/>
<Route
path="admin/scheduled-tasks"
element={
+389
View File
@@ -0,0 +1,389 @@
"use client";
/**
* 按钮管理(仅 admin):配置任务工作区(rwfx / 3qfx / xdfx,见 ``TaskFxWorkspace``)
* 左侧栏的可配置跳转按钮——改名称、改跳转方式与地址、启停、排序、增删。
*
* 全局共享、整体替换保存(``PUT /api/task-buttons``)。后端整张表为空时回退代码种子默认
* (rwfx 的 4 个历史按钮),此页首次进入也以种子回填工作副本,便于从当前行为起步。
* 见 [[task-buttons]]。
*/
import { useEffect, useMemo, useState } from "react";
import { Navigate } from "react-router-dom";
import { ArrowDown, ArrowUp, Download, MousePointerClick, Plus, Save, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
import { getStoredAuth } from "@/core/auth";
import {
DEFAULT_TASK_DEEPLINK_CONFIG,
fetchTaskDeeplinkConfig,
type TaskDeeplinkConfig,
} from "@/core/auth/task-deeplink-config";
import {
TASK_BUSINESSES,
TASK_BUSINESS_TARGETS,
defaultTaskButtons,
type TaskBusiness,
type TaskButton,
} from "@/core/auth/task-buttons";
import { useTaskButtonActions, useTaskButtons } from "@/strategy-components/api/task-buttons";
let _seq = 1;
const newId = (b: TaskBusiness) => `${b}-custom-${Date.now()}-${_seq++}`;
/** 归一化用于「脏」判断(按 id 排序后整体比较)。 */
function serialize(rows: TaskButton[]): string {
return JSON.stringify([...rows].sort((a, b) => a.id.localeCompare(b.id)));
}
export default function TaskButtonsPage() {
const isAdmin = getStoredAuth()?.system_role === "admin";
const { data: serverButtons = [], isLoading } = useTaskButtons();
const { save } = useTaskButtonActions();
const [cfg, setCfg] = useState<TaskDeeplinkConfig>(() => DEFAULT_TASK_DEEPLINK_CONFIG);
useEffect(() => {
let alive = true;
void fetchTaskDeeplinkConfig().then((c) => {
if (alive) setCfg(c);
});
return () => {
alive = false;
};
}, []);
const [rows, setRows] = useState<TaskButton[]>([]);
const [loadedKey, setLoadedKey] = useState<string | null>(null);
const [tab, setTab] = useState<TaskBusiness>("rwfx");
// 服务端首次/变化时回填工作副本(空表回填种子默认)。以序列化值判定,避免覆盖未保存编辑。
const sourceKey = useMemo(() => serialize(serverButtons), [serverButtons]);
useEffect(() => {
if (sourceKey !== loadedKey) {
setRows(serverButtons.length > 0 ? serverButtons : defaultTaskButtons(cfg));
setLoadedKey(sourceKey);
}
}, [sourceKey, loadedKey, serverButtons, cfg]);
const tabRows = useMemo(
() => rows.filter((r) => r.business === tab).sort((a, b) => a.sortOrder - b.sortOrder),
[rows, tab],
);
const dirty = useMemo(() => serialize(rows) !== sourceKey, [rows, sourceKey]);
if (!isAdmin) return <Navigate to="/page/workspace/chats/new" replace />;
const update = (id: string, patch: Partial<TaskButton>) =>
setRows((rs) => rs.map((r) => (r.id === id ? { ...r, ...patch } : r)));
const removeRow = (id: string) => setRows((rs) => rs.filter((r) => r.id !== id));
const addRow = () => {
const maxSort = tabRows.reduce((m, r) => Math.max(m, r.sortOrder), -1);
setRows((rs) => [
...rs,
{
id: newId(tab),
business: tab,
label: "新按钮",
linkType: "url",
target: "",
appendTaskId: true,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder: maxSort + 1,
},
]);
};
const moveRow = (id: string, dir: "up" | "down") => {
const list = [...tabRows];
const i = list.findIndex((r) => r.id === id);
const j = dir === "up" ? i - 1 : i + 1;
if (i < 0 || j < 0 || j >= list.length) return;
[list[i], list[j]] = [list[j], list[i]];
const reordered = list.map((r, idx) => ({ ...r, sortOrder: idx }));
setRows((rs) => [...rs.filter((r) => r.business !== tab), ...reordered]);
};
const handleSave = async () => {
const payload = rows.map((r) => ({ ...r, label: r.label.trim() }));
try {
await save.mutateAsync(payload);
toast.success("已保存按钮配置");
} catch (e) {
toast.error(e instanceof Error ? e.message : "保存失败");
}
};
const importDefaults = (business?: TaskBusiness) => {
const have = new Set(rows.map((r) => r.id));
const adds = defaultTaskButtons(cfg)
.filter((d) => !business || d.business === business)
.filter((d) => !have.has(d.id));
if (!adds.length) {
toast.info("没有可导入的默认按钮");
return;
}
setRows((rs) => [...rs, ...adds]);
toast.success(`已导入 ${adds.length} 个默认按钮`);
};
return (
<div className="flex size-full min-h-0 flex-col overflow-hidden bg-background">
<div className="border-border/70 flex items-center justify-between gap-3 border-b px-5 py-4">
<div className="flex items-center gap-2">
<MousePointerClick className="h-5 w-5 text-[var(--color-main,#0062D9)]" />
<div>
<div className="text-foreground text-base font-semibold">按钮管理</div>
<div className="text-muted-foreground text-xs">
配置任务工作区底部「快捷跳转」栏的按钮(名称 / 跳转方式 / 地址 / 启停 / 排序)
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => importDefaults()}>
<Download className="h-4 w-4" /> 导入全部默认
</Button>
<Button size="sm" onClick={handleSave} disabled={!dirty || save.isPending}>
<Save className="h-4 w-4" /> {save.isPending ? "保存中…" : "保存"}
</Button>
</div>
</div>
{/* 业务 tab:每个 tab = 一个任务深链页面,明确区分三种页面的按钮 */}
<div className="border-border/70 flex items-stretch gap-2 border-b px-5 pt-3">
{TASK_BUSINESSES.map((b) => {
const count = rows.filter((r) => r.business === b.code).length;
const active = tab === b.code;
return (
<button
key={b.code}
type="button"
onClick={() => setTab(b.code)}
className={cn(
"flex min-w-[8.5rem] flex-col gap-0.5 rounded-t-lg border border-b-0 px-4 py-2 text-left transition-colors",
active
? "border-[var(--color-main,#0062D9)] bg-[var(--color-main,#0062D9)] text-white"
: "border-border/70 text-muted-foreground hover:bg-muted bg-transparent",
)}
>
<span className="flex items-center gap-1.5 text-sm font-semibold">
{b.name}
<span
className={cn(
"rounded px-1.5 text-[11px] tabular-nums",
active ? "bg-white/20" : "bg-muted-foreground/15",
)}
>
{count}
</span>
</span>
<span className={cn("text-[11px]", active ? "text-white/80" : "opacity-70")}>
?goPath={b.goPath}
</span>
</button>
);
})}
</div>
{/* 当前页面说明 */}
{(() => {
const meta = TASK_BUSINESSES.find((b) => b.code === tab)!;
return (
<div className="border-border/70 bg-muted/40 text-muted-foreground border-b px-5 py-2 text-xs">
正在编辑「<span className="text-foreground font-medium">{meta.name}</span>
」页面的按钮 · {meta.desc} 下方按钮会显示在该页面底部的「快捷跳转」栏,从上到下对应栏内从左到右的顺序。
</div>
);
})()}
<div className="min-h-0 flex-1 overflow-y-auto p-5">
{isLoading ? (
<div className="text-muted-foreground text-sm">加载中…</div>
) : tabRows.length === 0 ? (
<div className="text-muted-foreground flex flex-col items-center gap-3 rounded-md border border-dashed p-6 text-center text-sm">
该页面暂无按钮。可「导入该页面默认按钮」一键填充,或点下方「添加按钮」自定义。
<Button variant="outline" size="sm" onClick={() => importDefaults(tab)}>
<Download className="h-4 w-4" /> 导入该页面默认按钮
</Button>
</div>
) : (
<div className="flex flex-col gap-3">
{tabRows.map((r, idx) => (
<div
key={r.id}
className="border-border/70 grid grid-cols-[1fr_auto] items-start gap-3 rounded-lg border bg-card/60 p-3"
>
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<label className="text-muted-foreground w-16 shrink-0 text-xs">名称</label>
<Input
value={r.label}
onChange={(e) => update(r.id, { label: e.target.value })}
placeholder="按钮名称"
className="h-8 max-w-xs"
/>
<label className="text-muted-foreground ml-2 shrink-0 text-xs">类型</label>
<Select
value={r.linkType}
onValueChange={(v) => update(r.id, { linkType: v as TaskButton["linkType"] })}
>
<SelectTrigger className="h-8 w-36">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="url">外部链接</SelectItem>
<SelectItem value="business">切换业务</SelectItem>
<SelectItem value="purpose">目的树弹框</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-wrap items-center gap-2">
<label className="text-muted-foreground w-16 shrink-0 text-xs">目标</label>
{r.linkType === "purpose" ? (
<span className="text-muted-foreground text-xs">
点击弹出当前任务的「任务目的」表格,无需配置目标。
</span>
) : r.linkType === "url" ? (
<>
<Input
value={r.target}
onChange={(e) => update(r.id, { target: e.target.value })}
placeholder="https://…(跳转地址)"
className="h-8 flex-1 min-w-[16rem]"
/>
<label className="text-muted-foreground ml-2 flex shrink-0 items-center gap-1.5 text-xs">
<Switch
checked={r.appendTaskId}
onCheckedChange={(v) => update(r.id, { appendTaskId: v })}
/>
追加参数
</label>
{r.appendTaskId && (
<div className="flex shrink-0 items-center gap-1 text-xs">
<span className="text-muted-foreground">?</span>
<Input
value={r.idParam}
onChange={(e) => update(r.id, { idParam: e.target.value })}
placeholder="id"
className="h-8 w-24"
title="查询参数名(如 id / task_id)"
/>
<span className="text-muted-foreground">=</span>
{/* 行动分析(xdfx):行动id 与任务id 不同,可选追加哪种;其它业务固定任务id */}
{tab === "xdfx" ? (
<Select
value={r.idKind}
onValueChange={(v) => update(r.id, { idKind: v as TaskButton["idKind"] })}
>
<SelectTrigger className="h-8 w-24">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="task">任务id</SelectItem>
<SelectItem value="action">行动id</SelectItem>
</SelectContent>
</Select>
) : (
<span className="text-muted-foreground">任务id</span>
)}
</div>
)}
<label className="text-muted-foreground ml-2 shrink-0 text-xs">打开方式</label>
<Select
value={r.openMode}
onValueChange={(v) => update(r.id, { openMode: v as TaskButton["openMode"] })}
>
<SelectTrigger className="h-8 w-32" title="外链打开方式">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="blank">新窗口</SelectItem>
<SelectItem value="self">当前窗口</SelectItem>
</SelectContent>
</Select>
</>
) : (
<Select value={r.target} onValueChange={(v) => update(r.id, { target: v })}>
<SelectTrigger className="h-8 w-48">
<SelectValue placeholder="选择目标业务" />
</SelectTrigger>
<SelectContent>
{TASK_BUSINESS_TARGETS.map((t) => (
<SelectItem key={t.code} value={t.code}>
{t.label}({t.code})
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</div>
<div className="flex items-center gap-1">
<label className="text-muted-foreground mr-1 flex items-center gap-1.5 text-xs">
<Switch
checked={r.enabled}
onCheckedChange={(v) => update(r.id, { enabled: v })}
/>
启用
</label>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
disabled={idx === 0}
onClick={() => moveRow(r.id, "up")}
title="上移"
>
<ArrowUp className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
disabled={idx === tabRows.length - 1}
onClick={() => moveRow(r.id, "down")}
title="下移"
>
<ArrowDown className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-destructive h-8 w-8"
onClick={() => removeRow(r.id)}
title="删除"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
)}
<Button variant="outline" size="sm" className="mt-4" onClick={addRow}>
<Plus className="h-4 w-4" /> 添加按钮
</Button>
</div>
</div>
);
}
+1 -1
View File
@@ -288,7 +288,7 @@ export default function WorkspaceRoutes({
element={
<WorkspaceLayout {...layoutProps}>
<ChatRuntime>
<AgentChatPage />
<AgentChatPage showAgentList />
</ChatRuntime>
</WorkspaceLayout>
}
@@ -678,3 +678,18 @@
[data-theme="lightblue"] .light-app-management-page .lam-dialog-save:active {
background-color: #0056C6;
}
/* ── iframe 菜单排序:拖拽行 + 拖拽手柄 ───────────────────────────────── */
.light-app-management-page .lam-reorder-row {
cursor: grab;
}
.light-app-management-page .lam-reorder-row:active {
cursor: grabbing;
}
/* 深蓝主题下手柄/箭头用次级文字色,避免在深底上发灰看不清 */
.dark .light-app-management-page .lam-drag-handle {
color: #4A6491;
}
.dark .light-app-management-page .lam-reorder-row:hover .lam-drag-handle {
color: #6E88B0;
}
@@ -31,6 +31,8 @@ export interface ChainCreatePayload {
coordinatorPrompt?: string | null;
/** 默认席位执行模式(flash/thinking/pro/ultra);null = 未设。 */
seatMode?: SeatMode | null;
/** 研讨前并行取数开关(逐条 opt-in);缺省 false。 */
gatherFirst?: boolean;
}
/** Partial update — send only what changed. */
@@ -46,12 +48,19 @@ export interface ChainUpdatePayload {
coordinatorPrompt?: string | null;
/** 默认席位执行模式;send `null` to clear, omit to leave. */
seatMode?: SeatMode | null;
/** 研讨前并行取数开关;send true/false 改,omit 不改。 */
gatherFirst?: boolean;
/** 发布开关:true 发布为公共 / false 取消发布;omit 不改。仅 owner 生效。 */
isPublic?: boolean;
}
/** 列表筛选范围:`mine` = 我的;`public` = 所有已发布的公共链条。 */
export type ChainScope = "mine" | "public";
/**
* 列表筛选范围:
* - `mine` = 我的;
* - `public` = 所有已发布的公共链条;
* - `all` = 所有账号的全部链条(**仅管理员**;后端对非管理员请求 `all` 退化为 `mine`)。
*/
export type ChainScope = "mine" | "public" | "all";
const BASE = () => `${getBackendBaseURL()}/api/roundtable-chains`;
@@ -76,6 +85,7 @@ interface ServerChain {
stage_goals?: (string | null)[] | null;
coordinator_prompt?: string | null;
seat_mode?: string | null;
gather_first?: boolean;
is_public?: boolean;
is_mine?: boolean;
owner_name?: string | null;
@@ -93,6 +103,7 @@ function toChain(s: ServerChain): BusinessChain {
stageGoals: Array.isArray(s.stage_goals) ? s.stage_goals : null,
coordinatorPrompt: s.coordinator_prompt ?? null,
seatMode: (s.seat_mode as SeatMode | null) ?? undefined,
gatherFirst: s.gather_first ?? false,
isPublic: s.is_public ?? false,
// 后端缺省时按「我的」处理(向后兼容旧响应)。
isMine: s.is_mine ?? true,
@@ -112,6 +123,7 @@ function fromCreate(p: ChainCreatePayload) {
...(p.stageGoals !== undefined ? { stage_goals: p.stageGoals } : {}),
...(p.coordinatorPrompt !== undefined ? { coordinator_prompt: p.coordinatorPrompt } : {}),
...(p.seatMode !== undefined ? { seat_mode: p.seatMode } : {}),
...(p.gatherFirst !== undefined ? { gather_first: p.gatherFirst } : {}),
};
}
@@ -126,6 +138,7 @@ function fromUpdate(p: ChainUpdatePayload) {
if (p.stageGoals !== undefined) out.stage_goals = p.stageGoals;
if (p.coordinatorPrompt !== undefined) out.coordinator_prompt = p.coordinatorPrompt;
if (p.seatMode !== undefined) out.seat_mode = p.seatMode;
if (p.gatherFirst !== undefined) out.gather_first = p.gatherFirst;
if (p.isPublic !== undefined) out.is_public = p.isPublic;
return out;
}
@@ -138,7 +151,7 @@ function fromUpdate(p: ChainUpdatePayload) {
* - `"public"`:所有已发布的公共链条(任何账号可见 / 可选入研讨)。
*/
export async function listChains(scope: ChainScope = "mine"): Promise<BusinessChain[]> {
const url = scope === "public" ? `${BASE()}?scope=public` : BASE();
const url = scope === "mine" ? BASE() : `${BASE()}?scope=${scope}`;
const res = await apiFetch(url, { method: "GET" });
const data = await readJson<{ chains: ServerChain[] }>(res, "list chains");
return (data.chains ?? []).map(toChain);
@@ -0,0 +1,68 @@
/**
* 大屏绘制智能体「独立页面」会话持久化 —— 按外部 taskId 存取(后端不按 user 分权)。
*
* 一个 taskId 一条会话:聊天记录(transcript)+ 最新结构化数据(reportJson)。
* 后端 `/api/dashboard-sessions/by-task/{taskId}`(GET 取 / PUT upsert)。
* 详见后端 `app/gateway/routers/dashboard_sessions.py`。
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
export interface DashboardSession {
taskId: string;
/** 聊天记录(大屏绘制智能体对话气泡数组;形状与 Step2Dialogue 一致,宽松存取)。 */
transcript: unknown[] | null;
/** 最新结构化数据(report-json 字符串);可被 parseReportJson 解析则视为「有效结果」。 */
reportJson: string | null;
updatedAt: string | null;
}
interface ServerDashboardSession {
task_id: string;
transcript: unknown[] | null;
report_json: string | null;
created_at?: string | null;
updated_at?: string | null;
}
const BASE = () => `${getBackendBaseURL()}/api/dashboard-sessions`;
function toClient(s: ServerDashboardSession): DashboardSession {
return {
taskId: s.task_id,
transcript: Array.isArray(s.transcript) ? s.transcript : null,
reportJson: s.report_json ?? null,
updatedAt: s.updated_at ?? null,
};
}
/** 取该 taskId 的会话;无(404)返回 null。 */
export async function getDashboardSessionByTask(taskId: string): Promise<DashboardSession | null> {
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}`, { method: "GET" });
if (res.status === 404) return null;
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`get dashboard session failed (${res.status}): ${text}`);
}
return toClient((await res.json()) as ServerDashboardSession);
}
/** upsert 该 taskId 的会话(只传需要更新的字段)。 */
export async function putDashboardSessionByTask(
taskId: string,
patch: { transcript?: unknown[]; reportJson?: string | null },
): Promise<DashboardSession | null> {
const body: Record<string, unknown> = {};
if (patch.transcript !== undefined) body.transcript = patch.transcript;
if (patch.reportJson !== undefined) body.report_json = patch.reportJson;
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`put dashboard session failed (${res.status}): ${text}`);
}
return toClient((await res.json()) as ServerDashboardSession);
}
@@ -0,0 +1,90 @@
/**
* 会商「前端调用报错」上报器。
*
* 服务端诊断只能记到「处理函数跑起来后抛的错」;而用户实际遇到的很多报错(nginx/网关
* 返回 502、网络中断、fetch 直接失败、SSE 里收到的 error 帧)发生在**客户端**侧。这里把
* 这些前端可观测到的报错 best-effort 上报到 `POST /api/roundtable-diagnostics/report`
* (scope="client",非 admin 接口),便于管理员在诊断页统一筛选用户使用时的报错。
*
* 设计:fire-and-forget + `keepalive`(页面跳转也能发出去)+ 绝不抛错(上报失败就算了,
* 不能让「报错上报」本身再影响会商流程)。
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
export interface RoundtableErrorReport {
stage: string;
event: string;
message: string;
level?: "error" | "warning" | "info";
detail?: unknown;
agentId?: string;
agentName?: string;
cycle?: number;
draftId?: string;
taskId?: string;
jobId?: string;
httpStatus?: number;
}
// 页面级上下文(draftId / taskId),由会商页设置,使每条上报都能归属到草稿/任务,
// 而无需把它们穿进每个底层 api 调用。
let _ctx: { draftId?: string; taskId?: string } = {};
export function setRoundtableErrorContext(ctx: { draftId?: string; taskId?: string }): void {
_ctx = { ..._ctx, ...ctx };
}
/** 据 agentType + agentName 推断诊断 stage(与后端 `_stage_for_agent` 对齐)。 */
export function stageForRoundtableAgent(
agentType: string | undefined,
agentName: string | null | undefined,
): string {
switch (agentName) {
case "roundtable-report":
return "step3_report";
case "roundtable-summary":
return "step3_summary";
case "roundtable-dashboard":
return "step3_dashboard";
case "roundtable-structure":
return "step3_structure";
default:
return agentType === "leader" ? "step2_leader" : "step2_seat";
}
}
export function reportRoundtableError(input: RoundtableErrorReport): void {
try {
const detail =
input.httpStatus != null && typeof input.detail !== "object"
? { httpStatus: input.httpStatus, raw: input.detail }
: input.httpStatus != null
? { httpStatus: input.httpStatus, ...(input.detail as Record<string, unknown>) }
: input.detail;
const body = JSON.stringify({
stage: input.stage,
event: input.event,
level: input.level ?? "error",
message: (input.message ?? "").slice(0, 2000),
detail,
jobId: input.jobId,
draftId: input.draftId ?? _ctx.draftId,
taskId: input.taskId ?? _ctx.taskId,
agentId: input.agentId,
agentName: input.agentName,
cycle: input.cycle,
});
void apiFetch(`${getBackendBaseURL()}/api/roundtable-diagnostics/report`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
keepalive: true,
}).catch(() => {
/* 上报失败静默 */
});
} catch {
/* 绝不抛错 */
}
}
@@ -133,6 +133,18 @@ export interface DraftStep3Snapshot {
* 与经典 `html`(模式一)并存互不覆盖。后台挂起与手动并行绘制都写这里。Optional.
*/
dashboardJson?: string | null;
/**
* 第三步「结果绘制(经典 HTML 看板)」生成过程的完整对话气泡(中间文字 + 步骤条),与第二步
* `step2RoundtableDialogues` 同形(`Step2Dialogue[]`)。存它使加载后能回显整段绘制过程,而非
* 只有最终 HTML。Optional —— 旧草稿没有该字段,恢复时回退为重建单条「历史记录」气泡。
*/
reportDialogues?: unknown[];
/** 经典看板各席位 write_file 调用重建的 stub(threadId → [stub ai message]),供加载后点开产物预览。 */
reportSeatStubMessages?: Record<string, unknown[]>;
/** 第三步「大屏多页」生成过程的完整对话气泡(中间文字 + 步骤条),同 `reportDialogues`。Optional。 */
dashboardDialogues?: unknown[];
/** 大屏各席位 write_file 调用重建的 stub。Optional。 */
dashboardSeatStubMessages?: Record<string, unknown[]>;
}
/**
@@ -152,6 +164,20 @@ export interface DraftStep3SummarySnapshot {
model: string;
/** The agent's closing chat text (the report body it echoed into the conversation). */
closing?: string;
/**
* 第三步「总结报告」生成过程的**完整对话气泡**(含中间文字内容 + 每条气泡的步骤条
* `steps`),与第二步 `step2RoundtableDialogues` 同形(`Step2Dialogue[]`)。存它使加载
* 草稿后能像第二步一样回显整段研讨过程,而不只是最终 md / 流程图。Optional —— 此前
* 的草稿没有该字段,恢复时回退为重建单条「历史记录」气泡。
*/
dialogues?: unknown[];
/** 各席位 write_file 调用重建的 stub(threadId → [stub ai message]),供加载后点开产物的虚拟预览。 */
seatStubMessages?: Record<string, unknown[]>;
/**
* 入库状态(idle/asking/running/done/later/declined)。存它使重载草稿后不重复询问
* 已入库/已选稍后的会商;恢复展示用。Optional —— 旧草稿无该字段。
*/
ingestStatus?: string;
}
/** Lightweight metadata row returned by the list endpoint. */
@@ -206,7 +232,7 @@ export interface DraftUpdatePayload {
const BASE = () => `${getBackendBaseURL()}/api/roundtable-drafts`;
async function readJson<T>(res: Response, ctx: string): Promise<T> {
export async function readJson<T>(res: Response, ctx: string): Promise<T> {
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`${ctx} failed (${res.status}): ${text}`);
@@ -217,8 +243,9 @@ async function readJson<T>(res: Response, ctx: string): Promise<T> {
// ── server ⇄ client field mapping ──────────────────────────────────────────
// Backend uses snake_case (furthest_step / created_at / updated_at); the rest
// of the frontend reads camelCase. Map at this boundary so callers stay clean.
// Shared with the task-scoped client (`task-drafts.ts`) — same wire shape.
interface ServerDraftMeta {
export interface ServerDraftMeta {
id: string;
task_id?: string | null;
title: string;
@@ -229,13 +256,13 @@ interface ServerDraftMeta {
job_id?: string | null;
}
interface ServerDraftFull extends ServerDraftMeta {
export interface ServerDraftFull extends ServerDraftMeta {
step1: DraftStep1Snapshot | null;
step2: DraftStep2Snapshot | null;
step3: DraftStep3Snapshot | null;
}
function toMeta(s: ServerDraftMeta): DraftMeta {
export function toMeta(s: ServerDraftMeta): DraftMeta {
const step = Math.min(3, Math.max(1, s.furthest_step || 1)) as 1 | 2 | 3;
return {
id: s.id,
@@ -249,7 +276,7 @@ function toMeta(s: ServerDraftMeta): DraftMeta {
};
}
function toRecord(s: ServerDraftFull): DraftRecord {
export function toRecord(s: ServerDraftFull): DraftRecord {
return {
...toMeta(s),
step1: s.step1 ?? null,
@@ -258,7 +285,7 @@ function toRecord(s: ServerDraftFull): DraftRecord {
};
}
function fromCreate(p: DraftCreatePayload) {
export function fromCreate(p: DraftCreatePayload) {
return {
...(p.id ? { id: p.id } : {}),
...(p.taskId ? { task_id: p.taskId } : {}),
@@ -270,7 +297,7 @@ function fromCreate(p: DraftCreatePayload) {
};
}
function fromUpdate(p: DraftUpdatePayload) {
export function fromUpdate(p: DraftUpdatePayload) {
const out: Record<string, unknown> = {};
if (p.title !== undefined) out.title = p.title;
if (p.furthestStep !== undefined) out.furthest_step = p.furthestStep;
@@ -298,17 +325,6 @@ export async function getDraft(id: string): Promise<DraftRecord | null> {
return toRecord(data);
}
/**
* 按外部任务 id 取最新一条草稿(后端忽略 user,不分权)。无则返回 null(404)。
* 无界嵌入抽屉打开时用于「该任务有聊天记录则回显最新一条」。
*/
export async function getLatestDraftByTask(taskId: string): Promise<DraftRecord | null> {
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}/latest`, { method: "GET" });
if (res.status === 404) return null;
const data = await readJson<ServerDraftFull>(res, "get latest draft by task");
return toRecord(data);
}
export async function createDraft(payload: DraftCreatePayload): Promise<DraftRecord> {
const res = await apiFetch(BASE(), {
method: "POST",
@@ -0,0 +1,188 @@
/**
* Step3 流程图「后端抽取 + 校验」SSE 客户端。
*
* 对应后端 `POST /api/flow-extract/stream`:后端独立调模型(不走总结线程,避开 coordinatorPrompt
* 的报告锚定)两段式产图——①流式抽取 flow-json(实时吐回,前端原样显示给用户看)→ ②模型校验/修复
* → 返回校验后的结构化图数据 `{title, nodes, edges}`。
*
* 这样把不稳定的「文本→结构」抽取 + 校验放后端,前端只负责实时显示抽取过程 + 拿最终图绘制。
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import type { FlowGraphData } from "@/roundtable-planning/lib/flow-graph";
/** 第三步输入框意图分类结果(与后端 /intent 对应)。 */
export type FlowIntent = "regenerate_report" | "modify_flow" | "regenerate_flow" | "ingest" | "qa" | "unclear";
/**
* 识别第三步输入框消息的意图(一次模型调用)。失败回退 "unclear"(前端发起澄清)。
* 参考 ai_writing 的一次性 JSON 意图识别范式。
*/
export async function classifyFlowIntent(req: {
message: string;
hasReport: boolean;
hasFlow: boolean;
/** 当前是否可入库(入库按钮已出现、未入库);为真才允许识别出 ingest 意图。 */
canIngest?: boolean;
model?: string;
signal?: AbortSignal;
}): Promise<{ intent: FlowIntent; reason: string }> {
try {
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/intent`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: req.message,
has_report: req.hasReport,
has_flow: req.hasFlow,
can_ingest: req.canIngest ?? false,
model: req.model,
}),
signal: req.signal,
});
if (!res.ok) return { intent: "unclear", reason: "" };
const data = (await res.json()) as { intent?: string; reason?: string };
const intent = (data.intent ?? "unclear") as FlowIntent;
return { intent, reason: data.reason ?? "" };
} catch {
return { intent: "unclear", reason: "" };
}
}
/** 「稍后入库」待命时输入框消息的入库意图(与后端 /ingest-intent 对应)。 */
export type IngestIntent = "start_ingest" | "add_data" | "other" | "unclear";
/**
* 识别「稍后入库」后用户在输入框的入库意图(一次模型调用)。
* 失败回退 "unclear"(前端发起协助让用户自己选)。
*/
export async function classifyIngestIntent(req: {
message: string;
model?: string;
signal?: AbortSignal;
}): Promise<{ intent: IngestIntent; reason: string }> {
try {
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/ingest-intent`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: req.message, model: req.model }),
signal: req.signal,
});
if (!res.ok) return { intent: "unclear", reason: "" };
const data = (await res.json()) as { intent?: string; reason?: string };
return { intent: (data.intent ?? "unclear") as IngestIntent, reason: data.reason ?? "" };
} catch {
return { intent: "unclear", reason: "" };
}
}
export interface FlowExtractRequest {
/** 报告 Markdown(优先数据来源)。 */
reportMd?: string | null;
/** 各席位交付(无报告时的数据来源)。 */
seatDeliveries?: Array<{ sender: string; content: string }>;
/** 业务链层级(stages 的 goal)。 */
chainLevels?: string[];
/** 业务链总控编排提示(写明层级时优先用它)。 */
coordinatorPrompt?: string | null;
/** 深链接业务码(rwfx→6BF 等)。非空 → 后端按业务链抽取规范强制注入完整层级。 */
businessCode?: string | null;
/** 根节点 label 强制值(xdfx:本次行动名称)。非空 → 根节点 n1 用它,不用任务名当根。 */
rootLabel?: string | null;
/** 推理模型名(沿用第三步所选)。 */
model?: string;
/** Phase 2 问答修改:当前流程图 + 指令 → 按指令改图(其余不变)。 */
currentGraph?: FlowGraphData | null;
instruction?: string;
signal?: AbortSignal;
/** 抽取流式增量(含 `<think>` 思考 + 正文 + JSON,前端原样渲染:思考块 + 代码块)。 */
onExtractDelta?: (text: string) => void;
/** 抽取结束、进入校验阶段。 */
onValidating?: () => void;
/** 校验/修复流式增量(同样含思考 + 正文,前端实时显示校验过程)。 */
onValidateDelta?: (text: string) => void;
/**
* 模型自动容错:后端某模型抽取失败,已切到下一个模型重抽。上层据此**清空已累计的抽取增量**
* (`onExtractDelta` 之前吐出的半截内容)并提示用户。`failedModel`/`nextModel`/`reason` 描述切换。
*/
onModelSwitch?: (info: { failedModel: string; nextModel: string; reason: string }) => void;
}
/**
* 消费 SSE,返回校验后的最终图。抽取阶段通过 `onExtractDelta` 实时回吐;
* 出错(后端 error 帧 / 网络)抛异常。
*/
export async function streamFlowExtract(req: FlowExtractRequest): Promise<FlowGraphData> {
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/stream`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
report_md: req.reportMd ?? null,
seat_deliveries: (req.seatDeliveries ?? []).map((s) => ({ sender: s.sender, content: s.content })),
chain_levels: req.chainLevels ?? [],
coordinator_prompt: req.coordinatorPrompt ?? null,
business_code: req.businessCode ?? null,
root_label: req.rootLabel ?? null,
model: req.model,
current_graph: req.currentGraph ?? null,
instruction: req.instruction ?? null,
}),
signal: req.signal,
});
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
throw new Error(`flow-extract failed (${res.status}): ${text}`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let graph: FlowGraphData | null = null;
let errored: string | null = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const rawLine of lines) {
const line = rawLine.trimEnd();
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (!data) continue;
let frame: Record<string, unknown>;
try {
frame = JSON.parse(data) as Record<string, unknown>;
} catch {
continue;
}
const event = typeof frame.event === "string" ? frame.event : "";
if (event === "extract_delta") {
const c = typeof frame.content === "string" ? frame.content : "";
if (c) req.onExtractDelta?.(c);
} else if (event === "validating") {
req.onValidating?.();
} else if (event === "validate_delta") {
const c = typeof frame.content === "string" ? frame.content : "";
if (c) req.onValidateDelta?.(c);
} else if (event === "model_switch") {
req.onModelSwitch?.({
failedModel: typeof frame.failed_model === "string" ? frame.failed_model : "",
nextModel: typeof frame.next_model === "string" ? frame.next_model : "",
reason: typeof frame.reason === "string" ? frame.reason : "",
});
} else if (event === "final") {
graph = (frame.graph as FlowGraphData) ?? null;
} else if (event === "error") {
errored = typeof frame.detail === "string" ? frame.detail : "未知错误";
}
}
}
if (errored) throw new Error(errored);
if (!graph || !Array.isArray(graph.nodes) || graph.nodes.length === 0) {
throw new Error("flow-extract 未返回有效流程图");
}
return graph;
}
@@ -0,0 +1,58 @@
/**
* 第三步「入库」功能门控 + 入库执行客户端。
*
* 入库不再由前端硬编码「有没有含『入库』关键字的技能」判定,而是让**结构化输出智能体**
* (`roundtable-structure`)读它挂载的入库技能 + 当前业务场景,**自行判断**是否有适合本
* 场景的入库技能(技能名可能含「六步法」等场景线索)。判定为可入库才显示「入库」按钮。
*
* 真正入库时,由结构化输出智能体走**完整 agent 运行时**(`POST /api/multi-agent/run/stream`,
* role=ingest)**自己挑技能、读 SKILL.md 并调用**完成入库——而不是前端代它调技能。
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
/** `/ingest-eligibility` 返回:是否可入库 + 选中的技能名 + 一句话依据。 */
export interface IngestEligibility {
canIngest: boolean;
skill: string;
reason: string;
}
/**
* 让结构化输出智能体判断「当前业务场景**是否有合适的入库技能**」(决定是否显示入库按钮)。
*
* 入参为业务场景线索(业务码 / 业务链名 / 总控编排提示 / 方案标题)+ taskId,由后端把挂在
* `roundtable-structure` 上、且已启用的技能交给模型对照判断。失败 / 未配置入库技能 → 不可入库。
*/
export async function checkIngestEligibility(req: {
taskId?: string | null;
businessCode?: string | null;
chainName?: string | null;
coordinatorPrompt?: string | null;
reportTitle?: string | null;
model?: string;
}): Promise<IngestEligibility> {
try {
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/ingest-eligibility`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
task_id: req.taskId ?? null,
business_code: req.businessCode ?? null,
chain_name: req.chainName ?? null,
coordinator_prompt: req.coordinatorPrompt ?? null,
report_title: req.reportTitle ?? null,
model: req.model,
}),
});
if (!res.ok) return { canIngest: false, skill: "", reason: "" };
const data = (await res.json()) as { can_ingest?: boolean; skill?: string; reason?: string };
return {
canIngest: !!data.can_ingest,
skill: data.skill ?? "",
reason: data.reason ?? "",
};
} catch {
return { canIngest: false, skill: "", reason: "" };
}
}
@@ -2,6 +2,7 @@ import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import type { ClarificationPayload } from "./multi-agent";
import { reportRoundtableError } from "./diagnostics-report";
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
export type { ClarificationPayload };
@@ -340,6 +341,11 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step1_intent", event: "intent_stream_http_error",
message: `第一步意图生成失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
});
throw new Error(`intent/stream failed (${res.status}): ${text}`);
}
@@ -425,6 +431,11 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
}
if (parsed.status === "error") {
result.errorDetail = parseIntentErrorDetail(parsed.error_detail);
reportRoundtableError({
stage: "step1_intent", event: "intent_error_frame",
message: `第一步意图生成报错:${(result.content || "").slice(0, 800)}`,
detail: result.errorDetail,
});
}
if (parsed.status === "clarification" && result.clarifications.length === 0) {
// Fallback path: no live `type:"tool"` clarification frames were seen
@@ -2,6 +2,7 @@ import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
import { reportRoundtableError, stageForRoundtableAgent } from "@/roundtable-planning/api/diagnostics-report";
export type ThreadIdMap = Record<string, string>;
@@ -74,6 +75,12 @@ export async function initMultiAgent(
tlog(`fetch.headers status=${res.status}`);
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step2_init", event: "init_http_error",
message: `第二步会商初始化失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
detail: { agentNames: payload.agentNames, mainAgentName: payload.mainAgentName },
});
throw new Error(`init multi-agent failed (${res.status}): ${text}`);
}
@@ -150,18 +157,34 @@ export async function initMultiAgent(
}
} catch (err) {
aborted = (err as Error)?.name === "AbortError" || payload.signal?.aborted === true;
if (!aborted) throw err;
if (!aborted) {
reportRoundtableError({
stage: "step2_init", event: "init_stream_exception",
message: `第二步会商初始化中断(网络不可达 / 连接中断 / 超时):${(err as Error)?.message ?? String(err)}`,
detail: { seatCount },
});
throw err;
}
}
tlog(`total ${(performance.now() - t0).toFixed(0)}ms (seats=${seatCount})`);
if (errorDetail) {
reportRoundtableError({
stage: "step2_init", event: "init_error_frame",
message: `第二步会商初始化报错:${errorDetail.slice(0, 800)}`,
});
throw new Error(`init multi-agent failed: ${errorDetail}`);
}
if (aborted) {
throw new DOMException("init aborted", "AbortError");
}
if (!threadIds || !mainAgentName) {
reportRoundtableError({
stage: "step2_init", event: "init_incomplete",
message: "第二步会商初始化流提前结束(未收到 init_done,可能连接被中断)",
detail: { seatCount, hasThreadIds: !!threadIds, mainAgentName },
});
throw new Error("init multi-agent stream ended without init_done");
}
return {
@@ -211,6 +234,17 @@ export interface StreamMultiAgentRequest {
reasoningEffort?: "minimal" | "low" | "medium" | "high";
/** 仅 special 用;ultra 档置真,给席位解锁 `task` 子代理工具。 */
subagentEnabled?: boolean;
/**
* 仅 special 用。会商席位「技能识别强化」开关(沿用所选业务链条配置)。置 true 时后端把该
* 席位配置的技能(含 SKILL.md 路径 + 必须先 read_file 的硬指令)拼进本轮任务,补偿弱模型。
* 与该席位 agent 自身 config.yaml 的同名开关取 OR。省略 = false(关)。
*/
seatSkillDirective?: boolean;
/**
* 深链接业务码(rwfx→6BF 等)。**仅方案总结报告(summary)单例消费**:非空 → 后端按业务链抽取规范
* 强制注入「完整性核对」指令,让总结核对产出相对业务链完不完整。普通会商省略 = 不注入。
*/
businessCode?: string | null;
skillStopNames?: string[];
/**
* 仅 leader 用。置 true 表示这是「派活后让总控判断继续/综合」的轮次:后端会把各已交付
@@ -263,6 +297,27 @@ export interface StreamMultiAgentRequest {
name?: string,
args?: Record<string, unknown>,
) => void;
/**
* 模型自动容错:后端检测到当前模型出问题(兜底错误文案 / 交付为空等),已自动切到下一个
* 模型并即将重跑本轮时触发。上层据此把该角色「正在流式的失败气泡」重置(清空已累计的增量
* 文本)并给用户一条「『X』模型异常,已切换『Y』继续」的提示。此回调可能多次触发(连续多个
* 模型都失败时)。触发后,本次 streamMultiAgent 仍会继续用新模型流式,最终照常 resolve。
*/
onModelSwitch?: (info: ModelSwitchInfo) => void;
}
/** 模型自动容错通知(`streamMultiAgent` 的 `onModelSwitch` 回调入参)。 */
export interface ModelSwitchInfo {
/** 角色:leader / seat / seat_parallel / report / summary / dashboard / ingest。 */
role: string;
/** 出问题的智能体 agent_name。 */
agentName: string;
/** 失败的模型名。 */
failedModel: string;
/** 已切换到的下一个模型名。 */
nextModel: string;
/** 失败原因(已翻译成简短中文,如「服务繁忙」)。 */
reason: string;
}
export interface ClarificationPayload {
@@ -296,6 +351,8 @@ export interface StreamMultiAgentResult {
content: string;
/** Echoed agent_name of the agent that produced this run. */
agentName: string | null;
/** 实际产出本轮结果的模型(发生模型自动容错时即最终切换到的模型);后端未下发时为 null。 */
modelUsed?: string | null;
/**
* Populated when the leader called ask_clarification — the run ended without
* dispatching, and the model is asking the user a question instead. When
@@ -442,6 +499,11 @@ function extractAiTextDelta(parsed: unknown): { text: string; id: string } | nul
export async function streamMultiAgent(
req: StreamMultiAgentRequest,
): Promise<StreamMultiAgentResult> {
// 整段包一层兜底:除已在具体分支上报的(HTTP 错误 / error 帧 / worker error 事件)外,
// 再兜住 fetch 直接 reject(网络不可达 / 连接被拒)与流式中途中断(连接重置 / 超时),
// 做到「能收集到的报错越全越好」。`reported` 防止与具体分支重复上报。
let reported = false;
try {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/run/stream`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -457,6 +519,10 @@ export async function streamMultiAgent(
thinking_enabled: req.thinkingEnabled,
reasoning_effort: req.reasoningEffort,
subagent_enabled: req.subagentEnabled,
// 仅 special 用;会商技能识别强化(沿用所选业务链条开关)。省略 → 后端按 false(关)处理。
seat_skill_directive: req.seatSkillDirective ?? false,
// 仅 summary 单例用;深链接业务码 → 后端注入业务链完整性核对。省略/空 → 不注入。
business_code: req.businessCode ?? null,
skill_stop_names: req.skillStopNames ?? [],
// 仅 leader 用;综合轮让后端注入各席位完整交付正文。省略 → 后端按 false 处理。
synthesis_mode: req.synthesisMode ?? false,
@@ -474,6 +540,17 @@ export async function streamMultiAgent(
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
// 用户实际遇到的报错(含进第三步常见的 502):HTTP 层就失败、SSE 都没建起来。
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, req.agentName),
event: "run_stream_http_error",
message: `「${req.displayName || req.agentName}」调用失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
agentId: req.agentName,
agentName: req.displayName || req.agentName,
detail: { agentType: req.agentType },
});
reported = true;
throw new Error(`run/stream failed (${res.status}): ${text}`);
}
@@ -501,6 +578,7 @@ export async function streamMultiAgent(
content: "",
agentName: null,
clarification: null,
modelUsed: null,
};
// Inferred SSE phase + a tiny helper so we only fire onPhaseChange when the
@@ -611,6 +689,43 @@ export async function streamMultiAgent(
frameSeq += 1;
if (debugEnabled) console.debug(debugLabel, `frame#${frameSeq} event=${lastEvent}`, parsed);
// worker 把 run 内异常(常见:第二步席位/Step3 模型调用失败)发成 `event: error`
// SSE 帧 `{message,name}`——它既不是 HTTP 错误也不是 `{status:"error"}` 终帧,
// 单独在这里捕获上报,否则这类「模型没调用成功」的报错会漏收集。
if (lastEvent === "error") {
const obj = parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : { raw: parsed };
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, req.agentName),
event: "run_worker_error_event",
message: `「${req.displayName || req.agentName}」运行报错:${String(obj.message ?? obj.name ?? "").slice(0, 800)}`,
agentId: req.agentName,
agentName: req.displayName || req.agentName,
detail: { ...obj, agentType: req.agentType, framesBeforeError: frameSeq },
});
}
// 模型自动容错帧:后端检测到当前模型出问题,已切到下一个模型并即将重跑本轮。
// 不是终态帧(无 content)→ 不结束流。清空已累计的(失败尝试的)tool_call 增量,
// 把 phase 退回 connected,并通知上层重置该角色气泡 + 给用户提示。随后新模型的
// 流式增量会照常通过 onTextDelta 继续累计到(已被上层清空的)气泡。
if (
parsed &&
typeof parsed === "object" &&
(parsed as Record<string, unknown>).status === "model_switch"
) {
const obj = parsed as Record<string, unknown>;
toolCallAcc.clear();
currentPhase = "connected";
req.onModelSwitch?.({
role: typeof obj.role === "string" ? obj.role : "",
agentName: typeof obj.agent_name === "string" ? obj.agent_name : req.agentName,
failedModel: typeof obj.failed_model === "string" ? obj.failed_model : "",
nextModel: typeof obj.next_model === "string" ? obj.next_model : "",
reason: typeof obj.reason === "string" ? obj.reason : "",
});
continue;
}
// Phase inference from LangGraph messages-tuple frames. We only flip
// to tool_calling/tool_result on chunks that clearly indicate them;
// everything else with non-empty AI text means we're streaming.
@@ -711,6 +826,22 @@ export async function streamMultiAgent(
if (typeof parsed.agent_name === "string") {
result.agentName = parsed.agent_name;
}
{
const mu = (parsed as Record<string, unknown>).model_used;
if (typeof mu === "string" && mu) result.modelUsed = mu;
}
// SSE error 帧(后端 stream_generator 在席位/Step3 run 失败时下发
// `{status:"error", content, agent_name}`):上报,便于收集用户侧报错。
if (result.message === "error") {
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, result.agentName || req.agentName),
event: "run_stream_error_frame",
message: `「${req.displayName || req.agentName}」运行报错:${(result.content || "").slice(0, 800)}`,
agentId: result.agentName || req.agentName,
agentName: req.displayName || req.agentName,
detail: { agentType: req.agentType, framesBeforeError: frameSeq },
});
}
continue;
}
@@ -728,6 +859,19 @@ export async function streamMultiAgent(
console.debug(debugLabel, `stream ended after ${frameSeq} frames; final content length=${result.content.length}`);
}
return result;
} catch (err) {
if (!reported && req.signal?.aborted !== true && (err as Error)?.name !== "AbortError") {
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, req.agentName),
event: "run_stream_exception",
message: `「${req.displayName || req.agentName}」调用异常(网络不可达 / 连接中断 / 超时):${(err as Error)?.message ?? String(err)}`,
agentId: req.agentName,
agentName: req.displayName || req.agentName,
detail: { agentType: req.agentType },
});
}
throw err;
}
}
export interface SessionArtifactFile {
@@ -829,12 +973,48 @@ export async function initReportThread(
});
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step3_report", event: "init_thread_http_error",
message: `结果绘制线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status, agentId: "roundtable-report", agentName: "结果绘制",
});
throw new Error(`init report thread failed (${res.status}): ${text}`);
}
const json = (await res.json()) as { agent_name: string; thread_id: string };
return { agentName: json.agent_name, threadId: json.thread_id };
}
/**
* Create a thread for the Step 3「大屏多页」dashboard-data agent
* (`roundtable-dashboard`, a built-in singleton — distinct from `roundtable-report`;
* its run policy disables ALL tools so it only emits a ```report-json block). Run it
* with {@link streamMultiAgent} (`agentType: "special"`, `agentName: "roundtable-dashboard"`,
* `dAgentThreadId: { [agentName]: threadId }`); the frontend then `extractReportData`s
* the streamed text. Follow-up Q&A / refinements reuse the SAME thread (do not re-init)
* so the agent keeps the prior dashboard context.
*/
export async function initDashboardThread(
options: { signal?: AbortSignal } = {},
): Promise<ReportThreadResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/dashboard/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
signal: options.signal,
});
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step3_dashboard", event: "init_thread_http_error",
message: `大屏页面线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status, agentId: "roundtable-dashboard", agentName: "大屏页面",
});
throw new Error(`init dashboard thread failed (${res.status}): ${text}`);
}
const json = (await res.json()) as { agent_name: string; thread_id: string };
return { agentName: json.agent_name, threadId: json.thread_id };
}
/**
* Create a thread for the Step 3「总结报告」summary agent (`roundtable-summary`,
* a built-in singleton — distinct from `roundtable-report`; this only spins up a
@@ -854,8 +1034,44 @@ export async function initSummaryThread(
});
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step3_summary", event: "init_thread_http_error",
message: `方案报告线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status, agentId: "roundtable-summary", agentName: "方案报告",
});
throw new Error(`init summary thread failed (${res.status}): ${text}`);
}
const json = (await res.json()) as { agent_name: string; thread_id: string };
return { agentName: json.agent_name, threadId: json.thread_id };
}
/**
* Create a thread for the Step 3「入库」structure agent (`roundtable-structure`,
* a built-in singleton — the same agent that extracts the flowchart, but this run
* uses the `ingest` run policy so its attached ingest skill actually executes).
* Run it afterwards with {@link streamMultiAgent} (`agentType: "special"`,
* `agentName: "roundtable-structure"`, `dAgentThreadId: { [agentName]: threadId }`):
* the agent picks the suitable ingest skill (its name may contain「六步法」), reads
* its SKILL.md and calls it — passing the taskId + summary report + structured flow.
*/
export async function initStructureThread(
options: { signal?: AbortSignal } = {},
): Promise<ReportThreadResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/structure/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
signal: options.signal,
});
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step3_structure", event: "init_thread_http_error",
message: `结构化输出线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status, agentId: "roundtable-structure", agentName: "结构化输出",
});
throw new Error(`init structure thread failed (${res.status}): ${text}`);
}
const json = (await res.json()) as { agent_name: string; thread_id: string };
return { agentName: json.agent_name, threadId: json.thread_id };
}
@@ -3,6 +3,7 @@ import { getBackendBaseURL } from "@/core/config";
import type { Agent } from "@/core/agents";
import type { IntentSummary } from "./intent";
import { reportRoundtableError } from "./diagnostics-report";
/**
* Agent-recommendation API. Sits between Step 1 (intent clarification) and
@@ -318,6 +319,11 @@ export async function streamRecommend(req: StreamRecommendRequest): Promise<Stre
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step2_recommend", event: "recommend_stream_http_error",
message: `智能体推荐失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
});
throw new Error(`recommend/stream failed (${res.status}): ${text}`);
}
@@ -373,6 +379,12 @@ export async function streamRecommend(req: StreamRecommendRequest): Promise<Stre
if (Array.isArray(parsed.picks)) {
result.picks = parsed.picks as RecommendPick[];
}
if (parsed.status === "error") {
reportRoundtableError({
stage: "step2_recommend", event: "recommend_error_frame",
message: `智能体推荐报错:${(result.content || "").slice(0, 800)}`,
});
}
continue;
}
@@ -15,6 +15,7 @@ import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import { getAvatarTypeFor } from "../lib/roundtable-constants";
import { reportRoundtableError } from "./diagnostics-report";
import { seatModeToRunParams } from "../lib/seat-mode";
import {
isTerminalJobStatus,
@@ -29,6 +30,11 @@ const BASE = () => `${getBackendBaseURL()}/api/roundtable-jobs`;
async function readJson<T>(res: Response, ctx: string): Promise<T> {
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "job", event: "job_api_http_error",
message: `后台作业接口「${ctx}」失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
});
throw new Error(`${ctx} failed (${res.status}): ${text}`);
}
return (await res.json()) as T;
@@ -81,6 +87,8 @@ function toStartBody(p: StartJobPayload) {
const seat = p.seatMode ? seatModeToRunParams(p.seatMode) : null;
return {
draftId: p.draftId ?? null,
// taskId 非空 → task 作业(按 task 共享、不分权,报告写回独立 task-draft 存储)。
...(p.taskId ? { taskId: p.taskId } : {}),
intent: p.intent,
agents: p.agents,
model: p.model,
@@ -90,6 +98,18 @@ function toStartBody(p: StartJobPayload) {
seedMessage: p.seedMessage,
threadIds: p.threadIds ?? null,
coordinatorName: p.coordinatorName ?? "roundtable-coordinator",
// 每席位技能识别强化映射 {agentId: bool}:沿用所选业务链条里各席位的开关;缺省 {}。
// 后端 run_seat 按 agentId 查表,与各席位 agent 自身开关取 OR。
seat_skill_directives: p.seatSkillDirectives ?? {},
// 每席位推理深度覆盖映射 {agentId: SeatMode|null}:沿用所选业务链条里各席位单独配的推理深度;
// 后端 run_seat 按 agentId 查表,覆盖优先、否则跟随作业级 seatMode(thinking/reasoning/subagent)。
seat_modes: Object.fromEntries(
Object.entries(p.seatModes ?? {}).filter(([, v]) => v != null) as [string, string][],
),
// 研讨前并行取数开关(来源链条 gatherFirst):true = 后台研讨前先并行取数再研讨。缺省 false。
gather_first: p.gatherFirst ?? false,
// 深链接业务码:后台总结报告据此做业务链完整性核对(写实业务如 rwfx 才生效)。空 → 不注入。
business_code: p.businessCode ?? null,
...(seat
? {
thinking_enabled: seat.thinking_enabled,
@@ -131,23 +151,31 @@ export function startJobKeepalive(payload: StartJobPayload): void {
}
}
/** 查作业快照。404 → null。 */
export async function getJob(jobId: string): Promise<RoundtableJob | null> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}`, { method: "GET" });
/** taskId 非空 → 追加 `task_id` 查询参(task 作业按 task 共享、不分权读取/控制)。 */
function taskQuery(taskId: string | null | undefined, sep: "?" | "&"): string {
return taskId ? `${sep}task_id=${encodeURIComponent(taskId)}` : "";
}
/** 查作业快照。404 → null。`taskId` 非空走 task 共享读取(不分权)。 */
export async function getJob(jobId: string, taskId?: string | null): Promise<RoundtableJob | null> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}${taskQuery(taskId, "?")}`, { method: "GET" });
if (res.status === 404) return null;
return mapJob(await readJson<Record<string, unknown>>(res, "get job"));
}
/** 查某草稿最近一个作业。无 → null。 */
export async function getJobByDraft(draftId: string): Promise<RoundtableJob | null> {
const res = await apiFetch(`${BASE()}?draft_id=${encodeURIComponent(draftId)}`, { method: "GET" });
/** 查某草稿最近一个作业。无 → null。`taskId` 非空走 task 共享读取(不分权)。 */
export async function getJobByDraft(draftId: string, taskId?: string | null): Promise<RoundtableJob | null> {
const res = await apiFetch(
`${BASE()}?draft_id=${encodeURIComponent(draftId)}${taskQuery(taskId, "&")}`,
{ method: "GET" },
);
const data = await readJson<Record<string, unknown> | null>(res, "get job by draft");
return data ? mapJob(data) : null;
}
/** 回答澄清后续跑。 */
export async function resumeJob(jobId: string, answer: string): Promise<RoundtableJob> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/resume`, {
/** 回答澄清后续跑。`taskId` 非空 → task 共享续跑(不分权)。 */
export async function resumeJob(jobId: string, answer: string, taskId?: string | null): Promise<RoundtableJob> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/resume${taskQuery(taskId, "?")}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ answer }),
@@ -155,9 +183,9 @@ export async function resumeJob(jobId: string, answer: string): Promise<Roundtab
return mapJob(await readJson<Record<string, unknown>>(res, "resume job"));
}
/** 取消作业。 */
export async function cancelJob(jobId: string): Promise<RoundtableJob> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/cancel`, { method: "POST" });
/** 取消作业。`taskId` 非空 → task 共享取消(不分权)。 */
export async function cancelJob(jobId: string, taskId?: string | null): Promise<RoundtableJob> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/cancel${taskQuery(taskId, "?")}`, { method: "POST" });
return mapJob(await readJson<Record<string, unknown>>(res, "cancel job"));
}
@@ -177,12 +205,12 @@ export interface StreamJobHandlers {
*
* 终态帧后后端会主动关闭流;本函数也在收到终态快照时调 onDone,调用方可据此 unsubscribe。
*/
export function streamJob(jobId: string, handlers: StreamJobHandlers): () => void {
export function streamJob(jobId: string, handlers: StreamJobHandlers, taskId?: string | null): () => void {
const controller = new AbortController();
void (async () => {
try {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/stream`, {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/stream${taskQuery(taskId, "?")}`, {
method: "GET",
signal: controller.signal,
});
@@ -211,7 +239,13 @@ export function streamJob(jobId: string, handlers: StreamJobHandlers): () => voi
continue;
}
if (frame.event === "error") {
handlers.onError?.(String(frame.detail ?? "unknown stream error"));
const detail = String(frame.detail ?? "unknown stream error");
reportRoundtableError({
stage: "job", event: "job_stream_error_frame",
message: `后台作业进度流报错:${detail.slice(0, 500)}`,
jobId, detail: { taskId },
});
handlers.onError?.(detail);
continue;
}
const job = mapJob(frame);
@@ -0,0 +1,83 @@
/**
* **Task-scoped** roundtable draft storage (taskId 深链聊天记录).
*
* Separate from the per-user `drafts.ts` client: records here are keyed **only by
* `taskId`** and are **not partitioned by user** (the deep-link audience shares
* them). Hits `/api/roundtable-task-drafts` (table `roundtable_task_drafts`),
* physically distinct from the personal `roundtable_drafts` store so the two
* never mix.
*
* The wire shape matches the personal store, so we reuse its types + mappers.
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import {
fromCreate,
fromUpdate,
readJson,
toMeta,
toRecord,
type DraftCreatePayload,
type DraftMeta,
type DraftRecord,
type DraftUpdatePayload,
type ServerDraftFull,
type ServerDraftMeta,
} from "@/roundtable-planning/api/drafts";
const BASE = () => `${getBackendBaseURL()}/api/roundtable-task-drafts`;
/** 按外部任务 id 列出该任务全部聊天记录(轻量 meta,newest first;不分权)。 */
export async function listTaskDraftsByTask(taskId: string): Promise<DraftMeta[]> {
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}`, { method: "GET" });
const data = await readJson<{ drafts: ServerDraftMeta[] }>(res, "list task drafts");
return (data.drafts ?? []).map(toMeta);
}
/** 按外部任务 id 取最新一条聊天记录(不分权)。无则 null(404)。 */
export async function getLatestTaskDraftByTask(taskId: string): Promise<DraftRecord | null> {
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}/latest`, { method: "GET" });
if (res.status === 404) return null;
const data = await readJson<ServerDraftFull>(res, "get latest task draft");
return toRecord(data);
}
/** Full task draft by id (不分权). Returns null on 404. */
export async function getTaskDraft(id: string): Promise<DraftRecord | null> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "GET" });
if (res.status === 404) return null;
const data = await readJson<ServerDraftFull>(res, "get task draft");
return toRecord(data);
}
/** Create a task draft. `payload.taskId` is required. */
export async function createTaskDraft(payload: DraftCreatePayload): Promise<DraftRecord> {
const res = await apiFetch(BASE(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(fromCreate(payload)),
});
const data = await readJson<ServerDraftFull>(res, "create task draft");
return toRecord(data);
}
export async function updateTaskDraft(id: string, patch: DraftUpdatePayload): Promise<DraftRecord | null> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(fromUpdate(patch)),
});
if (res.status === 404) return null;
const data = await readJson<ServerDraftFull>(res, "update task draft");
return toRecord(data);
}
export async function deleteTaskDraft(id: string): Promise<void> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "DELETE" });
if (!res.ok && res.status !== 404) {
const text = await res.text().catch(() => "");
throw new Error(`delete task draft failed (${res.status}): ${text}`);
}
}
@@ -1,4 +1,5 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import type { ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -214,7 +215,9 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
[content],
);
return (
// 经 portal 挂到 body:脱离会商页 <main>(`relative z-0`) 的层叠上下文,
// 否则 fixed 弹窗会被会商页头(z-40)/全局顶栏(z-45)盖住顶部。
return createPortal(
<div
className="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-6"
onMouseDown={(e) => {
@@ -287,6 +290,7 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
)}
</div>
</div>
</div>
</div>,
document.body,
);
};
@@ -31,6 +31,7 @@ import {
import { cn } from "@/lib/utils";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
import { getStoredAuth } from "@/core/auth";
import { listAgents } from "@/core/agents";
import { listChains, setChainPublic, type ChainScope } from "../api/chains";
@@ -71,7 +72,9 @@ export function BusinessChainListBody({
const [chains, setChains] = useState<BusinessChain[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// 筛选:我的 / 公共(已发布)。
// 管理员:额外多一个「全部」筛选,且可编辑 / 发布任意账号的链条。
const isAdmin = getStoredAuth()?.system_role === "admin";
// 筛选:我的 / 公共(已发布)/(管理员)全部。
const [scope, setScope] = useState<ChainScope>("mine");
const [publishingId, setPublishingId] = useState<string | null>(null);
// 实时名称表(id 小写 → 最新 name):用于把席位的落库快照名刷新成最新(agent 改名同步)。
@@ -147,9 +150,9 @@ export function BusinessChainListBody({
return (
<>
{/* 筛选:我的 / 公共 */}
{/* 筛选:我的 / 公共 /(管理员)全部 */}
<div className="shrink-0 flex items-center gap-1 rounded-lg border border-border bg-muted/40 p-0.5 self-start">
{(["mine", "public"] as const).map((s) => (
{((isAdmin ? ["mine", "public", "all"] : ["mine", "public"]) as ChainScope[]).map((s) => (
<button
key={s}
type="button"
@@ -161,7 +164,7 @@ export function BusinessChainListBody({
: "text-muted-foreground hover:text-foreground",
)}
>
{s === "mine" ? "我的" : "公共"}
{s === "mine" ? "我的" : s === "public" ? "公共" : "全部"}
</button>
))}
</div>
@@ -195,6 +198,7 @@ export function BusinessChainListBody({
<ChainRow
key={chain.id}
chain={chain}
canManage={isAdmin || chain.isMine !== false}
nameById={nameById}
publishing={publishingId === chain.id}
onSettings={() => onConfigure(chain.id)}
@@ -245,18 +249,20 @@ export function BusinessChainListDialog({
function ChainRow({
chain,
canManage,
nameById,
publishing,
onSettings,
onTogglePublic,
}: {
chain: BusinessChain;
/** 能否编辑 / 发布(本人链条 或 管理员)。 */
canManage: boolean;
nameById: Map<string, string>;
publishing: boolean;
onSettings: () => void;
onTogglePublic: () => void;
}) {
const isMine = chain.isMine !== false;
// 配置者用户名:后端返回 email,展示时取 @ 前的本地部分更像「用户名」。
const ownerName = chain.ownerName ? chain.ownerName.split("@")[0] : "";
return (
@@ -274,8 +280,8 @@ function ChainRow({
</span>
)}
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{/* 发布 / 取消发布:仅本人的链条可操作。 */}
{isMine && (
{/* 发布 / 取消发布:本人的链条或管理员可操作。 */}
{canManage && (
<Button
variant={chain.isPublic ? "secondary" : "outline"}
size="sm"
@@ -291,8 +297,8 @@ function ChainRow({
{chain.isPublic ? "取消发布" : "发布"}
</Button>
)}
{/* 设置(编辑):仅本人的链条;公共里别人的链条只读浏览。 */}
{isMine && (
{/* 设置(编辑):本人的链条或管理员;普通用户看别人的链条只读浏览。 */}
{canManage && (
<Button
variant="ghost"
size="sm"
@@ -147,19 +147,28 @@ export function BusinessChainPicker({
const chainMeta = { id: selectedChain.id, title: selectedChain.title };
const seatNameById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.name]));
const nameOf = (id: string) => nameById.get(id) ?? seatNameById.get(id) ?? id;
// 席位模型覆盖(链条配置):按 agent_id 取,空/缺省 = 跟随全局模型。
const modelById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.model ?? null]));
const modelOf = (id: string) => modelById.get(id) ?? null;
// 席位「会商技能识别强化」开关(链条配置):按 agent_id 取,缺省 = 关。
const skillById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.seat_skill_directive ?? false]));
const skillOf = (id: string) => skillById.get(id) ?? false;
// 席位「推理深度覆盖」(链条配置 seat_mode):按 agent_id 取,null/缺省 = 跟随链条级 seatMode。
const seatModeById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.seat_mode ?? null]));
const seatModeOf = (id: string) => seatModeById.get(id) ?? null;
// 链条带分层、过滤存活后仍并行 → dag 编排(携带快速/沙箱子模式);否则退回线性 chain。
if (dagPlan) {
// dag:席位顺序按 stage 展平(与 plan 一致)。
const agents = dagPlan.stages
.flatMap((st) => st.agentIds)
.map((id) => ({ agent_id: id, name: nameOf(id) }));
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode });
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), seatMode: seatModeOf(id) }));
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode, gatherFirst: selectedChain.gatherFirst ?? false });
return;
}
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id) }));
onConfirm({ agents, mode: "chain", chain: chainMeta });
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
onConfirm({ agents, mode: "chain", chain: chainMeta, gatherFirst: selectedChain.gatherFirst ?? false });
};
// 整片脱敏:链条卡片区(链条名/描述/席位智能体名)。输入框不受影响(Hook 跳过)。
@@ -0,0 +1,250 @@
/**
* 大屏绘制智能体「交互区」聊天面板(沙箱左 60%;右 40% 是抽取过程代码预览)。
*
* 从 `Step3DashboardMode` 抽出共享:圆桌 Step3「结果绘制·大屏」与独立大屏页
* (`DashboardAgentPage`)都复用同一套聊天 UI(流式气泡 + 模型选择 + 暂停/重画 +
* 修改输入框)。消息里不展示 report-json 本体(已在右侧沙箱实时渲染),用
* `stripReportFence` 替换成一句提示。
*/
import { useMemo, useRef, useState, type FormEvent } from "react";
import {
CheckCircle,
Loader2,
Pause,
RefreshCw,
SendHorizontal,
} from "lucide-react";
import { useLocalSettings } from "@/core/settings";
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
import type { ModelOption } from "@/roundtable-planning/components/Step3ReportMode";
import { ScrollToBottomButton } from "@/roundtable-planning/components/ScrollToBottomButton";
import { Step2Message } from "@/roundtable-planning/components/Step2Panel";
import { useAutoScroll } from "@/roundtable-planning/hooks/useAutoScroll";
import { useDialogueSpeedMetrics } from "@/roundtable-planning/hooks/useDialogueSpeedMetrics";
import type { UseStep3DashboardReturn } from "@/roundtable-planning/hooks/useStep3Dashboard";
import { stripReportFence } from "@/roundtable-planning/lib/report-template";
export interface DashboardChatPanelProps {
phase: UseStep3DashboardReturn["phase"];
dialogues: UseStep3DashboardReturn["dialogues"];
busy: boolean;
error: string | null;
onAsk: (message: string) => void;
onRedraw: () => void;
onPause: () => void;
onOpenPreview: () => void;
hasResult: boolean;
selectedModel: string;
availableModels: ReadonlyArray<ModelOption>;
modelsLoading: boolean;
setSelectedModel: (model: string) => void;
/** 面板副标题(默认对齐圆桌 Step3;独立大屏页可自定义说明)。 */
subtitle?: string;
/** 完成提示语(默认「已切换到大屏页面」;独立页不自动跳,可改文案)。 */
doneHint?: string;
}
export function DashboardChatPanel({
phase,
dialogues,
busy,
error,
onAsk,
onRedraw,
onPause,
onOpenPreview,
hasResult,
selectedModel,
availableModels,
modelsLoading,
setSelectedModel,
subtitle = "提炼研讨成果为大屏结构化数据(右侧实时显示抽取过程)",
doneHint = "数据已就绪,已切换到大屏页面。",
}: DashboardChatPanelProps) {
const inputLocked = phase === "creating";
const scrollRef = useRef<HTMLDivElement>(null);
const { atBottom, scrollToBottom } = useAutoScroll(scrollRef, [dialogues]);
const [localSettings] = useLocalSettings();
const speedMeterEnabled = localSettings.display.streamSpeedMeterEnabled;
const dialogueMetrics = useDialogueSpeedMetrics(dialogues);
const [text, setText] = useState("");
// 消息列表里不展示 report-json 结构化数据本体(它已在右侧沙箱实时渲染),
// 把数据块替换成一句「看右侧沙箱」的提示,避免左右两边重复刷整段 JSON。
const displayDialogues = useMemo(
() =>
dialogues.map((d) => {
const content = d.content ?? "";
if (!content) return d;
const stripped = stripReportFence(content, d.streaming === true);
return stripped === content ? d : { ...d, content: stripped };
}),
[dialogues],
);
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const t = text.trim();
if (!t || inputLocked) return;
setText("");
onAsk(t);
};
return (
<div className="flex h-full min-h-0 flex-col bg-slate-50/20">
{/* 面板头:智能体名 + 模型选择 + 暂停/重画 */}
<div className="shrink-0 flex items-center justify-between gap-2 border-b border-slate-100 bg-white px-4 py-2.5">
<div className="flex items-center gap-2 min-w-0">
<div className="w-6 h-6 shrink-0 rounded-lg bg-gradient-to-tr from-primary to-[var(--brand-200)] flex items-center justify-center text-white text-xs shadow-sm">
📊
</div>
<div className="leading-tight min-w-0">
<div className="text-xs font-bold text-slate-800 truncate">大屏绘制智能体</div>
<div className="text-[10px] text-slate-400 truncate">{subtitle}</div>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<select
id="step3-dashboard-model-select"
value={selectedModel}
onChange={(e) => setSelectedModel(e.target.value)}
disabled={busy || modelsLoading || availableModels.length === 0}
title={
modelsLoading
? "正在加载模型列表…"
: availableModels.length === 0
? "未在 config.yaml 中配置任何模型"
: busy
? "绘制中不可切换;完成后或重新绘制时生效"
: "切换绘制使用的推理模型(下次绘制生效)"
}
className="max-w-[160px] bg-slate-50/50 border border-slate-200 rounded-xl px-2.5 py-1.5 text-[11px] 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>
{busy ? (
<button
type="button"
onClick={onPause}
title="中止当前绘制"
className="bg-white border border-amber-200 text-amber-700 hover:bg-amber-50 text-[10.5px] font-bold px-2.5 py-1.5 rounded-xl flex items-center gap-1 transition"
>
<Pause className="w-3.5 h-3.5" />
中止
</button>
) : (
<button
type="button"
onClick={onRedraw}
title="丢弃上下文,从头重新绘制"
className="bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 text-[10.5px] font-bold px-2.5 py-1.5 rounded-xl flex items-center gap-1 transition"
>
<RefreshCw className="w-3.5 h-3.5 text-slate-500" />
重新绘制
</button>
)}
</div>
</div>
{/* 聊天记录 */}
<div className="relative flex-1 min-h-0 flex flex-col">
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-4 space-y-4 bg-white">
{phase === "creating" && dialogues.length === 0 && (
<div className="flex items-center gap-2 text-xs text-slate-500">
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary" />
正在初始化绘制线程…
</div>
)}
{displayDialogues.map((msg) => (
<Step2Message
key={msg.id}
msg={msg}
metric={speedMeterEnabled ? dialogueMetrics.get(msg.id) : undefined}
/>
))}
{busy && (
<div className="inline-flex items-center gap-2 rounded-full border bg-white px-2.5 py-1 text-[11px] text-slate-500">
<span className="bg-primary size-1.5 animate-pulse rounded-full" />
右侧沙箱实时显示数据抽取过程
</div>
)}
{phase === "error" && (
<div className="rounded-xl border border-rose-200 bg-rose-50 p-3 text-xs text-rose-700">
<div className="font-bold mb-1">绘制失败</div>
<div className="leading-relaxed break-all">{error}</div>
<button
type="button"
onClick={onRedraw}
className="mt-2 inline-flex items-center gap-1 text-[11px] font-bold text-rose-700 underline hover:text-rose-800"
>
<RefreshCw className="w-3 h-3" />
重试
</button>
</div>
)}
{phase === "done" && (
<div className="flex items-center gap-2 text-xs font-bold text-emerald-600">
<CheckCircle className="w-4 h-4" />
{doneHint}
{hasResult && (
<button
type="button"
onClick={onOpenPreview}
className="ml-1 inline-flex items-center gap-1 text-[11px] font-bold text-primary underline hover:opacity-80"
>
在沙箱打开 HTML 预览
</button>
)}
</div>
)}
</div>
{!atBottom && <ScrollToBottomButton onClick={scrollToBottom} />}
{/* 问答修改输入框 */}
<form onSubmit={handleSubmit} className="shrink-0 border-t border-slate-100 bg-white px-3 py-3">
<div className="flex items-end gap-2 rounded-2xl border border-slate-200 bg-slate-50/70 px-3 py-2 focus-within:border-primary/60 focus-within:bg-white focus-within:ring-2 focus-within:ring-[var(--brand-200)]/40">
<AutoGrowTextarea
maxHeight={224}
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
e.currentTarget.form?.requestSubmit();
}
}}
disabled={inputLocked}
rows={1}
placeholder={
busy
? "随时输入修改要求——发送会打断当前绘制并按新要求重出数据"
: "输入修改要求,例如:把风险分布换成柱状图,新增一个执行路线席位"
}
className="min-h-8 max-h-56 flex-1 resize-none bg-transparent py-1.5 text-xs leading-relaxed text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"
/>
<button
type="submit"
disabled={inputLocked || text.trim().length === 0}
title={inputLocked ? "正在初始化线程,请稍候" : "发送修改要求"}
className="mb-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary text-white transition hover:bg-[var(--brand-900)] disabled:cursor-not-allowed disabled:opacity-50"
>
{inputLocked ? <Loader2 className="h-4 w-4 animate-spin" /> : <SendHorizontal className="h-4 w-4" />}
</button>
</div>
</form>
</div>
</div>
);
}
@@ -18,6 +18,11 @@ export interface DispatchChainJobModalProps {
onOpenChange: (open: boolean) => void;
title?: string;
onView?: (job: RoundtableJob) => void;
/**
* 外部任务 id(taskId 深链会商)。非空 → 按 task 共享读取/控制作业(不分权),
* 任何人打开同一 task 都能看在跑的研讨流程图。普通模式留空。
*/
taskId?: string | null;
}
export function DispatchChainJobModal({
@@ -26,6 +31,7 @@ export function DispatchChainJobModal({
onOpenChange,
title,
onView,
taskId = null,
}: DispatchChainJobModalProps) {
const [job, setJob] = useState<RoundtableJob | null>(null);
@@ -36,24 +42,28 @@ export function DispatchChainJobModal({
}
let cancelled = false;
// 首帧快照:弹窗一打开就有内容,不必等 SSE 第一帧。
void getJob(jobId)
void getJob(jobId, taskId)
.then((j) => {
if (!cancelled && j) setJob(j);
})
.catch(() => {});
const unsubscribe = streamJob(jobId, {
onProgress: (j) => {
if (!cancelled) setJob(j);
const unsubscribe = streamJob(
jobId,
{
onProgress: (j) => {
if (!cancelled) setJob(j);
},
onError: () => {
/* 流错误静默:保留已拿到的最后一帧;可后续加 toast */
},
},
onError: () => {
/* 流错误静默:保留已拿到的最后一帧;可后续加 toast */
},
});
taskId,
);
return () => {
cancelled = true;
unsubscribe();
};
}, [open, jobId]);
}, [open, jobId, taskId]);
return (
<DispatchChainModal
@@ -75,7 +85,7 @@ export function DispatchChainJobModal({
jobId
? (answer) => {
// 乐观更新为 running,随后 SSE 会推真状态续上。
void resumeJob(jobId, answer)
void resumeJob(jobId, answer, taskId)
.then((j) => setJob(j))
.catch(() => {});
}
@@ -84,7 +94,7 @@ export function DispatchChainJobModal({
onCancel={
jobId
? () => {
void cancelJob(jobId)
void cancelJob(jobId, taskId)
.then((j) => setJob(j))
.catch(() => {});
}
@@ -15,12 +15,14 @@ import {
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import {
applyNodeChanges,
Background,
BackgroundVariant,
Handle,
MarkerType,
MiniMap,
Position,
ReactFlow,
ReactFlowProvider,
@@ -32,11 +34,14 @@ import {
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import {
Check,
FileText,
Loader2,
LocateFixed,
Maximize2,
Minimize2,
Pencil,
Trash2,
Workflow,
X,
ZoomIn,
@@ -44,14 +49,36 @@ import {
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useTheme } from "@/contexts/ThemeContext";
import {
FLOW_NODE_TYPE_META,
applyNodeEdit,
deleteNodeFromGraph,
flowNodeMeta,
FLOW_NODE_W,
layoutFlowGraph,
type FlowGraphData,
type FlowGraphNode,
type FlowOrientation,
} from "@/roundtable-planning/lib/flow-graph";
/**
* 深蓝主题色板(《深蓝色 UI 规范》ZS-004 / ZS-002)。浅色保持原 slate/white。
* 用于流程图弹窗在深色下的容器 / 头部 / 画布 / 连线 / 图例 / 小地图 / 详情弹窗。
*/
const DARK = {
pageBg: "#0C1836", // ZS-004-09 画布底
cardBg: "#122347", // ZS-004-08 头部 / 详情卡底
border: "#1A2F5A", // ZS-004-07 卡片边框
borderStrong: "#2D4473", // ZS-004-06 弱分割
text: "#C5CFE0", // ZS-004-02 正文
textMuted: "#6E88B0", // ZS-004-04 次级文字
primary: "#1677FF", // ZS-002-06 主色
link: "#4096FF", // ZS-002-05 链接
dots: "#2D4473", // 画布点阵
edge: "#4A6491", // ZS-004-05 静态连线
edgeActive: "#4096FF", // 活动连线
} as const;
interface FlowGraphPanelProps {
data: FlowGraphData;
/** 流式绘制中(决定蚂蚁线 + 自动 fitView 跟随)。 */
@@ -59,17 +86,34 @@ interface FlowGraphPanelProps {
onClose: () => void;
/** 沙箱里有 md 报告时提供:工具栏显示「MD 报告」按钮,点击切回 Markdown 预览。 */
onSwitchToReport?: () => void;
/** Phase 3:画布手动编辑——传入则节点详情弹窗出现「编辑 / 删除」,回写整张新图。 */
onChange?: (next: FlowGraphData) => void;
/** 布局方向:默认 "vertical"(自上而下);弹窗里用 "horizontal" 横向铺开。 */
orientation?: FlowOrientation;
/** 右下角缩略图(小地图)—— 弹窗大画布里便于纵览定位。 */
miniMap?: boolean;
}
// ── 自定义节点(按 type 着色的卡片)────────────────────────────────────────
function FlowCardNode({ data }: NodeProps) {
const node = (data as { node?: FlowGraphNode; scale?: number }).node;
const scale = (data as { node?: FlowGraphNode; scale?: number }).scale ?? 1;
const d = data as {
node?: FlowGraphNode;
scale?: number;
orientation?: FlowOrientation;
dark?: boolean;
};
const node = d.node;
const scale = d.scale ?? 1;
if (!node) return null;
const meta = FLOW_NODE_TYPE_META[node.type];
const meta = flowNodeMeta(d.dark ?? false)[node.type];
// 节点宽度随容器宽度缩放(宽时放大、窄时缩小)。
const scaledWidth = FLOW_NODE_W * scale;
// 横向布局连入/连出走左右两侧,纵向走上下。
const horizontal = d.orientation === "horizontal";
const targetPos = horizontal ? Position.Left : Position.Top;
const sourcePos = horizontal ? Position.Right : Position.Bottom;
const handleColor = d.dark ? "!bg-[#4A6491]" : "!bg-slate-400";
return (
<div
style={{
@@ -81,15 +125,15 @@ function FlowCardNode({ data }: NodeProps) {
className="cursor-pointer rounded-xl border-2 px-3 py-2 shadow-sm transition hover:shadow-md"
title="点击查看详情"
>
<Handle type="target" position={Position.Top} className="!h-1.5 !w-1.5 !bg-slate-400" />
<Handle type="target" position={targetPos} className={cn("!h-1.5 !w-1.5", handleColor)} />
<div className="mb-0.5 flex items-center gap-1.5">
<span style={{ background: meta.dot }} className="size-2 shrink-0 rounded-full" />
<span className="text-[9px] font-bold uppercase tracking-wider opacity-70" style={{ fontSize: `${9 * scale}px` }}>
{meta.label}
{node.group?.trim() || meta.label}
</span>
</div>
<div className="break-words font-bold leading-snug" style={{ fontSize: `${11.5 * scale}px` }}>{node.label}</div>
<Handle type="source" position={Position.Bottom} className="!h-1.5 !w-1.5 !bg-slate-400" />
<Handle type="source" position={sourcePos} className={cn("!h-1.5 !w-1.5", handleColor)} />
</div>
);
}
@@ -106,8 +150,13 @@ function FlowCanvasInner({
onToggleFullscreen,
onClose,
onSwitchToReport,
onChange,
orientation = "vertical",
miniMap = false,
}: FlowGraphPanelProps & { fullscreen: boolean; onToggleFullscreen: () => void }) {
const rf = useReactFlow();
const { theme } = useTheme();
const isDark = theme === "dark";
const [selectedId, setSelectedId] = useState<string | null>(null);
const [scale, setScale] = useState(1);
const containerRef = useRef<HTMLDivElement>(null);
@@ -136,7 +185,7 @@ function FlowCanvasInner({
};
}, [rf]);
const layoutNodes = useMemo(() => layoutFlowGraph(data), [data]);
const layoutNodes = useMemo(() => layoutFlowGraph(data, orientation), [data, orientation]);
const derivedNodes: Node[] = useMemo(
() =>
layoutNodes.map((n) => ({
@@ -144,9 +193,9 @@ function FlowCanvasInner({
type: "flowCard",
// 节点随 scale 放大 → 布局坐标同步乘 scale,间距一起拉开,避免同层重叠。
position: manualPosRef.current.get(n.id) ?? { x: n.x * scale, y: n.y * scale },
data: { node: n, scale },
data: { node: n, scale, orientation, dark: isDark },
})),
[layoutNodes, scale],
[layoutNodes, scale, orientation, isDark],
);
const [nodes, setNodes] = useState<Node[]>(derivedNodes);
@@ -165,7 +214,13 @@ function FlowCanvasInner({
() =>
data.edges.map((e) => {
const active = streaming && (e.to === newestNodeId || e.from === newestNodeId);
const color = active ? "#3b82f6" : "#94a3b8";
const color = active
? isDark
? DARK.edgeActive
: "#3b82f6"
: isDark
? DARK.edge
: "#94a3b8";
return {
id: `e-${e.from}->${e.to}`,
source: e.from,
@@ -174,11 +229,11 @@ function FlowCanvasInner({
animated: active,
style: { stroke: color, strokeWidth: active ? 2 : 1.5 },
markerEnd: { type: MarkerType.ArrowClosed, color, width: 16, height: 16 },
labelStyle: { fontSize: 10, fill: "#64748b", fontWeight: 700 },
labelBgStyle: { fill: "#ffffff", fillOpacity: 0.85 },
labelStyle: { fontSize: 10, fill: isDark ? DARK.text : "#64748b", fontWeight: 700 },
labelBgStyle: { fill: isDark ? DARK.cardBg : "#ffffff", fillOpacity: isDark ? 0.9 : 0.85 },
} satisfies Edge;
}),
[data.edges, streaming, newestNodeId],
[data.edges, streaming, newestNodeId, isDark],
);
// 流式中节点增加 → 画布平滑 fitView 跟随生长(用户暂停流后不再打扰)。
@@ -193,15 +248,30 @@ function FlowCanvasInner({
const selectedNode = selectedId ? data.nodes.find((n) => n.id === selectedId) ?? null : null;
return (
<div className="flex h-full min-h-0 flex-col">
<div
className="flex h-full min-h-0 flex-col"
style={isDark ? { background: DARK.pageBg } : undefined}
>
{/* 头部:标题 + 工具栏 */}
<div className="shrink-0 flex items-center justify-between gap-2 border-b border-slate-100 bg-white px-4 py-2.5">
<div
className={cn(
"shrink-0 flex items-center justify-between gap-2 border-b px-4 py-2.5",
isDark ? "" : "border-slate-100 bg-white",
)}
style={isDark ? { background: DARK.cardBg, borderColor: DARK.border } : undefined}
>
<div className="flex min-w-0 items-center gap-2">
<Workflow className="h-4 w-4 shrink-0 text-primary" />
<span className="truncate text-xs font-bold text-slate-800">
<span
className="truncate text-xs font-bold text-slate-800"
style={isDark ? { color: DARK.text } : undefined}
>
{data.title || "方案流程图"}
</span>
<span className="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[10px] text-slate-500">
<span
className="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[10px] text-slate-500"
style={isDark ? { background: "rgba(45,68,115,0.5)", color: DARK.textMuted } : undefined}
>
{data.nodes.length} 节点 · {data.edges.length} 连线
</span>
{streaming && (
@@ -217,7 +287,8 @@ function FlowCanvasInner({
type="button"
title="切回 Markdown 报告预览(流程图可随时再打开)"
onClick={onSwitchToReport}
className="mr-1 inline-flex h-7 items-center gap-1 rounded-lg border border-slate-200/70 bg-white px-2 text-[10.5px] font-bold text-slate-600 transition hover:border-primary/40 hover:text-primary"
className="mr-1 inline-flex h-7 items-center gap-1 rounded-lg border border-slate-200/70 bg-white px-2 text-[10.5px] font-bold text-slate-600 transition hover:border-primary/40 hover:text-primary dark:hover:text-primary"
style={isDark ? { background: "transparent", borderColor: DARK.border, color: DARK.text } : undefined}
>
<FileText className="h-3.5 w-3.5" />
MD 报告
@@ -262,13 +333,50 @@ function FlowCanvasInner({
deleteKeyCode={null}
proOptions={{ hideAttribution: true }}
>
<Background variant={BackgroundVariant.Dots} gap={18} size={1} color="#cbd5e1" />
<Background
variant={BackgroundVariant.Dots}
gap={18}
size={1}
color={isDark ? DARK.dots : "#cbd5e1"}
/>
{miniMap && (
<MiniMap
position="bottom-right"
pannable
zoomable
nodeColor={(n) => {
const t = (n.data as { node?: FlowGraphNode }).node?.type;
return (t && flowNodeMeta(isDark)[t]?.dot) || (isDark ? DARK.textMuted : "#94a3b8");
}}
nodeStrokeWidth={2}
maskColor={isDark ? "rgba(6,14,36,0.6)" : "rgba(240,240,240,0.6)"}
className={cn(
"!bottom-2 !right-2 !m-0 overflow-hidden rounded-lg border shadow-sm backdrop-blur-sm",
isDark ? "" : "border-slate-200/70 bg-white/90",
)}
style={
isDark
? { width: 168, height: 112, background: "rgba(18,35,71,0.9)", borderColor: DARK.border }
: { width: 168, height: 112 }
}
/>
)}
</ReactFlow>
{/* 图例 */}
<div className="pointer-events-none absolute bottom-2 left-2 flex flex-wrap items-center gap-x-2.5 gap-y-1 rounded-lg border border-slate-200/70 bg-white/85 px-2.5 py-1.5 backdrop-blur-sm">
{Object.entries(FLOW_NODE_TYPE_META).map(([type, meta]) => (
<span key={type} className="inline-flex items-center gap-1 text-[9.5px] font-semibold text-slate-500">
<div
className={cn(
"pointer-events-none absolute bottom-2 left-2 flex flex-wrap items-center gap-x-2.5 gap-y-1 rounded-lg border px-2.5 py-1.5 backdrop-blur-sm",
isDark ? "" : "border-slate-200/70 bg-white/85",
)}
style={isDark ? { background: "rgba(18,35,71,0.85)", borderColor: DARK.border } : undefined}
>
{Object.entries(flowNodeMeta(isDark)).map(([type, meta]) => (
<span
key={type}
className="inline-flex items-center gap-1 text-[9.5px] font-semibold text-slate-500"
style={isDark ? { color: DARK.textMuted } : undefined}
>
<span style={{ background: meta.dot }} className="size-1.5 rounded-full" />
{meta.label}
</span>
@@ -276,13 +384,15 @@ function FlowCanvasInner({
</div>
</div>
{/* 节点详情弹窗 */}
{/* 节点详情弹窗(传入 onChange 时可编辑 / 删除节点) */}
{selectedNode && (
<NodeDetailModal
node={selectedNode}
data={data}
dark={isDark}
onClose={() => setSelectedId(null)}
onJump={(id) => setSelectedId(id)}
onChange={onChange}
/>
)}
</div>
@@ -298,12 +408,15 @@ function ToolButton({
onClick: () => void;
children: React.ReactNode;
}) {
const { theme } = useTheme();
const isDark = theme === "dark";
return (
<button
type="button"
title={title}
onClick={onClick}
className="flex h-7 w-7 items-center justify-center rounded-lg border border-slate-200/70 bg-white text-slate-500 transition hover:border-primary/40 hover:text-primary"
style={isDark ? { background: "transparent", borderColor: DARK.border, color: DARK.textMuted } : undefined}
>
{children}
</button>
@@ -315,19 +428,42 @@ function ToolButton({
function NodeDetailModal({
node,
data,
dark = false,
onClose,
onJump,
onChange,
}: {
node: FlowGraphNode;
data: FlowGraphData;
dark?: boolean;
onClose: () => void;
onJump: (id: string) => void;
/** Phase 3:传入则可编辑 / 删除该节点(回写整张新图)。 */
onChange?: (next: FlowGraphData) => void;
}) {
const meta = FLOW_NODE_TYPE_META[node.type];
const meta = flowNodeMeta(dark)[node.type];
const labelOf = (id: string) => data.nodes.find((n) => n.id === id)?.label ?? id;
const incoming = data.edges.filter((e) => e.to === node.id);
const outgoing = data.edges.filter((e) => e.from === node.id);
const [editing, setEditing] = useState(false);
const [label, setLabel] = useState(node.label);
const [group, setGroup] = useState(node.group ?? "");
const [detail, setDetail] = useState(node.detail ?? "");
const handleSave = () => {
onChange?.(applyNodeEdit(data, node.id, { label, group, detail }));
setEditing(false);
onClose();
};
const handleDelete = () => {
if (typeof window !== "undefined" && !window.confirm(`删除节点「${node.label}」及其连线?此操作不可撤销。`)) {
return;
}
onChange?.(deleteNodeFromGraph(data, node.id));
onClose();
};
return (
<div
className="absolute inset-0 z-30 flex items-center justify-center bg-black/30 p-4 backdrop-blur-[1px]"
@@ -335,6 +471,7 @@ function NodeDetailModal({
>
<div
className="w-full max-w-md overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-xl"
style={dark ? { background: DARK.cardBg, borderColor: DARK.border } : undefined}
onClick={(e) => e.stopPropagation()}
>
<div
@@ -345,9 +482,9 @@ function NodeDetailModal({
<span style={{ background: meta.dot }} className="size-2.5 shrink-0 rounded-full" />
<span
className="shrink-0 rounded px-1.5 py-0.5 text-[10px] font-bold"
style={{ background: "#ffffffaa", color: meta.text }}
style={{ background: dark ? "rgba(6,14,36,0.45)" : "#ffffffaa", color: meta.text }}
>
{meta.label}
{node.group?.trim() || meta.label}
</span>
<h3 className="min-w-0 truncate text-sm font-bold" style={{ color: meta.text }}>
{node.label}
@@ -357,43 +494,157 @@ function NodeDetailModal({
type="button"
onClick={onClose}
className="shrink-0 rounded-md p-1 text-slate-500 hover:bg-white/60 hover:text-slate-700"
style={dark ? { color: DARK.textMuted } : undefined}
>
<X className="h-4 w-4" />
</button>
</div>
<div className="max-h-[50vh] space-y-3 overflow-y-auto p-4">
<div>
<div className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400">
详细说明
</div>
<p className="text-xs leading-relaxed text-slate-700">
{node.detail?.trim() || "(该节点未提供详细说明)"}
</p>
{editing ? (
<div className="max-h-[55vh] space-y-3 overflow-y-auto p-4">
<EditField label="节点名称(label)" value={label} onChange={setLabel} dark={dark} />
<EditField label="所属层级(group,如 目的 / 行为体)" value={group} onChange={setGroup} dark={dark} />
<EditField label="详细内容(detail,名称+理由)" value={detail} onChange={setDetail} multiline dark={dark} />
</div>
{incoming.length > 0 && (
<ConnectionList title="上游(来自)" entries={incoming.map((e) => ({ id: e.from, label: labelOf(e.from), edgeLabel: e.label }))} onJump={onJump} />
)}
{outgoing.length > 0 && (
<ConnectionList title="下游(去往)" entries={outgoing.map((e) => ({ id: e.to, label: labelOf(e.to), edgeLabel: e.label }))} onJump={onJump} />
)}
</div>
) : (
<div className="max-h-[50vh] space-y-3 overflow-y-auto p-4">
<div>
<div
className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400"
style={dark ? { color: DARK.textMuted } : undefined}
>
详细说明
</div>
<p
className="text-xs leading-relaxed text-slate-700 whitespace-pre-wrap"
style={dark ? { color: DARK.text } : undefined}
>
{node.detail?.trim() || "(该节点未提供详细说明)"}
</p>
</div>
{incoming.length > 0 && (
<ConnectionList title="上游(来自)" entries={incoming.map((e) => ({ id: e.from, label: labelOf(e.from), edgeLabel: e.label }))} onJump={onJump} dark={dark} />
)}
{outgoing.length > 0 && (
<ConnectionList title="下游(去往)" entries={outgoing.map((e) => ({ id: e.to, label: labelOf(e.to), edgeLabel: e.label }))} onJump={onJump} dark={dark} />
)}
</div>
)}
{/* 编辑 / 删除 操作栏(仅传入 onChange 时显示) */}
{onChange && (
<div
className="flex items-center justify-between gap-2 border-t border-slate-100 bg-slate-50/60 px-4 py-2.5"
style={dark ? { borderColor: DARK.border, background: "rgba(12,24,54,0.6)" } : undefined}
>
{editing ? (
<>
<button
type="button"
onClick={() => setEditing(false)}
className="rounded-lg px-2.5 py-1.5 text-[11px] font-bold text-slate-500 hover:bg-slate-200/60"
style={dark ? { color: DARK.textMuted } : undefined}
>
取消
</button>
<button
type="button"
onClick={handleSave}
className="inline-flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-[11px] font-bold text-white hover:bg-[var(--brand-900)]"
>
<Check className="h-3.5 w-3.5" />
保存
</button>
</>
) : (
<>
<button
type="button"
onClick={handleDelete}
className="inline-flex items-center gap-1 rounded-lg border border-rose-200 px-2.5 py-1.5 text-[11px] font-bold text-rose-600 hover:bg-rose-50"
>
<Trash2 className="h-3.5 w-3.5" />
删除节点
</button>
<button
type="button"
onClick={() => setEditing(true)}
className="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] font-bold text-slate-700 hover:border-primary/40 hover:text-primary"
style={dark ? { borderColor: DARK.border, color: DARK.text } : undefined}
>
<Pencil className="h-3.5 w-3.5" />
编辑
</button>
</>
)}
</div>
)}
</div>
</div>
);
}
function EditField({
label,
value,
onChange,
multiline,
dark = false,
}: {
label: string;
value: string;
onChange: (v: string) => void;
multiline?: boolean;
dark?: boolean;
}) {
const fieldStyle = dark
? { background: "rgba(6,14,36,0.45)", borderColor: DARK.border, color: DARK.text }
: undefined;
return (
<div>
<div
className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400"
style={dark ? { color: DARK.textMuted } : undefined}
>
{label}
</div>
{multiline ? (
<textarea
value={value}
onChange={(e) => onChange(e.target.value)}
rows={4}
className="w-full resize-none rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs leading-relaxed text-slate-800 focus:border-primary focus:outline-none focus:ring-1 focus:ring-[var(--brand-200)]/50"
style={fieldStyle}
/>
) : (
<input
value={value}
onChange={(e) => onChange(e.target.value)}
className="w-full rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs text-slate-800 focus:border-primary focus:outline-none focus:ring-1 focus:ring-[var(--brand-200)]/50"
style={fieldStyle}
/>
)}
</div>
);
}
function ConnectionList({
title,
entries,
onJump,
dark = false,
}: {
title: string;
entries: Array<{ id: string; label: string; edgeLabel?: string }>;
onJump: (id: string) => void;
dark?: boolean;
}) {
return (
<div>
<div className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400">
<div
className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400"
style={dark ? { color: DARK.textMuted } : undefined}
>
{title}
</div>
<div className="flex flex-wrap gap-1.5">
@@ -403,11 +654,15 @@ function ConnectionList({
type="button"
onClick={() => onJump(entry.id)}
className="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-slate-50 px-2 py-1 text-[11px] font-semibold text-slate-700 transition hover:border-primary/40 hover:text-primary"
style={dark ? { borderColor: DARK.border, background: "rgba(6,14,36,0.4)", color: DARK.text } : undefined}
title="查看该节点详情"
>
{entry.label}
{entry.edgeLabel && (
<span className="rounded bg-slate-200/80 px-1 text-[9px] text-slate-500">
<span
className="rounded bg-slate-200/80 px-1 text-[9px] text-slate-500"
style={dark ? { background: "rgba(45,68,115,0.6)", color: DARK.textMuted } : undefined}
>
{entry.edgeLabel}
</span>
)}
@@ -420,15 +675,19 @@ function ConnectionList({
// ── 外壳:覆盖右栏 / 全屏切换 ───────────────────────────────────────────────
export function FlowGraphPanel({ data, streaming, onClose, onSwitchToReport }: FlowGraphPanelProps) {
export function FlowGraphPanel({ data, streaming, onClose, onSwitchToReport, onChange, orientation, miniMap }: FlowGraphPanelProps) {
const [fullscreen, setFullscreen] = useState(false);
return (
const { theme } = useTheme();
const isDark = theme === "dark";
const inner = (
<div
className={cn(
"flex flex-col bg-white",
// 非全屏=填满所在面板(Step3 放在右侧沙箱位,不覆盖左侧消息列表);全屏才整页覆盖。
fullscreen ? "fixed inset-0 z-[80]" : "relative h-full min-h-0 w-full",
// 非全屏=填满所在面板(Step3 放在右侧沙箱位,不覆盖左侧消息列表);
// 全屏=覆盖整个视口(z 高于 app 顶部导航,保证顶部工具栏可见、可点「退出全屏」)。
fullscreen ? "fixed inset-0 z-[9999]" : "relative h-full min-h-0 w-full",
)}
style={isDark ? { background: DARK.pageBg } : undefined}
>
<ReactFlowProvider>
<FlowCanvasInner
@@ -438,8 +697,17 @@ export function FlowGraphPanel({ data, streaming, onClose, onSwitchToReport }: F
onToggleFullscreen={() => setFullscreen((f) => !f)}
onClose={onClose}
onSwitchToReport={onSwitchToReport}
onChange={onChange}
orientation={orientation}
miniMap={miniMap}
/>
</ReactFlowProvider>
</div>
);
// 全屏时 portal 到 body:脱离任何带 transform/overflow 的祖先(Step2 沙箱分栏等),
// 否则 `fixed` 会被祖先裁剪、顶部工具栏被 app 导航栏盖住(即本次 bug)。
if (fullscreen && typeof document !== "undefined") {
return createPortal(inner, document.body);
}
return inner;
}
@@ -34,6 +34,7 @@ function formatFileSize(bytes: number): string {
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
import { Button } from "@/components/ui/button";
import { useLocalSettings } from "@/core/settings";
import type { MessageMetric } from "@/components/workspace/messages/use-message-metrics";
@@ -66,6 +67,11 @@ import type { IntentSummary } from "@/roundtable-planning/api/intent";
export interface Step1PanelProps {
// ─── State ────────────────────────────────────────────────────
/**
* 头部左侧自定义内容(深链 taskId 模式:用「策划流程」小图取代默认标题)。
* 不传 → 显示默认「任务意图理解 (人机问答)」标题。右侧「问答轮次」始终保留。
*/
headerLeftSlot?: React.ReactNode;
interactiveMessages: InteractiveMessage[];
intentThreadId: string | null;
intentReady: object | null;
@@ -92,6 +98,7 @@ export interface Step1PanelProps {
export function Step1Panel(props: Step1PanelProps) {
const {
headerLeftSlot,
interactiveMessages,
intentThreadId,
intentReady,
@@ -156,14 +163,16 @@ export function Step1Panel(props: Step1PanelProps) {
return (
<div className="flex-1 flex flex-col min-h-0">
{/* Dialogue Header */}
<div ref={headerDzRef} className="shrink-0 px-6 py-4.5 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
<div className="flex items-center gap-2">
<MessageSquare className="w-4.5 h-4.5 text-primary" strokeWidth={2.5} />
<h3 className="text-sm font-extrabold text-slate-900">
任务意图理解 (人机问答)
</h3>
</div>
<span className="text-[11px] font-bold text-slate-400 bg-white border px-2 py-0.5 rounded-md">
<div ref={headerDzRef} className="shrink-0 px-6 py-4.5 border-b border-slate-100 flex items-center justify-between gap-3 bg-slate-50/50">
{headerLeftSlot ?? (
<div className="flex items-center gap-2">
<MessageSquare className="w-4.5 h-4.5 text-primary" strokeWidth={2.5} />
<h3 className="text-sm font-extrabold text-slate-900">
任务意图理解 (人机问答)
</h3>
</div>
)}
<span className="shrink-0 text-[11px] font-bold text-slate-400 bg-white border px-2 py-0.5 rounded-md">
问答轮次:{interactiveMessages.filter((m) => m.sender === "user").length} 轮
</span>
</div>
@@ -172,7 +181,8 @@ export function Step1Panel(props: Step1PanelProps) {
<div className="relative flex-1 min-h-0 flex flex-col font-normal">
<div
ref={step1ScrollRef}
className="flex-1 min-h-0 overflow-y-auto p-6 space-y-4 bg-white"
// overflow-x-hidden:消息列表只竖向滚(见 Step2Panel 同处注释),避免误触横向拖动抢滑块。
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-6 space-y-4 bg-white"
>
{interactiveMessages.map((msg) => (
<Step1Message
@@ -221,7 +231,7 @@ export function Step1Panel(props: Step1PanelProps) {
))}
</div>
)}
<textarea
<AutoGrowTextarea
id="input-text-area"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
@@ -233,10 +243,11 @@ export function Step1Panel(props: Step1PanelProps) {
}}
placeholder={
pendingIntentClarificationMsgId
? "也可在此输入自定义回答 (Enter 快速发送)"
: "请输入补充信息 / 回答问题 / 继续澄清 (Enter 快速发送)"
? "也可在此输入自定义回答 (Enter 发送 / Shift+Enter 换行)"
: "请输入补充信息 / 回答问题 / 继续澄清 (Enter 发送 / Shift+Enter 换行)"
}
className="w-full text-xs text-slate-700 placeholder:text-slate-400 resize-none h-[48px] focus:outline-none leading-relaxed font-normal"
className="w-full text-xs text-slate-700 placeholder:text-slate-400 min-h-[48px] max-h-80 focus:outline-none leading-relaxed font-normal"
maxHeight={320}
maxLength={500}
/>
@@ -40,6 +40,7 @@ function formatFileSize(bytes: number): string {
/** 后台挂起入口 —— 后端 _run_dag 已支持业务链分层并行,放出该入口。 */
const SHOW_BACKGROUND_SUSPEND = true;
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
import { useLocalSettings } from "@/core/settings";
import { cn } from "@/lib/utils";
import type { MessageMetric } from "@/components/workspace/messages/use-message-metrics";
@@ -550,7 +551,11 @@ export function Step2Panel(props: Step2PanelProps) {
)}
<div
ref={step2ScrollRef}
className="flex-1 min-h-0 overflow-y-auto p-6 space-y-4 bg-white border-t border-slate-150 border-b border-slate-150 shadow-inner"
// overflow-x-hidden:消息列表只竖向滚。否则 `overflow-y-auto` 单写时按 CSS 规范
// 另一轴会被计算成 auto,任何子元素溢出一两像素都会让整列横向可滚 → 鼠标移到右侧
// 竖滚条滑块时极易误触发横向拖动、抓不住滑块。宽内容(代码块/表格)在各自气泡内
// 已有 max-w-full + overflow-x-auto 自带横滚,故此处裁掉横向不影响查看。
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-6 space-y-4 bg-white border-t border-slate-150 border-b border-slate-150 shadow-inner"
>
{isInitializing && step2RoundtableDialogues.length === 0 && (
<div className="flex h-full flex-col items-center justify-center gap-3 py-12 text-slate-500">
@@ -696,16 +701,19 @@ export function Step2Panel(props: Step2PanelProps) {
</div>
)}
{pendingClarification.allowCustom !== false && (
<div className="flex items-center gap-2 pt-1">
<input
type="text"
<div className="flex items-end gap-2 pt-1">
<AutoGrowTextarea
value={clarificationDraft}
onChange={(e) => setClarificationDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") onSubmitClarification(clarificationDraft);
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
onSubmitClarification(clarificationDraft);
}
}}
placeholder="输入你的回答…"
className="flex-1 bg-white border border-amber-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-200 font-medium"
placeholder="输入你的回答…(Enter 发送 / Shift+Enter 换行)"
className="flex-1 bg-white border border-amber-300 rounded-xl px-3 py-2 text-xs leading-relaxed focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-200 font-medium"
maxHeight={280}
/>
<button
type="button"
@@ -751,16 +759,19 @@ export function Step2Panel(props: Step2PanelProps) {
))}
</div>
)}
<div className="flex items-center gap-3">
<input
type="text"
<div className="flex items-end gap-3">
<AutoGrowTextarea
value={customAgentInput}
onChange={(e) => setCustomAgentInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleInject();
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleInject();
}
}}
placeholder="作为指挥官,您可以随时插话输入指令,对智能体博弈朝向实施人工干预..."
className="flex-1 bg-white border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs focus:outline-none focus:border-primary focus:ring-1 focus:ring-[var(--brand-200)]/50 font-medium"
placeholder="作为指挥官,您可以随时插话输入指令,对智能体博弈朝向实施人工干预...(Enter 发送 / Shift+Enter 换行)"
className="flex-1 bg-white border border-slate-200 rounded-xl px-3.5 py-2.5 text-xs leading-relaxed focus:outline-none focus:border-primary focus:ring-1 focus:ring-[var(--brand-200)]/50 font-medium"
maxHeight={280}
/>
<input
@@ -15,9 +15,7 @@
import {
useEffect,
useMemo,
useRef,
useState,
type FormEvent,
} from "react";
import {
ArrowLeft,
@@ -27,30 +25,22 @@ import {
ExternalLink,
LayoutPanelTop,
Loader2,
Pause,
Pencil,
RefreshCw,
SendHorizontal,
Sparkles,
} from "lucide-react";
import { useLocalSettings } from "@/core/settings";
import { desensitizeDeep } from "@/lib/desensitize";
import type { DraftStep3Snapshot } from "@/roundtable-planning/api/drafts";
import { DashboardApp } from "@/roundtable-planning/dashboard/DashboardApp";
import { adaptReportData } from "@/roundtable-planning/dashboard/data-context";
import type { ModelOption } from "@/roundtable-planning/components/Step3ReportMode";
import { ScrollToBottomButton } from "@/roundtable-planning/components/ScrollToBottomButton";
import { Step2Message } from "@/roundtable-planning/components/Step2Panel";
import { DashboardChatPanel } from "@/roundtable-planning/components/DashboardChatPanel";
import { Step2SandboxLayout } from "@/roundtable-planning/components/Step2SandboxLayout";
import { DASHBOARD_VIEW_STORAGE_PREFIX } from "@/roundtable-planning/pages/DashboardStandalonePage";
import { useAutoScroll } from "@/roundtable-planning/hooks/useAutoScroll";
import { useDialogueSpeedMetrics } from "@/roundtable-planning/hooks/useDialogueSpeedMetrics";
import type { UseStep3DashboardReturn } from "@/roundtable-planning/hooks/useStep3Dashboard";
import {
parseReportJson,
renderDashboardHtml,
stripReportFence,
type DashboardTheme,
} from "@/roundtable-planning/lib/report-template";
import { useTheme } from "@/contexts/ThemeContext";
@@ -360,220 +350,3 @@ export function Step3DashboardMode({
</div>
);
}
// ── 交互区聊天面板(沙箱的左 60%;右 40% 是抽取过程代码预览) ──────────────────────────
function DashboardChatPanel({
phase,
dialogues,
busy,
error,
onAsk,
onRedraw,
onPause,
onOpenPreview,
hasResult,
selectedModel,
availableModels,
modelsLoading,
setSelectedModel,
}: {
phase: UseStep3DashboardReturn["phase"];
dialogues: UseStep3DashboardReturn["dialogues"];
busy: boolean;
error: string | null;
onAsk: (message: string) => void;
onRedraw: () => void;
onPause: () => void;
onOpenPreview: () => void;
hasResult: boolean;
selectedModel: string;
availableModels: ReadonlyArray<ModelOption>;
modelsLoading: boolean;
setSelectedModel: (model: string) => void;
}) {
const inputLocked = phase === "creating";
const scrollRef = useRef<HTMLDivElement>(null);
const { atBottom, scrollToBottom } = useAutoScroll(scrollRef, [dialogues]);
const [localSettings] = useLocalSettings();
const speedMeterEnabled = localSettings.display.streamSpeedMeterEnabled;
const dialogueMetrics = useDialogueSpeedMetrics(dialogues);
const [text, setText] = useState("");
// 消息列表里不展示 report-json 结构化数据本体(它已在右侧沙箱实时渲染),
// 把数据块替换成一句「看右侧沙箱」的提示,避免左右两边重复刷整段 JSON。
const displayDialogues = useMemo(
() =>
dialogues.map((d) => {
const content = d.content ?? "";
if (!content) return d;
const stripped = stripReportFence(content, d.streaming === true);
return stripped === content ? d : { ...d, content: stripped };
}),
[dialogues],
);
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const t = text.trim();
if (!t || inputLocked) return;
setText("");
onAsk(t);
};
return (
<div className="flex h-full min-h-0 flex-col bg-slate-50/20">
{/* 面板头:智能体名 + 模型选择 + 暂停/重画 */}
<div className="shrink-0 flex items-center justify-between gap-2 border-b border-slate-100 bg-white px-4 py-2.5">
<div className="flex items-center gap-2 min-w-0">
<div className="w-6 h-6 shrink-0 rounded-lg bg-gradient-to-tr from-primary to-[var(--brand-200)] flex items-center justify-center text-white text-xs shadow-sm">
📊
</div>
<div className="leading-tight min-w-0">
<div className="text-xs font-bold text-slate-800 truncate">大屏绘制智能体</div>
<div className="text-[10px] text-slate-400 truncate">提炼研讨成果为大屏结构化数据(右侧实时显示抽取过程)</div>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<select
id="step3-dashboard-model-select"
value={selectedModel}
onChange={(e) => setSelectedModel(e.target.value)}
disabled={busy || modelsLoading || availableModels.length === 0}
title={
modelsLoading
? "正在加载模型列表…"
: availableModels.length === 0
? "未在 config.yaml 中配置任何模型"
: busy
? "绘制中不可切换;完成后或重新绘制时生效"
: "切换绘制使用的推理模型(下次绘制生效)"
}
className="max-w-[160px] bg-slate-50/50 border border-slate-200 rounded-xl px-2.5 py-1.5 text-[11px] 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>
{busy ? (
<button
type="button"
onClick={onPause}
title="中止当前绘制"
className="bg-white border border-amber-200 text-amber-700 hover:bg-amber-50 text-[10.5px] font-bold px-2.5 py-1.5 rounded-xl flex items-center gap-1 transition"
>
<Pause className="w-3.5 h-3.5" />
中止
</button>
) : (
<button
type="button"
onClick={onRedraw}
title="丢弃上下文,从头重新绘制"
className="bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 text-[10.5px] font-bold px-2.5 py-1.5 rounded-xl flex items-center gap-1 transition"
>
<RefreshCw className="w-3.5 h-3.5 text-slate-500" />
重新绘制
</button>
)}
</div>
</div>
{/* 聊天记录 */}
<div className="relative flex-1 min-h-0 flex flex-col">
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto p-4 space-y-4 bg-white">
{phase === "creating" && dialogues.length === 0 && (
<div className="flex items-center gap-2 text-xs text-slate-500">
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary" />
正在初始化绘制线程…
</div>
)}
{displayDialogues.map((msg) => (
<Step2Message
key={msg.id}
msg={msg}
metric={speedMeterEnabled ? dialogueMetrics.get(msg.id) : undefined}
/>
))}
{busy && (
<div className="inline-flex items-center gap-2 rounded-full border bg-white px-2.5 py-1 text-[11px] text-slate-500">
<span className="bg-primary size-1.5 animate-pulse rounded-full" />
右侧沙箱实时显示数据抽取过程,完成后自动切到大屏页面
</div>
)}
{phase === "error" && (
<div className="rounded-xl border border-rose-200 bg-rose-50 p-3 text-xs text-rose-700">
<div className="font-bold mb-1">绘制失败</div>
<div className="leading-relaxed break-all">{error}</div>
<button
type="button"
onClick={onRedraw}
className="mt-2 inline-flex items-center gap-1 text-[11px] font-bold text-rose-700 underline hover:text-rose-800"
>
<RefreshCw className="w-3 h-3" />
重试
</button>
</div>
)}
{phase === "done" && (
<div className="flex items-center gap-2 text-xs font-bold text-emerald-600">
<CheckCircle className="w-4 h-4" />
数据已就绪,已切换到大屏页面。
{hasResult && (
<button
type="button"
onClick={onOpenPreview}
className="ml-1 inline-flex items-center gap-1 text-[11px] font-bold text-primary underline hover:opacity-80"
>
在沙箱打开 HTML 预览
</button>
)}
</div>
)}
</div>
{!atBottom && <ScrollToBottomButton onClick={scrollToBottom} />}
{/* 问答修改输入框 */}
<form onSubmit={handleSubmit} className="shrink-0 border-t border-slate-100 bg-white px-3 py-3">
<div className="flex items-end gap-2 rounded-2xl border border-slate-200 bg-slate-50/70 px-3 py-2 focus-within:border-primary/60 focus-within:bg-white focus-within:ring-2 focus-within:ring-[var(--brand-200)]/40">
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
e.currentTarget.form?.requestSubmit();
}
}}
disabled={inputLocked}
rows={1}
placeholder={
busy
? "随时输入修改要求——发送会打断当前绘制并按新要求重出数据"
: "输入修改要求,例如:把风险分布换成柱状图,新增一个执行路线席位"
}
className="min-h-8 max-h-28 flex-1 resize-none bg-transparent py-1.5 text-xs leading-relaxed text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"
/>
<button
type="submit"
disabled={inputLocked || text.trim().length === 0}
title={inputLocked ? "正在初始化线程,请稍候" : "发送修改要求"}
className="mb-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary text-white transition hover:bg-[var(--brand-900)] disabled:cursor-not-allowed disabled:opacity-50"
>
{inputLocked ? <Loader2 className="h-4 w-4 animate-spin" /> : <SendHorizontal className="h-4 w-4" />}
</button>
</div>
</form>
</div>
</div>
);
}
@@ -19,6 +19,7 @@ import type { ReportIntent, UseStep3ReportReturn } from "@/roundtable-planning/h
import type { UseStep3SummaryReturn } from "@/roundtable-planning/hooks/useStep3Summary";
import type { ThreadIdMap } from "@/roundtable-planning/api/multi-agent";
import { stripReasoning } from "@/roundtable-planning/lib/reasoning";
import { useMemo } from "react";
export interface Step3PanelProps {
threadIds: ThreadIdMap | null;
@@ -81,18 +82,25 @@ export function Step3Panel(props: Step3PanelProps) {
seatStubMessages,
} = props;
const seatDeliveries = step2RoundtableDialogues
.filter((d) => d.confidence === "子智能体交付")
.map((d) => ({
sender: String(d.sender ?? ""),
avatarType: String(d.avatarType ?? "blue"),
// 交付内容只保留模型生成的主体输出,剥离 `<think>...</think>` 推理过程
// —— 既用于渲染各席位交付卡片,也会喂给总结/报告模型,避免推理噪声污染。
content: stripReasoning(String(d.content ?? "")),
}));
const seatDeliveries = useMemo(
() =>
step2RoundtableDialogues
.filter((d) => d.confidence === "子智能体交付")
.map((d) => ({
sender: String(d.sender ?? ""),
avatarType: String(d.avatarType ?? "blue"),
// 交付内容只保留模型生成的主体输出,剥离 `<think>...</think>` 推理过程
// —— 既用于渲染各席位交付卡片,也会喂给总结/报告模型,避免推理噪声污染。
content: stripReasoning(String(d.content ?? "")),
})),
[step2RoundtableDialogues],
);
const seatNameMap = Object.fromEntries(
Object.entries(agentNameToRole).map(([k, v]) => [k, v.displayName]),
const seatNameMap = useMemo(
() => Object.fromEntries(
Object.entries(agentNameToRole).map(([k, v]) => [k, v.displayName]),
),
[agentNameToRole],
);
return (
@@ -30,6 +30,7 @@ import {
X,
} from "lucide-react";
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
import { useArtifacts } from "@/components/workspace/artifacts";
import { useLocalSettings } from "@/core/settings";
import { cn } from "@/lib/utils";
@@ -591,7 +592,7 @@ function AgentProgressPanel({
<div className="relative flex-1 min-h-0 flex flex-col">
<div
ref={scrollRef}
className="flex-1 min-h-0 overflow-y-auto p-4 space-y-4 bg-white"
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-4 space-y-4 bg-white"
>
{phase === "creating" && dialogues.length === 0 && (
<div className="flex items-center gap-2 text-xs text-slate-500">
@@ -670,7 +671,8 @@ function AgentProgressPanel({
className="shrink-0 border-t border-slate-100 bg-white px-3 py-3"
>
<div className="flex items-end gap-2 rounded-2xl border border-slate-200 bg-slate-50/70 px-3 py-2 focus-within:border-primary/60 focus-within:bg-white focus-within:ring-2 focus-within:ring-[var(--brand-200)]/40">
<textarea
<AutoGrowTextarea
maxHeight={224}
value={revisionText}
onChange={(e) => setRevisionText(e.target.value)}
onKeyDown={(e) => {
@@ -686,7 +688,7 @@ function AgentProgressPanel({
? "随时输入修改要求——发送会打断当前绘制并按新要求继续"
: "输入修改要求,例如:增加风险矩阵,执行路线改成时间轴"
}
className="min-h-8 max-h-28 flex-1 resize-none bg-transparent py-1.5 text-xs leading-relaxed text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"
className="min-h-8 max-h-56 flex-1 resize-none bg-transparent py-1.5 text-xs leading-relaxed text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"
/>
<button
type="submit"
@@ -10,11 +10,13 @@
* 互不影响(report 画 HTML 看板,summary 写 Markdown 报告 + 问答)。
*/
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { createPortal } from "react-dom";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
ArrowRight,
CheckCircle,
Database,
Download,
Eye,
FileText,
@@ -30,6 +32,7 @@ import {
X,
} from "lucide-react";
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
import { useArtifacts } from "@/components/workspace/artifacts";
import { useLocalSettings } from "@/core/settings";
import { cn } from "@/lib/utils";
@@ -45,7 +48,6 @@ import { FlowGraphPanel } from "@/roundtable-planning/components/FlowGraphPanel"
import {
detectFlowIntent,
extractFlowGraph,
stripFlowFence,
FLOW_FENCE_OPEN,
} from "@/roundtable-planning/lib/flow-graph";
import { ScrollToBottomButton } from "@/roundtable-planning/components/ScrollToBottomButton";
@@ -138,9 +140,18 @@ export function Step3SummaryMode({
const { open: artifactsOpen } = useArtifacts();
// ── 结构化流程图:流式提取回复末尾的 flow-json,增量绘制 ──────────────────
// 取最后一条含 flow-json 的智能体气泡(多轮修改后以最新一份为准)。
// ── 结构化流程图(Phase 1:后端「抽取+校验」)────────────────────────────
// 数据来源优先级:
// · flowPhase==="done" → 用后端校验后的结构化图 summary.flowGraph 绘制;
// · 抽取/校验进行中 → 不画(用户看对话气泡里实时滚动的 JSON + 状态条),等校验完成再绘制;
// · idle/error → 回退到对话气泡里解析 flow-json(手动 flow 续问路径 / 旧逻辑兜底)。
const flowGraph = useMemo(() => {
if (summary.flowPhase === "done" && summary.flowGraph) {
return { graph: summary.flowGraph, streaming: false };
}
if (summary.flowPhase === "extracting" || summary.flowPhase === "validating") {
return null;
}
for (let i = dialogues.length - 1; i >= 0; i--) {
const d = dialogues[i];
if (d.avatarType === "human") continue;
@@ -150,7 +161,7 @@ export function Step3SummaryMode({
if (graph) return { graph, streaming: d.streaming === true };
}
return null;
}, [dialogues]);
}, [dialogues, summary.flowPhase, summary.flowGraph]);
const [flowView, setFlowView] = useState(false);
const flowAutoOpenedRef = useRef(false);
@@ -158,9 +169,11 @@ export function Step3SummaryMode({
if (!flowGraph || flowGraph.graph.nodes.length === 0) return;
if (flowAutoOpenedRef.current) return;
flowAutoOpenedRef.current = true;
// 没开沙箱 → 自动打开流程图画布;沙箱开着 → 不抢占,只露出切换按钮。
if (!artifactsOpen) setFlowView(true);
}, [flowGraph, artifactsOpen]);
// taskId/深链模式:结构化输出是本模式的主交付 → 流程图一出现就自动聚焦画布
// (即便此前 md 沙箱已自动打开,也切到流程图)。
// 普通模式:没开沙箱才自动打开;沙箱开着不抢占,只露出切换按钮。
if (summary.autoFlow || !artifactsOpen) setFlowView(true);
}, [flowGraph, artifactsOpen, summary.autoFlow]);
// 沙箱里已写出的 md 报告(流程图画布上提供「MD 报告」切回按钮的锚点)。
const mdArtifact = useMemo(() => {
@@ -193,16 +206,10 @@ export function Step3SummaryMode({
ask(message, files);
};
// 气泡里不展示生 JSON:把 flow-json 块替换成一句引导语。
const displayDialogues = useMemo(
() =>
dialogues.map((d) => {
const content = d.content ?? "";
if (!content.includes(FLOW_FENCE_OPEN)) return d;
return { ...d, content: stripFlowFence(content, d.streaming === true) };
}),
[dialogues],
);
// 流程图抽取/校验的过程(思考 `<think>` + 文字说明 + flow-json 代码块)全部原样交给
// Step2Message 渲染:它用 splitInlineReasoning 把思考折叠成思考块、其余按 markdown 渲染
// (flow-json 显示为代码块)。用户要求显示完整过程、不只显示代码块,故不再 strip。
const displayDialogues = dialogues;
const [leftCollapsed, setLeftCollapsed] = useState(false);
// 右侧面板(沙箱预览或流程图画布)露出时自动收起左栏,关闭时复原——边沿触发,手动切换不回弹。
const rightPanelVisible = artifactsOpen || (!!flowGraph && flowView);
@@ -394,6 +401,7 @@ export function Step3SummaryMode({
}
: undefined
}
onChange={summary.setFlowGraph}
/>
) : undefined
}
@@ -404,6 +412,18 @@ export function Step3SummaryMode({
error={error}
busy={busy}
mdAvailable={!!mdArtifact}
flowPhase={summary.flowPhase}
onRegenerateFlow={summary.regenerateFlow}
pendingClarification={summary.pendingFlowClarification}
onResolveClarification={summary.resolveFlowClarification}
ingestAvailable={summary.ingestAvailable}
ingestStatus={summary.ingestStatus}
pendingIngestClarification={summary.pendingIngestClarification}
onResolveIngestChoice={summary.resolveIngestChoice}
onResolveIngestClarification={summary.resolveIngestClarification}
pendingFlowForIngest={summary.pendingFlowForIngest}
onResolveFlowForIngest={summary.resolveFlowForIngest}
onManualIngest={summary.runIngest}
onRetry={redraw}
onAsk={handleAsk}
onPause={pause}
@@ -546,6 +566,18 @@ function AgentProgressPanel({
error,
busy,
mdAvailable,
flowPhase,
onRegenerateFlow,
pendingClarification,
onResolveClarification,
ingestAvailable,
ingestStatus,
pendingIngestClarification,
onResolveIngestChoice,
onResolveIngestClarification,
pendingFlowForIngest,
onResolveFlowForIngest,
onManualIngest,
onRetry,
onAsk,
onPause,
@@ -562,6 +594,23 @@ function AgentProgressPanel({
busy: boolean;
/** 沙箱里是否已有 md 报告 —— 决定提示语(纯流程图轮没有 .md 可预览/下载)。 */
mdAvailable: boolean;
/** 后端流程图抽取阶段(Phase 1)。 */
flowPhase: UseStep3SummaryReturn["flowPhase"];
/** 仅重新生成流程图(模型挂了切模型后重试)。 */
onRegenerateFlow: () => void;
/** 意图模糊待澄清的原始消息(非空 → 展示选项让用户定)。 */
pendingClarification: string | null;
onResolveClarification: UseStep3SummaryReturn["resolveFlowClarification"];
/** 入库技能是否可用(决定入库询问卡 + 手动入库按钮是否出现)。 */
ingestAvailable: boolean;
ingestStatus: UseStep3SummaryReturn["ingestStatus"];
pendingIngestClarification: string | null;
onResolveIngestChoice: UseStep3SummaryReturn["resolveIngestChoice"];
onResolveIngestClarification: UseStep3SummaryReturn["resolveIngestClarification"];
/** 入库时尚无流程图 → 展示「是否先生成流程图」协助。 */
pendingFlowForIngest: boolean;
onResolveFlowForIngest: UseStep3SummaryReturn["resolveFlowForIngest"];
onManualIngest: UseStep3SummaryReturn["runIngest"];
onRetry: () => void;
onAsk: (message: string, files?: File[]) => void;
onPause: () => void;
@@ -574,6 +623,16 @@ function AgentProgressPanel({
}) {
const scrollRef = useRef<HTMLDivElement>(null);
const { atBottom, scrollToBottom } = useAutoScroll(scrollRef, [dialogues]);
// 新一轮气泡出现(如:md 报告完成后自动续跑的结构化输出轮、用户发问)→ 强制滚到底,
// 让用户看到新阶段(修「调用结构化输出时不自动下滑」)。仅在气泡**条数**增加时触发,
// 流式增量内容仍由 useAutoScroll 的「在底部才跟随」逻辑处理,不抢用户向上翻阅。
const prevDialogueCountRef = useRef(dialogues.length);
useEffect(() => {
if (dialogues.length > prevDialogueCountRef.current) {
scrollToBottom();
}
prevDialogueCountRef.current = dialogues.length;
}, [dialogues.length, scrollToBottom]);
// 「回答速度指示器」—— 与主页面共用全局开关 streamSpeedMeterEnabled。
const [localSettings] = useLocalSettings();
const speedMeterEnabled = localSettings.display.streamSpeedMeterEnabled;
@@ -648,7 +707,7 @@ function AgentProgressPanel({
{/* 消息列表 —— 与第 2 步同款气泡(流式正文 + 工具步骤卡 + 文件卡)。 */}
<div className="relative flex-1 min-h-0 flex flex-col">
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto p-4 space-y-4 bg-white">
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-4 space-y-4 bg-white">
{phase === "creating" && dialogues.length === 0 && (
<div className="flex items-center gap-2 text-xs text-slate-500">
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary" />
@@ -692,6 +751,28 @@ function AgentProgressPanel({
</div>
)}
{/* 后端流程图「抽取+校验」状态条(Phase 1)。 */}
{(flowPhase === "extracting" || flowPhase === "validating") && (
<div className="inline-flex items-center gap-2 rounded-full border border-blue-200 bg-blue-50 px-2.5 py-1 text-[11px] font-bold text-blue-600">
<Loader2 className="w-3 h-3 animate-spin" />
{flowPhase === "extracting" ? "结构化流程图抽取中(JSON 实时输出)…" : "流程图校验 / 修复中…"}
</div>
)}
{flowPhase === "error" && (
<div className="rounded-xl border border-amber-200 bg-amber-50 p-3 text-xs text-amber-800">
<div className="font-bold mb-1">流程图生成失败</div>
<div className="leading-relaxed">模型可能不稳定。可在上方切换模型后重试。</div>
<button
type="button"
onClick={onRegenerateFlow}
className="mt-2 inline-flex items-center gap-1 text-[11px] font-bold text-amber-800 underline hover:text-amber-900"
>
<RefreshCw className="w-3 h-3" />
重新生成流程图
</button>
</div>
)}
{phase === "done" && (
<div className="flex items-center gap-2 text-xs font-bold text-emerald-600">
<CheckCircle className="w-4 h-4" />
@@ -702,6 +783,115 @@ function AgentProgressPanel({
)}
</div>
{!atBottom && <ScrollToBottomButton onClick={scrollToBottom} />}
{/* 意图模糊 → 让用户自己定(不自作主张) */}
{pendingClarification && (
<div className="shrink-0 border-t border-amber-100 bg-amber-50/60 px-3 py-2.5">
<div className="mb-1.5 text-[11px] font-bold text-amber-800">
没太理解你的意思,你是想——
</div>
<div className="flex flex-wrap gap-1.5">
{(
[
{ k: "regenerate_report", t: "重新生成报告" },
{ k: "modify_flow", t: "修改流程图" },
{ k: "regenerate_flow", t: "重新生成流程图" },
{ k: "qa", t: "只是提问" },
] as const
).map((o) => (
<button
key={o.k}
type="button"
onClick={() => onResolveClarification(o.k)}
className="rounded-lg border border-amber-300 bg-white px-2.5 py-1.5 text-[11px] font-bold text-amber-800 transition hover:bg-amber-100"
>
{o.t}
</button>
))}
</div>
</div>
)}
{/* 流程图已生成 → 询问是否入库(入库技能可用时)。 */}
{ingestAvailable && ingestStatus === "asking" && (
<div className="shrink-0 border-t border-emerald-100 bg-emerald-50/60 px-3 py-2.5">
<div className="mb-1.5 text-[11px] font-bold text-emerald-800">
流程图已生成,是否进行数据入库?
</div>
<div className="flex flex-wrap gap-1.5">
{(
[
{ k: "now", t: "现在入库" },
{ k: "later", t: "稍后入库" },
{ k: "never", t: "不入库" },
] as const
).map((o) => (
<button
key={o.k}
type="button"
onClick={() => onResolveIngestChoice(o.k)}
className="rounded-lg border border-emerald-300 bg-white px-2.5 py-1.5 text-[11px] font-bold text-emerald-800 transition hover:bg-emerald-100"
>
{o.t}
</button>
))}
</div>
</div>
)}
{/* 入库时尚无流程图 → 协助:数据入库以流程图为核心内容,先问是否生成流程图。 */}
{ingestAvailable && pendingFlowForIngest && (
<div className="shrink-0 border-t border-amber-100 bg-amber-50/70 px-3 py-2.5">
<div className="mb-1.5 text-[11px] font-bold text-amber-800">
当前还没有生成流程图,数据入库需要流程图。是否先生成流程图?
</div>
<div className="flex flex-wrap gap-1.5">
{(
[
{ k: "generate", t: "生成流程图" },
{ k: "cancel", t: "暂不入库" },
] as const
).map((o) => (
<button
key={o.k}
type="button"
onClick={() => onResolveFlowForIngest(o.k)}
className="rounded-lg border border-amber-300 bg-white px-2.5 py-1.5 text-[11px] font-bold text-amber-800 transition hover:bg-amber-100"
>
{o.t}
</button>
))}
</div>
</div>
)}
{/* 「稍后入库」自由文字意图模糊 → 让用户在入库语境下自己定。 */}
{ingestAvailable && pendingIngestClarification && (
<div className="shrink-0 border-t border-emerald-100 bg-emerald-50/60 px-3 py-2.5">
<div className="mb-1.5 text-[11px] font-bold text-emerald-800">
没太理解你的入库意思,你是想——
</div>
<div className="flex flex-wrap gap-1.5">
{(
[
{ k: "start_ingest", t: "开始入库" },
{ k: "add_data", t: "补充内容后再入库" },
{ k: "other", t: "只是提问 / 改报告" },
] as const
).map((o) => (
<button
key={o.k}
type="button"
onClick={() => onResolveIngestClarification(o.k)}
className="rounded-lg border border-emerald-300 bg-white px-2.5 py-1.5 text-[11px] font-bold text-emerald-800 transition hover:bg-emerald-100"
>
{o.t}
</button>
))}
</div>
</div>
)}
<form onSubmit={handleAskSubmit} className="shrink-0 border-t border-slate-100 bg-white px-3 py-3">
{/* 已选附件预览(发送时随指令上传到总结线程,供智能体读取) */}
{askFiles.length > 0 && (
@@ -729,7 +919,8 @@ function AgentProgressPanel({
</div>
)}
<div className="flex items-end gap-2 rounded-2xl border border-slate-200 bg-slate-50/70 px-3 py-2 focus-within:border-primary/60 focus-within:bg-white focus-within:ring-2 focus-within:ring-[var(--brand-200)]/40">
<textarea
<AutoGrowTextarea
maxHeight={224}
value={askText}
onChange={(e) => setAskText(e.target.value)}
onKeyDown={(e) => {
@@ -744,9 +935,25 @@ function AgentProgressPanel({
? "生成中也可随时插话干预:发送将打断当前轮并据此继续…"
: "继续对话:改报告(如「执行路线写细些」)/ 改流程图(如「总结成结构化输出」「流程图加上验收环节」)/ 提问"
}
className="min-h-8 max-h-28 flex-1 resize-none bg-transparent py-1.5 text-xs leading-relaxed text-slate-800 placeholder:text-slate-400 focus:outline-none"
className="min-h-8 max-h-56 flex-1 resize-none bg-transparent py-1.5 text-xs leading-relaxed text-slate-800 placeholder:text-slate-400 focus:outline-none"
/>
{/* 手动入库(入库技能可用、且已过流程图询问阶段时显示):直接在总结线程跑入库技能。 */}
{ingestAvailable &&
ingestStatus !== "asking" &&
ingestStatus !== "running" &&
ingestStatus !== "idle" && (
<button
type="button"
onClick={() => onManualIngest()}
title="进行数据入库(由结构化输出智能体调用入库技能,过程见消息列表步骤条)"
className="mb-0.5 flex h-8 shrink-0 items-center gap-1 rounded-xl border border-emerald-200 bg-emerald-50 px-2.5 text-[11px] font-bold text-emerald-700 transition hover:bg-emerald-100 active:scale-95"
>
<Database className="h-3.5 w-3.5" />
数据入库
</button>
)}
{/* 上传文件(参考第一/二步:本地选取,发送时上传到总结线程) */}
<input ref={fileInputRef} type="file" multiple className="hidden" onChange={pickFiles} />
<button
@@ -799,7 +1006,10 @@ function ContentModal({
onClose: () => void;
headerAction?: React.ReactNode;
}) {
return (
// 经 portal 挂到 body:页面 <main> 是 `relative z-0`(浅蓝主题层叠基线),会把
// 内部 fixed 弹窗困在 z-0 层叠上下文里,被会商页头(z-40)/全局顶栏(z-45)盖住顶部。
// 挂到 body 后脱离该上下文,z-50 才真正盖在顶栏之上,弹窗标题栏正常显示。
return createPortal(
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[1px] p-4"
onClick={onClose}
@@ -823,7 +1033,8 @@ function ContentModal({
</div>
<div className="flex-1 overflow-y-auto p-5">{children}</div>
</div>
</div>
</div>,
document.body,
);
}
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff. Show more