Compare commits

...
1461 Commits
Author SHA1 Message Date
gozeros 754b61572c sync snapshot from LAN repo (source master-zg @ 40658c74) 2026-11-05 10:58:49 +08:00
gozeros ea9dcff9c0 sync update from LAN repo (source master @ ca48c4ec) 2026-11-05 10:53:54 +08:00
gozeros 8bc8b0e082 sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4) 2026-10-21 14:51:31 +08:00
董宏凯 4f7f07504a Merge branch 'master-nj' into 'master'
fix(buttons): 行动分析宿主路由支持切换任务id/行动id

See merge request knowledge-base-bj/deerflow-code!39
2026-09-07 09:53:09 +00:00
董宏凯 1244fb1f2f 代码提交 2026-09-07 17:30:53 +08:00
吉鑫升 3ca5528640 feat(knowledge): support standalone file ingestion and configurable wiki entry
Use neutral knowledge-service labels and sanitize user-facing task errors.
2026-09-07 17:07:27 +08:00
董宏凯 250db4de04 fix(buttons): 行动分析宿主路由支持切换任务id/行动id
- TaskButtonsPage: 宿主路由追加任务id时,行动分析(xdfx) tab 下增加 idKind 下拉框可选任务id/行动id,与外部链接类型一致
- runTaskButton: host 分支按 idKind 取 ctx.actionId 或 ctx.taskId(行动id缺失回退任务id),与 url 分支同规则
- AGENTS.md: 同步更新 idKind 适用范围说明(url/host 均适用)
2026-09-07 15:56:50 +08:00
董宏凯 f9b6d7e322 Merge branch 'master-nj' into 'master'
feat: 新增报告协作页,并强化 Deep Research 运行诊断与报告兜底

See merge request knowledge-base-bj/deerflow-code!38
2026-09-07 06:58:42 +00:00
董宏凯 6edb6fa7aa 本地模式线上区分-v1 2026-09-07 14:57:17 +08:00
董宏凯 cf9fe58905 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj
Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	frontend-web/src/components/workspace/workspace-nav-chat-list.tsx
#	frontend-web/src/pages/WorkspaceRoutes.tsx
#	offline-backend-20260512/backend/app/gateway/app.py
#	offline-backend-20260512/backend/app/gateway/deps.py
#	offline-backend-20260512/backend/pyproject.toml
2026-09-07 14:46:36 +08:00
董宏凯 56bb4f141d 代码提交 2026-09-06 22:17:53 +08:00
董宏凯 75f288b241 代码提交 2026-09-06 20:49:35 +08:00
董宏凯 bf42a48fcc 代码提交 2026-09-06 20:25:14 +08:00
董宏凯andCursor 5e953c9fcb feat(report-collaboration): complete RC-BE-015–018 backend, eval suite, and MySQL sync
Ship report rewrite/version APIs, security budget and audit persistence, AgentScope worker wiring, and the 20-task quality eval harness so the frontend can integrate against a stable contract once enabled in config.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 17:32:15 +08:00
董宏凯 814a44f0b9 代码修改 2026-09-05 11:28:25 +08:00
董宏凯 b80433f091 chore: 同步仓库执行说明与约束文档
功能说明:\n- 更新仓库根目录 AGENTS.md 为当前约定和功能说明口径\n- 主要是开发约束与架构说明的同步,供后续提交与协作流程对齐
2026-09-04 23:18:59 +08:00
董宏凯 5c75e1af16 feat(deep-research): 强化任务链路可靠性并接入 agentfx 报告助手种子
功能说明:\n- 重构 Deep Research 调度与执行链,补齐 dispatcher、executor、live hub 与依赖注入入口,提升任务下发、执行、回调的稳定性\n- 增强运行时持久化与恢复能力,接入业务映射、任务来源与任务事件日志模型,覆盖持久化与执行可靠性关键路径测试\n- 新增 agentfx 报告助手 seed 与任务报告导入脚本配置,支持离线环境快速初始化与任务流模板回填\n- 完善 deep-research 与 thread_runs 路由参数编排,兼容不同业务映射与运行入口的前后端联动\n- 补充前端 agentfx deep-link 解析,保证 deep-research 场景下的登录跳转与任务上下文一致
2026-09-04 23:18:52 +08:00
董宏凯 438772f0b7 feat(frontend): 上线报告协作与多轮 RAG 消息聚合体验
功能说明:\n- 新增报告协作页(Report Collaboration)核心状态层、消息适配与会话面板,支持按节点/阶段选择和协作上下文展示\n- 补齐 report-collaboration API 与类型定义,并接入页面路由/构建路径,形成可运行的协作链路\n- 重构多轮 RAG 与 write/artefact 消息分组逻辑,优化 AgentChat 与 DeepResearch 场景下的消息展示顺序与可读性\n- 新增/更新 DeepResearch 前端页面(Workbench、报告配置、沙箱联动)以承接报告生成与复用能力\n- 增加报表协作相关单测,覆盖事件归并、消息适配与关键 reducer 行为
2026-09-04 23:18:27 +08:00
吉鑫升 dea4697ea0 feat: improve knowledge sync and entity alignment 2026-09-04 18:43:12 +08:00
g zy 7dbac9cc56 Merge branch 'gzy_browser' into 'master'
fix

See merge request knowledge-base-bj/deerflow-code!37
2026-09-04 03:21:48 +00:00
Rocky Kwok a723a9ca02 fix 2026-09-04 11:16:38 +08:00
董宏凯 e58da3fbdf 代码提交 2026-09-03 20:06:54 +08:00
吉鑫升 60e2c72514 feat: preserve Wiki vectors across knowledge transfers and add local BGE-M3
Unify Wiki reading, preserve metadata and graph links, add asynchronous file-backed transfers, and reuse compatible vectors. Includes regression coverage and live acceptance notes.
2026-09-03 19:21:10 +08:00
董宏凯 1eae02f782 代码提交 2026-09-03 17:45:06 +08:00
董宏凯andCursor db333a4c33 feat: 重构多轮RAG展示并完善报告协作、业务链审核与 agentfx 种子
抽出专用多轮RAG消息列表并升级会话模型;强化报告协作画布与检查器;业务链普通用户改为提交审核;扩展 agentfx 报告技能种子,并将含 admin 的用户名自动提权为管理员。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 17:34:16 +08:00
董宏凯andCursor f109a95535 feat: 新增报告协作页,并强化 Deep Research 运行诊断与报告兜底
支持浏览器侧素材快照撰写、拒绝报告读时修复、Mermaid PNG 导出与 Word 导出加固。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 11:16:50 +08:00
吉鑫升 49d9ced04f Merge branch 'ji' into master 2026-09-03 10:25:57 +08:00
董宏凯 c2153ec238 Merge branch 'master-nj' into 'master'
feat(workflow): 增加会话级多智能体任务规划运行能力

See merge request knowledge-base-bj/deerflow-code!36
2026-09-02 09:55:59 +00:00
吉鑫升 6b724bd00d feat: improve assistant knowledge import and database compatibility 2026-09-02 17:55:17 +08:00
董宏凯 65d6b61d5d 开发计划 2026-09-02 14:57:34 +08:00
董宏凯 1c891df8fb feat(backend): 新增页面报告设计器 Seed 与模板工具
功能说明:\n- 新增页面报告设计器的路由级 seed 接口与初始化模板资源加载能力\n- 新增内置页面报告模板工具,实现报告生成流程中的模板路径与参数接入\n- 补充页面报告模板与相关资产目录,供运行时/离线环境直接读取\n- 将页面报告配置与工具链纳入后端启动路径,支持离线部署下可复用的默认模板
2026-09-02 12:52:40 +08:00
董宏凯 6d326a21cd feat(backend): 完善 Workflow 与 DeepResearch 的运行链路与持久化能力
功能说明:\n- 重构并增强工作流网关执行链路,支持更完整的 proposal 与 run 调度参数透传\n- 增加 DeepResearch/workflow 运行事件持久化能力并补齐建表 SQL 与查询/保存接口适配\n- 优化 lead agent 与 deep research runner 的中间态处理,增强线程收集与执行链并发控制\n- 调整工作流执行器与任务路由,提升兼容性并完善错误与回放行为\n- 补充回归测试:deep_research 持久化、workflow 并发、定义加载、引擎执行、run 流程等覆盖
2026-09-02 12:52:37 +08:00
董宏凯 f5bf7897b9 feat(frontend): 支持 Roundtable 写文件流式预览与消息流聚合展示
功能说明:\n- 为写文件工具链增加流式预览状态模型(in-flight、chunk 归并、已完成)\n- 在消息面板中支持 write_file 流式 artifact 的动态插入/更新与完成态呈现\n- 优化 artifact 详情页的文件名与来源显示,兼容流式生成中文件路径\n- 在 Roundtable 工作流 step2 流程中注入与监听 write_file 事件,支持多阶段消息统一展示\n- 补充单测覆盖:streaming-write-preview、write-file-in-flight、streaming-artifacts 等关键路径
2026-09-02 12:52:33 +08:00
Administrator fbd8dec48f feat: add skill and assistant knowledge bases 2026-09-02 00:49:13 +08:00
吉鑫升 dd0ee282df feat: add artifact library and improve public wiki 2026-09-01 18:18:28 +08:00
董宏凯 553f72604a Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-09-01 15:36:47 +08:00
董宏凯 9455160101 fix(prompt-input): 提供可选上下文入口并避免历史路由切换期异常 2026-09-01 14:51:21 +08:00
董宏凯 519e4c0c01 feat(chat): 修复 Strategy/Workspace 统一聊天布局与历史路由归属 2026-09-01 14:51:16 +08:00
董宏凯 dbf62e5889 feat(deep-research): 优化深度研究侧边栏与结构配置弹窗的暗色主题适配
为深度研究沙箱预览区和工作流配置弹窗补充暗色下背景与边框配色,避免在深色模式出现对比度不足和样式不一致。
2026-09-01 13:47:39 +08:00
董宏凯 aeb9a55497 feat(agent-chat): 修复智能体会话归属与历史路由恢复:侧边栏按当前agent过滤会话并携带agent上下文跳转,补充旧线程路径回溯到智能体工作区,防止误入通用问答,并完善输入框记忆按钮显隐与侧边栏展开入口,提升体验一致性。 2026-09-01 13:47:31 +08:00
董宏凯 051e66f7d8 feat(chat): 优化聊天页布局与 iframe 工具栏行为 2026-09-01 12:49:03 +08:00
董宏凯 1706a24182 feat(workflow): 增加会话级多智能体任务规划运行能力
提交范围聚焦于工作流编排新增:新增 workflow_planning 路由与前后端运行入口(workflow_planning.py、workflow_proposal_planner.py、workflow_deep_research_adapter.py),支持基于会话的提案-规划-执行流程,满足任务驱动式多智能体协作。

完成网关层运行时适配:扩展 workflow_resource_checks、workflow_executor、workflow_runs、workflow_agent_runner 与依赖注入,新增/更新配置(config.yaml、workflow_config),并补充 lead_agent 路径与节点实现,确保 Planner 与普通工作流运行态衔接一致。

补齐持久化与建模:新增 workflow_planning 持久化模块与 MySQL migration(20260831_01_workflow_planning_sessions),注册 SQL 与模型、内存 store,并扩展错误/表达式/validator/节点语义以承载新会话态输入输出。

增强文档与测试:新增会话式多智能体编排中文说明、更新开发文档与 AGENTS 指南、补充 workflow_engine/workflow_runs 回归测试,提高新路径的行为可验证性;同时留存 seed 资产(workflow-planner)便于一体化部署。
2026-09-01 11:47:30 +08:00
董宏凯 38857c425b 代码提交 2026-09-01 11:09:23 +08:00
董宏凯 99f1ca6029 Merge branch 'master-nj' of http://192.168.0.200/knowledge-base-bj/deerflow-code 2026-08-31 23:21:32 +08:00
董宏凯 a020458eeb Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code 2026-08-31 23:21:00 +08:00
董宏凯 8e49fd2e95 代码分析 2026-08-31 23:20:48 +08:00
fengxiangdebaozi 57b6a89f20 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj
# Conflicts:
#	frontend-web/src/components/workspace/messages/message-group.tsx
#	offline-backend-20260512/backend/packages/harness/deerflow/agents/lead_agent/prompt.py
2026-08-31 20:12:05 +08:00
吉鑫升 90e94994f5 Merge remote-tracking branch 'origin/master' into master 2026-08-31 18:06:10 +08:00
吉鑫升 8e0d755b57 fix: preserve knowledge base references 2026-08-31 18:02:05 +08:00
吉鑫升 40542db400 feat: add configurable chat display modes 2026-08-31 17:49:48 +08:00
董宏凯 ac92f29db1 chore(persistence): 增加 Workflow Studio 表重建开关与迁移兼容修正
提交内容:为数据库生命周期增加按白名单清单重建 Workflow Studio 表的受限流程,限定仅 MySQL 且检查当前连接数据库名称一致,避免误删非目标 schema。

启动流程中新增 DEER_FLOW_REBUILD_WORKFLOW_SCHEMA 环境变量入口与持久层重建 API,并在 lifespan 里按需执行;导出到 persistence 包,便于后续调用与测试复用。

迁移与模型修复:将 workflow 相关大文本字段切到 MySQL LONGTEXT,不再给 TEXT/LONGTEXT 设置 server_default;新增 draft_canvas_schema_json 的迁移回填与非空约束变更,规避 MySQL 5.7 对默认值限制。

测试覆盖:补充 workflow 定义 ddl 长文本断言与 schema 重建保护性测试(仅允许清单表、数据库名不匹配直接拒绝),并把新测试文件加入版本追踪。
2026-08-31 16:45:06 +08:00
董宏凯 f0ddade8a7 feat(roundtable): 增强多智能体 Step2 流式推理与产物展示
提交内容:将 roundtable 的流式消息拆分为文本与 think 推理,支持思考内容以 <think> 形式内联渲染,解决仅返回 reasoning token 时的内容空洞问题。新增 stream-reasoning 工具与单元测试,保证 reasoning 首包到正文的闭合行为稳定。

交互与预览修正:write_file/str_replace 工具的沙箱打开策略改为更接近实时席位行为,不再因为文件后缀限制阻塞临时脚本写入可视化;通过新增 streaming-artifacts 工具统一处理可预览路径、最终交付产物过滤与目录快照比对,支持 bash/脚本直接落盘场景在流式阶段自动发现新增文档。

体验细节:步骤面板文件卡片从工具路径与最终 artifact 统一收敛,避免 read_file 点击误触发;自动滚动逻辑新增布局高度抖动识别,防止模型推理渲染导致的误判向上滚动。
2026-08-31 16:45:01 +08:00
董宏凯 fbf9031e25 feat(会商第三步): 恢复普通会商完整成果并隔离8BF报告模式
- 为普通多智能体会商恢复报告完成后的结构化流程图、最终方案展示、经典结果绘制和大屏多页,并保持三个生成流独立并行。

 - 8BF 入口显式采用 report-only 模式:只生成和编辑 Markdown 总结报告,不再启动或露出流程图、结果绘制及大屏功能。

 - 结构化流程图增加抽取、校验、暂停、失败重试和歧义选择交互;报告完成后状态文案准确切换,自动滚动定位到抽取与校验进度。

 - 为总结报告、经典 HTML 绘制和大屏虚拟 write_file 补齐完成结果及历史恢复处理,避免并行分支或旧草稿让完成产物误显示为生成中。

 - 最终方案展示中的已落盘文件直接按完成态预览,并恢复 MD、HTML 等文件类型徽标,不再被提交按钮覆盖。
2026-08-30 21:24:47 +08:00
董宏凯 2254841822 fix(会商第二步): 恢复总控派活实时展示并修正沙箱预览状态
- 流式解析改为跟踪当前 tool call id,连续多次 agent_orchestration 派活时前端即时展示最新席位和任务,不再等模型完整回复后一次性出现。

 - 总控派活步骤按 tool call 独立归档并合并增量参数,避免同名工具调用互相覆盖或只显示半截任务。

 - 沙箱自动打开改为按单个产物预览键管理:用户关闭当前文件后不反复弹出,但后续新文件仍可自动预览。

 - 为圆桌虚拟 write_file 补齐工具完成结果,并在席位收尾和历史草稿恢复时兜底收口,防止完成文件长期显示“正在生成”。
2026-08-30 21:24:30 +08:00
董宏凯 74fc849241 fix(会商滚动): 让第二、三步新消息与结构化进度即时定位到底部
- 为圆桌滚动钩子增加强制落底能力,阶段切换和布局变化不再被平滑滚动的旧高度截断。\n- 第二步用户发送消息后立即下滑到底部,不再等待模型首个输出。\n- 经典结果绘制与大屏对话面板接入内容高度观察,新增气泡、Markdown 和工具卡继续增高时保持跟随。\n- 保留用户手动上翻时的正常阅读行为,仅在新一轮发起或关键阶段切换时强制定位。
2026-08-30 21:24:08 +08:00
董宏凯 dd560ceb46 fix: 会商沙箱预览头仅在可提交的 Markdown 产物显示提交按钮 2026-08-30 20:02:21 +08:00
董宏凯 a4f95a4fa9 fix: 会商第一步隐藏继续追问与跳过此项按钮 2026-08-30 20:02:21 +08:00
董宏凯 b92a26cdd4 fix: 会商第二步只对可预览成品出文件卡/开沙箱,去掉干预并发送按钮 2026-08-30 20:02:21 +08:00
董宏凯 7066798ab0 chore: 配置新增 qwen3.8-flash 模型 2026-08-30 20:02:15 +08:00
董宏凯 222595d6c4 feat: 工作流画布支持草稿试运行(target=draft 执行当前草稿图) 2026-08-30 20:02:15 +08:00
董宏凯 3384f2e51c fix: 会商席位与总控角色隔离,编排能力只归总控 2026-08-30 20:02:09 +08:00
董宏凯 ff80cc110d fix: 写作管线步骤条改用不涉及检索的文案
- 「拆解检索问题」→「梳理写作思路」(已梳理出 N 个论述角度)
- 「检索参考资料」→「整理对话资料」(已整理 1/2 个论述角度的
  资料 · 累计 N 条)
- 管线实际只汇总对话已收集的资料再成稿,原文案会让用户误以为
  管线在重新检索;测试补标签断言防止回退
2026-08-30 16:21:02 +08:00
董宏凯 2ab3ab8444 fix: 写作管线整批接收对话检索结果,不再自己检索
- 相关性过滤新增位置通道:收割器给每条材料标记来源消息位置,课题
  请求之后的检索结果整批入池(与语言/词面无关)——线上中文课题 +
  英文检索结果被纯词面匹配误杀 31/35 条,报告只带着 4 条残料在写
- 课题切换保护保留:新请求之前的旧课题检索仍按词面强过滤,不凑
  门槛、不入报告;对话里找不到课题消息时退化为原词面过滤
- 删除死代码 HarvestPlusSearchMaterialProvider(retrieve=True 的
  自检索补充分支,早已被显式忽略):写作管线只负责写文件,检索
  全部由对话完成成为结构保证
- 测试:锚点规则(澄清回答不充当新课题)、中文课题+英文资料整批
  保留、课题切换旧检索过滤等场景,25 个用例入库(此前该测试文件
  一直被 tests/* 忽略规则挡在版本库外)
2026-08-30 16:20:55 +08:00
董宏凯 f7e6ed65bd fix: retry httpx timeout family as transient LLM errors
Live incident: the compatible-mode provider stalled mid-stream after
200 OK (~17s without data) and raised httpx.ReadTimeout, which was not
in the retriable exception-name set, so the call failed after 1
attempt and killed the whole run. Add ReadTimeout/ConnectTimeout/
WriteTimeout/PoolTimeout/TimeoutError/ConnectError to the transient
set in LLMErrorHandlingMiddleware (retry with backoff, then a
transient fallback message instead of generic), and add ReadTimeout/
ConnectTimeout to ai_writing's classify_exception for model
switching.
2026-08-30 15:53:51 +08:00
董宏凯 4964967295 fix: writing mode first-report allows only the pipeline to write the report
- Strip write_file/str_replace/bash from the model binding in the
  first-report run: after_model rewrites only fire after a full model
  response, so any bound write tool let weak models draft the whole
  essay into tool args (write_file content or bash cat>/python
  heredocs) for tens of invisible seconds before interception
- Hallucinated hand-writes are still handled: after_model rewrites
  bash cat >/python open('w')/tee and leftover write calls to
  deep_research_report; wrap_tool_call rejects whatever reaches the
  tool layer; post-success writes are dropped, nudged to a 2-3
  sentence summary, and patched with a fallback closing message so
  the turn never ends silently
- The rewritten pipeline call carries topic = original request
  (clarification answers skipped) plus focus = clarification answers,
  so the pipeline writes the clarified subject instead of the raw
  prompt text; prompts updated to match (tools unavailable, call the
  tool directly, do not draft first)
- Frontend write-step interception and streaming preview scoping now
  applies only in writing mode; normal mode shows/previews writes
  exactly as before
2026-08-30 15:53:43 +08:00
董宏凯andCursor 49c01cb72b fix: writing mode uses chat search then pipeline write only
Keep deep_research_report as a write-only deliverable from conversation materials, block post-success rewrite loops with a summary nudge, fill thin/empty pools from model knowledge, and open the sandbox only on real report.md content.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 12:41:04 +08:00
董宏凯andCursor 9afb9750e5 Merge branch 'master' into master-nj
Keep Win7 flowchart SVG labels and bring over Mermaid syntax repair plus HTML chart color downleveling.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 09:28:52 +08:00
董宏凯andCursor f18994fd38 fix: show generated HTML charts on Win7 Chrome
Rewrite oklch/color-mix and space-separated rgb before iframe preview so pie and bar fills are not dropped on Chrome 109.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 09:25:09 +08:00
董宏凯andCursor 7c15ca6710 fix: show sandbox flowcharts on Win7 Chrome and repair common Mermaid syntax
Disable HTML labels so nodes use native SVG text, and rewrite bare edge labels plus invalid class statements before render.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 09:05:29 +08:00
董宏凯 31cfa93408 feat: 智能体列表页引导改为手动触发,完成/跳过不再跳转创建页
- AgentGuide 新增 autoStart 属性(默认 true),列表页挂载传 false:进智能体列表页不再自动弹引导,仅由头部「使用引导」按钮手动触发
- 去掉 list 段与创建页的联动:finish 不再 router.push,最后一步按钮恢复默认「完成」,跳过/走完都就地结束并写记忆
- AGENTS.md 同步更新智能体引导条目
2026-08-30 08:53:34 +08:00
董宏凯andCursor b164e70541 fix: unlock send immediately after SSE close
Normal Q&A no longer waits on GET /runs before the next message. Probe run status only on 409 or dropped streams.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 08:48:53 +08:00
董宏凯 17cf849361 代码提交 2026-08-30 01:25:20 +08:00
董宏凯andCursor 4ac7bc21cd feat: 优化对话历史与会商引导体验
列表引导改为手动触发且不跳转创建页;历史 Tab 展示会商步骤/链条与深度研究模板;Step2 增加暂停与内容高度跟随滚动,并修复旧草稿恢复兜底。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 20:25:21 +08:00
董宏凯andCursor 832e180c52 fix: 改进流式 write_file 沙箱预览与 Mermaid 旧浏览器兼容
同轮次非末尾 write_file 也能自动打开沙箱并跳过 JSON 大文件预览;Mermaid 改用 SVG 标签;agentfx 强制先写 md 再写 json。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:21:39 +08:00
董宏凯andCursor 875001a8c0 feat: 对话历史页收纳会商/写作/深度研究 Tab,侧栏移除重复入口
ChatsPage 新增四类历史 Tab 与统一搜索筛选 UI;简洁模式侧栏不再展示会商与写作列表;深度研究页支持 ?session= 深链打开指定记录。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 15:43:02 +08:00
董宏凯andCursor 36653c53a6 feat: 补充对话历史页深度研究 Tab 组件
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 13:01:58 +08:00
董宏凯andCursor 37517c2778 fix: 嵌套深链改为按路由去 chrome,顶层不再清除共用 embed.session
避免全量父页清掉老版内层深链仍依赖的 embed.session;深链问答/会商/大屏绘制由 isHostNestedSurfacePath 控制 chrome,并抽取对话历史 Tab 共享行组件。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 13:01:46 +08:00
吉鑫升 3715af3138 chore: move offline release assets to standalone repository 2026-08-27 23:35:57 +08:00
吉鑫升 973500a0f0 fix: preserve LF in offline deployment assets 2026-08-27 22:35:57 +08:00
吉鑫升 d9a94245fc feat: standardize DeerFlow offline deployment 2026-08-27 22:06:43 +08:00
董宏凯 1764d0d5f2 Merge branch 'master-nj' into 'master'
fix: 8BF 无 taskId 开全新会话,公共链条发布联动席位智能体

See merge request knowledge-base-bj/deerflow-code!35
2026-08-27 13:48:17 +00:00
董宏凯andCursor 84370e2072 fix: 8BF 无 taskId 开全新会话,公共链条发布联动席位智能体
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 21:47:31 +08:00
董宏凯 0289a76fce Merge branch 'master-nj' into 'master'
feat: 新增 agentfx 任务深链与研判报告入库流程

See merge request knowledge-base-bj/deerflow-code!34
2026-08-27 10:39:04 +00:00
董宏凯andCursor 32e509b2b3 fix: 岗位会商 handoff 将上游产物镜像到当前席位沙箱
席位线程隔离导致下游 read_file 找不到上游路径;镜像到 workspace/upstream 并改写 handoff 引用,附带安全路径校验与 SQL 回退测试。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 18:35:17 +08:00
董宏凯 440b490b0d Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-27 16:33:33 +08:00
董宏凯andCursor 52b9cbf707 feat: 新增 agentfx 任务深链与研判报告入库流程
支持 goPath=agentfx 的 iframe 嵌入问答、内置研判助手种子与报告导入协助卡,并完善深度研究流式报告能力。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 16:32:22 +08:00
吉鑫升 1b43205c1b feat: improve skill uploads and agent runtime stability 2026-08-27 11:28:03 +08:00
吉鑫升 11326eeb1c feat: improve skill uploads and agent runtime stability 2026-08-27 11:14:23 +08:00
吉鑫升 485a8fa9d9 feat: standardize Word export and Office conversion 2026-08-27 00:09:53 +08:00
董宏凯 4ce2f3a502 Merge branch 'master-nj' into 'master'
feat: 智能体问答页右侧面板受控折叠,收起整列归零并在 header 提供展开入口

See merge request knowledge-base-bj/deerflow-code!33
2026-08-26 10:25:11 +00:00
董宏凯andCursor 6e9e89a6cb fix: 流式自动开沙箱分阶段收起侧栏,避免同帧布局卡顿
新增 preOpen 两阶段标记,先错开收起左右侧栏再展开沙箱;智能体详情面板据此提前收起,减少与沙箱展开同帧叠加造成的卡顿。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 18:24:06 +08:00
董宏凯andCursor 90d29ed232 feat: 智能体问答页右侧面板受控折叠,收起整列归零并在 header 提供展开入口
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 17:37:23 +08:00
董宏凯 d9de41dd67 代码修改 2026-08-26 17:15:04 +08:00
董宏凯 f1245da3e4 Merge branch 'master-nj' into 'master'
feat: 舆情分析智能体改为经 Gateway 转发外部 AG-UI 网关

See merge request knowledge-base-bj/deerflow-code!32
2026-08-26 09:00:55 +00:00
董宏凯 38c3de39f0 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj
# Conflicts:
#	AGENTS.md
#	frontend-web/src/pages/AgentChatPage.tsx
2026-08-26 16:37:41 +08:00
董宏凯andCursor 33639e5b89 fix: 修复嵌套 iframe 污染 embed 会话与协助卡后流式显示异常
顶层窗口通过 topOwned 标记自愈老版嵌套页写脏的 embed.session;协助卡提交后避免冻结 checkpoint 覆盖实时 SSE,并仅在服务端回显新 human 消息时清除乐观气泡。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 16:28:10 +08:00
吉鑫升 676b00afb6 Merge branch 'ji' into master 2026-08-26 16:07:37 +08:00
吉鑫升 0980eea975 feat: unify formal Word export 2026-08-26 16:02:23 +08:00
董宏凯 eba3008482 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-26 15:48:23 +08:00
吉鑫升 9b904ac3dd Merge branch 'ji' into master
# Conflicts:
#	offline-backend-20260512/backend/CLAUDE.md
#	offline-backend-20260512/backend/README.md
#	offline-backend-20260512/backend/app/gateway/routers/llmwiki.py
#	offline-backend-20260512/backend/config.yaml
#	offline-backend-20260512/backend/packages/harness/deerflow/config/llmwiki_config.py
#	offline-backend-20260512/backend/tests/test_llmwiki_weknora.py
2026-08-26 15:46:58 +08:00
董宏凯 704438b3d2 bug修改 2026-08-26 15:46:49 +08:00
吉鑫升 d35d075669 feat: add compact toolbox and public wiki vector search 2026-08-26 14:40:57 +08:00
董宏凯 910cee9e67 用户引导沙箱优化 2026-08-26 14:14:26 +08:00
董宏凯 21f3787b8b 代码修改 2026-08-26 11:30:39 +08:00
董宏凯 33b719d460 用户引导 2026-08-26 11:09:43 +08:00
董宏凯 c6fcf51e0c 用户引导 2026-08-26 09:41:53 +08:00
董宏凯andCursor 62a3faa7c8 feat: 舆情分析智能体改为经 Gateway 转发外部 AG-UI 网关
前端不再直连上游 SSE,改为 POST /api/sentiment-agent/stream 由后台代理转发,支持关闭 TLS 校验并回传完整错误信息。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 18:26:48 +08:00
董宏凯 d87dfec2de Merge branch 'master-nj' into 'master'
feat: 业务链条发布审核流程 + 编辑器去除岗位职责输入框

See merge request knowledge-base-bj/deerflow-code!31
2026-08-25 09:35:16 +00:00
董宏凯 5c0864bf0a Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-25 17:33:40 +08:00
董宏凯andCursor 8ce3a62826 fix: 岗位会商历史按用户隔离,并为 write-file 预览启用 AI 写作视图
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 17:32:56 +08:00
董宏凯 8c3d6a02fc feat: 业务链条发布审核流程 + 编辑器去除岗位职责输入框
- 发布改为可选「确认审核 / 直接发布」:链条编辑页与圆桌「业务链条」弹窗行为一致;审核中可撤回
- 管理员在业务链条列表新增「待审核」筛选,审核发布后进入公共库
- 后端 roundtable_chains 新增 pending_review 字段(启动期自动补列)与 scope=pending 筛选;新增审核流程测试
- 编辑器席位去掉「岗位职责」输入框(保存时存量值原样保留)
2026-08-25 17:30:29 +08:00
吉鑫升 e053b36b6e fix: harden wiki delivery and leaderboard performance 2026-08-25 16:58:13 +08:00
吉鑫升 9f29ecae9e fix: harden wiki delivery and leaderboard performance 2026-08-25 16:57:42 +08:00
吉鑫升 4b86106a24 fix: restore embedded wiki images and optimize vector sync 2026-08-25 11:26:27 +08:00
董宏凯 043b0900d5 Merge branch 'master-nj' into 'master'
Master nj

See merge request knowledge-base-bj/deerflow-code!30
2026-08-25 03:26:03 +00:00
吉鑫升 0c5e2e8cb0 fix: restore embedded wiki images and optimize vector sync 2026-08-25 11:24:01 +08:00
董宏凯 40d06b781a 接口调整 2026-08-25 11:23:53 +08:00
董宏凯 c5328e6a35 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-24 20:47:55 +08:00
董宏凯 babc5e95c6 代码提交 2026-08-24 20:47:31 +08:00
吉鑫升 1736227723 feat: complete public wiki and embedded previews 2026-08-24 20:41:24 +08:00
吉鑫升 30943159bf feat: complete public wiki and embedded previews 2026-08-24 20:40:44 +08:00
董宏凯 007ed5a7de Merge branch 'master-nj' into 'master'
Master nj

See merge request knowledge-base-bj/deerflow-code!29
2026-08-24 09:08:51 +00:00
董宏凯 ebc727e4fd 代码提交 2026-08-24 17:08:22 +08:00
吉鑫升 bc49df4561 feat: add public wiki embeds and ES query routing 2026-08-24 15:21:28 +08:00
董宏凯 cdb8aa5f81 弹窗样式修改 2026-08-24 14:45:25 +08:00
吉鑫升 e818c24769 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	.gitignore
#	frontend-web/src/components/workspace/artifacts/context.tsx
#	frontend-web/src/components/workspace/messages/message-group.tsx
#	offline-backend-20260512/backend/CLAUDE.md
#	offline-backend-20260512/backend/README.md
#	offline-backend-20260512/backend/app/gateway/app.py
#	offline-backend-20260512/backend/app/gateway/deps.py
#	offline-backend-20260512/backend/app/gateway/routers/llmwiki.py
2026-08-24 14:21:19 +08:00
吉鑫升 49babb6d25 feat: improve wiki document and artifact views 2026-08-24 14:01:10 +08:00
Administrator 3785345353 feat: add local LLMWiki wiki vector index 2026-08-24 00:49:31 +08:00
董宏凯 daaa0eab26 Merge branch 'master-nj' into 'master'
feat: 深度研究支持独立新报告与原文改写,并完善沙箱、模型管理与全文改写

See merge request knowledge-base-bj/deerflow-code!28
2026-08-23 14:30:21 +00:00
董宏凯andCursor 541bc3280f fix: 岗位会商本轮只允许 present_files 一次,避免重复产物卡
弱模型写完报告后仍会再调用一次 present_files,前端会画出两张相同卡片。上限同时覆盖呈现,已呈现则只催收尾。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-23 21:26:57 +08:00
董宏凯andCursor b81d200eca fix: 协助卡停轮与提交防 409,隐藏配置向导会话,并限制岗位会商产物重复写入
澄清中间件改为 ToolMessage + after_model 停轮,前端提交前取消残留 run;系统/向导 thread_type 从对话列表排除;岗位总结席位加 write_file 上限。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-23 20:29:59 +08:00
董宏凯andCursor 51afebb394 feat: 报告结构支持检索方向/来源与智能新增,并修复协助卡停轮与宿主跳转
为深度研究报告结构增加检索方向与技能来源、对话式智能新增页与详情排版;澄清中间件在 after_model 可靠结束本轮,避免弱模型出卡后继续生成;任务按钮补充 host 跳转与相关深链能力。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 17:46:06 +08:00
董宏凯andCursor a5a9c952e8 feat: 深度研究支持独立新报告与原文改写,并完善沙箱、模型管理与全文改写
新报告不再覆盖当前文件卡片,写入时打开沙箱;步骤条仅在改写原文时位于卡片上方。同时补齐改写本地回退、模型管理与会商第三步相关改动。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 21:46:04 +08:00
吉鑫升 4c9f75f31e feat: add fixed questions and improve authentication 2026-08-21 17:58:39 +08:00
董宏凯 7c34e18ad6 Merge branch 'master-nj' into 'master'
fix: 单轮 RAG 步骤条思考内容支持可点击参考序号

See merge request knowledge-base-bj/deerflow-code!27
2026-08-20 09:04:49 +00:00
董宏凯andCursor 11f928bc95 feat: 新增独立企业深度研究工作台,并接入工作流报告结构与 8BF 深色锁定
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 16:43:03 +08:00
董宏凯andCursor e881c242fe feat: 岗位职责迁至业务链席位,并支持 WeKnora 嵌入页知识库切换
将岗位职责从智能体配置迁移到业务链席位 JSON,会商面板只读展示;WeKnora 嵌入 iframe 支持在授权可见范围内切换知识库并重新签发会话。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 22:26:40 +08:00
董宏凯andCursor e860357563 fix: 单轮 RAG 步骤条思考内容支持可点击参考序号
把思考区的 `[n]` 按正文同一套引用规则渲染,并去掉回答气泡里重复的 Thought for a few seconds。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 21:21:22 +08:00
董宏凯 c69fde22bd Merge branch 'master-nj' into 'master'
feat: 支持会商 Markdown 产物提交到任务过程,并补充 Angular 对接文档

See merge request knowledge-base-bj/deerflow-code!26
2026-08-19 12:38:26 +00:00
董宏凯andCursor 0ce060693b feat: 会商链条启停与深度研究报告结构,并完善问答展示与 8BF 返回。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 20:37:34 +08:00
董宏凯 be4851555d 代码提交 2026-08-19 17:11:36 +08:00
董宏凯andCursor 3afa76894f feat: 完善会商产物提交匹配与流式写文件预览
席位流程图按已提交 Markdown 对齐;流式未命名产物不再误请求 artifacts API,并兼容临时文件名路径。同时补强会话流中断识别与 8BF/岗位会商展示。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 17:08:52 +08:00
董宏凯andCursor acf538ac01 feat: 简介模式菜单按类型 A/B 分套,兼容未配置的旧部署
两套网页可通过 runtime-config.js 的 VITE_COMPACT_MENU_TYPE 加载各自左侧菜单;缺省或旧页面不传参数时仍读取原来的类型 A 数据。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 16:59:34 +08:00
董宏凯andCursor 5e1765d889 feat: 完善 8BF 会商第一步产物与智能体列表,第二步对话区对齐第一步样式
抽出共用分析成果卡片,第一步展示第二、三步 Markdown 产物;智能体列表对齐岗位会商选择样式。第二步对话面板改为深蓝顶栏,第一步保留可配置返回按钮。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 12:12:35 +08:00
董宏凯andCursor 30799f17be fix: 节流会商流式写文件预览,避免 Maximum update depth
write_file 的 content 在每个 SSE chunk 中持续增长,原先会反复触发 React 状态更新并打断整页;现改为按身份入参去重、节流发布 stub,并收口第 3 步为 Markdown 报告工作台。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 23:23:46 +08:00
董宏凯andCursor dcfaa199bf feat: 支持会商 Markdown 产物提交到任务过程,并补充 Angular 对接文档
8BF/会商工作区可将 Markdown 产物一键提交到任务过程报告,后端记录提交状态以便跨用户与刷新后保持已提交;同时为 Angular 智能体对话对接文档补上前后端参考代码索引。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 20:08:51 +08:00
董宏凯 33b0af333c Merge branch 'master-nj' into 'master'
增强 Deep Research 可靠性,并接入 8BF 任务卡片与会商上下文。

See merge request knowledge-base-bj/deerflow-code!25
2026-08-18 09:55:17 +00:00
董宏凯 172250e6b5 代码提交 2026-08-18 17:54:07 +08:00
董宏凯andCursor 15a46b903a 增强文档改写配图与深度研究流式稳定性,并完善 8BF/会商工作区。
全文改写支持可选配图与思考过程展示,深度研究接入 DashScope 原生出图并剥离内联 think 标签;8BF 会商补齐第一步工作区与任务卡回退,同时限制热重载扫描范围。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 17:46:11 +08:00
吉鑫升 8af4fed89d feat: update knowledge workspace and menu configuration 2026-08-18 15:23:14 +08:00
Administrator 64a5305bbf feat: add markdown word editor for knowledge workspace 2026-08-18 00:44:29 +08:00
董宏凯 819e537aa3 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-17 19:30:37 +08:00
吉鑫升 68c4896088 fix: stabilize auth sync and stream recovery for ji 2026-08-17 19:27:39 +08:00
董宏凯andCursor 771957429a 增强 Deep Research 可靠性,并接入 8BF 任务卡片与会商上下文。
修复 MySQL 读写分离下的持久化与 SSE 重连问题,报告完成前先落库;8BF 嵌入页支持 taskId 任务卡与独立意图 metadata;前端统一 createClientId 并更新 runtime 配置。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:16:05 +08:00
吉鑫升 5bf08c83a6 Merge remote-tracking branch 'origin/master' into ji 2026-08-17 15:53:36 +08:00
吉鑫升 3ab2c9b282 feat: improve WeKnora source preview and wiki management 2026-08-17 15:53:19 +08:00
吉鑫升 94cf37a2ae fix: normalize system messages before model calls 2026-08-17 10:12:43 +08:00
董宏凯 47faa9bcdf 代码提交 2026-08-16 21:48:38 +08:00
董宏凯 5901246030 Merge branch 'master-nj' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-16 20:43:43 +08:00
董宏凯 44e0b7596b Merge branch 'master-baogao' into 'master'
Master baogao

See merge request knowledge-base-bj/deerflow-code!24
2026-08-16 11:21:33 +00:00
董宏凯 178572bc7f 代码提交 2026-08-16 19:17:45 +08:00
董宏凯 70da7c5649 代码提交 2026-08-15 12:51:58 +08:00
fengxiangdebaozi 5c586652af daimhebing1 2026-08-14 21:25:29 +08:00
fengxiangdebaozi 067f602732 代码提交 2026-08-14 19:31:15 +08:00
董宏凯 96bfdacee5 Merge branch 'master-nj' into 'master'
Master nj

See merge request knowledge-base-bj/deerflow-code!23
2026-08-14 05:01:17 +00:00
董宏凯 500dab29ab Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-14 12:57:04 +08:00
董宏凯 4d688ddbd8 代码提交 2026-08-14 12:56:55 +08:00
Administrator 8193cc53d5 fix: stabilize embedded WeKnora detail page 2026-08-14 11:32:33 +08:00
Administrator a28ad2140e fix: stabilize embedded WeKnora detail page 2026-08-14 11:29:58 +08:00
董宏凯 7b37415604 Merge branch 'master-nj' into 'master'
feat: 岗位会商命令幂等与圆桌后台作业租约调度

See merge request knowledge-base-bj/deerflow-code!22
2026-08-14 03:17:53 +00:00
董宏凯 c4d244881f Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-14 11:15:37 +08:00
董宏凯andCursor 75963c9ad9 feat: 岗位会商命令幂等与圆桌后台作业租约调度
岗位会商写操作引入 command_id 幂等与版本锁,前端支持同键重试;圆桌后台作业改为 DB 租约 dispatcher、去重与草稿 outbox 补偿,并持久化 intent turns。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 11:08:12 +08:00
Administrator 11e54550ed fix: harden WeKnora proxy and configurable search 2026-08-13 23:44:47 +08:00
fengxiangdebaozi 4f536d9b39 feat(frontend): add workspace single and multi round rag 2026-08-13 21:05:31 +08:00
Administrator b527bc94bb fix: stabilize WeKnora embed session cookie 2026-08-13 20:42:24 +08:00
Administrator 54fd0e7316 fix: route WeKnora embed through backend prefix 2026-08-13 20:22:50 +08:00
Administrator 6dbaf40f99 fix: preserve WeKnora embed proxy prefix 2026-08-13 19:17:01 +08:00
Administrator 3aeb6ac5ce fix: authenticate WeKnora API client 2026-08-13 17:41:30 +08:00
董宏凯 5a4881053d Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-13 16:44:47 +08:00
董宏凯 cebc44ff82 代码提交 2026-08-13 16:43:31 +08:00
Administrator 56044d9cb7 fix: improve llmwiki search integration 2026-08-13 16:03:08 +08:00
吉鑫升 4809ee7db3 fix: update offline backend llmwiki support 2026-08-13 11:17:11 +08:00
Administrator a4a1e73b8e chore: configure VS Code launch tasks 2026-08-13 10:36:06 +08:00
Administrator 5123b7bdd7 chore: configure WeKnora admin password 2026-08-13 10:29:08 +08:00
Administrator e189349eeb fix: sync llmwiki embed theme 2026-08-13 10:25:49 +08:00
董宏凯 f2e81d8875 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-12 16:00:35 +08:00
董宏凯 e5e0f3a7c3 代码提交 2026-08-12 16:00:26 +08:00
吉鑫升 c4fd9dd7da Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	.gitignore
#	frontend-web/src/components/workspace/input-box.tsx
#	frontend-web/src/core/threads/types.ts
#	frontend-web/src/pages/ChatPage.tsx
2026-08-12 15:55:51 +08:00
吉鑫升 b4d076a2d4 fix: harden WeKnora knowledge permissions and details 2026-08-12 15:45:28 +08:00
董宏凯 bc82072710 Merge branch 'master-nj' into 'master'
feat: 管理员可删除内置技能并管理技能内文件

See merge request knowledge-base-bj/deerflow-code!21
2026-08-12 07:08:19 +00:00
董宏凯andCursor bf023d746a feat: 管理员可删除内置技能并管理技能内文件
新增内置技能删除与技能文件删除 API,允许管理员编辑/删除内置技能文件;技能设置页与文件预览弹窗同步支持删除操作。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 15:05:29 +08:00
董宏凯 fb5024ea82 Merge branch 'master-nj' into 'master'
feat: 模型配置支持删除,岗位行动规划对接任务系统字典与批量新增 Skill

See merge request knowledge-base-bj/deerflow-code!20
2026-08-12 06:48:24 +00:00
董宏凯andCursor c9c2dc7ea8 feat: 模型配置支持删除,岗位行动规划对接任务系统字典与批量新增 Skill
模型管理新增 DELETE 接口与前端删除能力(支持含斜杠的模型名);行动规划改为 9 字段 JSON,prepare 传入 taskId/字典并绑定 position-roundtable-action-create Skill。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 14:47:14 +08:00
董宏凯 2a869f4ff6 Merge branch 'master-nj' into 'master'
feat: 添加管理员模型配置页面与 config.yaml 模型管理 API

See merge request knowledge-base-bj/deerflow-code!19
2026-08-12 06:44:18 +00:00
fengxiangdebaozi af509eb670 Merge branch 'master-nj' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj 2026-08-12 14:32:57 +08:00
fengxiangdebaozi 783e698b6e 代码提交 2026-08-12 14:32:47 +08:00
董宏凯andCursor ba912acf72 feat: 添加管理员模型配置页面与 config.yaml 模型管理 API
新增 /api/admin/models 路由(读写 config.yaml models 段、连接测试、写前备份),以及工作区「模型配置」管理页与侧栏入口。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 21:45:56 +08:00
吉鑫升 e0c09f6704 feat: integrate WeKnora llmwiki knowledge flow 2026-08-11 18:13:30 +08:00
董宏凯 17a12bb7b6 Merge branch 'master-nj' into 'master'
feat: 岗位会商独立意图智能体与四项意图 schema

See merge request knowledge-base-bj/deerflow-code!18
2026-08-11 05:00:55 +00:00
董宏凯andCursor f8757d1a43 feat: 岗位会商独立意图智能体与四项意图 schema
岗位会商 Step 1 改用 position-roundtable-intent 智能体,输出 coreGoals/riskWarnings/keyPoints/strategicSignificance 四项数组;支持单轮多张协助卡、按轮次计澄清上限,并兼容旧会话 objective/constraints 映射。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 13:00:16 +08:00
董宏凯 69b95f0d6d Merge branch 'master-nj' into 'master'
feat(frontend): 岗位会商页面布局与意图理解交互优化

See merge request knowledge-base-bj/deerflow-code!17
2026-08-11 04:59:37 +00:00
董宏凯 ca32a22c0d 代码提交 2026-08-10 15:11:47 +08:00
董宏凯 3eb307c5c5 代码提交 2026-08-10 14:26:49 +08:00
董宏凯 49af497085 代码修改 2026-08-05 21:15:36 +08:00
董宏凯andCursor 8b732b43ee fix(frontend): 同路径二次 write_file 时重挂岗位会商沙箱
按 tool-call 身份区分预览,避免同路径重写复用旧 previewKey 导致沙箱不刷新。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 00:54:15 +08:00
董宏凯andCursor 69e455274a fix(frontend): 岗位会商沙箱在 write_file 流式阶段实时打开并刷新
content 先于 path 到达时用临时文件名开沙箱,流式快照改走外部 store 避免整页重渲染卡顿。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 00:51:38 +08:00
董宏凯andCursor e939dc4548 feat(frontend): 岗位会商页面布局与意图理解交互优化
完善 PositionRoundtable 样式与输入组件,补充 SVG 资源,并同步 Step1 意图相关逻辑。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 21:52:54 +08:00
董宏凯 1ffead7ee2 岗位会商样式修改 2026-08-02 15:33:26 +08:00
董宏凯 a0a75a9964 Merge branch 'dhk-1' into 'master'
fix: avoid MySQL thread_meta refresh races and harden roundtable bootstrap

See merge request knowledge-base-bj/deerflow-code!16
2026-07-31 13:11:29 +00:00
董宏凯 37964d1f95 代码修改 2026-07-31 21:09:54 +08:00
董宏凯andCursor a9d66536c3 fix: avoid MySQL thread_meta refresh races and harden roundtable bootstrap
Skip post-commit ORM refresh on threads_meta creates so concurrent MySQL
read/write-split deployments no longer fail with Could not refresh instance;
clean up partial roundtable threads on checkpoint failure, and ship related
position-roundtable/frontend build fixes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 21:00:56 +08:00
董宏凯 a968c3b5cd Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-code!15
2026-07-29 14:27:46 +00:00
董宏凯 e52261fc3d fix: preserve full chat embed mode navigation 2026-07-29 22:25:42 +08:00
董宏凯 4450f342d8 页面嵌套修改 2026-07-29 21:53:32 +08:00
董宏凯 213dd841b5 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-1 2026-07-28 19:18:52 +08:00
董宏凯 816c46d447 代码提交 2026-07-28 19:17:40 +08:00
g zy db857ddd4d Merge branch 'gzy_dev_new' into 'master'
fix: fix iframe agent selector width

See merge request knowledge-base-bj/deerflow-code!14
2026-07-28 03:30:12 +00:00
Rocky Kwok 9be0c6555f fix: fix iframe agent selector width 2026-07-28 11:27:47 +08:00
g zy e475c37f1d Merge branch 'gzy_dev_new' into 'master'
Gzy dev new

See merge request knowledge-base-bj/deerflow-code!13
2026-07-28 03:14:47 +00:00
Rocky Kwok d86c9d48a6 fix: remove iframe general chat entry 2026-07-28 11:12:00 +08:00
Rocky Kwok 008c9ede6e fix: preserve iframe plugin chat mode 2026-07-28 11:03:28 +08:00
董宏凯 151ecceb85 feat: 更新主题配置与系统设置 2026-07-27 21:31:09 +08:00
董宏凯 1555d5344b feat: 优化8BF业务链流程图与深色配置弹窗 2026-07-27 21:30:57 +08:00
董宏凯 bd8ec41914 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-code!12
2026-07-27 11:25:40 +00:00
董宏凯 1e21e559fb merge: 合并远端 dhk-1 最新改动 2026-07-27 19:22:59 +08:00
董宏凯 e496221dc3 Merge remote-tracking branch 'origin/master' into HEAD 2026-07-27 19:19:01 +08:00
董宏凯 5bf3955b26 代码提交 2026-07-27 19:16:12 +08:00
董宏凯 1ab3329f6d feat: 新增8BF多智能体会商页面 2026-07-27 19:00:14 +08:00
董宏凯 e70bb4aa6f feat: 新增8BF多智能体会商页面 2026-07-27 18:59:42 +08:00
g zy b22d0200c3 Merge branch 'gzy_dev_new' into 'master'
fix(frontend): preserve iframe theme across login

See merge request knowledge-base-bj/deerflow-code!11
2026-07-27 02:16:32 +00:00
Rocky Kwok fb73ae0471 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into gzy_dev_new 2026-07-27 10:06:33 +08:00
Rocky Kwok 75aad4eef6 fix(frontend): preserve iframe theme across login
The iframe login used a fixed queryless redirect and called setTheme, which both dropped the iframe theme and persisted it into the normal site's shared theme storage.
2026-07-27 09:54:22 +08:00
董宏凯 cec2996861 Merge branch 'dhk-1' into 'master'
feat(沙箱): md 产物支持 AI 写作编辑与划词改写

See merge request knowledge-base-bj/deerflow-code!9
2026-07-26 13:20:20 +00:00
fengxiangdebaozi 239b798c5d Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-1
# Conflicts:
#	frontend-web/src/components/workspace/workspace-nav-menu.tsx
#	offline-backend-20260512/backend/app/gateway/routers/multi_agent.py
2026-07-26 20:55:50 +08:00
董宏凯 f1e53ef5c0 功能:完善自定义主题与独立登录会话 2026-07-26 18:19:50 +08:00
g zy a368037e81 Merge branch 'gzy_dev_new' into 'master'
fix:iframe切换颜色

See merge request knowledge-base-bj/deerflow-code!8
2026-07-26 09:10:27 +00:00
Rocky Kwok 59f2f56124 fix:iframe切换颜色 2026-07-26 17:01:09 +08:00
董宏凯 3779bb69ef fix: load model keys from environment 2026-07-26 13:08:09 +08:00
董宏凯 25153dbd84 代码修改 2026-07-24 14:12:42 +08:00
董宏凯 91ba47bf47 代码提交 2026-07-24 11:24:11 +08:00
董宏凯 28bf1ac7b2 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-1
# Conflicts:
#	frontend-web/src/position-roundtable/components/PositionBuiltinAgentChat.tsx
#	frontend-web/src/position-roundtable/components/PositionNodeChat.tsx
2026-07-24 10:41:38 +08:00
董宏凯 45df500a9c 代码提交 2026-07-24 10:33:28 +08:00
fengxiangdebaozi f32de510fe 代码泰囧 2026-07-23 16:27:35 +08:00
fengxiangdebaozi 21722b9f5a 代码提交 2026-07-23 16:03:34 +08:00
董宏凯 f49def09ea 代码修改 2026-07-23 16:00:39 +08:00
董宏凯 4948a80c56 代码提交 2026-07-23 15:53:43 +08:00
董宏凯 7d249a81ce Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-1
# Conflicts:
#	frontend-web/src/position-roundtable/components/PositionBuiltinAgentChat.tsx
#	frontend-web/src/position-roundtable/components/PositionNodeChat.tsx
2026-07-23 15:11:43 +08:00
董宏凯 1d07025f74 代码修改 2026-07-23 15:08:00 +08:00
fengxiangdebaozi 91c5d43c48 代码提交 2026-07-23 15:07:23 +08:00
董宏凯 b60d9ed09e 代码修改 2026-07-23 14:29:12 +08:00
董宏凯 56740ecf56 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-1 2026-07-23 12:38:52 +08:00
董宏凯 9f788e37de 样式修改 2026-07-23 12:38:48 +08:00
fengxiangdebaozi 0634337858 feat: 支持登录隐藏壳层和路由跳转参数 2026-07-23 11:16:11 +08:00
董宏凯 08ce3dda73 merge: integrate dhk-dev into dhk-1 2026-07-23 10:38:48 +08:00
董宏凯 c8f69781e4 样式修改 2026-07-23 10:10:47 +08:00
董宏凯 13bfa719ee feat: refine position roundtable workflow 2026-07-22 22:22:38 +08:00
董宏凯 359bd28f2c fix: polish position roundtable artifact preview 2026-07-22 18:41:46 +08:00
fengxiangdebaozi 7bd032ec77 feat: 支持岗位会商任务和意图编辑 2026-07-22 17:44:34 +08:00
董宏凯 790267ac43 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-1
# Conflicts:
#	frontend-web/src/position-roundtable/pages/PositionRoundtablePage.tsx
2026-07-22 17:02:07 +08:00
董宏凯 d9844e0180 打开沙箱错误修改 2026-07-22 16:53:56 +08:00
fengxiangdebaozi 6ade3b69b9 feat: refine position roundtable workflow 2026-07-22 16:53:10 +08:00
董宏凯 ae184f434d Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-1 2026-07-22 15:43:13 +08:00
董宏凯 055523bf33 代码修改 2026-07-22 15:43:06 +08:00
fengxiangdebaozi 866bc0f8d8 样式修改 2026-07-22 15:42:29 +08:00
fengxiangdebaozi 1bc203b5cd 岗位会商 2026-07-22 15:40:00 +08:00
fengxiangdebaozi 1cd99a5a90 feat(position-roundtable): add delivery rejection workflow 2026-07-21 20:16:52 +08:00
fengxiangdebaozi 2ca8a23102 feat(position-roundtable): add delivery workflow scaffolding 2026-07-21 19:48:39 +08:00
fengxiangdebaozi 97ce19973d docs(position-roundtable): plan delivery workflow 2026-07-21 19:31:08 +08:00
fengxiangdebaozi 783774d3f3 fix(position-roundtable): align header controls 2026-07-21 19:30:55 +08:00
fengxiangdebaozi 85e119db08 feat(position-roundtable): add standalone position collaboration 2026-07-21 17:50:24 +08:00
吉鑫升 5436719bfb Merge branch 'master-dev' into 'master' 2026-07-21 14:47:46 +08:00
吉鑫升 e571caaf2c fix: keep offline start script minimal 2026-07-21 14:46:58 +08:00
吉鑫升 5d2997b6a0 fix: preserve offline deployment LF files 2026-07-21 14:39:57 +08:00
吉鑫升 f8cb7be18c chore: add offline backend wheelhouse deployment 2026-07-21 14:35:06 +08:00
董宏凯 b93b82fcaf Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-1 2026-07-21 11:00:19 +08:00
董宏凯 d0b4832ed7 代码提交 2026-07-21 10:58:56 +08:00
fengxiangdebaozi 4ffd5a3c94 feat(frontend): add position roundtable workspace 2026-07-20 20:41:37 +08:00
董宏凯 2d6992d656 feat(frontend): adapt TDesign themes 2026-07-20 20:10:22 +08:00
董宏凯 bb7291a97c Merge branch 'dhk-1' into 'master'
feat: 支持深色主题顶栏 Logo 位置配置

See merge request knowledge-base-bj/deerflow-code!5
2026-07-17 13:08:45 +00:00
fengxiangdebaozi a699545c4c feat: 支持深色主题顶栏 Logo 位置配置 2026-07-17 21:07:48 +08:00
董宏凯 2c331aa744 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-code!4
2026-07-16 14:45:42 +00:00
fengxiangdebaozi 82dd9fb08f feat: 支持主题系统Logo与欢迎页开关 2026-07-16 22:31:22 +08:00
fengxiangdebaozi b97aa77adc fix: 会商界面适配字号设置 2026-07-16 16:26:43 +08:00
fengxiangdebaozi d7d101814f fix: 修复深色导航与会商悬浮样式 2026-07-16 11:21:52 +08:00
董宏凯 871d98e6f2 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-code!3
2026-07-16 01:57:37 +00:00
fengxiangdebaozi 3cd093a8a2 地址修改 2026-07-16 09:56:54 +08:00
fengxiangdebaozi 4a59da7ff0 fix: 优化侧栏并接入品牌脱敏 2026-07-16 09:48:40 +08:00
董宏凯 d7ad0624b7 代码提交 2026-07-15 16:13:03 +08:00
董宏凯 27e6b0b23e Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into dhk-dev
# Conflicts:
#	frontend-web/src/open-canvas/components/ai-writing/AIWritingForm.tsx
2026-07-11 19:01:10 +08:00
董宏凯 55b5c2cc9f 代码部署说明 2026-07-11 18:58:16 +08:00
董宏凯 d5d5199f6d Merge branch 'dhk-1' into 'master'
代码合并

See merge request knowledge-base-bj/deerflow-code!2
2026-07-11 10:16:38 +00:00
fengxiangdebaozi 0bd0ac41cd 代码合并 2026-07-11 18:16:08 +08:00
董宏凯 b1c396717b Merge branch 'dhk-1' into 'master'
feat(message-token-usage): 速度条下方常驻颜色含义图例

See merge request knowledge-base-bj/deerflow-code!1
2026-07-11 10:12:52 +00:00
fengxiangdebaozi 388a9133fc fix: adapt frontend for legacy Chrome and runtime config 2026-07-11 16:55:08 +08:00
董宏凯 221e947488 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-dev
# Conflicts:
#	frontend-web/src/open-canvas/components/ai-writing/AIWritingForm.tsx
#	frontend-web/src/open-canvas/components/ai-writing/AIWritingPanel.tsx
#	offline-backend-20260512/backend/CLAUDE.md
#	offline-backend-20260512/backend/app/gateway/services.py
#	offline-backend-20260512/backend/tests/test_ai_writing_knowledge_base.py
2026-07-03 22:28:21 +08:00
董宏凯 a1c63a1fe5 代码提交 2026-07-03 22:11:50 +08:00
吉鑫升 db2f21191c fix(frontend): handle clipboard fallback and markdown word export 2026-07-03 16:54:16 +08:00
董宏凯 195ef3ee40 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!169
2026-07-03 08:37:06 +00:00
fengxiangdebaozi f3511e5cd0 样式修改 2026-07-03 16:35:52 +08:00
fengxiangdebaozi 96947d7636 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-07-03 14:56:49 +08:00
fengxiangdebaozi 034a379ecd 技能提交 2026-07-03 14:56:35 +08:00
董宏凯 da856f2b58 fix: improve ai writing chat streaming and intent handling 2026-07-02 17:43:23 +08:00
董宏凯 845c87e3ee feat: add AI writing chat workspace 2026-07-02 13:56:46 +08:00
董宏凯 7d9c0894f8 fix: limit roundtable chain rail height 2026-07-02 11:17:52 +08:00
吉鑫升 ae30a20739 Merge remote-tracking branch 'origin/master' into ji 2026-07-02 11:15:06 +08:00
吉鑫升 7e7d3c9846 fix: truncate rwfx 3q context 2026-07-02 11:05:12 +08:00
吉鑫升 daff70c34f fix: include rwfx 3q status in context 2026-07-02 10:43:16 +08:00
董宏凯 94188db9ea Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!168
2026-07-02 02:15:43 +00:00
董宏凯 b12497898a fix: polish roundtable chain rail toggle 2026-07-02 10:14:40 +08:00
董宏凯 3e51208024 feat: add roundtable chain rail scroll 2026-07-02 10:06:24 +08:00
吉鑫升 36a3851233 feat: inject 3q context into rwfx chat 2026-07-02 10:03:34 +08:00
董宏凯 54190d7a83 提交代码 2026-07-01 19:24:23 +08:00
fengxiangdebaozi 2215ec3c49 feat: add user-assisted xdfx skill flow 2026-07-01 19:21:18 +08:00
董宏凯 d21dbeb214 feat: refine ai writing search flow 2026-07-01 18:00:14 +08:00
董宏凯 ba0c32dcee Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!167
2026-07-01 09:51:15 +00:00
fengxiangdebaozi f5efe9b041 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-07-01 17:50:33 +08:00
fengxiangdebaozi a4a44e1154 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-07-01 17:50:06 +08:00
fengxiangdebaozi cef08638af 技能修改 2026-07-01 17:49:51 +08:00
董宏凯 025e43f4c5 feat: improve ai writing imitation flow 2026-07-01 17:16:12 +08:00
董宏凯 fa04ab8b5a fix: filter position-granted agent favorites 2026-07-01 14:51:14 +08:00
董宏凯 f3e5a3bb35 fix: prevent notebook writing redirect to agent chat 2026-07-01 14:48:40 +08:00
董宏凯 0547fb1715 提交 2026-07-01 11:22:26 +08:00
董宏凯 bb6b9bd84b feat: add ai writing imitation mode 2026-07-01 11:21:41 +08:00
g zy f485d4fff3 Merge branch 'gzy' into 'master-dev'
fix: 注释插件管理

See merge request knowledge-base-bj/deerflow-server!166
2026-07-01 02:25:19 +00:00
董宏凯 4bfaeb728b fix: disable ssl verification for intranet ai writing search 2026-07-01 10:21:52 +08:00
Rocky Kwok 2b0ba2a68b fix: 注释插件管理 2026-07-01 10:08:46 +08:00
董宏凯 c8cdd1d0b2 Merge branch 'dhk-1' into 'master'
统一外部 access_token 存储与轻应用 URL 拼接,修复嵌入会话鉴权隔离。

See merge request knowledge-base-bj/deerflow-server!165
2026-06-30 11:21:42 +00:00
董宏凯 8fbfd35296 Add scheduled HTML templates no19-no27 2026-06-30 19:18:48 +08:00
董宏凯 dfb745a5e4 代码提交 2026-06-30 16:04:51 +08:00
吉鑫升 c23350f17b fix: isolate user concurrency from internal agent runs 2026-06-30 14:56:29 +08:00
吉鑫升 124eb04a6b Merge remote-tracking branch 'origin/master-dev' into ji-dev 2026-06-30 11:34:45 +08:00
吉鑫升 b4206d6421 Add Redis-backed concurrency gate 2026-06-30 11:25:44 +08:00
董宏凯andCursor 537e2e4d06 fix(登录): token 登录补全 userInfo + 全方式打印路由参数
- 把「拉外部用户信息(yUserId→consumer)」与登录鉴权方式解耦:只要 URL 带
  yUserId 就填充 userInfo(含 token 登录,consumer 失败非致命),修复 token
  登录后 userInfo 残缺、iframe/轻应用拿不到 yUserId/userName/gateDepartName/
  typeName/accessToken 的问题。
- token 登录用 auth.username 写入正确用户名(不覆盖 consumer 已落的 userName)。
- 保留 yUserId 优先级(onlineTicket/toolToken 仅在无 yUserId 时启用)。
- 新增登录路由参数 + 落地结果日志(令牌脱敏),方便排查各登录方式取值问题。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 23:36:33 +08:00
董宏凯andCursor 9268c73776 feat(沙箱): md 产物支持 AI 写作编辑与划词改写
- 新增 MarkdownAiEditor,复用 AI 写作的 TipTap 编辑器与 AI 改写流程

- 沙箱 md 增加 AI 写作视图切换,默认仍为预览;单文件隐藏文件名避免工具栏错位

- 单智能体聊天页开启 allowVirtualMarkdownEdit,生成完成后可编辑

- 会商总结页续看时自动收起研讨原料侧栏

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 23:08:55 +08:00
fengxiangdebaozi 6378cd33bd 统一外部 access_token 存储与轻应用 URL 拼接,修复嵌入会话鉴权隔离。
将 access_token 纳入 scoped storage 迁移,yUserId 登录优先并独立持久化 token;轻应用/按钮管理默认改用 access_token 参数名,支持 hash 路由占位符替换与自动追加。
2026-06-29 23:00:31 +08:00
fengxiangdebaozi 8c6d08d6bf Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-29 18:08:37 +08:00
fengxiangdebaozi 29082b349d 技能修改 2026-06-29 18:08:09 +08:00
Administrator 7d8656bfde fix xdfx task start context recovery 2026-06-29 17:45:46 +08:00
fengxiangdebaozi 45ce14e15a Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-29 17:39:52 +08:00
g zy 8947223255 Merge branch 'gzy' into 'master-dev'
fix: iframe底部选择智能体

See merge request knowledge-base-bj/deerflow-server!164
2026-06-29 09:36:11 +00:00
Rocky Kwok 5a420189b1 fix: iframe底部选择智能体 2026-06-29 17:35:36 +08:00
g zy 17650afe96 Merge branch 'revert-f22a6a99' into 'master'
Revert "Merge branch 'revert-d8af6c8f' into 'master'"

See merge request knowledge-base-bj/deerflow-server!163
2026-06-29 09:19:24 +00:00
g zy 80fce34c1a Revert "Merge branch 'revert-d8af6c8f' into 'master'"
This reverts merge request !158
2026-06-29 09:19:17 +00:00
g zy ae31c50424 Merge branch 'gzy' into 'master-dev'
Gzy

See merge request knowledge-base-bj/deerflow-server!162
2026-06-29 09:14:43 +00:00
Rocky Kwok 794aab1007 fix: recode 2026-06-29 17:14:01 +08:00
Rocky Kwok be06cac223 fix: reset code 2026-06-29 17:12:18 +08:00
Administrator b0db8cc3d8 feat: 优化定时任务 Markdown 阅读页 2026-06-29 17:08:38 +08:00
g zy 0dab5a8121 Merge branch 'gzy' into 'master-dev'
fix: chore

See merge request knowledge-base-bj/deerflow-server!161
2026-06-29 09:05:30 +00:00
Rocky Kwok c012146c18 fix: chore 2026-06-29 17:04:50 +08:00
fengxiangdebaozi 6851c96a45 技能提交 2026-06-29 16:59:23 +08:00
g zy f75f4f9db1 Merge branch 'gzy' into 'master-dev'
feat: iframe增加智能体显示

See merge request knowledge-base-bj/deerflow-server!159
2026-06-29 08:47:03 +00:00
g zy f22a6a9957 Merge branch 'revert-d8af6c8f' into 'master'
Revert "Merge branch 'gzy' into 'master'"

See merge request knowledge-base-bj/deerflow-server!158
2026-06-29 08:45:40 +00:00
fengxiangdebaozi 210cb5117f fix: polish compact workspace controls 2026-06-29 16:44:13 +08:00
Administrator 0c663f5f7c Merge remote-tracking branch 'origin/master' into ji-dev 2026-06-29 16:43:45 +08:00
g zy 75e8a90ac7 Revert "Merge branch 'gzy' into 'master'"
This reverts merge request !157
2026-06-29 08:43:19 +00:00
g zy d8af6c8f48 Merge branch 'gzy' into 'master'
feat: iframe增加智能体显示

See merge request knowledge-base-bj/deerflow-server!157
2026-06-29 08:43:11 +00:00
Rocky Kwok 1ab4216ccb feat: iframe增加智能体显示 2026-06-29 16:42:38 +08:00
Administrator d39b58255d 并发版 2026-06-29 16:09:51 +08:00
Administrator cd2ca406a5 Merge branch 'master-dev' into ji-dev 2026-06-29 15:12:24 +08:00
Administrator 637be00946 feat: improve agent skill selection 2026-06-29 15:09:27 +08:00
Administrator 0dd93421c4 feat: enhance public task markdown preview 2026-06-29 14:42:47 +08:00
Administrator e27321cb23 feat: enhance public task markdown preview 2026-06-29 14:40:26 +08:00
g zy 6157b42f5a Merge branch 'gzy' into 'master'
Gzy

See merge request knowledge-base-bj/deerflow-server!156
2026-06-29 06:33:12 +00:00
Rocky Kwok be4b180d92 fix: 智能体对应 2026-06-29 14:31:55 +08:00
Rocky Kwok e9e4c181b9 feat: 插件管理及域名和智能体对应 2026-06-29 14:31:40 +08:00
fengxiangdebaozi eb61b332a2 Add XDFX skill data artifacts 2026-06-29 10:25:36 +08:00
fengxiangdebaozi 4fce6f9104 Add intranet retrieval diagnostics for AI writing 2026-06-29 10:21:10 +08:00
fengxiangdebaozi bcd656fb49 代码提交 2026-06-28 18:50:59 +08:00
Administrator 2d3033434b Fix async thread title generation flow 2026-06-28 18:09:48 +08:00
Administrator d522498cc9 ji 2026-06-28 00:23:01 +08:00
fengxiangdebaozi 65449ffd71 merge dhk-1 yuser login cache 2026-06-27 19:58:57 +08:00
fengxiangdebaozi 006c5bc4c1 fix: cache yuser login info by user id 2026-06-27 19:57:06 +08:00
Administrator a046d19ce1 fix: improve model concurrency limiting 2026-06-27 18:57:01 +08:00
Administrator aca089e8ef feat: add per-model concurrency limits 2026-06-27 18:57:01 +08:00
董宏凯 24eb629773 Merge branch 'dhk-1' into 'master'
feat(ai写作): 历史记录可继续未完成的会话(从checkpoint续跑)

See merge request knowledge-base-bj/deerflow-server!155
2026-06-27 09:31:57 +00:00
fengxiangdebaozi 1847eb9d6a fix(auth): normalize external accessToken and preserve on empty yUser login 2026-06-27 17:29:52 +08:00
董宏凯 44d7304f8e Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-27 16:00:47 +08:00
董宏凯andCursor 5de74e90dc feat(ai写作): 左栏智能体 Tab 内嵌问答并优化模块侧栏
AI 写作页默认展示智能体 Tab,在页内复用 ai-writing 模块配置与 AgentChatPage;确认类型后侧栏扁平展示类型名并支持整块收起动画。同步历史回看、流式续跑、改写菜单与 researcher 检索相关改动。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-27 15:53:51 +08:00
Administrator 6fdca41a1d Merge branch 'ji' into master 2026-06-27 15:13:45 +08:00
Administrator c978a25b7f Fix 3qfx task context fallback 2026-06-27 15:12:28 +08:00
董宏凯andClaude Opus 4.8 c11307aa67 feat(ai写作): 历史记录可继续未完成的会话(从checkpoint续跑)
历史列表里 in_progress/draft_ready/review_ready 记录加绿色▶️「继续未完成」按钮
(点标题亦可);done/error/background 不可继续。多 worker 安全——与4个确认卡同机制,
全基于共享 checkpoint(gateway GET /threads/{id}/state + /history 读,任意 worker)。

链路:continueWriting(sessionId) → closeHistory + 设活跃 sessionId → useStream
fetchStateHistory 拉该 thread checkpoint 进 stream.values → host rehydrate effect
(continueTargetRef 守卫,每 thread 一次)用 buildRehydrateSnapshot 重建已完成阶段;
status=awaiting_* → 显示确认卡等用户操作,否则 submit({command:{}}) 从 checkpoint
续跑当前阶段。重新加回 buildRehydrateSnapshot + rehydrate action。

入口在侧栏 WritingHistoryItem。刷新=重置不受影响(这是显式点击,非自动重连)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 13:12:47 +08:00
吉鑫升 199269712f Merge branch 'ji' into master
账号级登录口令(白名单管理页设明文口令,凭 /login/<用户名>?password= 直登)。
2026-06-27 11:19:58 +08:00
吉鑫升andClaude Opus 4.8 9572b66ecb feat(白名单): 账号级登录口令——管理员设明文口令,用户凭 /login/<用户名>?password= 直登
白名单管理页可给单个账号设明文登录口令(users.login_password,可空):
设置后该账号用户名直登(/login/username)须带匹配 ?password=,且优先于全局共享口令门;
未设口令的账号行为不变。前端登录 URL 已支持透传 ?password=,无需改登录页。

- 后端:UserRow/User 新增 login_password + 仓储映射;/login/username 账号级口令闸门
  (_lookup_user_by_username 仅查不建);新管理员接口 PUT /users/{id}/login-password;
  UserListItem 暴露明文(仅 admin 列表);migration 20260625_04 + 幂等补列 SQL。
- 前端:白名单页新增「登录口令」列(设置/修改/清除 + 复制登录链接);
  core/auth api+hooks 增 setUserLoginPassword/useSetUserLoginPassword(含 Y-Log)。
- 文档:根 + 后端 CLAUDE.md 同步。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 11:03:39 +08:00
董宏凯 45315f18d2 Merge branch 'dhk-1' into 'master'
fix(ai写作): 恢复内网直连检索(知识库检索)空地址回退默认端点

See merge request knowledge-base-bj/deerflow-server!154
2026-06-26 16:02:52 +00:00
董宏凯andClaude Opus 4.8 e889cc25cf fix(ai写作): 历史记录 in_progress 不再误显示「进行中」转圈
刷新=重置后,开始过但没跑完的会话 DB status 永远停在 in_progress、且无任何活进程,
历史列表却转圈显示「进行中」,误导用户以为还在运行。改为中性、不转圈的「未完成」
(text-slate-400)。真正在跑的 background(后台挂起,有 executor 驱动)保留「挂起中」转圈。
改 WRITING_STATUS_PILL(侧栏列表) + STATUS_LABELS(下拉)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 00:01:32 +08:00
董宏凯andClaude Opus 4.8 8385d1913a fix(ai写作): 继续从checkpoint续跑(修resume_is_map) + 刷新=重置不重连
后端 worker(runtime/runs/worker.py): 空 command(无 resume/update/goto)不再构造
Command()(会因无挂起 interrupt 抛 'resume_is_map' 未绑定错误),改为 astream(None)
让 Pregel 续跑 checkpoint 里挂起的当前阶段节点。有 resume/update/goto 时(4个干预卡)
仍走 Command,行为不变。前端"继续"发空 command:{} 即从当前阶段续跑、不回 intent。

按用户要求把"断网/刷新自动重连续跑"整套移除(刷新=重置即可):
- 删 sessionStorage 持久化 + reconnectTargetRef + 恢复/持久化 effect + host rehydrate
- 删 buildRehydrateSnapshot/rehydrate action(保留 clear_streaming)
- 提交去掉 onDisconnect:'continue'/streamResumable;reconnectOnMount 改 false
- 卸载不再自动后台挂起;刷新断 SSE 后端默认 cancel 取消 run,页面回 idle

手动暂停/继续保留:暂停=stream.stop(),继续=clear_streaming+空command 从checkpoint续。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 23:44:37 +08:00
董宏凯andClaude Opus 4.8 9f462beec5 fix(ai写作): 继续(暂停后)从checkpoint续跑而非从头重跑意图
根因:resumeWriting 的 stream.submit(undefined) 没带 command。后端 worker
(runtime/runs/worker.py:283) 只有收到 command 才翻成 Command() 让 Pregel 从最近
checkpoint 恢复;不带 command 时按 graph_input 起新一轮=从图入口 intent_parser
重跑,于是"规划大纲/检索素材时暂停后继续又从识别意图开始"。

修复:继续时带空 command:{},走 Command 恢复路径(与4个干预卡续跑同机制),
Pregel 从 checkpoint 续跑当前未完成阶段(已完成阶段不丢),不再重跑 intent。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 23:31:48 +08:00
董宏凯andClaude Opus 4.8 4f0c75e76e feat(ai写作): 暂停/继续 + 断网刷新后自动重连续跑
需求:写作任一活跃阶段(素材搜集/大纲/写作/审核中)断网也能继续。

断网续跑(纯前端,后端无需改):
- 所有 stream.submit 加 onDisconnect:'continue'(断开后端不取消 run,继续跑到
  下一个确认点等待);不开 streamResumable(避免与 rehydrate 重复累积时间线)
- 活跃 sessionId 存 sessionStorage,刷新后渲染期同步恢复 → threadId 首帧即交给
  useStream(reconnectOnMount) 重连该 run
- 重连后用 graph values 快照 buildRehydrateSnapshot 重建 reducer(rehydrate
  action),素材/大纲/草稿/审核/时间线立刻回显;currentPause 由 interrupt effect 设
- 去掉卸载时"自动后台挂起跑完"(会自动替用户确认),改为自然续跑等待;显式后台挂起按钮保留

手动暂停/继续:
- ENABLE_PAUSE_RESUME_UI 开启;暂停=stream.stop()(已完成阶段已落 checkpoint),
  继续=clear_streaming 后从 checkpoint 重新 submit 续跑(重跑当前阶段,已完成不丢)
- 按钮"停止"→"暂停"(Pause 图标)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 23:20:48 +08:00
董宏凯andClaude Opus 4.8 2097587b42 feat(ai写作): 左侧研究栏加历史记录列表(参考会商样式)+侧栏可收起
- ResearchSidebar 底部新增「历史记录」列表,跟随侧栏自然滚动;样式对齐
  多智能体会商 HistoryDropdown(圆角卡片+divide-y+状态药丸+打开/改名/删除)
- 点历史记录在右侧区域显示历史回看,左侧栏保留(showSidebar 含历史态)
- 侧栏顶部加「收起」按钮,收起为细窄展开条(页面承载 sidebarCollapsed)
- 「挂起中」记录点击经 window 事件 ai-writing:show-progress 打开进度流程图弹窗

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 22:54:10 +08:00
董宏凯 53af352ce8 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-26 22:14:31 +08:00
董宏凯andClaude Opus 4.8 0089af94d3 fix(ai写作): 恢复内网直连检索(知识库检索)空地址回退默认端点
knowledge_base 检索类型遇到空 intranet_search_url 会短路报「未配置」、返回 0
素材,导致「内网直连检索不能用」。旧版 get_search_provider(search_provider=
intranet) 在空地址时由 IntranetSearchProvider 回退内置默认内网端点,所以不配
地址也能直连。本次去掉该短路,空地址原样下传由 provider 回退默认端点,恢复旧逻辑。

- researcher.py: knowledge_base 分支无条件构造 IntranetSearchProvider
- test_ai_writing_knowledge_base.py: 空地址用例改为断言回退默认端点仍出素材
- backend CLAUDE.md: 检索类型段说明更新

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 22:13:19 +08:00
吉鑫升 26ab6f663c Merge branch 'ji' into master
完善并发监控图表(整数刻度Y轴 + 图例 + 说明)
2026-06-26 21:23:40 +08:00
吉鑫升andClaude Opus 4.8 bce0abba6e fix(监控): 完善并发监控图表——整数刻度Y轴 + 图例 + 说明
- 修复并发量图左轴出现「0 0 0 1 1」重复刻度:值很小时改用整数刻度(nice
  ticks,0/1/2…无重复),并修正按 axisMax 归一
- 每张图加图例(带当前读数)+ 一句中文说明,讲清每条线含义:
  并发量=峰值(红)/平均(橙);出字速度=平均(蓝)/最慢(紫)
- 修复两张图共用同一个 SVG 渐变 id 导致的颜色串用(改 useId 唯一化)
- 空数据态更友好(虚线占位 + 引导开启采样)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 21:23:08 +08:00
董宏凯 c732fd75e4 Merge branch 'dhk-1' into 'master'
feat(定时任务): 新增 9 个 HTML 模板,下拉补齐为 no.1~no.18(只展示)

See merge request knowledge-base-bj/deerflow-server!153
2026-06-26 12:51:31 +00:00
董宏凯 89232d7521 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-26 20:50:47 +08:00
吉鑫升 9ef8b1990e Merge branch 'ji' into master
实时并发监控 + 真正停止对话 + 409 中文化(管理员排行榜)
2026-06-26 20:40:56 +08:00
吉鑫升andClaude Opus 4.8 26f8010a57 feat(监控): 管理员排行榜实时并发监控 + 真正停止对话 + 409 中文化
- 排行榜页顶部新增「实时并发监控」面板(admin-only):当前并发大模型调用数 +
  调用列表(用户/智能体/类型/已运行时长),每行「停止」+「全部停止」经
  RunManager.cancel 真正中断 LLM 流式调用,减轻大模型压力
- 并发量折线图(峰值/均值,按分钟/小时):新增轻量后台采样器写入新表
  concurrency_samples(create_all 自动建表),可按分/时聚合
- 大模型出字速度折线图(tokens/秒,按分钟/小时):复用 llm_call_metrics 聚合,
  便于定位是模型/供应商慢
- 后台采样可开关、默认关闭(opt-in)、运行时切换免重启、对线上零影响
  (单条极小 INSERT、保留期清理、查询有上限、全程 best-effort)
- 409 中文化:上一轮未结束又发新问题时返回中文提示,前端 onError 友好映射

后端:runtime/runs/manager.py(list_active)、persistence/concurrency(新模块)、
config/system_settings(ConcurrencyMonitorSettings)、gateway/routers/admin_active_runs、
app.py(采样后台任务)、services.py(409)。前端:core/admin/{active-runs,hooks}、
components/workspace/admin/concurrency-monitor、AdminUserLeaderboardPage、threads/hooks。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 20:29:26 +08:00
董宏凯andClaude Opus 4.8 abf97cdc78 feat(大屏绘制): 战情大屏隐藏顶部标题区,只保留导航 Tab
DashboardApp 顶部 Header(标题+副标题+生成时间)在 usingPages 模式下整块隐藏,
dashboard-agent 战情大屏直接从导航 Tab 起;会商 Step3 大屏行为不变。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 14:36:29 +08:00
fengxiangdebaozi 4d10590511 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-26 11:04:19 +08:00
fengxiangdebaoziandClaude Opus 4.8 3d60651491 feat(ai-writing): 检索类型加回「知识库检索」(直连内网 ES 接口)
弱模型常识别不了配置技能(deepseek-chat 等),恢复旧的"不用技能"检索路径
作为独立检索类型 knowledge_base:绕过技能编排,直接调
ai_writing.intranet_search_url 内网知识库 ES 接口(IntranetSearchProvider)
对检索词并发检索;未配地址 → 无素材 + skill_error 告警。

- researcher.py: material_source 归一保留 knowledge_base + 新增直连内网分支
- state.py: material_source 三值注释
- 前端 AIWritingForm/WritingFormContext/types: 下拉新增「知识库检索」
- tests/test_ai_writing_knowledge_base.py: 直连/未配/不编排技能 3 用例
- backend CLAUDE.md: 检索类型段更新为三值

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 10:04:57 +08:00
董宏凯andClaude Opus 4.8 a400989f64 feat(定时任务): 新增 9 个 HTML 模板,下拉补齐为 no.1~no.18(只展示)
- 从 zt-0625 加入 no.8/no.9/no.10/no.11/no.14/no.15/no.16/no.17/no.18
- 新 no.8/no.9 的 id 用 no8b/no9b(no8/no9 已被显示名 no.12/no.13 的模板占用)
- 重排 TEMPLATES 使下拉按显示名升序 no.1→no.18;均 convertible=False 只展示
- 测试覆盖全部 id 存在、显示名覆盖 1~18、各模板文件可读为完整 HTML

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 09:55:34 +08:00
董宏凯 2a1f50f726 Merge branch 'ji' into 'master'
fix(ai写作): 弱模型也能真正执行技能脚本(执行优先的强提示)

See merge request knowledge-base-bj/deerflow-server!152
2026-06-25 15:00:57 +00:00
fengxiangdebaoziandClaude Opus 4.8 158d157af4 feat(ai写作): 内网检索接口执行诊断写入 material_package.intranet_debug(排查用)
- material_package 新增 intranet_debug:是否配置/端点/知识库/超时/每个检索词命中数与
  报错/原始响应片段/总命中数/是否被采用为兜底/status(not_configured|pending|ran|
  cancelled|crashed)。随 values 事件回前端,前端忽略该字段,仅供 devtools 排查。
- 新增 config ai_writing.intranet_search_debug(默认 false):开启后即使技能成功也跑完
  内网并记录完整结果,用于验证内网接口是否真能通。
- 前端不改动。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 22:55:27 +08:00
fengxiangdebaoziandClaude Opus 4.8 1ed004fbb1 fix(ai写作): 弱模型也能真正执行技能脚本(执行优先的强提示)
弱模型在 lead agent 能执行 py 脚本、在 ai写作子智能体却不能:根因是子智能体的
_MATERIAL_OUTPUT_CONTRACT 过度强调"只输出 JSON",弱模型据此跳过工具执行直接吐空 JSON。
对齐 lead agent 的 skill_system 强框架,把契约改成"执行优先":

- 第一步强制先用 bash 实际运行技能脚本(给出 cd 技能目录 && python3 scripts/..py 的命令形态),
  严禁不调用工具就直接输出 JSON/凭记忆编造
- JSON 输出降级为第二步"检索完成后再整理"
- task 末尾追加"现在立刻开始执行检索"的强指令,进一步推动弱模型先动手

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 22:50:10 +08:00
吉鑫升 38f98cdf5c Merge branch 'ji' into master
# Conflicts:
#	offline-backend-20260512/backend/scripts/sql/column_additions_mysql.sql
2026-06-25 21:49:12 +08:00
吉鑫升andClaude Opus 4.8 a417124c21 feat(auth): 登录白名单细化为黑名单模式(approved 默认放行)+ 同步构建产物
- approved 放行标记默认 True:新账号首次登录即放行,登录白名单开关打开时只拦截
  被管理员显式「取消放行」(approved=False) 的用户;enforce_user_approved 放在
  各登录端点拿到 user 后、签发 JWT 前调用,admin 永远放行。
- 同步调整 LoginWhitelistPage / local_provider / models / system_settings /
  迁移 20260625_02 / user model / column_additions_mysql.sql 与 CLAUDE.md。
- 更新 backend/backend.zip 构建产物。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 21:41:15 +08:00
吉鑫升andClaude Opus 4.8 f3f11461de fix(open-3qfx): 免登录建会话补 default 用户上下文,修复 thread_meta 不落库
开放接口 /api/open/3qfx/ask 免登录、无 user context,start_run 写 thread_meta
前先 thread_store.get() 默认 user_id=AUTO,resolve_user_id(AUTO) 在无 context 时
抛 RuntimeError 被 start_run 的 try/except 当「非致命」吞掉,thread_meta 行从未
创建,前端按 metadata.taskId 怎么也搜不到这条会话(run 却已建)。

- 调 start_run 前显式 set_current_user 为 default 用户桶(后台 run_agent task
  在 create_task 时快照此 context,故后台运行也归属 default,符合任务深链对话
  全局共享、按创建者解析文件的语义),thread_meta 正常落库。
- 把 cop_task_detail_* 配置补到实际加载的 offline-backend-20260512/config.yaml
  (此前只加在不生效的 backend/config.yaml)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 21:40:57 +08:00
董宏凯 2e79cee24a Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!151
2026-06-25 13:30:25 +00:00
fengxiangdebaozi 1fd997303e Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-25 21:29:14 +08:00
吉鑫升 cc017a22c7 Merge branch 'ji' into master 2026-06-25 20:38:33 +08:00
AdministratorandClaude Opus 4.8 5f01e8dd03 feat(message-token-usage): 速度条图例按当前速度只显示对应颜色
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 20:29:26 +08:00
fengxiangdebaozi ce69905950 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-25 19:54:58 +08:00
fengxiangdebaozi 71e7b9dd63 代码提交 2026-06-25 19:54:37 +08:00
吉鑫升andClaude Opus 4.8 58357547c9 Merge branch 'ji' into master
按钮管理「登录参数」两套实现冲突解决——两分支各自独立给跳转按钮加了登录态追加能力,
二者正交、保留两套,互不影响:
- master: login_params (JSON 列 login_params_json,从 userInfo 解析,类似轻应用登录参数)
- ji: append_auth + auth_token_param + auth_name_param (token 登录时追加 token1+用户名)

迁移 revision 碰撞修复(两分支都用了 20260625_01):重编号为线性链
  20260620_02 → 20260625_01 (login_params) → 20260625_02 (auth_params) → 20260625_03 (users_approved)
并同步 column_additions_mysql.sql 注释里的 migration 编号。

前后端 task_buttons(model/sql/memory/router/前端 type·api·admin 页)均保留两套字段;
两份 CLAUDE.md 文档合并为同时记录两种机制。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 19:36:43 +08:00
AdministratorandClaude Opus 4.8 fe7c6cb8f7 feat(open-3qfx): 开放接口按 taskId 直接发起 3qfx 第一次问答
新增 POST /api/open/3qfx/ask(无需登录,/api/open/ 白名单 + CSRF 豁免):
只传一个 taskId,后端解析 3Q 业务配置的智能体 + 按 id 拉取 cop-task-detail
拼出与前端一致的开场白,新建带 metadata.{taskId,agent_id} 的真实会话并后台
启动持久化运行,立即返回 thread_id(随后在 3qfx 任务工作区对话列表观看)。

- start_run() 增加 keyword-only enforce_access(默认 True);开放接口传 False
  绕过按当前(无)登录用户的智能体可见性校验
- task_deeplink 配置新增 cop_task_detail_url / _authorization / _test + mock
- tests/test_open_3qfx.py(10 项,tests/ 被 .gitignore 故未入库)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 19:19:17 +08:00
fengxiangdebaoziandClaude Opus 4.8 dc5b83e8cd Merge branch 'dhk-3': 会商第一步分析记录按业务链筛选
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 18:09:37 +08:00
fengxiangdebaoziandClaude Opus 4.8 27fffbec61 feat(会商第一步): 分析记录按业务链筛选(漏斗下拉, 选项从草稿chainTitle去重)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 18:08:36 +08:00
AdministratorandClaude Opus 4.8 d35d121261 feat(auth): 登录白名单也拦「接口问答」(已登录的 run 接口按用户放行)
开关开启时,未放行用户(非 admin)即便持旧 token,直接调发起问答的 run 接口
(/api/threads/{id}/runs[/stream|/wait]、/api/runs/{stream|wait})也返回 403,
不止拦登录。在 AuthMiddleware 解析出 user 后仅对问答 run 请求复用
enforce_user_approved;GET 列表/join/cancel/feedback 及普通浏览不受影响;
内部/渠道调用与无鉴权 /api/open/chat 不在此范围。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 17:37:47 +08:00
fengxiangdebaozi 368673c3b4 Merge branch 'dhk-1': ai写作技能检索稳定接收数据 + 内网兜底优化 2026-06-25 17:06:01 +08:00
fengxiangdebaoziandClaude Opus 4.8 854de9b43c fix(ai写作): 技能检索稳定接收数据(复用参考文献提取+截断抢救+上限早停)
- 复用主智能体「参考文献」模式的提取逻辑(deerflow.runtime.references)解析技能JSON,字段并集兼容
- bash输出中间截断时逐条抢救完整记录对象,不再因大JSON解析失败而全丢
- 所有退出路径(超时/递归上限/异常)都从tool输出收割,不依赖模型最终汇总
- 达到max_materials上限即停止驱动模型,修复步骤条爆100+条/素材超额
- 步骤条实时显示每次检索获得多少条数据
- 内网兜底:与技能并行预跑、响应解析兼容两套接口字段、0结果换简单检索词重试、超时放宽到10分钟

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 17:05:09 +08:00
Administrator 0aa55eb333 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-25 16:09:51 +08:00
AdministratorandClaude Opus 4.8 1d1ab384ef feat(auth): 登录白名单(注册后管理员审批放行 + 全局开关)
用户仍可自助注册,普通账号默认 approved=False(待审批),admin 建号即 True;
存量用户迁移回填 True 避免锁死。系统设置 login_whitelist.enabled 总开关:关=
所有人可登录,开=仅已放行用户(或 admin)可登录。三登录端点建号后、发 token 前
经 enforce_user_approved 拦截,未放行返回 403 PENDING_APPROVAL。管理员在「白名单
管理」页(设置下拉入口)切总开关 + 逐用户放行。取消放行只拦下次登录。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 16:09:38 +08:00
吉鑫升andClaude Opus 4.8 864224e07c feat(message-token-usage): 速度条下方常驻颜色含义图例
生成结束后在速度条下方展示一行图例(SpeedLegend),把进度条配色归并为用户视角的
延迟正常/微长/长 + 无响应四类说明,帮助用户理解速度条颜色代表的模型生成延迟状态。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 16:07:54 +08:00
吉鑫升andClaude Opus 4.8 04b38a4a25 fix(task-buttons): append_auth 显式 server_default 修复旧库 /api/task-buttons 报 500
旧库已存在 task_buttons 表时,启动期自动补列 _ensure_orm_columns_sync 会跳过
「NOT NULL 且无 server_default」的列,导致 2026-06-25 新增的 append_auth 永远补不上,
GET /api/task-buttons 查询报 Unknown column → 500。给该列加 server_default="0" 后,
重启即自动 ALTER TABLE 补列,与迁移 20260625_01 保持一致。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 15:57:26 +08:00
吉鑫升andClaude Opus 4.8 f8b40353ef feat(task-buttons): 跳转按钮可追加登录态 token+username + token 登录离线测试映射
rwfx/3qfx/xdfx 任务工作区的可配置跳转按钮(按钮管理)新增「追加登录态」开关:
url 类型按钮可在外链后拼 ?token=<token1>&username=<登录名>(参数名可配,默认
token/username),供跳转目标外部系统识别当前登录用户。

- 仅 token 登录(login/token)生效: token1 = ?authToken=,username = 后端用
  token 调 getTokenInfo 解析出的原始登录名(非邮箱前缀/非解 JWT)。二者登录时
  经 persistLoginCredentials 存入 login.token1/login.username(scoped-storage
  自动隔离嵌入/独立会话);非 token 登录读不到 token1 则跳过追加。
- 后端 UsernameLoginResponse 回传 username(原始名,规避邮箱归一化有损);
  token_login 加 mock_tokens 离线测试映射(123ewq->admin),命中即跳过外网
  getTokenInfo,便于本地全链路联调。
- task_buttons 加列 append_auth/auth_token_param/auth_name_param
  (migration 20260625_01 + 幂等 SQL)。

Tests: test_task_buttons.py, test_auth_login_modes.py(mock token/username 回传)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 14:52:07 +08:00
fengxiangdebaoziandClaude Opus 4.8 893f1e6933 fix(会商第三步): 流程图入库限 rwfx-A + 修复跳过报告生成流程图出现双调度中卡片
- 入库功能仅 rwfx-A(businessCode 6BF)深链会商模式提供,其它业务深链生成流程图不再出现入库按钮/询问
- 流程图抽取串行化:auto 自动出图与用户「跳过报告直接生成流程图」手动出图竞态时,先中止上一轮、复用/移除被取代气泡,保证任意时刻只有一张流程图卡片

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 12:29:45 +08:00
fengxiangdebaoziandClaude Opus 4.8 04e6d0aa00 fix(ai写作): 前端实时接收技能步骤(此前被白名单丢弃,只在快照里一次性显示)
根因在前端:后端 _emit_skill_step 以 writer({"type":"skill_search_step", **step})
发出,**step 里的 type(invoke_skill/list_skills/skill_result/select_skills/
match_skills/skill_error/fallback/stop_early)会覆盖外层 "skill_search_step",
所以 custom 事件实际 type 是这些内层值。customToProgressEvent 的白名单没有它们,
直接 return null 丢弃——后端逐条实时发(SSE id 时间戳已证实分散在 0~76s),前端却
全扔了,技能步骤只能等节点结束的素材包快照一次性出现(前端一直 loading)。

修复:customToProgressEvent 按内层 step 类型识别,实时归一成 skill_search_step
事件(与快照里的 step 同格式),让技能调用过程一步步实时进时间线。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 01:20:21 +08:00
fengxiangdebaoziandClaude Opus 4.8 1d6659f9e7 fix(ai写作): 技能步骤从节点协程 emit,custom 事件真正实时刷给前端
前端/SDK 都是实时的(onCustomEvent 逐条即触发,draft_chunk 同链路就实时)。
问题在后端:技能步骤原来在节点内的嵌套 agent.astream 里直接 emit,custom 事件
被攒到整段跑完才一次性吐到 SSE(后端在跑、前端一直 loading)。

改为:嵌套 astream 跑后台任务,只把工具调用塞进 asyncio.Queue;真正的 writer
由 researcher 节点**自身协程**从队列取出来调(与 draft_chunk 同一上下文),
custom 事件即被 LangGraph 实时刷给前端。撤掉上一版无效的 sleep(0)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 01:04:49 +08:00
fengxiangdebaoziandClaude Opus 4.8 a4a67c1a00 fix(ai写作): 技能流式每步主动让出事件循环,custom 事件实时刷给前端
前端 skill_search_step 已是 pushImmediate(实时渲染),但事件在节点内的嵌套
agent.astream 里发出后没及时让出事件循环,被攒到整段跑完才一次性吐到 SSE,
前端看着像卡死。每个 chunk 处理完 await asyncio.sleep(0) 主动让出,促使刚 emit
的 custom 事件实时刷给前端(对齐 draft_chunk 的实时行为)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 00:48:57 +08:00
fengxiangdebaoziandClaude Opus 4.8 8f773d3f1b fix(ai写作): 技能调用实时流式显示 + 去掉大纲拼检索词/复用检索词
- 技能调用过程改为实时流式:run_skill_via_real_agent 不再 to_thread 阻塞跑
  executor.execute(),而是复用其 agent/state 构建后在图事件循环里 astream,
  每个工具调用(读 SKILL.md / bash / 检索)实时推一条步骤到时间线——内网慢时
  用户能看到技能在执行,不会以为卡死。整段 asyncio.wait_for 卡 5 分钟超时。
- 回退检索词相关改动(实测无用、且结合大纲后检索词变长不利按词匹配):
  - intent_parser 不再顺便生成 keywords,删 precomputed_keywords 状态字段;
  - researcher 不再复用,每次自己现生成检索词(回到原行为);
  - 检索词提示词去掉「结合大纲/{outline_section}」,删 keyword_outline_section。
  保留:关思考、技能真实运行时、技能目录修复、内网兜底。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 00:33:57 +08:00
fengxiangdebaoziandClaude Opus 4.8 c0305c9269 fix(ai写作): 修复内网技能检不出东西(技能目录路径 + 模型 + 兜底 + 开关)
对比主智能体与 AI 写作两份调用日志定位到根因:真实 agent 路径只注入了
SKILL.md 内容、没告诉模型技能在容器内的目录,模型用相对路径跑脚本
(python3 scripts/search)→ No such file。主智能体则 cd 进技能绝对目录再跑。

- _skill_agent:注入 skill.get_container_path() 的绝对目录,要求先 cd 再执行
  脚本/用绝对路径(对齐主智能体 skill_view 拿 location 后的行为)。
- researcher:跑技能的 agent 改用用户选定的写作主模型(model_name_fallback=None),
  不再用常配成外网的 keyword_model,避免技能 agent 连不上自己的模型。
- researcher:所有技能都 0 条时,最终兜底直连内网 ES 接口(IntranetSearchProvider),
  受 ai_writing.intranet_search_url 控制。
- config.yaml:开 researcher_skill_agent=true(内网技能必须走真实运行时),
  新增 intranet_search_url / intranet_knowledge_base 兜底配置项。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 23:52:32 +08:00
吉鑫升andClaude Opus 4.8 6989dd45f1 fix(chat): 问答回答时间戳不再漂移到当前电脑时间
AI 回答无自身时间戳,原先在首次渲染时用 new Date() 兜底,导致
未在原会话完成、或从历史重新加载的回答显示加载时刻而非真实时间。
改为让 AI 回答继承同轮提问的可靠 client_ts(turnTime),并停止给
AI 消息打 now 戳;显示层优先用提问时间,可自愈历史错误时间。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 22:57:21 +08:00
fengxiangdebaoziandClaude Opus 4.8 d8b43e7579 fix(ai写作): 技能检索超时硬编码 5 分钟(内网慢检索不被过早切断)
内网检索很慢,原 120s 在三个真正生效的层把检索切断。统一硬编码 300s,
不依赖环境变量(部署方不一定会配):
- researcher._SKILL_SEARCH_TIMEOUT_SECONDS:120(env) → 300(写死),删掉 _env_int;
  作用于直连/定向技能检索的 wait_for,也传给真实智能体路径。
- IntranetSearchProvider 默认 httpx 超时:120 → 300(直连内网 ES 的真正瓶颈)。
- run_skill_via_real_agent 整段运行上限:max(timeout_s, 300),至少 5 分钟。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 22:54:42 +08:00
fengxiangdebaozi 4f68235c94 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-24 22:45:42 +08:00
吉鑫升 c1143564ef Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-24 22:42:21 +08:00
吉鑫升andClaude Opus 4.8 ea2ea9783e feat(task-deeplink): xdfx 开场信息追加行动标题与行动内容
xdfx(行动分析)深链开场信息原先只附行动id(action_id),现额外
拼上行动标题(actionName)与行动内容(narration)。优先读登录时
缓存的行动详情(readActionDetail),无缓存再 fetchActionDetail,避免
重复请求。buildOpeningText 第三参数由 actionId 改为 ActionOpeningInfo。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 22:34:25 +08:00
吉鑫升andClaude Opus 4.8 e3e93712b6 feat(task-deeplink): xdfx 开场信息追加行动标题与行动内容
xdfx(行动分析)深链开场信息原先只附行动id(action_id),现额外
拼上行动标题(actionName)与行动内容(narration)。优先读登录时
缓存的行动详情(readActionDetail),无缓存再 fetchActionDetail,避免
重复请求。buildOpeningText 第三参数由 actionId 改为 ActionOpeningInfo。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 22:33:09 +08:00
fengxiangdebaoziandClaude Opus 4.8 afb78a6943 feat(ai写作): 素材收集专家按真实智能体运行时跑技能 + 步骤条对齐
- 新增 run_skill_via_real_agent:复用 SubagentExecutor(与 lead agent / 子智能体
  同一套运行时),加载技能 SKILL.md + 全套工具 + 懒加载沙箱,让技能的真实检索逻辑
  (读文件 / 调内网接口 / MCP)真正执行,再按 JSON 契约收割结构化素材;researcher 的
  _execute_skill 在 researcher_skill_agent 开启时切到它,失败/空结果回退直连检索。
  解决内网技能(在别的智能体里好使)在 AI 写作里检不出东西的问题。
- 步骤条轻量对齐别的智能体:技能调用拆成「读取 SKILL.md → 执行检索 → 检索到 N 条」
  三段(前两段新增,结果段沿用 skill_result);前端 SkillStepsCard 零改动。
- 含 roundtable-planning(业务链选择 / Step2 编排)的进行中改动。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 22:19:30 +08:00
董宏凯andClaude Opus 4.8 1a127ef602 chore(定时任务): 替换 no.3 模板内容为 no.3-1.html(仍只展示)
- templates/no3/no3.html 覆盖为新版(73KB,const DATA = {…} 内联)
- id/name/注册不变,仍为 convertible=False 只展示

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 22:17:24 +08:00
AdministratorandClaude Opus 4.8 acc29c8121 fix(middlewares): 标题模型推理不再泄漏到 UI 流 + open/ephemeral 会话避免无谓 DB 访问
- title: 标题模型用隔离 config(不继承父级 streaming callbacks),force_disable_thinking,<think> 块清洗,避免推理 token 进入实时流/运行日志
- uploads: 无文件的普通对话轮次直接跳过,不再解析线程归属(避免命中 DB)
- thread_data: ephemeral 会话用当前登录用户解析数据目录
- thread_paths: open-/__skill-review__ 等合成线程视为 local-only,直接用当前用户
- frontend: 新增 build:test 构建脚本

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:20:12 +08:00
董宏凯andClaude Opus 4.8 ca31490241 chore(定时任务): no.9 模板显示名称改为 no.13(id 仍为 no9)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:11:33 +08:00
董宏凯andClaude Opus 4.8 6c42f86e30 chore(定时任务): no.8 模板显示名称改为 no.12(id 仍为 no8)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:09:56 +08:00
董宏凯 5b818836d7 Merge branch 'dhk-1' into 'master'
fix(登录): redirect 透传登录 URL 其余 query 到目标页

See merge request knowledge-base-bj/deerflow-server!150
2026-06-24 11:49:00 +00:00
fengxiangdebaozi 3ea8e73389 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-24 19:48:15 +08:00
fengxiangdebaoziandClaude Opus 4.8 c117e296cb feat(ai写作): 草稿局部修改只改命中章节,支持改章节标题,修改时右侧流式重写
用户在草稿确认填修改意见(user_revise)时,按章节定位只重写命中章节、
其余字节级保留;新增范围识别区分「改标题」与「改正文」,改标题同步回写
outline 使其持久生效(修复改章节标题不生效);整体性/结构性意见自动回退
整篇重写。前端新增 isRevising:修改时右侧先恢复初始占位(清空旧稿),
重写流到达后实时展示被改章节的流式重写。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 19:45:00 +08:00
fengxiangdebaoziandClaude Opus 4.8 42f55251f2 feat(ai写作): 历史回看右侧成稿可编辑并保存回历史记录
- 后端新增 PUT /api/ai-writing/sessions/{id}/draft(属主校验,draft_title 可选)
- 前端历史模式放开只读,工具栏新增「保存」按钮持久化修改
- 实时写作完成态保持原样(仅导出,不落库)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 18:32:11 +08:00
fengxiangdebaoziandClaude Opus 4.8 304e1b637a feat(ai写作): 意图解析顺便生成检索词 + 修复快捷模式
- 意图解析(intent_parser)与意图理解共用同一次 LLM 调用顺便生成检索词
  (结合意图 + 大纲覆盖各章节主题),存入 state.precomputed_keywords;
  researcher 首轮直接复用,省掉素材收集阶段单独的「生成检索词」LLM 往返。
  解析失败/为空时回退到 researcher 自己生成(优雅降级);re_search 仍重新生成。
  keyword_outline_section 提到 _utils 供两处共用。
- 修复快捷模式:之前被「大纲先行确认」改动拖累,先误成「问一堆问题」,再被我
  过度修正成「不生成大纲」。现修正为——快捷模式 = 用默认选项、不逐项澄清提问
  (make_lead_agent 在快捷模式下直接不挂 ask_clarification 工具,物理上问不了),
  但**仍生成并确认大纲**再提交;普通模式不变。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 18:32:10 +08:00
fengxiangdebaoziandClaude Opus 4.8 49173d9c28 feat(ai写作): 大纲整理可见化 + 检索词结合大纲 + 素材/大纲阶段关思考
- 草稿确认卡:「给出修改意见」「让编辑继续审核」移到「确认定稿」上方。
- 大纲整理阶段文案:用户自带大纲时显示「整理你的大纲」而非「规划大纲」
  (OutlineStreamingView / 骨架屏 / 状态栏,按 request.userOutline 切换)。
- 素材收集专家:用户自带大纲时把大纲原文带入检索词生成,让关键词结合写作
  意图覆盖各章节主题(_keyword_outline_section,agent + legacy 两路)。
- 素材收集(检索词/排序)与大纲整理/生成阶段强制关闭思考
  (create_chat_model force_disable_thinking:GLM thinking.disabled +
  Qwen/vLLM enable_thinking=false),关不掉的模型仍由 ThinkTagParser 把
  <think> 分流到思考框正常展示。disable_thinking 串入
  _utils.get_model/llm_json 与 _agent_runner.stream/run_writing_agent。
- 含草稿「局部修改」WIP(writer_draft 只重写命中章节)及外观控件改动。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 18:32:10 +08:00
董宏凯andClaude Opus 4.8 8678ceb422 feat(定时任务): 新增第九个 HTML 模板 no.9(只展示)
- no.9.html(160KB)复制进 templates/no9/;数据用 `const DATA = {…}`(= 前有空格,同 no.6),
  当前引擎正则要求 const DATA=,不匹配,故先注册为 convertible=False 只展示
- 前端下拉/参考列表自动出现 no.9
- 测试覆盖 no.9 存在/只展示/文件可读

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 18:17:56 +08:00
董宏凯andClaude Opus 4.8 31cd19aabb feat(定时任务): 新增第八个 HTML 模板 no.8(只展示)
- no.8.html(77KB)复制进 templates/no8/;数据存于 <script id="DATA"
  type="application/json"> 元素(同 no.4/no.7 元素注入),当前引擎只支持 const VAR= 行注入,
  故先注册为 convertible=False 只展示
- 前端下拉/参考列表自动出现 no.8
- 测试覆盖 no.8 存在/只展示/文件可读

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 18:16:34 +08:00
董宏凯andClaude Opus 4.8 60029ae3dc feat(定时任务): 新增第七个 HTML 模板 no.7(只展示)
- no.7.html(605KB)复制进 templates/no7/;数据存于 <script id="PAGE_DATA"
  type="application/json"> 元素(同 no.4 类元素注入),当前引擎只支持 const VAR= 行注入,
  故先注册为 convertible=False 只展示
- 前端下拉/参考列表自动出现 no.7
- 测试覆盖 no.7 存在/只展示/文件可读

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 18:13:38 +08:00
董宏凯andClaude Opus 4.8 4f62703477 feat(定时任务): 新增第六个 HTML 模板 no.6(只展示)
- no.6.html(266KB)复制进 templates/no6/;数据用 `const DATA = {…}`(= 前有空格),
  当前引擎正则要求 const DATA=,不匹配,故先注册为 convertible=False 只展示
- 前端下拉/参考列表自动出现 no.6
- 测试覆盖 no.6 存在/只展示/文件可读

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 18:09:47 +08:00
董宏凯andClaude Opus 4.8 c0af23aefe feat(定时任务): 新增第五个 HTML 模板 no.5(只展示)
- no.5.html(174KB)复制进 templates/no5/;数据用 `let DATA = {…}`(let+空格,非
  const DATA= 行),当前引擎行注入正则不匹配,故先注册为 convertible=False 只展示
- 前端下拉/参考列表自动出现 no.5
- 测试覆盖 no.5 存在/只展示/文件可读

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 17:51:12 +08:00
董宏凯andClaude Opus 4.8 6a6195f883 feat(定时任务): 新增第四个 HTML 模板 no.4(只展示)
- no.4.html(3.9MB)复制进 templates/no4/;数据存于 <script id="app-data"
  type="application/json"> 元素(非 const DATA= 行),当前引擎只支持 const VAR= 行注入,
  故先注册为 convertible=False 只展示,转换后续接(需扩展元素注入)
- 前端下拉/参考列表从 API 拉取,no.4 自动出现
- 测试覆盖 no.4 存在/只展示/文件可读

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 17:45:40 +08:00
吉鑫升 1a87077642 Merge branch 'ji' into master
并入: loop 跨事件循环 DB 访问修复(asyncmy attached to a different loop)、y-log 前缀、全角参考文献角标识别

# Conflicts:
#	CLAUDE.md
2026-06-24 17:13:45 +08:00
fengxiangdebaoziandClaude Opus 4.8 e9c8d1cea2 feat(ai写作): 自带大纲/会商及研究模板等前后端改动
提交工作区中 AI 写作(表单/时间线/历史/上下文/流式 hook/类型)、
研究模板配置页、lead_agent、researcher/graph/state 及 gateway/config
的进行中改动。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 16:15:39 +08:00
fengxiangdebaoziandClaude Opus 4.8 d2c76100f2 perf(ai写作): 用户自带大纲整理提速并流式化
用户自带大纲时「整理大纲」原有两个阻塞式非流式 LLM 调用,内网模型
<think> 关不掉导致用户长时间干等:

- 素材关联(每次都调)改为确定性词重叠 _assign_materials_heuristic,
  零 LLM、瞬时;有编号/标题/缩进的大纲整理几乎零等待。
- 散文化大纲的 LLM 归一改为流式 _stream_normalize_user_outline:
  ThinkTagParser 把思考推思考框、正文实时打字机展示并累积解析;
  并在 OUTLINE_NORMALIZE_USER 末尾追加 /no_think。
- researcher 路径只做确定性解析,解析不出返回 None,交给 writer_outline
  流式归一(outline_chunk 在该阶段天然映射大纲思考框)。
- 移除废弃的 OUTLINE_MATERIAL_ASSIGN_* 提示词与 llm_json 死引用。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 16:15:39 +08:00
吉鑫升andClaude Opus 4.8 6aff165d09 fix(db): 路由跨 loop 的 DB 访问回引擎主 loop,消除 asyncmy "attached to a different loop"
会商/定时任务/沙箱工具等在 worker 线程的临时 loop 上用 asyncio.run 跑全局引擎连接池的
DB 操作,连接被绑定到随即关闭的临时 loop;池子回收/释放该连接时 asyncmy
_terminate_graceful_close 在错误的 loop 上触发 future,持续刷
"got Future attached to a different loop"。

- engine.py: 新增 run_db_blocking(fire_and_forget_db_write 的带返回值版本)。离开主 loop
  时用 run_coroutine_threadsafe 把协程送回主 loop 执行、阻塞调用线程拿结果;仅在无主 loop
  或正同步处于主 loop 内(送回会死锁)时退回临时 loop。
- thread_paths / prompt / skill_tools: 三处同步→异步阻塞读桥(任务owner解析/常驻技能/
  技能可见性)改走 run_db_blocking,删除各自重复的 _run_coro_blocking。
- llm/tool metrics 中间件: fire-and-forget 写改走 fire_and_forget_db_write。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 15:57:04 +08:00
吉鑫升andClaude Opus 4.8 5ecf28e60c feat(y-log/knowledge): 日志前缀改 CM助手-全量 + 入库 nodeName 按标题去时间戳保持一致
1. Y-Log 上报 optDetail 前缀 B1-CM助手 → CM助手-全量(全量替换 44 个前端文件 + 文档)
2. 知识库入库 nodeName 改为只取 md5(标题).md(去掉时间戳),同一篇 md 每次入库一致,避免重复记录

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 15:46:51 +08:00
g zy fb103b6ad9 Merge branch 'gzy' into 'master'
Gzy

See merge request knowledge-base-bj/deerflow-server!149
2026-06-24 07:42:20 +00:00
Rocky Kwok 71a865dc0c Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-06-24 15:41:25 +08:00
Rocky Kwok 8ed54448c2 feat: 打开 browser_act 2026-06-24 15:40:56 +08:00
董宏凯andClaude Opus 4.8 5a2441cc9f feat(定时任务): 新增第三个 HTML 模板 no.3(只展示)
- no.3.html(3.8MB)复制进 templates/no3/,无 const DATA= 注入点 → 注册为
  convertible=False 只展示模板(同 no.2,后续接转换再开)
- 前端下拉/参考列表从 API 拉取,no.3 自动出现,无需前端改动
- 测试覆盖 no.3 存在/只展示/文件可读

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 14:38:49 +08:00
董宏凯andClaude Opus 4.8 089d3e171f fix(定时任务): 抽取开关只控制模板HTML数据,不再影响Markdown等正常操作
- 之前关闭抽取会整段跳过 gather/agent,连带把 Markdown 生成也跳过了
- 改为:抽取开关只决定 HTML 用「抽取数据」还是「模板默认数据」;require_markdown 独立——
  需要时照常跑 gather 产出 .md 并校验/带出,与开关无关
- gather 仅在 do_extract(开关开+有描述+可转换) 或 require_markdown 时跑一次,两者复用同一次
- 只展示模板恒不抽取,但仍尊重 require_markdown;_finalize_template_html 支持 extra_files 带出 .md
- 测试:关闭抽取+必须Markdown → 仍产出.md/不转换/HTML用默认数据

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 14:23:45 +08:00
xu hd ed71df1b60 Merge branch 'xuhd' into 'master'
fix(notebook): 来源搜索导入后立刻显示占位卡并刷新来源列表

See merge request knowledge-base-bj/deerflow-server!148
2026-06-24 05:15:19 +00:00
xuhdandClaude Sonnet 4.6 85cd2c888e fix(notebook): 来源搜索导入后立刻显示占位卡并刷新来源列表
- handleImport 成功后调用 onUploadComplete 通知父组件(原先缺失)并关闭弹窗
- 新增 pendingImportTitles state,同步导入后立刻渲染 PendingSourceCard
- sources 刷新后按标题匹配移除占位卡并自动选中新来源

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 13:14:36 +08:00
董宏凯andClaude Opus 4.8 6673121f3f feat(定时任务): 选内置模板时加「执行数据抽取」开关,关闭则直接用默认数据
- html_config.template_extract(默认关,仅参考选 tpl:<id> 时显示开关):
  关闭→跳过检索/转换,直接用模板默认数据填充;开启→才执行检索+转换抽取
- 后端 _run_html_template_reference 在只展示分支后先判开关
- 前端 ScheduledTasksPage:参考选内置模板时显示 Switch,存进 html_config.template_extract,编辑回显
- 测试覆盖 开/关 两条路径

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 13:09:16 +08:00
董宏凯andClaude Opus 4.8 4898ea0a85 build(harness): 显式把 no.1/no.2 HTML 模板纳入打包,保证新机器内置可见
- harness pyproject [tool.hatch.build] artifacts 显式包含 templates/**/*.html,
  任何构建方式(wheel/sdist)都带上模板(已验证 wheel 内含 no1/no2)
- 模板文件本就 git 跟踪、源码安装直读、内置 agent 启动自动 seed —— 新机器 clone
  装好即可直接看到
- 加自检测试 test_all_registered_template_files_exist

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 13:05:43 +08:00
董宏凯andClaude Opus 4.8 7d9a0637ca fix(定时任务): 模板子页面空内容回退原数据,避免子页面显示不全
- 引擎 merge_with_reference:按顶层键(=子页面)逐一合并,转换结果里没抽到有效内容的
  子页面/字段回退模板原有数据(_has_content/_merge_fill 递归,列表/标量整体保留,
  字典逐键回退空分支);整体为空等价于返回模板默认数据
- _run_html_template_reference:描述与任务prompt都为空→直接用原数据不检索;转换成功后
  对结果做 merge_with_reference 补空子页面
- _run_template_fill_attempt 同样套用 merge,空子页面一致回退
- 测试覆盖 _has_content/merge 各场景 + 端到端空子页面回退/空描述用原数据

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 12:20:12 +08:00
董宏凯andClaude Opus 4.8 ba885ca201 fix(定时任务): require_html 选内置模板时用真实模板出页,保留全部子页面
- 模板是 JS 驱动多页 SPA,子页面靠脚本从 DATA 渲染;之前用 style_reference 抽 CSS 摘要
  让模型自由渲染,结果只剩主页、子页面全丢
- 改为:_run_html_page_attempt 见 tpl:<id> 参考即提前分支到 _run_html_template_reference,
  用真实模板文件出页——可转换模板=检索数据→转换→fill_template;只展示模板=原样输出;
  转换失败兜底默认数据,保证页面与子页面始终可用
- 抽出 _convert_to_template_data / _finalize_template_html 复用,删除已废弃的 style_reference
- 测试覆盖:真模板保留 const DATA/script/id=tabs;只展示原样;转换失败回退

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:47:16 +08:00
董宏凯andClaude Opus 4.8 ec60b77a71 feat(定时任务): 必须生成HTML的「参考收藏页面」加入 no.1/no.2 模板作为风格参考
- 引擎 template_fill.style_reference:抽取模板 <style> CSS + 去脚本结构骨架(~13-28KB),
  剥掉巨大数据常量,供 require_html 渲染模型模仿风格;reference_template_id 解析 tpl:<id>
- 调度器 _run_html_page_attempt:参考来源为 tpl:<id> 时用模板风格参考,否则走收藏 store
- 前端 ScheduledTasksPage:require_html 模式下「参考收藏页面」列表加入「模板:no.1/no.2」,
  值存 tpl:<id>;htmlTemplates 在 require_html 时也拉取
- 文档同步

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:09:48 +08:00
董宏凯andClaude Opus 4.8 ae3788a87d feat(定时任务): 模板数据转换器对话页加「页面模板+渲染预览」调试入口
- 后端 POST /api/scheduled-tasks/template-fill/render:不调模型,抽取回复里的 JSON
  → 校验 → 填充,返回完整 HTML + 校验错误/缺失字段(非法也照样填充便于看效果),
  只展示模板原样返回
- 前端仅 template-json-builder 智能体的 AgentChatPage:顶部加页面模板下拉 +「渲染预览」
  按钮,取最近一条 AI 回复填进所选模板,弹窗用 sandbox=allow-scripts iframe 预览 +
  校验状态;严格按 agent id 门控,不影响其他智能体对话页
- 文档同步

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 10:00:18 +08:00
吉鑫升andClaude Opus 4.8 3e68260afa fix(citations): 识别全角参考文献角标(全角数字/合并/区间)
正文里的引用角标识别此前全角括号只支持单个半角数字 【1】,
导致 【1】(全角数字)、【1,2】/【1,2】/【1、2】(合并)、
【1-3】/【2~5】(区间) 等中文常见写法无法识别成参考文献。

补齐全角括号的「全角数字 / 合并 / 区间」三种形态,转成半角后交给
原有半角逻辑统一处理;仍保留 isValidIndex 闸门,避免把正文里的
【3】(越界)、【附录】(非数字) 误判为引用。新增 inline-citations.test.ts。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 22:14:52 +08:00
fengxiangdebaoziandClaude Opus 4.8 f551c7af9b fix(登录): redirect 透传登录 URL 其余 query 到目标页
?redirect=/page/strategy/dashboard-agent&taskId=3334 时把 taskId 等非登录消费参数
透传到目标页 query(目标自带同名参数优先),鉴权类参数不透传以防泄漏到地址栏。
修复跳转后目标页「缺少 taskId」。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 22:10:40 +08:00
董宏凯 b1ef4ccb1a Merge branch 'dhk-1' into 'master'
feat(定时任务): 模板转换支持纯文本/含JSON文本/纯JSON三种源输入

See merge request knowledge-base-bj/deerflow-server!147
2026-06-23 13:53:18 +00:00
fengxiangdebaozi e3631a9fd6 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-23 21:52:27 +08:00
fengxiangdebaoziandClaude Opus 4.8 8241f8dd6b feat(登录): 新增 ?redirect= 参数,登录后跳转指定站内页面
支持 ?redirect=page/strategy/dashboard-agent(可不带前导斜杠、可自带 query),
优先级高于 taskId/goPath 深链与默认首页;仅接受站内相对路径,拒绝绝对/协议相对
URL 与反斜杠以防开放式跳转。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 21:51:59 +08:00
董宏凯andClaude Opus 4.8 3d2cc9e5cd fix(深链会商): Step2 文件产物虚拟预览仅在有内容时用,否则回退 HTTP 按创建者解析(修复跨账号看不到)
- useStep2Orchestration.openArtifactPreview: stub 无内容(str_replace/跨账号草稿恢复)时不再短路,
  回退到 artifacts HTTP 接口,并优先用子席位 thread(roundtable 线程→后端按对话创建者解析+放行跨账号)
- findSeatArtifactSource 一并返回 stub 捕获的 content 供判断
- 附:模板数据转换器「源数据抽取」手工测试清单文档

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 21:47:46 +08:00
fengxiangdebaozi e263d86fc3 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-23 21:22:02 +08:00
fengxiangdebaozi 151384b26d 代码修改 2026-06-23 21:21:49 +08:00
fengxiangdebaozi 030ede6887 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-23 21:07:05 +08:00
fengxiangdebaozi e6ca2bf64f Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-23 21:06:19 +08:00
fengxiangdebaozi 47cff9e2f9 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-23 21:06:09 +08:00
fengxiangdebaozi 6742346eb4 代码提交 2026-06-23 21:05:58 +08:00
吉鑫升 b5e682cfd2 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-23 21:01:05 +08:00
吉鑫升 2193c4484b Merge remote-tracking branch 'origin/master' into ji 2026-06-23 20:58:41 +08:00
Administrator 4fc3d7dae2 Merge remote-tracking branch 'origin/master' into ji 2026-06-23 20:57:01 +08:00
Administrator 6f0f9fb1fc Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji
# Conflicts:
#	CLAUDE.md
2026-06-23 20:52:39 +08:00
AdministratorandClaude Opus 4.8 df9c59e21c feat(y-log): 问答按 LLM 调用各记一条 + 全量补齐各 API 操作埋点
- 问答日志从「每轮 onFinish 一条」改为 useThreadStream onLangChainEvent
  监听 on_chat_model_end,每次大模型调用结束各上报一条(含子代理)
- 广覆盖各 API client 成功路径:查看(view)/查询(search)/新增(create)/
  编辑(edit)/删除(delete)/启停(enabled·disabled)/导入导出,补齐此前
  整模块零埋点与漏掉的单条详情 GET;跳过高频 typeahead/轮询/bootstrap

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:42:54 +08:00
AdministratorandClaude Opus 4.8 6131eda219 feat(y-log): 问答按 LLM 调用各记一条 + 全量补齐各 API 操作埋点
- 问答日志从「每轮 onFinish 一条」改为 useThreadStream onLangChainEvent
  监听 on_chat_model_end,每次大模型调用结束各上报一条(含子代理)
- 广覆盖各 API client 成功路径:查看(view)/查询(search)/新增(create)/
  编辑(edit)/删除(delete)/启停(enabled·disabled)/导入导出,补齐此前
  整模块零埋点与漏掉的单条详情 GET;跳过高频 typeahead/轮询/bootstrap

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:41:07 +08:00
吉鑫升andClaude Opus 4.8 14082b3e7b fix(深链): 删除接口空响应体也判成功
dropSixOrSevenData 成功时返回空响应体,原 success: obj.success === true
永远为 false,导致删除已成功却总弹「清除失败/无法覆盖」。改为
success: obj.success !== false:请求未抛错即算成功,仅显式 {success:false} 才失败。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:28:18 +08:00
董宏凯andClaude Opus 4.8 00181ebde8 feat(定时任务): 模板转换支持纯文本/含JSON文本/纯JSON三种源输入
- template_fill.extract_embedded_json:字符串感知平衡扫描,从含 JSON 的文本里抠出
  内嵌 {…}/[…](纯文本返回 None)
- 调度器转换 prompt 预识别内嵌 JSON,单独标注「识别到的结构化数据」并保留原文;
  纯文本则让模型按语义理解;conversion prompt 重写覆盖三种形态
- 内置 agent SOUL 说明三种源数据形态
- 文档同步

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:28:05 +08:00
董宏凯 320f2ef814 Merge branch 'dhk-1' into 'master'
feat(深链会商): rwfx-A/3qfx-A 首条消息附带 taskId,xdfx-A 附带 taskId+actionId

See merge request knowledge-base-bj/deerflow-server!146
2026-06-23 12:09:45 +00:00
fengxiangdebaoziandClaude Opus 4.8 8b022bffc5 feat(深链会商): rwfx-A/3qfx-A 首条消息附带 taskId,xdfx-A 附带 taskId+actionId
会商 Step1 自动发送的「任务信息」现追加任务/行动 id,与单智能体路径口径一致,
id 标签统一用驼峰(taskId / actionId)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:08:33 +08:00
董宏凯 5fddb08e04 Merge branch 'dhk-1' into 'master'
fix(roundtable): xdfx-A 深链会商聊天记录按行动id隔离存储

See merge request knowledge-base-bj/deerflow-server!145
2026-06-23 11:48:10 +00:00
fengxiangdebaozi 0fedb6ffd8 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-23 19:47:54 +08:00
董宏凯andClaude Opus 4.8 498e3c6a84 fix(深链): 「上一步」进大屏绘制页强制显示全局导航栏+侧边栏
- PageLayout 对 /strategy/dashboard-agent 路由强制 pageSidebarAllowed(不受界面模式/
  会话级 sidebar 标志影响;仍尊重 embed=1 嵌入态隐藏),避免从去 chrome 的深链工作区进来后整页无顶栏/侧栏
- 「上一步」按钮 openMode 改回 self(同窗导航;forceChrome 后同窗/新窗都能带回 chrome)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:47:02 +08:00
fengxiangdebaozi 85aa242fd5 Merge branch 'master' into dhk-1 2026-06-23 19:45:41 +08:00
fengxiangdebaoziandClaude Opus 4.8 6f94a40303 fix(ai-writing): 写作分栏拖拽条不再压住左侧滚动条
隐形拖拽热区只向右(草稿区留白)延伸 + 抓手微右移,避免鼠标抓左侧时间线滚动条时
误触左右 resize 导致滑不动;不留任何视觉间隙。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:37:30 +08:00
董宏凯andClaude Opus 4.8 34893007a7 feat(深链会商): rwfx-A 复用单智能体 3q 预检闸门,未完成引导前往三情会商(3qfx-A)
- 抽出共用组件 RwfxSqReportGate(单/多智能体共用),targetGoPath 参数化「前往」目标
- 单智能体 TaskFxWorkspace 改为 import 共用组件(默认 3qfx),清理因抽离失效的 import
- 多智能体会商 RoundtablePlanningPage 深链 rwfx-A 挂同一闸门,目标 3qfx-A(三情会商)
- 改一处两处都生效,避免双份逻辑漂移

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:26:00 +08:00
Administrator 053d3e300e Merge branch 'ji' into master (操作日志 Y-Log 上报)
# Conflicts:
#	CLAUDE.md
2026-06-23 19:22:53 +08:00
吉鑫升andClaude Opus 4.8 a1fbfaf864 feat(xdfx): 行动历史查询与删除(与 rwfx 共用 dropSixOrSevenData 删除接口)
- 删除接口统一为 dropSixOrSevenData:rwfx 传 ?taskId=、xdfx 传 ?actionId=,另一参数直接不出现在 URL
- xdfx 工作区新增「清除记录」按钮(按行动id 删除),删除前预检「行动历史是否存在」
- action_history_url 配置位(地址待提供,留空则不查询/不阻断删除)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:14:16 +08:00
fengxiangdebaoziandClaude Opus 4.8 b8c78ba06e feat(ai-writing): 大纲先行确认 + 新文章类型识别 + 参考文献 + 编辑器修复
- 写作配置 Q&A 改为「先流式生成大纲并多轮确认 → 再确认意图」,放宽轮数上限
- 意图识别出列表外的新文章类型时带上类型名+简介(仅本次写作临时使用)
- 成稿支持参考文献:正文 [n] 角标 + 文末按出现顺序的「参考文献」列表(表单开关,默认开)
- 流式接取未闭合 <think> 思考内容,首 token 前加「正在整理…」占位
- 修复右侧编辑器输入空格只出一次、光标跳字(避免自激回灌 setContent 重置光标)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:07:03 +08:00
董宏凯andClaude Opus 4.8 cd33aaeded feat(定时任务): 内置「模板数据转换器」按 HTML 模板填充 JSON 生成大屏
- 模板填充引擎 template_fill.py:模板注册表 + schema 骨架 + 结构校验 + 行级安全填充;
  模板自带 DATA 即 schema 来源。no.1 可转换填充(含 MANIFEST 更新时间刷新),
  no.2 暂为「只展示」(convertible=False) 原样输出已有数据
- 内置 agent template-json-builder(seed + SOUL),随 lifespan 注入,自动出现在
  定时任务「执行智能体」下拉
- 调度器新增模板填充执行分支 _run_template_fill_attempt:源 JSON→大模型转换→
  结构校验→失败回喂重试;空源/只展示模板直接用模板默认数据,绝不失败
- API:GET /api/scheduled-tasks/html-templates
- 前端:选中该 agent 后条件渲染「HTML模板」下拉 + .json 上传,只展示型模板隐藏 JSON 输入
- 文档同步(前后端 CLAUDE.md)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 18:00:00 +08:00
吉鑫升andClaude Opus 4.8 5aa66fc07d chore(backend): 放宽递归与循环检测阈值
- build_run_config recursion_limit 100 -> 250
- LoopDetectionMiddleware 默认阈值放宽(warn/hard/window/tool-freq)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 17:48:23 +08:00
吉鑫升andClaude Opus 4.8 23d170cde1 fix(rwfx): 3q 无数据时不默认发送问题,仅「不去3q分析」才发送
问题:rwfx 进入时的 3q 预检弹框与「目的树为空自动发送第一次问题」相互独立,
导致 3q 无数据时弹框出现的同时问题已被自动发出。

修复:新增 rwfx 专用 3q 门控(rwfx-sq-gate.tsx,RwfxSqGateProvider + useRwfxSqGate),
把自动发送交给门控——
- 3q 完成/无法判定 → 立即发送;
- 3q 未完成 → 弹「前往 3qfx」框并挂起发送,仅当用户「暂不(不去3q分析)」或关闭弹框才发送;
  点「前往 3qfx」则跳转并丢弃发送。
TaskPurposePanel 自动开始改调 gateStart(onStart);手动「开始问答」/覆盖确认不受影响。
替换原独立的 RwfxSqReportGate(它弹同一个框但没门控自动发送)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 17:48:23 +08:00
AdministratorandClaude Opus 4.8 d2be3b206d feat(y-log): 操作日志上报(前端直连 + 后端公开只读下发地址)
- 后端新增 y_log 公开只读配置:YLogConfig + AppConfig.y_log +
  GET /api/public/config/y-log,地址写在 config.yaml(mtime 热重载)
- 前端核心 src/core/log/:writeYLog(双门控/异步即发即忘/永不抛错/
  去ip-host/对象序列化裁剪/optResult恒0)+ 配置加载 + token1 隔离存取
- 登录(token)持久化 token1 并报登录、登出先报后清;启动预热配置
- 各 API client 成功路径埋点:敏感词/菜单/按钮/技能地址/轻应用、
  会商草稿+任务草稿+后台任务、智能体/定时任务/知识库、Word导出,
  以及问答完成钩子(ChatPage/AgentChatPage onFinish)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 17:46:08 +08:00
董宏凯andClaude Opus 4.8 1a2ef0a537 feat(大屏绘制): 战情大屏样式优化与脱敏全覆盖
- 去掉顶栏与「生成于」时间标签;无数据时仅显示「暂无数据」、隐藏导航与标题
- 战情各页 + 导航 Tab 文本全部脱敏(响应式取后台敏感词,避免 replaceDesensitizeMap 时序竞态)
- 全页最小字号 16px,调整行高/对齐;表格加横向滚动防溢出
- 关键事件改时间线样式(灰色虚线 + 浅红空心圆圈节点),敌情三块改单行全宽
- 应对方案渲染 Markdown;处置建议由 7 列大表改为单条卡片(字段标签改 #222222)
- 通用过滤引用角标([[1]] / 资料[[1]] / (资料[[1]]) 等,解析末尾整树清洗)
- safelist + 本页兜底 CSS 修复 border 语义色回退成灰色(时间线圆圈/FooterNote 强调条)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 12:36:36 +08:00
xu hd ce3a5b6bf9 Merge branch 'xuhd' into 'master'
feat(frontend): 来源弹窗加loading + 笔记页暗色适配 + 主题透传

See merge request knowledge-base-bj/deerflow-server!144
2026-06-23 03:28:12 +00:00
xuhdandClaude Sonnet 4.6 91a6183757 feat(notebook): 来源上传优化 + 工作室问答停止回答功能
- 上传来源后显示处理中占位卡,轮询成功后自动选中该来源
- 失败时不选中,占位卡去重(已在真实列表中则不显示)
- 输入框三态:空→无按钮,有内容→发送箭头,streaming→停止按钮

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 11:27:40 +08:00
g zy 076cdc746e Merge branch 'gzy' into 'master'
Gzy

See merge request knowledge-base-bj/deerflow-server!143
2026-06-23 02:57:41 +00:00
Rocky Kwok 1c2e524b28 fix: iframe页面子智能体不跳出,增加按钮 2026-06-23 10:56:51 +08:00
xuhdandClaude Sonnet 4.6 42ce20b4df feat(frontend): 来源弹窗加loading + 笔记页暗色适配 + 主题透传
- 来源上传弹窗 A系统基因库 tab 搜索时显示 loading spinner
- NetworkActor 组件初始加载时显示 loading spinner(初始状态设为 true)
- StudioNotebooksPage 笔记卡片支持暗色主题样式
- StudioNotebookDetailPage / NotebookAIWritingPage 跳转时透传 themekey 参数

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 10:07:13 +08:00
Rocky Kwok 1cbc0e2dd6 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-06-23 09:21:01 +08:00
董宏凯andClaude Opus 4.8 fc632f26e9 feat(大屏绘制): 战情七页版式 + 对接 selectSqReport 真实数据
- 新增 dashboard-agent 独占战情多页(总览/敌情/我情/战场环境/情况判断/决心建议/处置建议),
  经 DashboardApp 的可选 pages 插槽注入,会商 Step3 大屏多页样式零影响
- 总览由六类数据聚合;六个详情页对接 selectSqReport(防御式解析,容错不抛错,
  接口为空显示「暂无数据」)
- 展示层 desensitizeDeep 脱敏 + 请求加载框;去掉所有「更多」按钮

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 22:47:43 +08:00
fengxiangdebaozi adabfa2fe3 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-22 21:03:19 +08:00
吉鑫升 ec56fa671b Merge branch 'ji'
# Conflicts:
#	CLAUDE.md
2026-06-22 21:02:35 +08:00
fengxiangdebaoziandClaude Opus 4.8 f144a59c97 fix(roundtable): xdfx-A 深链会商聊天记录按行动id隔离存储
xdfx 深链 URL ?taskId= 原始值即 actionId(登录时解析成真实任务id)。
一个任务可派生多个行动,各行动会商需互相独立,故聊天记录/后台作业
按 actionId 存取,而非解析出的真实 taskId。

新增 recordTaskIdOf(prefill)=actionId??taskId,应用到草稿 CRUD/回显
(useDraftPersistence/useRoundtableDrafts/loadLatestByTask) 与后台作业
(startJob/getJobByDraft/cancelJob/startJobKeepalive)。目的树/入库/任务
详情/底部快捷跳转栏仍用真实 taskId。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 21:01:34 +08:00
吉鑫升andClaude Opus 4.8 dd942cdd60 feat(xdfx): 行动分析聊天记录按行动id划分 + 首问追加 action_id
xdfx 单智能体问答不再按 task_id 划分聊天记录,改按「行动id(action_id)」划分:
- TaskContext 增加 partitionByAction 标记 + taskThreadMetadata 统一产出线程标签
- xdfx 新建线程额外打 metadata.actionId,对话列表按 actionId(+agent_id) 过滤
- 仍保留 metadata.taskId 以维持后端「任务深链对话全局共享」语义
- 首次提问开场信息追加「行动id(action_id)为…」
- useTaskThreads 增加 actionId 过滤参数;useChatsBase 从上下文派生
rwfx / 3qfx 行为不变。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 21:00:22 +08:00
吉鑫升andClaude Opus 4.8 fbec222eb4 Merge branch 'ji' into master
合并 ji 的功能:开放问答接口(/api/open/chat[/stream] 回传生成文件 + 临时不留存)、
技能地址管理、智能体详情「最近对话」等。
冲突 frontend StrategyRoutes.tsx 已解决:同时保留 admin/roundtable-diagnostics(master)
与 admin/skill-addresses(ji) 两个管理员路由。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 19:39:35 +08:00
吉鑫升andClaude Opus 4.8 7c55a577ad feat(open-chat): 开放问答接口回传生成文件 + 临时不留存
- /api/open/chat[/stream] 新增 include_files(默认开),把智能体在 outputs 目录
  生成的文件(name/virtual_path/encoding(text|base64)/content)随结果回传,
  解决"报告写进文件、answer 只回一段总结"导致拿不到完整内容的问题;
  既无 answer 也无文件时返回 502。
- 无状态运行标记 ephemeral:lead agent 跳过记忆与知识库中间件(不召回/不留存/
  不自动沉淀),取完文件后清理临时线程目录,做到"通过本接口的聊天记录不存储"。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 19:36:30 +08:00
董宏凯 57ffe1a706 Merge branch 'dhk-1' into 'master'
feat(layout): 简洁模式右上角加换肤 + 界面模式下拉切换

See merge request knowledge-base-bj/deerflow-server!142
2026-06-22 11:17:40 +00:00
吉鑫升andClaude Opus 4.8 06b169d7a1 feat(skill-addresses): 新增技能地址修改记录,支持单次记录回退
后端:
- 每次「应用」写一份 {id}.manifest.json(记录本次 from→to 替换明细/文件数/处数),
  放在备份目录的同级,避免被回退误恢复或计入文件数
- GET /backups 返回每条记录的 replaced_total + replacements;POST /rollback/{id} 回退单条

前端:
- 把「撤销上次」升级为「修改记录」面板:每条显示时间/改了哪些地址/文件数,
  带「回退此次」(二次确认);应用后自动展开
- BackupEntry 类型扩展 replacedTotal + replacements

同步更新前后端 CLAUDE.md。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:05:05 +08:00
吉鑫升andClaude Opus 4.8 7487395e44 feat(skill-addresses): 地址检索升级为多关键词匹配
- 空格分隔多个关键词,全部命中(地址或技能名任一包含)才显示,便于在大量地址中收窄
- 搜索框加清除按钮 + 更清晰的占位提示
- 过滤时列表头显示「命中 / 总数」

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:55:44 +08:00
吉鑫升andClaude Opus 4.8 26557b30a0 feat(skill-addresses): 将「技能地址管理」并入管理员「技能管理」页的标签页
- SkillAddressesPage 主体抽成可复用的 SkillAddressesPanel(默认导出保留旧路由作直链回退)
- AdminSkillsPage 顶部加 Tabs:技能列表 + 技能地址管理(嵌入 panel)
- 移除 page-sidebar 左下角设置下拉里两处独立的「技能地址管理」入口
- 同步更新前后端 CLAUDE.md 文档

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:35:42 +08:00
吉鑫升andClaude Opus 4.8 f8228847ab fix(skill-addresses): 补提交被 gitignore 漏掉的 address_scan 引擎模块
skills/ 忽略规则误伤了 packages/harness/deerflow/skills/address_scan.py,
导致部署环境缺模块、启动报 ModuleNotFoundError: deerflow.skills.address_scan。
强制纳入跟踪。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:29:10 +08:00
吉鑫升andClaude Opus 4.8 6b480fdbe9 feat: 新增技能地址管理与开放问答接口,完善任务工作区
- 新增「技能地址管理」页面与 /api/skill-addresses 路由(扫描/预览/批量替换技能内地址)
- 完善 /api/open/chat 开放问答接口与模型工厂、网关配置
- 调整任务工作区、侧边栏与路由
- 将本地 0622/ 临时目录与 __pycache__/ 加入忽略,不提交

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:17:54 +08:00
fengxiangdebaoziandClaude Opus 4.8 0a456e9146 feat(ai-writing): 后台挂起改为即时返回,乐观标记历史「挂起中」
点击「转后台」后立刻 reset 回初始页,挂起请求 fire-and-forget;
历史下拉靠 markBackground/clearBackground 乐观标记马上显示「挂起中」,
不等后端确认,与「多智能体会商」交互一致。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:07:53 +08:00
fengxiangdebaoziandClaude Opus 4.8 b59cbd51d9 feat(ai-writing): 各阶段模型调用自动容错,失败时换下一个模型继续
参考多智能体会商的容错思路:意图解析/大纲/正文/审核四个 LLM
环节失败时,按 config.yaml models 顺序换下一个模型重跑该环节,
并通过 model_switch 事件在前端时间线提示「『X』模型<原因>,
已自动切换到『Y』继续」。正文逐章节、审核逐维度独立切换,
已生成的章节/维度保留;意图解析成功的模型还会写回 state
供下游阶段沿用,避免每阶段重复经历同一次失败。

- nodes/_model_fallback.py: 候选模型链 + 异常分类 + model_switch
  事件构造(沿用 ROUNDTABLE_MODEL_FALLBACK[_MAX] env 开关)
- intent_parser/writer_outline/writer_draft/editor: 失败循环换模型
- 前端 types/reducer/timeline: 新增 model_switch 事件类型,按
  stage 复位对应流式缓冲并以 amber 系统提示渲染

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:07:53 +08:00
fengxiangdebaoziandClaude Opus 4.8 23743ee193 chore: 精简 AI 写作示例文案
ai-writing 表单/检索/欢迎页的占位与示例改为通用文案。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:07:53 +08:00
董宏凯andClaude Opus 4.8 7748661963 feat(roundtable): 历史卡片显示所用业务链(自由模式) + 诊断只收报错日志
- 历史「分析记录」卡片/侧边栏列表:把「第X步」改为本次会商所用业务链名,
  无链条显示「自由模式」。后端 list 轻量 meta 从 step2 正则抽取 chain_title
  (不整体解析大块 JSON),个人草稿 + task 草稿两个 store 都覆盖。
- 会商诊断改为只收集报错日志:record_diagnostic 写库前丢弃 level==info
  运行日志(begin/consensus/gather/job_started),只留 warning/error。
  单点收口覆盖前台/后台/recorder 全部写路径;诊断页标题改「会商报错日志」。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 16:36:31 +08:00
fengxiangdebaoziandClaude Opus 4.8 e28277b21b feat(layout): 全量模式右上角也加界面模式切换
复用 appearance-controls 的 LayoutModeSwitcher,Header 操作区在换肤旁
补上界面模式下拉,与简洁模式右上角保持一致。LayoutModeSwitcher 新增
fallback 属性指明 mode 未设置时的兜底界面(Header 传 full,ChatPage 传 compact)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 15:43:55 +08:00
吉鑫升andClaude Opus 4.8 32476c7ad4 feat: 智能体详情新增「最近对话」列表,完善推荐问题与任务深链配置
- 新增 AgentRecentChats 组件,在智能体详情面板底部按 agent_id 展示最近对话
- 调整问答/智能体侧边栏与最近对话列表展示逻辑
- 补充 dashboard-input、task-deeplink 相关配置与线程工具方法
- 后端推荐问题接口标签处理及 position_sync 微调,新增相关测试

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 14:47:43 +08:00
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
吉鑫升andClaude Opus 4.8 16ba5deb0e feat(agents): 智能体归属/发布操作前增加「账号已切换」提醒
- 新增 useLiveAccount 钩子:跟踪「实时」登录账号(随 storage/focus 刷新),
  并与组件挂载时捕获的账号对比;token 存 localStorage 会被同浏览器其他标签页
  共享,另一标签页登录会静默替换本页 API 所用账号
- agent-card / agent-detail-panel / publish-square-picker-dialog / NewAgentPage
  接入该钩子,切换账号后对归属/发布类操作做提醒,避免误归属

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 11:30:15 +08:00
吉鑫升andClaude Opus 4.8 2b6424b3ff feat(open-chat): 新增 /api/open/chat 开放问答接口
- 无需登录(/api/open/ 加入 auth 白名单 + CSRF 豁免),供外部系统直接调用本项目智能体做问答
- 可指定模型(model_name)与智能体(agent_name 中文名称,扫描 agents/*/config.yaml 解析为运行 id);GET /api/open/agents 列出可选名称
- 只返回最终结果(answer = 最后一段 markdown),不含中间过程/工具调用
- 可靠关闭思考:thinking_enabled=false 时下发 thinking_force_disabled,经 create_chat_model(force_disable_thinking=True) 强制注入 enable_thinking=false(及 GLM thinking.type=disabled),覆盖只声明 supports_thinking 的内网 vLLM/Qwen 模型(与生成标题关思考一致)
- 一次性问答设 is_scheduled_run 跳过自动起标题

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 11:21:56 +08:00
fengxiangdebaoziandClaude Opus 4.8 79f1a004a0 feat(layout): 简洁模式右上角加换肤 + 界面模式下拉切换
抽出共享 appearance-controls(ThemeSwitcher 按 tone 适配 banner/content
配色,新增图标+下拉的 LayoutModeSwitcher);Header 复用换肤组件,简洁模式
ChatPage 顶栏右上角补上换肤与界面模式切换,与全量模式保持一致。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 11:02:51 +08:00
Rocky Kwok b89933e60a chore: ignore 2026-06-22 10:55:00 +08:00
fengxiangdebaozi 548cfd1719 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-22 10:47:15 +08:00
fengxiangdebaozi 7d32b41e90 加载框样式 2026-06-22 10:46:57 +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
g zy dd631d57d4 Merge branch 'gzy' into 'master'
feat: 按钮样式变更

See merge request knowledge-base-bj/deerflow-server!131
2026-06-17 06:29:32 +00:00
ZyGuo a3c8c50212 feat: 按钮样式变更 2026-06-17 13:49:06 +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
吉鑫升 5f39879e4d Merge remote-tracking branch 'origin/master' into ji 2026-06-16 21:08:37 +08:00
吉鑫升andClaude Opus 4.8 342fa8265a feat: 知识批量沉淀改为后台任务,避免 nginx 504
- /ingest/threads/batch 新增 background 参数(默认 true),立即返回 {queued:true}
- 抽取循环抽出 _run_batch_ingest,后台路径显式传入 created_by
- 前端知识库页与输入框、线程 hooks/types 配套调整
- config.yaml 上下文压缩测试值

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 21:07:17 +08:00
董宏凯 1fa2338ac3 Merge branch 'dhk-1' into 'master'
feat(task): 任务详情(cop-task-detail)登录深链增加本地假数据开关

See merge request knowledge-base-bj/deerflow-server!130
2026-06-16 13:07:13 +00:00
董宏凯 56e17f826c Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 21:06:22 +08:00
董宏凯 bc5c2fa3d4 样式修改 2026-06-16 21:06:14 +08:00
fengxiangdebaozi 44cb118f95 bug修复 2026-06-16 20:59:44 +08:00
fengxiangdebaoziandClaude Opus 4.8 1ece2c5a4f fix: 修复全量模式综合管理用户排行榜泄漏到其他侧边栏
综合管理菜单存在两个 id 相同的「用户排行榜」子项,侧边栏以
key={item.id} 渲染导致 React keyed reconciliation 失效,离开综合
管理切换到其他一级菜单时重复 key 的节点无法正确卸载,残留到新的
侧边栏。删除冗余的 adminOnly 重复项(保留的项已通过 userPath 同时
覆盖 admin/非 admin)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:59:14 +08:00
董宏凯andClaude Opus 4.8 2fce5e61c9 feat(ui): 全量版通用问答侧栏深蓝主题适配 + 任务深链接口路径修正
- general-qa-sidebar:侧栏底色 bg-white → bg-sidebar(随主题,深蓝主题=深蓝);
  「新对话」按钮底色 color-mix 混 transparent 而非 white;智能体图标底色改用
  《深蓝 UI 规范》§1.1.7/§1.1.8 的蓝-青系(替换原高彩度玫瑰/琥珀/翠绿渐变)
- task-deeplink:cop-task-detail 接口路径修正 taskAnalysSearch → taskAnalyseSearch
- 同步 mock-data 路径 + CLAUDE.md 文案

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:57:21 +08:00
董宏凯andClaude Opus 4.8 d5d0494928 feat(task): 任务详情(cop-task-detail)登录深链增加本地假数据开关
- 新增 VITE_MOCK_COP_TASK_DETAIL 开关(默认 false 走真实接口;true 时该接口走本地假数据,
  供 consumer 外网不可达时调试),与 VITE_USE_REAL_DATA 独立
- utils/request.ts 按开关把 cop-task-detail 请求切到本地 mock adapter
- task-mock-data.ts 增加 cop-task-detail 假数据 + matcher/adapter
- 各 .env(development/network/production/sit) + .env.example 补充该开关说明

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:57:21 +08:00
Administrator b380575f16 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	frontend-web/src/core/page-layout/sidebar-menu.ts
#	frontend-web/src/core/system-settings/api.ts
#	frontend-web/src/core/system-settings/hooks.ts
#	frontend-web/src/strategy-components/Header.tsx
#	offline-backend-20260512/backend/CLAUDE.md
#	offline-backend-20260512/backend/app/gateway/routers/system_settings.py
#	offline-backend-20260512/backend/packages/harness/deerflow/config/system_settings.py
#	offline-backend-20260512/backend/scripts/sql/column_additions_mysql.sql
2026-06-16 20:01:42 +08:00
AdministratorandClaude Opus 4.8 c21a1127f8 feat: 提炼模板弹窗加宽,后端配置上下文压缩测试值
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 19:50:33 +08:00
董宏凯 e621ce88e6 Merge branch 'dhk-1' into 'master'
feat(ai-writing): 进入写作后自动收起研究模板侧栏

See merge request knowledge-base-bj/deerflow-server!129
2026-06-16 11:50:26 +00:00
董宏凯 761491ec41 代码修改 2026-06-16 19:50:07 +08:00
董宏凯 a35ed77ff0 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 19:41:40 +08:00
董宏凯andClaude Opus 4.8 245ac969a7 feat(task-deeplink): 会商/智能体问答嵌入任务管理布局
任务深链(goPath=3qfx/3qfx-A 等)跳转的多智能体会商 / 单智能体问答
改为嵌进「任务管理」对应业务上下文,侧边栏保持 COH中任务→对应业务 高亮。

- StrategyRoutes: task-management 配下新增 6 条嵌入路由(每业务 roundtable + agent)
- AgentChatPage: 新增 chatBasePath 可选属性,覆盖发消息后 URL 改写 / 新会话路径
- task-deeplink: 跳转目标改为业务别 task-management 嵌入路由(BUSINESS_TASK_BASE)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 19:41:28 +08:00
fengxiangdebaoziandClaude Opus 4.8 ab21911696 feat(ai-writing): 进入写作后自动收起研究模板侧栏
把侧栏+内容区抽成 Provider 内组件 AIWritingBody,读 useAIWriting 状态:
status==='idle' && 非历史模式才显示研究模板侧栏;开始写作/查看历史后收起,写作区铺满。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 19:41:05 +08:00
董宏凯 380407ae2f Merge branch 'dhk-1' into 'master'
代码提交

See merge request knowledge-base-bj/deerflow-server!128
2026-06-16 11:31:03 +00:00
fengxiangdebaozi c0e89044c7 代码提交 2026-06-16 19:30:36 +08:00
吉鑫升andClaude Opus 4.8 4f0494a97a feat: 聊天增加回到最新悬浮钮,智能体面板生成即收起
- 复用 ConversationScrollButton 接入 MessageList,滚离底部时显示一键回到最新问答的悬浮按钮;新增 scrollButtonClassName 以适配各页输入框高度
- 智能体详情面板改用 open+selectedArtifact 判定收起,流式写文件开始即收起让位预览,不再等生成结束

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 19:24:48 +08:00
董宏凯 baf3fadce6 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!127
2026-06-16 11:02:34 +00:00
fengxiangdebaozi ecf068a61c Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 19:01:59 +08:00
fengxiangdebaozi ecaaec939d 路由修改 2026-06-16 19:01:52 +08:00
董宏凯 e3c1adb71a Merge branch 'dhk-1' into 'master'
feat(qa-center): 问答中心左侧栏改造(0616 需求 2-5)

See merge request knowledge-base-bj/deerflow-server!126
2026-06-16 10:56:47 +00:00
董宏凯 ce165ece69 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 18:56:13 +08:00
董宏凯 63bddfdea7 代码修改 2026-06-16 18:56:04 +08:00
fengxiangdebaozi 208a02a912 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 17:59:35 +08:00
fengxiangdebaozi f750b7f04d 地址修改 2026-06-16 17:59:27 +08:00
fengxiangdebaoziandClaude Opus 4.8 ba5aeefe98 feat(ai-writing): 研究模板独立实体 + 配置页 + 内置范例 + 点击直接进入写作(0616 #5)
后端:
- 新持久化包 research_templates(表 ai_writing_research_templates,create_all 建表,注册 models/__init__),deps 接 research_template_store
- 路由 /api/ai-writing/research-templates CRUD(在 ai_writing.py)
- 内置范例 网摘/周报/要讯(DEFAULT_RESEARCH_TEMPLATES + seed_defaults,表空时由 list 接口幂等播种)
- tests/test_research_templates.py(9 passed)

前端:
- api/ai-writing-research-templates.ts + hooks/useResearchTemplates.ts
- 配置页 ResearchTemplatesConfigPage(/page/canvas/research-templates)CRUD
- ResearchSidebar 研究模板改用研究模板实体;点击回填整张表单并直接 startWriting 进入写作;顶部齿轮进配置页

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:59:05 +08:00
吉鑫升andClaude Opus 4.8 d82b5ed884 feat: 摘要中间件增加压缩日志,提炼模板编辑框定高
- summarization_middleware: 真正压缩与复用缓存均记录 info 日志,便于无 stream writer 场景(定时任务/渠道/测试)排查
- KnowledgeManage: 提炼模板 system prompt 编辑框固定为 50vh 高度,内部滚动

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 17:40:14 +08:00
xu hd 12f50123dc Merge branch 'xuhd' into 'master'
Xuhd

See merge request knowledge-base-bj/deerflow-server!125
2026-06-16 09:27:02 +00:00
xuhd 4511c0dee7 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-06-16 17:26:19 +08:00
xuhd f6809349d2 来源上传组件样式优化 2026-06-16 17:26:13 +08:00
吉鑫升andClaude Opus 4.8 97da7dc87f feat: 推荐问题配置支持按标签搜索并在列表展示标签
- 后端列表接口为每个推荐问题附带 tags,并支持 tag_ids OR 过滤
- 前端配置页新增 TagSearchBar(标题/内容搜索 + 标签筛选),卡片展示标签
- 打标签后失效 recommended-questions 查询,列表即时刷新
- 过滤时禁用拖拽排序,避免破坏 sort_order

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 16:52:30 +08:00
董宏凯andClaude Opus 4.8 45049975c2 feat(roundtable): 多智能体会商 + 业务链条页脱敏
- 区域级脱敏 Hook useDesensitizeSubtree:对左右侧面板、顶部标题、
  业务链条选择器/列表弹窗/列表页/配置页/映射页整片脱敏(文本节点,
  跳过 input/textarea 等可编辑控件)
- 消息列表正文保持原文,仅智能体名称脱敏(senderName / 席位名 / 流程图节点)
- Step3 总结/报告/大屏、推荐弹窗等结果面板脱敏
- 沙箱产物预览不脱敏:ArtifactFileDetail 加 disableDesensitize,会商沙箱传入
- desensitize.ts 新增 desensitizeDeep 递归脱敏结构化数据

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 16:43:29 +08:00
fengxiangdebaoziandClaude Opus 4.8 0e4caa5a66 feat(ai-writing): 课题研究笔记本内嵌打开 + 新建/所有空间入口(0616 #5)
- 左栏点笔记本/所有空间 → 右侧内嵌打开(不跳路由),写作布局保持挂载(display:none,不丢 setup 线程),顶部「返回写作」
- ResearchSidebar 加「新建空间」(弹窗 createSearchSpace) 与「所有空间」入口
- StudioNotebookDetailPage 加可选 notebookId prop;StudioNotebooksPage 加可选 onOpenNotebook(内嵌时卡片走回调而非 Link),列表内点空间内嵌打开详情
- 内嵌笔记本详情用 ChatRuntime 包裹(修复 useArtifacts must be used within an ArtifactsProvider)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 16:38:22 +08:00
fengxiangdebaoziandClaude Opus 4.8 f39cffcb9a feat(qa-center): 问答中心左侧栏改造(0616 需求 2-5)
- 多智能体会商:Step1 落地左栏「业务链(public 前3) + 分析记录」;点链=勾选(autoChainResult),第一步澄清后点「进入研讨」才按链执行
- zzJC/zzXD:独立模块路由 /page/strategy/qa/{zzjc,zzxd},常驻左栏(按 agent 标签分组 + 仅本模块会话的聊天记录),点智能体模块内切换不跳页,默认落地配置类型下首个智能体
- zzJC/zzXD admin 设置:左栏齿轮→单选类型(TDesign)配置面板+智能体预览;后端 system_settings.agent_modules 持久化(GET 开放/PUT admin)+ test_agent_modules
- 课题研究:左栏「研究模板(文章类型) + 笔记本」;模板点击预填表单,笔记本点击设为素材来源(selectedNotebookId 上提 WritingFormContext)
- 通用问答:全量模式历史侧栏默认展开

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 16:38:22 +08:00
吉鑫升andClaude Opus 4.8 5182ea5d11 feat: 技能收藏与常驻(always-on)支持
- 新增 skill_favorites / skill_always_on 迁移与持久化模型字段
- skills 路由、存储、前端设置页支持收藏与常驻
- 调整摘要中间件与 lead agent 提示词
- 同步岗位 position_sync 及相关配置清理

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 16:37:43 +08:00
吉鑫升andClaude Opus 4.8 5ebbb82d66 feat: 知识库文件夹/模板、技能压缩设置与摘要窗口调优
- 知识库新增文件夹与模板支持(模型/仓储/服务/迁移),前端知识管理组件
- 岗位管理模型与接口完善
- 技能新增压缩设置页与相关存储/工具能力
- 系统设置扩展配置项
- 摘要中间件 keep 窗口改用 token 预算(16000),减少重复压缩

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 15:23:54 +08:00
吉鑫升andClaude Opus 4.8 e6662cf673 refactor: 移除提示词模板页面及相关接口,精简岗位/标签/用户提示词模型
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 14:32:21 +08:00
董宏凯 fe0dc8d1a5 Merge branch 'dhk-1' into 'master'
feat(roundtable): 第二步席位执行模式(快速/思考/专业问答/多智能体)+ 子智能体任务卡片 + 后台完成跨页通知 + 链条默认模式持久化

See merge request knowledge-base-bj/deerflow-server!124
2026-06-16 06:19:04 +00:00
董宏凯 8794c51f88 提交 2026-06-16 14:18:15 +08:00
董宏凯andClaude Opus 4.8 8d1669adad feat(roundtable): 后台作业按用户并发限流 + 草稿持久化优化
后台挂起作业每个 agent 轮次(leader/seat/report/summary/dashboard)开跑前
先取该用户的后台并发额度(默认 2,ROUNDTABLE_BACKGROUND_SLOTS_PER_USER 可调),
跑完释放;同一用户多个后台作业共享额度,避免把单连接 SQLite checkpointer 和
离线模型端点打满拖垮前台实时会商。前台实时路径不经过此额度,不受限。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 14:17:30 +08:00
董宏凯andClaude Opus 4.8 da3d38013e feat(ai-writing): 素材收集技能调用失败时容错回退到其他技能
默认/选中技能调用失败(超时、报错、全部检索词失败)时不再直接报错,
改用其他技能继续检索:节点 emit skill_error 步骤(带真实原因),配置技能
全部失败且无新素材时跑 fallback 兜底(内置知识库检索优先,再到目录其它已
启用技能)。前端 SkillStepsCard 渲染 skill_error(玫红)/ fallback(琥珀),
时间线展示"技能报错→改用其他技能搜集"。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 14:15:49 +08:00
g zy b2ef4ce89e Merge branch 'gzy' into 'master'
feat: iframe增加智能体选择

See merge request knowledge-base-bj/deerflow-server!123
2026-06-16 05:07:03 +00:00
ZyGuo f525c49267 feat: iframe增加智能体选择 2026-06-16 13:06:36 +08:00
吉鑫升andClaude Opus 4.8 838e986670 feat: 导航菜单新增岗位管理与提示词模板入口
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 11:14:47 +08:00
吉鑫升 fa70b31873 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	frontend-web/src/components/workspace/input-box.tsx
#	offline-backend-20260512/backend/CLAUDE.md
2026-06-16 11:07:31 +08:00
吉鑫升andClaude Opus 4.8 3855c30edd feat: 新增岗位管理、提示词模板与资源标签,完善用户提示词与推荐问题接口
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 10:49:36 +08:00
董宏凯 c7dccf8c0b Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 10:09:35 +08:00
董宏凯 2526304394 sd 2026-06-16 10:09:30 +08:00
fengxiangdebaozi e1da39253a Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-16 10:06:14 +08:00
fengxiangdebaozi 6b49741e69 代码修改 2026-06-16 10:05:54 +08:00
吉鑫升andClaude Fable 5 2f414c6e08 fix: HTML 预览子页面改用 JS 切换,避免沙箱 blob 导航被拦截
上一版通过设置 location.hash 触发 CSS :target 切页,但沙箱 blob
iframe 禁止导航到自身 blob URL,浏览器报 Not allowed to load local
resource,且 :target 仅在真实片段导航时更新,注定失效。改为完全
不动 hash,用 JS 模拟 html-multipage 技能的 .page/.pages 显示隐藏
(内联 display 覆盖类级 CSS),普通目录锚点仍平滑滚动。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 09:19:15 +08:00
董宏凯andClaude Opus 4.8 9ed5420381 feat(light-app): 应用管理页加类型分类筛选 + 修复深色顶栏标题高分屏内边距
- 应用管理工具栏新增「全部/新页跳转/iframe嵌套」分类切换,选中 iframe
  嵌套时出现挂载菜单下拉,可按 mountLocation 进一步筛选(深色/浅蓝主题适配)
- 深色顶栏 .header-center-title 内边距由固定 155px 改为 8.07vw,随视口
  等比缩放以匹配 background cover,修复 4K 等高分屏两侧菜单贴近中间的问题

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 22:33:18 +08:00
董宏凯andClaude Sonnet 4.6 69c8c14c91 fix(nav): 修复问答梳理等带子路径页面的导航高亮丢失问题
KnowledgeBasePage 加载后自动跳转至 /knowledge/:noteId,原精确路径匹配
导致顶栏和侧边栏选中态丢失。将 hasActiveChild / isItemActive /
menuItemContainsPath 等 8 处判断统一改为前缀匹配
(pathname === path || pathname.startsWith(path + "/")),
覆盖浅色侧边栏、深色侧边栏、顶部导航栏三套组件。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 20:50:26 +08:00
董宏凯andClaude Sonnet 4.6 88b1a330a6 fix(roundtable): 修复弹窗被顶部导航栏遮挡的 z-index 问题
将全局 Header z-[2101] 降为 z-[45]、圆桌页内部 header z-[2000] 降为 z-[40],
使两者低于 Shadcn Dialog 遮罩层 z-50,弹窗打开时可正常覆盖导航栏。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 18:32:07 +08:00
董宏凯 9e481cdcaa Merge branch 'dhk-1' into 'master'
feat(theme): 浅蓝色主题适配 —— COH任务三子页 + 应用中心子页

See merge request knowledge-base-bj/deerflow-server!122
2026-06-15 10:21:08 +00:00
fengxiangdebaozi db50493577 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-15 18:20:39 +08:00
fengxiangdebaoziandClaude Opus 4.8 3907034a1d feat(roundtable): 第二步席位执行模式(快速/思考/专业问答/多智能体)+ 子智能体任务卡片 + 后台完成跨页通知 + 链条默认模式持久化
- 席位执行模式:选择参会智能体弹窗加模式选择器,映射 thinking/reasoning/subagent
  透传 recommend/chain/dag 三条编排;后端 _special_run 覆盖 seat policy(仅席位,
  总控不变);ultra 解锁席位 task 子代理(custom 流回传 task_running 实时进度)。
- 子智能体任务卡片:复用主聊天 SubtaskCard + SubtaskContext,从席位流解析 task
  调用/结果,在 Step2 气泡渲染多张任务卡片(覆盖业务链条路径)。
- 后台挂起也按所选模式跑(StartParams→inprocess gateway→run_seat 覆盖 policy)。
- 后台作业完成全工作区跨页通知:RoundtableJobNotifier 挂在 PageLayout 常驻层,
  作业终态弹「达成共识」同款浮窗。
- 业务链条可配「默认执行模式」并持久化(roundtable_chains.seat_mode;选链时弹窗
  默认用它,仍可临时改)。
- 修复后台 Step3 HTML 看板概率截断:deepseek max_tokens=4096 单轮写不完长 HTML,
  产物自愈重试上限 2→5,让 append 续写写完整(同惠及 summary/dashboard)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 18:20:20 +08:00
董宏凯andClaude Sonnet 4.6 b1b2540dc0 feat(theme): 浅蓝色主题适配 —— COH任务三子页 + 应用中心子页
- ThemeContext: 新增 data-theme="lightblue" 属性管理,支持红/蓝双浅色主题
- strategy-data.css: 新增 [data-theme="lightblue"] 变量覆盖块(与浅红默认共存)
- SentimentAnalyzes / TaskAnalyzes / ActionAnalyzes / KanbanColumn / TaskCard / ActionColumn:
  isDark ? dark : isLightBlue ? blue : red 三路适配
- LightAppListPage: 应用列表页品牌色(标题点、徽章、搜索 focus、计数、进入按钮)浅蓝适配
- LightAppNoteQAPage: 问答发送按钮浅蓝适配
- light-app-management.css: 新增 [data-theme="lightblue"] CSS 覆盖块(主按钮、保存、开关、输入 focus 等)
- light-app-pages.css: 浅蓝模式页面底色轻染 #F9FCFF

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 18:16:06 +08:00
董宏凯 5dc1ed5685 Merge branch 'dhk-1' into 'master'
fix(sandbox): 修复 Markdown 编辑保存后内容被重置回原值

See merge request knowledge-base-bj/deerflow-server!121
2026-06-15 09:11:09 +00:00
董宏凯 1ad8da5ef2 代码提交 2026-06-15 17:04:53 +08:00
董宏凯andClaude Opus 4.8 22e9f18d08 chore(chat): 移除 landing 紧凑态底部 V1.2 免责声明
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 16:55:10 +08:00
董宏凯andClaude Opus 4.8 b6c9265e31 feat(light-app): 轻应用中心列表/管理页深蓝主题适配
- 新增 light-app-pages.css / light-app-management.css,引入《深蓝色 UI 规范》
  tokens,.dark 下覆盖页面底图、页头文案、主按钮、表格、下拉弹层等
- 列表/管理页根节点加 className 钩子与 dark: 背景类,浅色样式不变

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 16:55:06 +08:00
董宏凯andClaude Opus 4.8 ee6ab38c37 feat(nav): 浅色模式导航重构(顶栏一级 + 侧边栏二级图标卡 + 三级右侧列)
浅色(红/蓝)主题改为与深色一致的导航逻辑,颜色经 --brand-* 变量自动切换:
- 一级导航正常横排进顶栏(白字落在 banner 上,选中加粗 + 底部粗白线)
- 二级导航为侧边栏图标卡片(图标主题色、文字 #222222、选中铺满列宽 + 右侧粗边)
- 三级导航改到侧边栏二级右侧的「三级列」:激活二级项有三级时整列展开、
  侧边栏 96→236px 整体变宽并带过渡动画,主内容左内边距同步平滑右移
- 顶栏三级横条改为仅深色用;浅色不支持侧边栏收起
- 任务管理二级项改用区分图标(ClipboardList/Activity/Gauge/Radar)
- 字体统一用全局 --font-sans,修复雅黑兜底下加粗不生效
- 抽出 getActiveThirdLevelItems / useActiveThirdLevel 供侧边栏与 PageRoutes 共用

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 16:53:21 +08:00
董宏凯andClaude Opus 4.8 fbd237531e fix(roundtable-share): 修复分享拿不到总控结论/各席位交付 + 分享总结报告与大屏多页
排查发现后台作业把结果写进 step2.runs[activeRun],而顶层 step2 残留前台 seed
的陈旧气泡(无交付、无结论)。_result_sections 旧逻辑「顶层为空才回退 run」因顶层
非空而永不回退,导致分享页 consensus 与 seat_deliveries 为空。改为优先读活动 run
(与前端 hydrate 一致),已有分享链接无需重建即生效。

同时把第三步另外两个产物纳入分享:
- 方案总结报告(step3.summaryReport.md,Markdown 内联渲染)
- 大屏多页(step3.dashboardJson,用应用内 React 大屏 DashboardApp 渲染,新增
  /roundtable-share/:code/dashboard 路由,与应用渲染/新窗口打开同源)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 12:57:33 +08:00
董宏凯andClaude Opus 4.8 49101ef0e8 feat(roundtable): 第二/三步沙箱 md 文件支持用户编辑
复用主聊天页同款 ArtifactFileDetail 编辑能力:新增 allowVirtualMarkdownEdit
开关,圆桌沙箱里 write-file 虚拟 md 在流式结束后切回真实 artifacts API
(可加载 + PATCH 保存),由 Step2SandboxLayout 与 HighFidelityReport 启用。
主聊天页等其它调用方默认关闭、行为不变。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 12:57:18 +08:00
董宏凯 8751ee7361 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-15 11:39:24 +08:00
董宏凯andClaude Haiku 4.5 01012ff300 feat(settings): 轻应用登录参数与界面模式管理员默认
- 登录时从路由参数 yUserId/access_token 获取并存入 userInfo
- 轻应用管理页路由参数新增 userName/gateDepartName/typeName 选项
- 添加系统默认界面模式设置(管理员可指定全量/简洁)
- useLayoutMode hook 支持优先级:用户自选 > 管理员默认 > 会话级

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-06-15 11:39:02 +08:00
fengxiangdebaoziandClaude Opus 4.8 2a2bb4d28e fix(sandbox): 修复 Markdown 编辑保存后内容被重置回原值
useArtifactContent 查询键含 publicShareCode(5 元素),而 onSuccess
的 setQueryData 仅用 4 元素,精确哈希不匹配导致写入幽灵缓存、真实缓存
仍为旧值;保存后 useEffect 据旧 content 重置 draftContent。改用
setQueriesData 前缀匹配命中真实缓存。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 11:37:24 +08:00
fengxiangdebaozi ce04f14f58 Merge branch 'origin/dhk-1' into dhk-1
Resolve CLAUDE.md conflict by keeping remote version.
2026-06-15 11:13:42 +08:00
fengxiangdebaozi 16b36e2b9f 代码修改 2026-06-15 11:02:33 +08:00
董宏凯 c597941128 Merge branch 'dhk-1' into 'master'
fix(roundtable): 查看编排流程图按钮直接进入基本信息步骤

See merge request knowledge-base-bj/deerflow-server!120
2026-06-14 14:29:41 +00:00
董宏凯andCursor ab22b50faf fix(roundtable): 查看编排流程图按钮直接进入基本信息步骤
移除弹窗预览,改为跳转到第二步以便同时编辑基本信息并查看流程图。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-14 19:37:22 +08:00
董宏凯 7785091bae Merge branch 'dhk-1' into 'master'
feat(圆桌): 业务链条配置页流程图点阵放大 + 侧边栏菜单项按设计稿还原

See merge request knowledge-base-bj/deerflow-server!119
2026-06-14 11:31:50 +00:00
董宏凯 56449ed129 feat(ui): theme & layout improvements
- Dark-blue theme background assets and styling integration
- Appearance settings with layoutMode (full/compact) preference
- Settings dialog and auth context updates
- AI writing form and panel refinements
- Open Canvas context updates
- Roundtable planning styling and dashboard enhancements
- Strategy components and header updates
- Light app management and routing improvements
- Global style enhancements for dark theme
- Various page layout and workspace routing optimizations
2026-06-14 19:30:54 +08:00
董宏凯 da2864f422 fix(chat): align compactChrome logic with layoutMode preference for dark-blue bg
ChatPage's compactChrome was still using readSidebarEnabled() alone, but
PageRoutes now honors the explicit layoutMode setting (full/compact). When a
user sets layout to 'full' without portal login, PageRoutes shows chrome but
ChatPage didn't apply workspace-chat-bg, hiding the dark-blue theme background.

Now ChatPage mirrors PageRoutes' logic: prioritize layoutMode, fallback to
readSidebarEnabled() if unset.
2026-06-14 19:30:04 +08:00
董宏凯andCursor c702119e66 feat(ui): 浅蓝主题、外观设置与圆桌看板主题适配,优化工作区布局
新增 lightblue 主题与外观设置联动,圆桌 Step3 看板/report 统一配色;工作区侧边栏、输入框与轻应用 iframe 主题参数同步更新。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-14 12:43:16 +08:00
董宏凯 30d4f9667b 样式修改 2026-06-13 20:43:18 +08:00
董宏凯andClaude Opus 4.8 cd3a71baab feat(agents): 内置智能体筛选(仅管理员)+ 内置 agent 默认用途标签
- 后端 scope=builtin(user_id IS NULL)加入 sql/memory 的 scope 过滤;
  /api/agents 扩展 scope 正则并加 admin 闸门(非管理员请求 403)
- 新增 _builtin_agent_tag_seed:启动时幂等给功能型内置 agent 按用途打标签
  (roundtable-* → 多智能体规划,ai-writing-* → AI写作),只追加不覆盖;
  无用途的内置 agent 不打标签
- 前端 agent-gallery 新增「内置智能体」Tab(仅 system_role==admin 可见),
  scope 类型在 api.ts/hooks.ts 同步

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 20:42:26 +08:00
董宏凯andClaude Opus 4.8 391409b6c0 feat(圆桌): 查看运行中作业改为接管回前端续跑 + 后台挂起续跑方案文档
- onView 运行中/待澄清作业改走 takeOverRunningJob:cancelJob 停后端 →
  handleLoadDraft 恢复作业真实线程/协调名/对话 → 解除只读闸门 →
  resumeLiveTakeover 在作业线程上由前端继续实时流式编排
- hydrateFromDraft 同步写 threadIdsRef/coordinatorNameRef,使接管同帧可读真实线程
- 新增 docs/multi-agent-后台挂起续跑实现方案.md(仅方案,待实现)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 18:49:19 +08:00
董宏凯andClaude Opus 4.8 25dbeb7a9a feat(圆桌): 业务链条配置页流程图点阵放大 + 侧边栏菜单项按设计稿还原
- ChainFlowDiagram 点阵背景点尺寸/不透明度上调,更接近设计稿颗粒感
- 全局侧边栏菜单项:锐利方角(2px)、选中整高左竖条、图标 hover 微放大、间距微调;保留原菜单内容与红/青配色

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 18:41:50 +08:00
董宏凯 12360c6f3f Merge branch 'dhk-1' into 'master'
轻应用主题参数:随当前主题色映射传值

See merge request knowledge-base-bj/deerflow-server!118
2026-06-13 10:01:30 +00:00
董宏凯andClaude Opus 4.8 61754acb87 feat(圆桌): 后台挂起按钮移至顶部暂停按钮右侧 + 实时研讨复位历史闸门
- Step2 顶部「暂停/恢复会商」右侧新增「后台挂起」按钮(查看历史时隐藏),移除底部干预栏里的旧入口
- handleConfirmAgents 从第一步开启实时研讨时复位 loadedFromDraftRef,修复看过历史后再开新讨论按钮不出现的问题
- 大屏 dashboard 多组件样式与业务链条编辑页细节调整

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 17:37:14 +08:00
董宏凯andClaude Opus 4.8 634cb1413b feat(圆桌): 业务链条配置页按设计稿还原
统计卡 + 筛选工具栏(我的/公共/搜索/排序/网格列表) + 富链条卡(流程脉络图),
数据来自 /api/roundtable-chains 按用户隔离;品牌主色 #CF1322,深蓝模式按规范取色。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 16:32:40 +08:00
董宏凯andClaude Opus 4.8 2fa40c5e96 feat(圆桌): 大屏多页席位多样式+新窗口React页+布局优化+切历史记录刷新
- 新窗口打开改为渲染应用内 React 大屏(独立全屏路由 /roundtable-dashboard,
  经 localStorage 传数据,无侧边栏),替代原自包含 HTML blob
- 总览页布局:上半两列(总控共识+竞争力排行),核心风险分布下移到数据研判中心后
- 席位交付/执行路线网格列数自适应(grid.ts):不足4个卡片撑满整行
- 席位专页主体多样式变体(SeatShowcase):框架矩阵/洞察卡阵/双栏对比/清单核对/
  发布声明,按席位序号轮转分配,总结席位固定发布声明,全部数据驱动
- 修复切换历史记录时大屏/报告不刷新:渲染期复位入口闸门+hydrate依赖草稿id,
  hydrateSaved清残留data;数据切换时大屏自动回总览页

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 16:32:32 +08:00
董宏凯 432c12fbac @
feat(圆桌): Step3 大屏多页模板重构 + 独立 dashboard 组件化

- 新增 roundtable-planning/dashboard 模块化大屏(DashboardApp + 各分析卡片
  组件 + data-context + 类型/样式)
- Step3DashboardMode 接入新 dashboard,report-template 大屏 HTML 模板重写
- useStep3Dashboard 配套调整

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@
2026-06-13 15:32:49 +08:00
董宏凯 146c8e76f0 @
feat(圆桌): 业务链条显示配置人 + 配置页拆两步并新增精美流程图

- 列表/弹窗卡片显示「配置人」(后端把 owner user_id 解析为 email,
  ChainResponse 增 owner_id/owner_name,store 输出 owner_id)
- 配置编辑器拆为两步:第一步基本信息(描述改多行文本),第二步链条编排
- 第一步有编排内容时,左侧基本信息 + 右侧 ChainFlowDiagram 流程图:
  直角连线、点节点开详情抽屉、连线显示阶段目标(依赖)、滚轮缩放、
  拖动平移、全屏 + 全屏右下角缩略图

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@
2026-06-13 15:32:37 +08:00
董宏凯 e9f44c8f0f @
feat(圆桌): 大屏多页浅色模板重写为蓝图工程图风(参考设计图)

- 浅色 palette 改玫瑰红(#E11D48)+slate 中性+白底网格,席位色序对齐设计图
- 卡片四角红色角标 + slate 网格 overlay(蓝图风);KPI 加彩色图标
- 共识竖条摘要 + 要点列表;席位卡进度条 + 风险药丸;席位专页精致化
- 新增折线图 svgLine(趋势),donut 升级镂空中心数字+图例;契约加 line 类型
- 图表保持纯 SVG(零依赖离线自包含,沙箱/新窗口/下载/分享通用,与参考源码一致)
- 深色保持深蓝 token 套同结构

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@
2026-06-13 10:51:10 +08:00
董宏凯 f3202f95b6 Merge remote-tracking branch 'origin/dhk-1' into dhk-1 2026-06-13 10:37:16 +08:00
董宏凯 d5f319d9cb @
feat(圆桌): Step3 三产物并行 + 大屏多页模式 + 后台挂起查看恢复流程

后台挂起 Step3:
- engine 总结报告/结果绘制/大屏数据 asyncio.gather 三流并行,故障隔离
- request.state 回归修复(进程内虚拟 request 补 state),恢复后台报告
- ROUNDTABLE_JOB_GATEWAY 默认 inprocess;产物自愈重试(截断/缺失纠偏)
- 大屏后端只产 report-json(dashboardJson),前端按当前主题渲染

结果绘制大屏多页模式(模式二):
- report-template 模板渲染(report-json→大屏HTML),零截断、主题跟随
- 与模式一同款交互(流式+沙箱+可修改);沙箱新窗口打开按钮

最终方案展示:左侧席位栏+总控头像、交付/文件合并、收展动画、内联沙箱

后台挂起查看=恢复实时流程:
- handleLoadDraft 返回 Promise,await hydrate 后订阅 streamJob SSE 跟随
- saveDraftNow 强制存(发起前+查看前各一次)防丢

第二步优化:总控判断串/并行(并行单列可写)、席位上下文+交付模板、
peerDeliveries、失败重试、共识标记、流程图小窗(缩放/拖动/并行批)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@
2026-06-13 10:36:46 +08:00
fengxiangdebaoziandClaude Opus 4.8 74324f4585 轻应用主题参数:随当前主题色映射传值
- 主题参数改为按系统主题(red/dark-blue)映射取目标应用对应的值
- 应用管理弹窗用结构化映射编辑器(逐主题色配置目标值,默认同名)
- iframe 嵌套显式传入当前主题色,切主题时 src 重建
- 读取/保存时规范化映射串;解析支持 light/dark 等别名,取不到回退主题色名而非恒为 red

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 22:30:31 +08:00
吉鑫升andClaude Fable 5 21e53310f8 fix: HTML 预览锚点点击同步 hash,修复多页面技能子页面切换失效
预览 iframe 注入的锚点拦截脚本只 preventDefault + scrollIntoView,
URL hash 从未改变,html-multipage 技能基于 CSS :target 的子页面
切换永远不命中,子页面 section 保持隐藏,点击无效。改为拦截后
同步 location.hash 触发 :target 切页,仅当目标元素已渲染时再平滑滚动。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 21:49:32 +08:00
董宏凯 a7596001c5 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 21:46:05 +08:00
董宏凯 93243298e1 代码修改 2026-06-12 21:45:55 +08:00
fengxiangdebaozi ca098e821f Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 21:39:48 +08:00
fengxiangdebaozi 00d6bd8595 主题色修改 2026-06-12 21:38:38 +08:00
董宏凯 f0c85c4795 后台挂起功能修改 2026-06-12 21:38:20 +08:00
吉鑫升andClaude Opus 4.8 74113b3e6e feat: 智能体与技能列表显示创建时间字段
- 新增共享 formatDateTime 工具(YYYY-MM-DD HH:mm)
- agent-card 卡片/列表视图在发布者下方显示创建时间
- skill 设置页 metaNodes 显示创建时间

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 21:20:33 +08:00
董宏凯 cca954d01c Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 20:29:03 +08:00
吉鑫升 d825cc7cfe Merge branch 'ji' 2026-06-12 20:28:27 +08:00
董宏凯 ffca4261d7 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 20:27:39 +08:00
董宏凯 865a0bfaf6 代码修改 2026-06-12 20:27:34 +08:00
吉鑫升andClaude Opus 4.8 595da9f339 fix: 私密广场首次加载默认 page=1,使搜索/标签过滤生效
私密广场标签页传 page: pages.private,初始为 undefined,被 JSON.stringify 丢弃后后端走非分页分支忽略 search/tag_ids。补上 ?? 1 兜底,与主标签页一致。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 20:27:29 +08:00
吉鑫升andClaude Opus 4.8 44b4a4beba feat: 注册知识入库接口 + 优化大规模知识图谱力导向布局
- 后端 Gateway 挂载 /api/knowledge-ingest 路由(发布 md 制品)
- 知识图谱力模拟按节点规模缩放斥力/截断距离/冷却速率,避免数百节点时布局长时间不收敛
- 斥力与碰撞改为基于均匀网格的近邻对计算,并增加每帧最大位移限制防止抖动与飞出

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 20:14:22 +08:00
董宏凯 c66c359432 Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!117
2026-06-12 11:33:18 +00:00
fengxiangdebaozi 1214ea0d91 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 19:30:56 +08:00
fengxiangdebaozi cfa05e01c4 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 19:30:46 +08:00
Administrator 6a71272b79 Merge remote-tracking branch 'origin/master' into ji 2026-06-12 18:48:20 +08:00
Administrator b9b55b4e5b fix: 调整提问导航悬浮索引到右侧居中 2026-06-12 18:48:18 +08:00
董宏凯andCursor 3f2aef2925 Merge remote-tracking branch 'origin/dhk-1' into dhk-1,保留本地应用中心菜单配置。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 18:48:11 +08:00
fengxiangdebaozi 7a8a29639f 代码修改 2026-06-12 18:45:04 +08:00
董宏凯andCursor becfd9b211 Merge branch 'origin/dhk-1' into dhk-1,解决 sidebar-menu 冲突并保留应用中心菜单。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 18:38:53 +08:00
fengxiangdebaozi c6b17d5946 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 18:34:14 +08:00
fengxiangdebaozi e24e058ab2 代码修改 2026-06-12 18:32:58 +08:00
Administrator e74ef4b7dc Merge branch 'ji' into master 2026-06-12 18:28:13 +08:00
董宏凯 c2f6d4fd6f Merge branch 'dhk-1' into 'master'
AI 写作四阶段内置智能体 Phase 1-4 落地

See merge request knowledge-base-bj/deerflow-server!116
2026-06-12 10:20:27 +00:00
Administrator 2862eee33b chore: 提交本地修改 2026-06-12 18:09:07 +08:00
fengxiangdebaozi 3ad920457a Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 17:54:10 +08:00
fengxiangdebaozi 768c6860f5 feat: Header 顶部二三级菜单与 AI 写作表单收起优化 2026-06-12 17:53:52 +08:00
董宏凯andCursor 369efc784b 应用管理页样式对齐参考设计,修复参数明细弹层被裁切问题。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 17:50:56 +08:00
xu hd 522327d807 Merge branch 'xuhd' into 'master'
feat(studio): 上传组件用我的笔记 token + 关闭上传弹窗刷新来源列表

See merge request knowledge-base-bj/deerflow-server!115
2026-06-12 09:38:20 +00:00
xuhd 915233c5b6 Merge remote-tracking branch 'origin/master' into xuhd 2026-06-12 17:24:13 +08:00
吉鑫升andClaude Opus 4.8 229830ee89 feat: 智能体 md 产物一键发布到外部知识入库接口
- 智能体新增「入库模板名」(template_name) 配置,持久化到 config.yaml
  并经 AgentCreate/Update/Response 回读(NewAgentPage / AgentDetailPanel)
- 新增 POST /api/knowledge-ingest/publish:把 md 标题+全文发到 knowes,
  标题字段先「名称」失败再用同一 nodeName 换「标题」重试一次
- md 产物预览右上角新增「发布入库」按钮(仅智能体会话且配置了模板名时显示)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 16:38:04 +08:00
董宏凯andCursor dd329e7a4f 圆桌第二步支持按席位筛选会商记录,左侧角色卡与消息头像联动。
新增 seat-filter 归一化匹配逻辑,点击角色卡或气泡头像可只看该席位发言,并支持一键显示全部。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 16:36:58 +08:00
g zy da56a53a9c Merge branch 'gzy' into 'master'
Gzy

See merge request knowledge-base-bj/deerflow-server!114
2026-06-12 08:33:39 +00:00
ZyGuo 3f014a6fe1 feat: chats_iframe去掉侧边栏和主题 2026-06-12 16:32:28 +08:00
吉鑫升andClaude Fable 5 d9d5780ea7 feat: 提问导航悬浮索引 + 知识库召回会话级开关 + 智能体技能白名单收紧
- 新增 QuestionNavigator:聊天/智能体页右侧悬浮提问索引,点击滚动定位到对应消息(message-list 为 human 消息生成锚点 id)
- 知识库召回开关从单会话头部按钮迁移到侧边栏,改为会话级内存开关(刷新重置,不再写 localStorage),开启时所有对话默认携带 knowledge_rag_enabled
- 智能体可配置技能收紧为「内置 + 自己的 + 已发布到广场的」(新增 core/skills/utils.ts 的 isAgentSkillCandidate,NewAgentPage 与 agent-detail-panel 共用)
- 智能体详情面板在 artifact 预览展开/新文件生成时自动收起让位
- 启用 html-multipage 技能并更新后端 CLAUDE.md 文档

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 16:10:00 +08:00
董宏凯 9002ae157a Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 15:48:53 +08:00
董宏凯 f279613f5d 代码提交 2026-06-12 15:48:48 +08:00
董宏凯andCursor b58e731c19 圆桌会商各步接入流式回答速度指示器,复用主聊天 SpeedPill 与全局开关。
新增 DialogueSpeedMeter 与 useDialogueSpeedMetrics,在 Step1/2/3 气泡底部展示 tok/s 与耗时。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 15:43:58 +08:00
fengxiangdebaozi 9d73f27146 feat: light app center and iframe refactor 2026-06-12 15:40:09 +08:00
吉鑫升andClaude Fable 5 81f2a48c6d feat: 公开嵌入页主题支持外部指定 + 排行榜入口移至左上角
- 公开页(/share、/public、/roundtable-share)新增 ?theme= 与
  deerflow:set-theme postMessage 两种外部主题指定方式,经
  usePublicEmbedTheme 接成 next-themes forcedTheme,不写 localStorage
- 排行榜入口从欢迎语旁移到 workspace-header 左上角应用名旁
- 新增 docs/embed-public-pages-theme.md 嵌入主题使用文档

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 15:12:17 +08:00
吉鑫升andClaude Fable 5 57a87d6322 feat: MySQL 索引长度兼容 + 启动自动补列 + 未发布徽标与查询加载态
后端:
- 索引/唯一键改用 mysql_length 前缀索引,适配 MySQL 767 字节限制(error 1071):knowledge_notes、knowledge_entities、knowledge_graph_blacklist、agent_skills、feedback
- engine.py 新增 _ensure_orm_columns_sync:启动时对比 ORM 元数据,自动 ALTER TABLE 补齐缺失的可空/带默认值列及其索引
- 新增 scripts/audit_index_key_lengths.py 审计全部索引键长度
- 更新 backend/CLAUDE.md 迁移说明

前端:
- 智能体卡片/技能列表:所有者与管理员可见未发布徽标
- 智能体广场:服务端查询进行中时灰显旧结果并悬浮加载提示
- 排行榜入口从 Header 移到欢迎语旁
- threads/hooks.ts:抽取 updateCachedThreadLists 统一处理数组与分页两种缓存形态

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 14:51:50 +08:00
董宏凯 728a4b1170 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 14:10:08 +08:00
董宏凯 9de85591bc 提交 2026-06-12 14:09:12 +08:00
董宏凯andClaude Fable 5 086c280e5d 圆桌第三步流程图模式 + 后台 DAG 任务编排
- 方案总结报告:用户要求结构化输出/流程图时跳过 md 直出 flow-json 流程图,
  报告用文字展示;报告与流程图均可多轮修改、互相切换(detectFlowIntent 识别意图)
- 流程图画布放右侧沙箱位(sidePanel 插槽)不覆盖消息列表,可与 md 预览切换;
  节点随容器宽度自适应缩放并 fitView 居中
- 后台挂起支持真 DAG 编排(分层并行/阶段目标/总控提示词),新增
  orchestration_plan 持久化列 + 迁移;大弹窗流程图按 DAG 分层渲染

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 13:52:17 +08:00
AdministratorandClaude Opus 4.8 da677f87d5 feat: 公开页背景色支持 iframe 外部配置 + CM助手旁排行榜入口
- 新增 usePublicBackground:公开页(排行榜/分享/会商分享/计划任务)支持
  嵌套方通过 ?bg=/?text= 查询参数或 postMessage 覆盖背景/文字色
- Header 左上角 CM助手 旁新增「排行榜」按钮,新标签打开公开排行榜页

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 12:21:25 +08:00
吉鑫升andClaude Fable 5 28098b3155 feat: 知识库实体筛选、技能白名单收紧、嵌入主题与提问组件优化
- 知识库笔记列表支持按实体精确筛选(路由/服务/仓储层透传,关系图索引查询)
- 自定义智能体技能白名单在 skill_view 与 skill_manage 的 list/view 别名上同样生效;
  config 未声明 skills 时视为无可见技能
- 嵌入圆桌主题解析默认深蓝,强制主题期间不再写 localStorage 覆盖主站选择
- 智能体提问建议拆出 agent-question-chips 组件,编辑器与详情面板联动优化
- 新增 qa-client 问答测试脚本

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 11:09:32 +08:00
xuhdandClaude Opus 4.8 c268348e29 feat(studio): 上传组件用我的笔记 token + 关闭上传弹窗刷新来源列表
- document-upload-popup: 新增 getNotebookToken(),上传/导入到笔记后端
  (source/import、documents/fileupload)改用「我的笔记」token;
  其余请求由调用方在 init.headers 自带 Authorization,不再注入本系统 token
- query-client-provider: 导出 queryClient 单例,便于非 hook 处读取缓存的 token
- network-actor: consumerUrl 改为读 VITE_AIPI_CONSUMER_URL;修复 source/import
  headers 语法并去掉重复 token
- StudioNotebookDetailPage: DocumentUploadDialogProvider 增加 onClose,
  关闭上传弹窗时刷新来源列表与 source_count

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 10:14:49 +08:00
fengxiangdebaozi b33426416b Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-12 09:19:47 +08:00
fengxiangdebaozi cf3dd2d225 代码修改 2026-06-12 09:19:38 +08:00
吉鑫升 11bc442f10 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-12 09:19:23 +08:00
ZyGuo 41ce95cbf1 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-06-12 09:07:23 +08:00
董宏凯 75258db0a2 提交 2026-06-12 00:38:17 +08:00
董宏凯andClaude Fable 5 df8bf895ef 圆桌第三步与业务链条增强:主题跟随/插话暂停/提示词优化/结构化流程图
- 结果绘制跟随日/夜间主题(深色按深蓝 UI 规范令牌绘制),提示词注入真实生成时间
- 绘制支持暂停与随时插话(线程存活时免带原料续线程省 token)、失败自动重试一次、草稿主题不匹配提示条
- 总结报告优先执行用户最终总结要求(结构化输出/重点席位可整体替换默认章节)
- 业务链条总控提示词与各阶段目标加「AI 优化」按钮(新接口 POST /api/roundtable-chains/optimize-prompt)
- 总结报告 flow-json 结构化流程图:流式增量绘制、最新连线蚂蚁线动画、拖拽/缩放/复位/全屏、节点详情弹窗、沙箱切换按钮/无沙箱自动打开
- roundtable-report / roundtable-summary 两个内置智能体 SOUL 更新(双主题、多轮修改允许读底稿、KPI 估算标注、流程数据契约)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 00:37:45 +08:00
Administrator 1b86373a54 feat: 知识库标签/实体关联跳转 + 会话重连容错
前端:
- Wiki 标签与实体改为可点击,弹出 RelatedNotesDialog 查看关联知识
- 知识库首次进入自动打开最近笔记,避免空白阅读区
- 流式重连识别 "Run not found",清理 sessionStorage 残留 key 并静默回退历史

后端:
- 线程鉴权区分 not found / not accessible,并支持 DB 切换产生的孤儿线程认领
- run 查询/join 在内存未命中时回退持久化存储,重启后返回干净的终止 SSE 而非 404
2026-06-11 23:19:09 +08:00
董宏凯andCursor a4a9a4d26e AI 写作四阶段内置智能体 Phase 1-4 落地
新增 ai-writing-researcher/outliner/writer/editor 种子 agent、_agent_runner 与 use_builtin_agents 灰度开关;四节点可按 flag 切换 SOUL 模式;时间线补大纲规划师配色并更新改造文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 22:58:38 +08:00
董宏凯 1a41ac97d2 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-11 22:09:40 +08:00
董宏凯 55aab67383 需求梳理 2026-06-11 22:09:35 +08:00
fengxiangdebaozi 76e2e67af8 Merge branch 'dhk-1' into master 2026-06-11 21:52:39 +08:00
fengxiangdebaozi b682ff5d08 Step3 总结报告支持随时插话、暂停与附件上传
生成中可打断并续问,输入框支持上传参考文件并随消息注入总结线程。
2026-06-11 21:51:59 +08:00
fengxiangdebaozi 2d74f8883e Step3 总结报告与顶栏主题背景图
新增 roundtable-summary 智能体及前后端 Step3 Markdown 总结流程;顶栏在浅/深主题下分别使用红/深蓝横幅背景。
2026-06-11 21:51:59 +08:00
吉鑫升andClaude Fable 5 e7b51a30a3 fix: 智能体可见性对齐——列表可见即可打开问答,消除 404
get_visible 此前比列表过滤更严格(仅 内置/本人/已发布),导致私密广场
智能体(转私密强制 published=false)和「我的」里已收藏但被取消发布的
智能体能在列表看到、点开问答却 404(前端连带报 X.map is not a function)。

- AgentRepository._visible_filter / MemoryAgentStore._is_fetchable:
  单条读取放宽为所有列表口径的并集(+is_private 豁免、+本人收藏豁免)
- 详情接口与 _enforce_agent_access 运行门禁:管理员回退 get_any,
  对齐 ?admin=true 全量列表
- 普通未发布草稿对陌生人仍不可见,隐私不放开
- 本地新增 tests/test_agent_visibility.py 覆盖 SQL/Memory 双实现
  (tests/ 目录在本仓库被 gitignore,不随提交)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 21:25:36 +08:00
吉鑫升 0b98d18483 Merge remote-tracking branch 'origin/master' into ji 2026-06-11 20:28:15 +08:00
吉鑫升andClaude Fable 5 3d6f35391e feat: 对话列表显示总数,SOUL 编辑区高度自适应收敛
- 新增 POST /threads/count:与 /threads/search 同一套过滤(标题搜索、
  系统会话排除),仅返回 {total};ThreadMetaStore 增加 count 方法
  (SQL 走 COUNT(*),JSON 过滤分批扫描计数)
- 对话页面搜索框下常驻显示「共 N 条对话」,分页条显示 当前页/总页数
  (useThreadsCount,仅随筛选条件变化,翻页不重复请求)
- 智能体右侧 SOUL 预览改为 40vh 上限自适应展开(不再全部展开);
  详情面板/卡片编辑/创建页的 SOUL 输入框统一为适中高度 + 可拖拽

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 20:26:44 +08:00
吉鑫升 10047de745 Merge remote-tracking branch 'origin/master' 2026-06-11 20:00:26 +08:00
吉鑫升 82600a3404 Merge branch 'ji' 2026-06-11 19:59:58 +08:00
董宏凯 b73eb77b95 Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!113
2026-06-11 11:59:48 +00:00
董宏凯 1fca24765a 代码修改 2026-06-11 19:59:23 +08:00
吉鑫升andClaude Opus 4.8 f107ebc46d feat: 完善知识图谱交互与 Agent/线程持久化
- 知识图谱画布、侧边栏、详情面板交互优化,新增图谱相关 API 与 hooks
- Agent 卡片与详情面板调整,对话页面重构
- 线程元数据持久化增强(base/memory/sql),knowledge 仓储与导出补充
- 网关路由 agents/knowledge/threads 同步更新

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 19:58:34 +08:00
吉鑫升 f2ffae8a22 Merge remote-tracking branch 'origin/master' into master 2026-06-11 18:59:15 +08:00
吉鑫升andClaude Opus 4.8 ea78fe9726 fix(checkpointer): use_postgres 回退为 false 恢复本地 SQLite 聊天历史
- 发版 40206dc9 将 checkpointer 切到空的远程 Postgres 导致历史不可见,
  且迁移/dual-read 未生效;翻回 SQLite 恢复历史
- config.yaml(backend): 注释掉暂不使用的模型条目

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 18:58:28 +08:00
吉鑫升andClaude Opus 4.8 7d61bc09bc feat: 新增表格文件预览,优化知识图谱与 Agent 详情交互
- 新增 spreadsheet-preview 组件及 xlsx 解析工具,支持产物中的表格文件预览
- 优化知识图谱画布、详情面板及样式
- 调整 Agent 详情面板、聊天与消息列表交互

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 17:43:09 +08:00
董宏凯 b1231fd981 Merge branch 'dhk-1' into 'master'
wujie应用联调

See merge request knowledge-base-bj/deerflow-server!112
2026-06-11 09:41:04 +00:00
董宏凯andCursor bcc3d617a0 Merge branch 'ji' into dhk-1
Resolve column_additions_mysql.sql conflict: keep square_id columns from master and roundtable_drafts.task_id from dhk-1.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 17:40:08 +08:00
fengxiangdebaozi 6890176c76 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-11 17:38:43 +08:00
fengxiangdebaozi d12c50ea4e 样式修改 2026-06-11 17:38:36 +08:00
董宏凯 31525e79a8 套用wujie修改 2026-06-11 17:36:20 +08:00
董宏凯 c48317672c 样式修改 2026-06-11 17:21:24 +08:00
董宏凯 f3ca996116 wujie应用联调 2026-06-11 17:11:28 +08:00
吉鑫升 5daa4b3e20 Merge remote-tracking branch 'origin/master' into ji 2026-06-11 16:39:30 +08:00
吉鑫升 80e84de868 Merge remote-tracking branch 'origin/hlh' into ji 2026-06-11 16:35:18 +08:00
吉鑫升 7efd811e75 feat: update knowledge and agent UI 2026-06-11 16:18:38 +08:00
xu hd 5e68f81a1f Merge branch 'xuhd' into 'master'
chore(env): 添加我的笔记相关环境变量配置

See merge request knowledge-base-bj/deerflow-server!111
2026-06-11 08:05:17 +00:00
吉鑫升andClaude Fable 5 bebe4feccf chore(leaderboard): 用户排行榜当天快照刷新间隔默认调整为半天
ADMIN_LEADERBOARD_TODAY_TTL_SECONDS 默认值 300s -> 43200s,
当天数据约每半天重算一次;调度器 tick、凌晨定稿与手动“刷新当天”不变。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 14:57:27 +08:00
吉鑫升andClaude Opus 4.8 e684de30bd feat(knowledge): 知识库 wiki/知识图谱重构,新增发布广场选择弹窗
- 知识库页拆分出 wiki 组件(侧边栏/目录树/Markdown 阅读器等)
- 知识图谱页拆分出 knowledge-graph 组件并增强交互
- 新增发布广场选择弹窗 publish-square-picker-dialog
- config.yaml 新增 MiniMax-M2.5 / Ling-flash-2.0 / DeepSeek-V4-Pro 模型

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 14:52:25 +08:00
xuhd bd0d922737 Merge branch 'xuhd' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-06-11 14:20:29 +08:00
xuhd 1668c1da87 Merge remote-tracking branch 'origin/master' into xuhd
# Conflicts:
#	frontend-web/.env.production
#	frontend-web/.env.sit
#	frontend-web/package.json
#	offline-backend-20260512/backend/config.yaml
2026-06-11 14:19:01 +08:00
xuhdandClaude Opus 4.8 95dec0e72e fix(studio): 修复流式返回时空间引用角标渲染错乱
Streamdown 的 parseIncompleteMarkdown 会把流式途中未闭合的 [[cite:N
当作未完成链接改写成 [[cite:N](streamdown:incomplete-link),导致
rehypeCitations 匹配失败、引用闪成坏链接。送入渲染前剥除未完成的引用
标记,待 ]] 到齐再由 rehype 渲染为上标。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 14:11:21 +08:00
liuq_1233 5a33f66ad6 修改上传来源的文件类型提示 2026-06-11 11:58:52 +08:00
xuhdandClaude Opus 4.8 33276dae76 docs(knowledge): 经济交往时间线 markdown 排版规范化
在加粗事件标题后补空行,统一列表前的空白。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 11:45:47 +08:00
xuhdandClaude Opus 4.8 b0e48b6bda refactor(studio): 文案“我的笔记/笔记本”统一改为“我的空间”
涉及空间详情页、AI 写作表单/上下文/类型、researcher 注释及 env 注释。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 11:45:35 +08:00
吉鑫升andClaude Opus 4.8 f0aec4cd7f feat(square): 新增发布广场功能,智能体/技能按广场分类展示
- 后端新增 PublishSquare/PublishSquaresSettings 配置与读写接口
- agents/skills 增加 square_id 字段及对应迁移脚本
- 前端新增发布广场设置页、技能转移选择器,画廊按广场分 Tab 展示
- lead_agent prompt 及若干持久化层适配调整

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 11:37:42 +08:00
xuhdandClaude Opus 4.8 5ed636bce4 chore(frontend): env 注释中“笔记本”改为“空间”
统一前端各环境 env 文件注释文案,与界面命名保持一致。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 11:31:49 +08:00
xuhdandClaude Opus 4.8 fa6191b448 fix(studio): 移除来源卡片悬停 tooltip,失败来源显示报错并可删除
- 去掉来源卡片 hover 时弹出的自定义 tooltip div
- status 为 failed 的来源卡片显示红色报错图标与提示,禁用选中,保留删除按钮

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 11:30:52 +08:00
董宏凯 93ca273312 Merge branch 'tjl' into 'master'
tjl

See merge request knowledge-base-bj/deerflow-server!110
2026-06-11 03:21:02 +00:00
xuhd 82d14351fc 修改名称 笔记本改为 空间 2026-06-11 11:19:26 +08:00
吉鑫升andClaude Opus 4.8 3845d5090b feat(knowledge): 支持文件导入沉淀知识,知识图谱可视化随主题切换
- 后端新增 /api/knowledge/ingest/file:上传 md/txt/pdf/word/ppt/excel,
  转 Markdown 后走 wiki-capture LLM 蒸馏为陈述式知识笔记,失败回退逐字草稿
- service.capture_file + 文档专用蒸馏提示词,按主题拆分 1~4 页
- 知识图谱导出 HTML 支持 ?theme=light|dark,布局稳定后冻结,
  按度数缩放节点,悬停/点击聚焦邻居
- 前端知识库页新增「导入文件」对话框与 ingestKnowledgeFile API
- 智能体问答页与简介侧边栏 UI 优化;批量人物蒸馏脚本提取正文逻辑修正

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 10:25:27 +08:00
吉鑫升andClaude Opus 4.8 17bb3715d1 feat(agents): 智能体问答页落地态展示常用问题入口并默认展开简介栏
- 落地页 Hero 以"Hi,我是{名称}"问候,将管理员配置的常用问题渲染为可点击的引导气泡,点击即发起对话
- 右侧智能体简介栏改为默认展开,作为主要"专家信息"卡片,仍可手动收起

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 09:52:27 +08:00
ZyGuo f28426063f Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-06-11 09:46:10 +08:00
吉鑫升 6efe1b80c5 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-11 09:34:45 +08:00
吉鑫升andClaude Opus 4.8 01696f75e9 新增批量人物蒸馏脚本,精简排行榜相关接口
- batch-distill: 独立单文件脚本,按时间窗调用线上服务批量蒸馏人物档案
- 精简 admin_users / public_leaderboard 路由及前端排行榜页面

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 09:34:34 +08:00
AdministratorandClaude Opus 4.8 e97017b297 feat(agents): 智能体常用问题——侧边栏展示并一键提问
新增 common_questions(常用问题)字段:后端贯通 agents_config、
config.yaml 读写与 create/update API,前端 Agent 类型补充字段并在
AgentChatPage 新增 AgentInfoSidebar 组件展示常用问题,点击即填充并提交。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 08:34:39 +08:00
AdministratorandClaude Opus 4.8 22222308a1 feat(summarization): 非破坏性上下文压缩——保留原始对话仅在请求时瞬态压缩
重写 DeerFlowSummarizationMiddleware:将 stock before_model 的
RemoveMessage(REMOVE_ALL_MESSAGES) 改为 no-op,改在 wrap_model_call 中
瞬态压缩为 [summary, *recent],完整原始对话仍保留在 state 中,前端继续
渲染用户真实问答。summary 消息标记 hide_from_ui 且永不持久化,按 thread
缓存以避免每次模型调用都触发 LLM。前端 isHiddenFromUIMessage 额外隐藏旧
版本持久化的 name="summary" 消息。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 08:34:28 +08:00
Administrator 7fb3870247 @
feat(summarization): 非破坏性上下文压缩——保留原始对话仅在请求时瞬态压缩

重写 DeerFlowSummarizationMiddleware:将 stock before_model 的
RemoveMessage(REMOVE_ALL_MESSAGES) 改为 no-op,改在 wrap_model_call 中
瞬态压缩为 [summary, *recent],完整原始对话仍保留在 state 中,前端继续
渲染用户真实问答。summary 消息标记 hide_from_ui 且永不持久化,按 thread
缓存以避免每次模型调用都触发 LLM。前端 isHiddenFromUIMessage 额外隐藏旧
版本持久化的 name="summary" 消息。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@
2026-06-11 08:34:09 +08:00
董宏凯 c57696cf80 Merge branch 'dhk-1' into 'master'
接口地址修改

See merge request knowledge-base-bj/deerflow-server!109
2026-06-10 13:57:49 +00:00
董宏凯 0784f30e23 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-10 21:57:12 +08:00
董宏凯 9af93ecde6 接口地址修改 2026-06-10 21:57:04 +08:00
fengxiangdebaozi d9e3a87911 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-10 19:39:06 +08:00
fengxiangdebaozi f01789a17e 多智能体会商上传文件 2026-06-10 19:38:58 +08:00
董宏凯 688514eab6 Merge branch 'dhk-1' into 'master'
接口地址修改

See merge request knowledge-base-bj/deerflow-server!108
2026-06-10 11:25:24 +00:00
董宏凯 3d069179d6 接口地址修改 2026-06-10 19:24:58 +08:00
董宏凯 f90a6e7082 Merge branch 'dhk-1' into 'master'
code

See merge request knowledge-base-bj/deerflow-server!107
2026-06-10 11:14:40 +00:00
董宏凯 406c02ad07 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-10 19:08:50 +08:00
董宏凯 3bc824b462 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-10 19:08:39 +08:00
董宏凯 c705e0b5ae 样式修改 2026-06-10 19:08:32 +08:00
吉鑫升 3a04ba5726 Merge remote-tracking branch 'origin/master' into ji 2026-06-10 19:01:16 +08:00
董宏凯 60a6db8b47 Merge branch 'dhk-1' into 'master'
feat(roundtable): 第一步识别出的意图支持手动编辑并保存

See merge request knowledge-base-bj/deerflow-server!106
2026-06-10 10:59:29 +00:00
fengxiangdebaozi cf5550ab0a 接口地址修改 2026-06-10 18:58:55 +08:00
董宏凯 19aeba5fab Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-10 17:44:51 +08:00
董宏凯 d9afd8d887 代码提交 2026-06-10 17:44:44 +08:00
hkdong 7422f083b4 tjl 2026-06-10 17:19:27 +08:00
xuhd 06508cfb7c Merge remote-tracking branch 'origin/master' into xuhd 2026-06-10 17:15:51 +08:00
xuhdandClaude Opus 4.8 980d8ba44f chore(deps): declare mermaid dependency
补上 b0fdeab9 引入 mermaid 图表渲染(roundtable 产物预览)时漏提交的
依赖声明,否则全新 pnpm install 后构建会因找不到 mermaid 失败。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 17:15:28 +08:00
吉鑫升andClaude Opus 4.8 d658b05ee9 feat(skills): 安装成功后引导填写/AI生成中文名 + 生成超时提至60s
- 上传安装技能成功后,弹窗进入「设置中文名」步骤:用户可手动填写,或用所选大模型自动生成默认值,亦可跳过(回退英文名)
- 技能中文名生成超时由 30s 提高到 60s(思考模式构建时已关闭)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 17:14:42 +08:00
xuhdandClaude Opus 4.8 123fe36ee4 refactor(studio): rename 笔记本 to 空间 in workspace nav and notebook pages
统一术语:侧边栏「新建笔记本/所有笔记本」、笔记列表与笔记本管理页的
新建按钮与弹窗标题,全部由"笔记本"改为"空间"。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 17:13:23 +08:00
xuhdandClaude Opus 4.8 4bf4b96fa9 feat(notebook): redesign ai-writing header to space-info-only glass pill
移除品牌"索财笔记"与右侧"这是我的笔记"标签,header 只保留空间信息;
空间徽章重做成玻璃胶囊(渐变图标徽标 + 已连接状态点),高度 44→52px,
顶部加品牌高光线与 hover 微光,延续索财深蓝品牌色阶。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 17:06:21 +08:00
fengxiangdebaozi b8680275e5 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-10 17:01:25 +08:00
fengxiangdebaozi e03ca7b4bd 代码修改 2026-06-10 17:01:17 +08:00
吉鑫升andClaude Opus 4.8 3178b4c45e fix(auth): CSRF/鉴权中间件兼容反向代理路径前缀 + 无会话请求豁免
清空浏览器缓存后(尤其 token 换登录)报「CSRF token missing」。根因:
反向代理把请求转发到带前缀的路径(如 /xxx/api/v1/auth/login/token),
FastAPI 用 root_path 剥前缀做路由,但 Starlette 中间件跑在路由之前,
看到的仍是带前缀的 path,导致 CSRF 豁免名单与公开路径白名单(精确/前缀
匹配)全部失配。清缓存前靠 localStorage 残留 token 当 Bearer 绕过 CSRF,
清掉后裸奔才暴露。

- 新增 proxy_path.app_relative_path:匹配前按 root_path / X-Forwarded-Prefix
  剥掉代理前缀(无前缀时 no-op)。
- csrf_middleware:should_check_csrf / is_auth_endpoint 改用应用相对路径;
  补上漏收的 /api/v1/auth/login/token 豁免;新增「无 access_token 会话
  cookie 则跳过 CSRF」兜底(无会话请求不存在可被跨站伪造利用的会话)。
- auth_middleware:公开路径判断改用应用相对路径,避免 /xxx/api/public/*
  分享页被误判 401。
- langgraph_auth:无 access_token cookie 时跳过 CSRF,与网关链路一致。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 15:51:01 +08:00
吉鑫升andClaude Opus 4.8 413f92e270 fix(migrations): 合并 alembic 多头(skill_name_zh 与 chain-stages 分支)
20260609_01(skills.name_zh)直接挂在 20260608_01 之下,与
20260608_02..06(chain-stages/parallel-agent 分支)形成两个 head,导致
`alembic upgrade head` 报 Multiple head revisions。新增空 merge 版本
20260609_02 同时指向 20260608_06 与 20260609_01,使 head 归一。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 14:39:37 +08:00
董宏凯 bd426ed1d3 da 2026-06-10 12:51:13 +08:00
董宏凯 ca9960c8bc 代码修改 2026-06-10 12:51:05 +08:00
xuhd 6b9e1f3c2a 2222 2026-06-10 12:37:13 +08:00
xuhd b8d3a549df buggggg 2026-06-10 11:27:48 +08:00
吉鑫升andClaude Opus 4.8 546dec67a1 fix(agents): 私有 tab 未解锁时隐藏搜索栏
私有广场只有在功能可用且校验过密码后才解锁;未解锁时展示门禁/解锁提示并
隐藏关键词/标签搜索栏(此时没有可筛选的列表)。TagSearchBar 按 tab key 重挂载,
切 tab 时内部关键词输入与展开状态随父级筛选一起重置。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 11:24:52 +08:00
吉鑫升andClaude Opus 4.8 d61aa853f1 feat(admin): 用户排行榜每日快照——手动刷新当天 + 凌晨自动定稿前一天
- 新增 POST /api/admin/users/leaderboard/refresh-today:同步强制重建当天快照
  并返回合并区间;前端 useRefreshTodayLeaderboard + AdminUserLeaderboardPage
  「刷新当天」按钮
- Gateway 调度循环在每日 ADMIN_LEADERBOARD_FINALIZE_HOUR(默认凌晨1点)对前一天
  强制重算一次,避免临近午夜落库的 runs/tool-calls 漏统计;判定逻辑下沉为纯函数
  deerflow.persistence.admin_stats.finalize.should_finalize_previous_day
- 新增 scripts/sql/column_additions_mysql.sql:既有 MySQL 库手动补列的幂等脚本
  (Alembic 自动迁移已禁用,create_all 不改既有表)
- CLAUDE.md 补充排行榜快照、Schema 迁移约定,并补齐技能/知识库选模型的文档

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 11:24:21 +08:00
吉鑫升andClaude Opus 4.8 96e0d695c0 feat(skills,knowledge): 中文名补全与知识库沉淀支持可选大模型并明确大模型报错
技能中文名:
- 单个「AI 生成」与「一键补充中文名」均可在请求体 model_name 选择大模型
- 一键补充改为仅管理员开放
- _generate_skill_name_zh 在模型自身失败(构建/超时/API 报错)时抛
  SkillNameZhModelError,与模型返回无效名称区分;单个接口返回
  502「大模型报错,无法补全技能中文名」,批量在 model_error 中带回代表性报错

知识库沉淀:
- 对话保存到知识库 / 批量导入均新增可选 model_name(透传至 capture_thread
  → extract_thread_llm_multi)
- 批量返回 llm_fallback 计数;模型异常时仍按既有逻辑回退规则抽取并落草稿,
  前端明确提示「已改用规则抽取」(保存按钮保持后台异步)

前端新增 components/workspace/model-name-select.tsx 复用下拉(默认=系统配置模型)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 11:23:01 +08:00
吉鑫升andClaude Opus 4.8 8fbbfc8093 feat(frontend): 广场搜索体验优化与切换tab重置筛选
- 智能体广场:切换 我的/广场/私密广场 时清空重置搜索/标签/排序/发布者筛选
- 通用搜索栏(TagSearchBar):新增「搜索」按钮与回车立即触发(跳过防抖)、
  搜索中转圈提示,新增 hideTags / searchPlaceholder 选项
- 定时任务广场:新增客户端搜索(名称/摘要/创建者,兼容脱敏文本)
- agents 分页 hook 暴露 isFetching 以驱动搜索中状态

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 09:37:39 +08:00
ZyGuo 853a349265 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-06-10 09:19:37 +08:00
ZyGuo 621d4c82af chore: apik 2026-06-10 09:18:38 +08:00
Administrator 87e0ae683e Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	offline-backend-20260512/backend/app/gateway/app.py
#	offline-backend-20260512/backend/config.yaml
#	offline-backend-20260512/backend/packages/harness/deerflow/persistence/models/__init__.py
#	offline-backend-20260512/backend/packages/harness/deerflow/runtime/checkpointer/async_provider.py
2026-06-10 09:09:26 +08:00
AdministratorandClaude Opus 4.8 44c0f6189b wip: 合并 master 前暂存本地改动
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 08:36:47 +08:00
董宏凯 64afa9a1ed 代码提交 2026-06-09 22:52:12 +08:00
AdministratorandClaude Opus 4.8 1ce15fbb15 style(knowledge): 实体改回纯展示(不可点击),chip 精致化
按需求去掉点击筛选,实体为静态彩色 chip:色点 + 名称 + 胶囊型类型标签。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 20:34:59 +08:00
董宏凯 ace30af202 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-09 20:08:06 +08:00
董宏凯 559340143e 代码提交 2026-06-09 19:51:56 +08:00
董宏凯 ae29bb4ca8 Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!105
2026-06-09 11:48:57 +00:00
AdministratorandClaude Opus 4.8 f6af9379b7 feat(knowledge): 笔记页实体可点击筛选 + chip 美化
- 实体改为按钮:点击即在左侧列表筛出提及该实体的知识(清空来源/状态筛选)
- chip 加阴影/hover 上浮/类型 ring 标签/实体区 Sparkles 图标,更精致

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 19:48:20 +08:00
董宏凯 57e286b8ad Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-09 19:45:51 +08:00
fengxiangdebaozi 7acedfd385 代码修改 2026-06-09 19:41:48 +08:00
董宏凯 946799d19d Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-09 19:41:08 +08:00
董宏凯 7282a32859 提交代码 2026-06-09 19:41:01 +08:00
董宏凯 5080f1dc39 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!104
2026-06-09 09:19:14 +00:00
fengxiangdebaozi cba165933c 提交代码 2026-06-09 17:18:40 +08:00
xuhdandClaude Opus 4.7 e54f42c0eb fix(skill_manage): refuse agent writes to human-authored skills
Even after the previous owner check, the agent could still patch/edit
a UI-uploaded skill (source=upload) it happened to own. Uploaded skills
represent human-reviewed content; letting the agent rewrite them risks
silent drift from what the user approved.

Add _assert_skill_is_agent_authored which reads usage.json and refuses
unless source==agent. Wired into all five write actions
(create/edit/patch/delete/write_file/remove_file). Skills with no usage
entry default to source=upload, so legacy and adopted-orphan skills are
also refused — only skills the agent created via mark_agent_created in
the create flow stay editable.

Note: this check is independent of skill_store availability (it reads
the usage file, not the DB), so it runs even when skill_store is None.
Tests that exercise non-create paths against pre-existing skills will
need to call mark_agent_created first or mock get_entry.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 16:00:44 +08:00
xuhdandClaude Opus 4.7 c493639119 feat(skill-review): strict-mode prompt + raise min_tool_calls 3 to 5
The review agent was creating too many low-value skills. Three changes
tighten the funnel:

- review_worker prompt: rewritten in "保守模式". Default decision is
  do-nothing. To create, all five AND conditions must hold (>=5 tool
  calls with step dependencies, an explicit fail->fix->success episode,
  cross-scenario reusability, no >=70% overlap with skill_list, can
  produce >=300 chars of substance). Adds 7 explicit NO categories
  (single-tool loops, one-off queries, LLM common knowledge, etc.)
  and a 4-question self-check before any create. Hard cap of 1 new
  skill per review, with patch preferred over create.
- min_tool_calls: 3 -> 5. Matches the prompt's ">=5 steps" hard
  condition so trivial turns never reach the LLM reviewer.
- Updated config.yaml, the default-value assertion in
  test_skill_review_worker, and the middleware docstring's "(default
  3)" annotation to keep all three references in sync.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 16:00:29 +08:00
董宏凯andClaude Opus 4.8 cc5ada1f3d feat(roundtable): 第一步识别出的意图支持手动编辑并保存
「当前意图摘要」卡新增编辑态:核心目标(必填)、约束、关键假设(可增删列表),
保存后由 useStep1Intent.updateIntentReady 覆盖权威 intentReady,下游(Step 2
种子消息 buildInitialIntent、侧栏摘要卡、step2Locked)随之生效,并落草稿持久化。

持久化用「计数 + effect」触发 handleManualSave,避免 enqueueSave 闭包在 setState
flush 前读到旧意图的竞态(与 step2/step3 计数触发器同构)。聊天气泡内的绿色意图卡
保持为历史记录,右侧「当前意图摘要」为可编辑的当前值。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 15:58:24 +08:00
xuhdandClaude Opus 4.7 539a8bcec8 fix(skill_manage): block cross-user writes on patch/edit/write_file/remove_file
Only delete had a DB owner check via _assert_agent_may_delete. The other
four write actions only called ensure_custom_skill_is_editable, which
just verifies the directory exists under skills/custom/ — it does not
check owner_user_id. Any agent that knew a skill's name could overwrite
or strip support files from another user's UI-uploaded skill.

Generalise the helper to _assert_agent_may_modify (same three rules:
no DB row / built-in owner=None / owner mismatch) and call it from
edit, patch, delete, write_file, and remove_file. Hoist user_id +
skill_store to the top of the lock block so the four newly-guarded
branches stay one-liners and create/delete reuse the same handles.
Behaviour preserved when skill_store is None (no DB) — matches the
existing delete fallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 15:49:26 +08:00
xuhdandClaude Opus 4.7 4416348c51 fix(studio): hide sidebar group until token resolves; remove VITE_STUDIO_ENABLED
- workspace-nav-studio: return null while isLoading so the "工作室" group
  no longer briefly mounts and then unmounts when getTokenByEmail returns
  "用户不存在" (404). Skeleton branch became dead code, removed.
- studio/hooks: switch all three token queries from retry: 1 to false —
  account-not-found is a permanent error; retry just doubled isError latency.
- env: drop VITE_STUDIO_ENABLED everywhere (env.ts + 7 env files +
  workspace-nav-chat-list). Sidebar availability is now decided at runtime
  by token success instead of a build-time flag.
- env: add VITE_AIPI_PRESENT_URL + VITE_AIPI_KNOWES_URL for the document
  upload popup's A-system jump + B-system knowledge iframe; reuse the
  existing VITE_AIPI_KNOWLEDGE_URL for the Y-system iframe.
- document-upload-popup: replace 8 hardcoded URLs (6 present, 1 knowes,
  1 knowlibrary) with the corresponding env vars.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 15:48:24 +08:00
xuhd bd0eceda61 Merge remote-tracking branch 'origin/master' into xuhd
# Conflicts:
#	offline-backend-20260512/backend/config.yaml
2026-06-09 15:43:40 +08:00
fengxiangdebaozi dddd3c1670 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-09 14:06:18 +08:00
fengxiangdebaozi 10795d55e6 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-09 14:06:01 +08:00
fengxiangdebaozi 230fab013a 代码合并 2026-06-09 14:05:51 +08:00
董宏凯 2082d20b88 Merge branch 'dhk-1' into 'master'
feat(roundtable): 业务链条流程图改弹窗 + 每阶段「本阶段目标」注入总控

See merge request knowledge-base-bj/deerflow-server!103
2026-06-09 05:43:00 +00:00
董宏凯andClaude Opus 4.8 c230f7a6c6 feat(parallel-agents): 子智能体禁派活/脚本(防模仿总控) + 面板能力完善
后端 parallel_agents.py:每个并行席位 excluded_tools 增加 agent_orchestration
(派活) 与 bash(脚本逃逸),并在任务消息里加「角色边界」护栏——根治弱模型拿到
带「总控/业务链条」语气的任务后模仿总控输出「总控调度指令…」、绕道 glob/bash
翻找派活脚本的问题。新增 /api/parallel-agents/auth/token 取 token 端点
(auth/csrf 豁免)。

parallel-agents-vue 面板:协作澄清卡片、步骤图标/步骤展示、API 与类型完善等。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 13:41:39 +08:00
董宏凯andClaude Opus 4.8 3405795371 fix(roundtable): 业务链条「本阶段目标」串行链可保存/回显 + 新增「总控提示词」
本阶段目标 bug:每步只有一个智能体(无并行)时,stageGroupsToStagePayload/
stageGroupsToStageGoals 一律折叠为 null(旧设计=线性链),导致目标保存即丢、
无从回显。改为「有并行 或 任一 stage 填了目标」就落显式分层,串行带目标链按
分层 DAG 跑(总控逐阶段按目标派活);BusinessChainPicker 同步:有并行/有目标/
有总控提示都走 dag。

新增「总控提示词」(per-chain,仅 dag 模式生效):写给总控的整体派活指引。
后端 roundtable_chains 加 coordinator_prompt LONGTEXT 列 + migration 20260608_06;
前端编辑器加输入框,注入 buildDagStageLeaderTask 每阶段派活提示。填了总控提示
也强制显式分层(forceExplicit),否则纯线性链里被静默忽略。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 13:41:20 +08:00
AdministratorandClaude Opus 4.8 b70ed38d51 feat(knowledge): 图谱跟随删除 + 笔记页展示实体 + 标签美化
图谱不随删除变化的根因:实体/关系删除时从不清理,build_graph 又把所有实体
都当节点,导致已删笔记的实体(六福珠宝/COMEX/CM助手…)永久残留。

- build_graph 只保留被「活笔记」提及的实体,孤儿实体节点不再出现(render 层兜底,
  历史脏数据无需迁移即生效)
- delete_note 删除时 clear_note_relations + prune_orphan_entities,DB 同步收敛
- get_note 返回 entities(repo.list_note_entities),笔记详情页展示实体
- 前端:实体按类型彩色 chip 展示(人物/机构/概念/产品/技术/地区…),标签改为 pill 样式
- 测试:get_note 返回实体 + 删除后图谱与实体表同步收敛

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 23:39:25 +08:00
AdministratorandClaude Opus 4.8 70bb2783b9 chore(knowledge): 每次沉淀必打入口/结果日志,便于确认是否触发
success 路径原先完全静默,导致"看不到日志"无法区分"没触发"还是"日志不可见"。
现在每次 capture_thread 至少打 [knowledge] capturing… + 结果/跳过/失败 各一行。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 23:11:54 +08:00
AdministratorandClaude Opus 4.8 d9fc7c9fdf chore(knowledge): 沉淀决策日志统一加 [knowledge] 前缀,跳过提到 WARNING 级
便于 docker logs 一条 grep 抓全部捕获决策(跳过/回退/失败):
  docker logs deerflow-vite-gateway 2>&1 | grep "\[knowledge\]"

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 22:55:44 +08:00
董宏凯 1938c80061 代码提交 2026-06-08 22:52:18 +08:00
AdministratorandClaude Opus 4.8 76320ca5a3 fix(knowledge): 模型判定 should_ingest=false 时直接跳过,不再落草稿
日志显示寒暄/无效会话并非 LLM 调用失败,而是模型正确返回 should_ingest=false。
上一版把这种情况也当失败回退、堆成草稿,反而把无价值对话存进了库。

- llm_extractor: 模型显式 should_ingest=false 且无 notes → 抛 LLMRejectedIngest
- capture_thread: 捕获后抛 EmptyThreadError → 整条跳过、不入库(寒暄/总结此页这类不再进库)
- 仅当真正失败(API 报错 / 非 JSON)才回退规则抽取并落草稿
- 兼容包装 extract_thread_llm 吞掉该异常返回 None
- 更新测试(should_ingest=false 跳过)+ CLAUDE.md

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 22:49:00 +08:00
AdministratorandClaude Opus 4.8 4aef81284a feat(knowledge): 出处标记渲染 + 相关笔记按标签精确匹配 + LLM 回退落草稿
A) 前端把 ^[inferred]/^[ambiguous] 渲染成「推测」「存疑」小角标(原先原样显示文本)
B) 相关笔记只按"区分性标签"精确匹配(去掉标题/摘要关键词检索——中文分词导致
   助手/知识图谱/页面 等泛词误关联,如「AI助手打招呼」被错误拉进 Related);
   无区分性标签则不关联、不渲染 ## Related 段
C) LLM 提炼启用但失败时不再静默回退成"原文堆砌":
   - 回退笔记落为 draft(草稿)而非 approved,便于复核
   - capture_thread 记 WARNING 并返回 llm_fallback;router 透出该标志
   - llm_extractor 在 JSON 解析失败/无 notes 时补充可诊断的 WARNING 日志

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 22:22:28 +08:00
AdministratorandClaude Opus 4.8 e7ff07debd feat(knowledge): 项目名改 zncm + 去除元链接噪音 + 创建人显示人名
- project_name 默认 deerflow → zncm(config.yaml + 配置默认 + 模块内字面量)
- related_links() 返回空:笔记 Related 不再注入 index/_meta/taxonomy/hub 结构链接,
  只保留真实相关笔记的可点 [[标题]];无相关笔记且无来源时不再渲染 ## Related 段
- 移除随之多余的项目 hub 页脚手架(index.md/_meta/taxonomy.md 仍由 obsidian 脚手架保留,可解析)
- GET /notes/{id} 用 auth provider 把 created_by/updated_by(UUID) 解析为邮箱
  (created_by_name/updated_by_name),前端 footer 显示人名、解析不到才显示短 id
- 仅对新沉淀笔记生效,现有笔记不动

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 21:50:56 +08:00
AdministratorandClaude Opus 4.8 df3fac1032 feat(knowledge): 可跳转 wikilink + 真实相关 note + 一对话多页
- [[wikilink]] 解析器:note id / vault_path / 标题 / vault 元页 / missing
- 前端 MarkdownRenderer 把非数字 [[...]] 渲染成可点链接,元页弹窗查看,缺失置灰
- vault 脚手架补建项目 hub 页,三个结构性链接(index/taxonomy/hub)始终可跳
- capture 时按标题+摘要+区分性标签检索同主题 note,注入真实 [[标题]] 到 Related + 记 related 图谱边
- LLM 提取支持 notes[] 数组,一次对话拆 1~4 页并按标题互链(multi_note_enabled 开关)
- 新增接口 POST /resolve、GET /notes/{id}/wikilinks、GET /vault-page
- 新增配置 related_notes_enabled / related_notes_limit / multi_note_enabled

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 21:20:31 +08:00
吉鑫升andClaude Opus 4.8 92a46003f8 feat: 知识库一键后台保存 + 对话置顶仅首页 + 排行榜页面增强
- 知识库「保存」改为一键触发,无需填表;后端经 BackgroundTasks 异步沉淀到 wiki,点击立即返回 {queued:true}
- 对话列表置顶分区仅在第一页展示,翻页后不再重复顶置
- 公开/管理员排行榜页面重构与维度增强;排行榜页改为整页统一滚动

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 19:59:55 +08:00
Administrator 24db448cfd Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-08 19:12:34 +08:00
hlh 9e14c2e289 禁用了知识库技能,添加了知识库memory 2026-06-08 18:35:05 +08:00
AdministratorandClaude Opus 4.8 e750df3c0d docs: 知识库阶段二至四(RAG/治理/图谱)更新 CLAUDE.md
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 18:33:08 +08:00
AdministratorandClaude Opus 4.8 81e4fd92ce feat(knowledge): 阶段三 知识治理 + 阶段四 图谱增强
阶段三(治理):
- sensitive.py:写入前脱敏 token/密钥/手机号/身份证/邮箱(sensitive_redaction_enabled)
- 版本快照:更新前写 knowledge_note_versions;GET /notes/{id}/versions
- dedup.py:标题/摘要 Jaccard + 内容哈希查重;GET /duplicates、POST /merge(来源并入主条目、重复项归档)
- auto_ingest.py:独立后台队列/线程沉淀,不阻塞问答;中间件 after_agent 在 auto_ingest_enabled 时入队;价值判断(最小字符)+ skip_existing 去重;自动沉淀落 draft 待审

阶段四(图谱):
- LLM 抽取 entities/relations;service 存 knowledge_entities/knowledge_relations 并连边
- exporter.build_graph 支持实体节点 + note→entity/entity→entity 边;graph.html/json 增强
- GET /api/knowledge/graph 返回产品图谱数据

前端:知识库页「查重合并」对话框 + 相关 api/hooks
配置:sensitive_redaction_enabled / dedup_similarity_threshold / entity_extraction_enabled
测试:tests/test_knowledge.py 20 passed

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 18:31:33 +08:00
AdministratorandClaude Opus 4.8 683cc6d76e feat(knowledge): 阶段二 向量 RAG 与召回注入
- embeddings.py:OpenAI 兼容 embedding 客户端,未配置时关键词兜底
- chunking.py + knowledge_embeddings 表:Markdown 分块与向量索引(Python 余弦)
- search.py:keyword/vector/hybrid 三种模式,向量不可用自动降级
- 笔记创建/更新自动重建向量索引;新增 /reindex 维护接口
- KnowledgeRagMiddleware:按对话级开关 knowledge_rag_enabled 注入 <knowledge-context>,接入 lead agent 中间件链(默认随 config.knowledge.rag_enabled)
- service.build_rag_context(wiki-query 风格分层召回)
- 笔记版本快照(knowledge_note_versions)+ GET /notes/{id}/versions
- 前端:聊天页「知识库」对话级 RAG 开关 + 类型字段
- 新增 entities/relations 表(阶段四预置)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 18:18:04 +08:00
吉鑫升 fb692a0555 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-08 18:02:14 +08:00
吉鑫升andClaude Opus 4.8 40206dc94d fix: Postgres store 自愈连接池 + 启用 PG checkpointer + 分析查询超时按服务端适配
- async_provider: AsyncPostgresStore 改用连接池(check_connection 校验),
  避免单条长连接在服务重启/空闲超时后永久失效;池大小可经
  DEER_FLOW_PG_POOL_MIN/MAX 环境变量调整
- admin_users: 排行榜分析查询的每语句超时按服务端区分
  (MySQL>=5.7.4 max_execution_time / MariaDB max_statement_time /
  MySQL<=5.6 跳过 / PostgreSQL statement_timeout)
- config.yaml: checkpointer.use_postgres 置为 true

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 18:01:55 +08:00
吉鑫升andClaude Opus 4.8 50d70a5050 feat: 对话列表支持分页、收藏、置顶
收藏(is_favorite)/置顶(is_pinned)作为布尔标记存入对话已有 metadata,
复用现有 PATCH /api/threads/{id} 与 search 往返,无需后端改动与迁移。

- hooks: 新增 useUpdateThreadMetadata + useToggleThreadPin/Favorite
- utils: 新增 isThreadPinned/isThreadFavorite/sortThreadsPinnedFirst
- 侧边栏: 置顶优先排序 + 下拉菜单收藏/置顶项 + 置顶图标
- 对话页: 置顶区 + 全部/收藏过滤 + 页码翻页(每页20) + 行内收藏/置顶按钮
- i18n: zh-CN/en-US/types 新增相关文案

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 18:01:03 +08:00
AdministratorandClaude Opus 4.8 8463289f75 feat(knowledge): LLM 提炼陈述式知识(wiki-capture 规范),规则抽取兜底
之前沉淀直接堆砌对话原文。现默认用大模型按 wiki-capture 规范提炼为 Context/Finding/Reasoning/Implications/Related 结构化陈述式知识,过滤寒暄与中间推理;LLM 不可用或解析失败时回退规则抽取。新增 llm_extractor.py + 配置 llm_extract_enabled/extract_model_name/extract_max_input_chars。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 18:00:46 +08:00
董宏凯andClaude Opus 4.8 b101ee7fc9 feat(roundtable): 业务链条左栏卡片拖动手柄 + 加入按钮 + 智能体详情抽屉
- 左栏候选卡片加拖动手柄(与右栏席位一致),仅点手柄才拖动
- 加入改为显式「加入」按钮,点卡片本体改为打开详情抽屉
- 右栏席位操作区加「查看详情」按钮,打开同一抽屉
- 新增 AgentDetailSheet:按需拉取(useAgent)展示名称/模型/描述/
  标签/技能+工具组/人设,对齐智能体详情页内容

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 18:00:42 +08:00
AdministratorandClaude Opus 4.8 d06c8d49d7 feat: 工作台左侧导航新增「知识库」入口
之前只加在了 strategy shell 的 sidebar-menu,工作台 shell 用的是 WorkspaceNavChatList,这里补上入口指向 /page/workspace/knowledge。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 17:55:11 +08:00
AdministratorandClaude Opus 4.8 e193c2df21 feat: 接入知识库聊天入口与前端路由
在聊天页工具栏接入「保存到知识库」按钮,并补回 /page/workspace/knowledge 列表/详情/图谱路由(此前被回退丢失)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 17:43:55 +08:00
AdministratorandClaude Opus 4.8 cc99ebba81 feat: 产品内知识库(obsidian-wiki 兼容 vault)
后端:新增自包含 deerflow.knowledge 模块(models/repository/schemas/
extractor/sources/markdown_vault/manifest/obsidian_adapter/exporter/
search/service),通过 deps.py 装配为 app.state.knowledge_service,
挂载 /api/knowledge 路由;config.yaml 增加 knowledge 配置段,
AppConfig 注册 KnowledgeConfig,ORM 注册 4 张 knowledge_* 表。

前端:新增知识库页面(KnowledgeBasePage/KnowledgeGraphPage)、
core/knowledge api/hooks/types、聊天侧 knowledge-save-trigger,
侧边栏增加「知识库」入口。

知识库为全局共享,不做 user_id 隔离,写入记录 created_by/updated_by
作为审计。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 17:38:28 +08:00
吉鑫升andClaude Opus 4.8 80d2db6315 feat: 公开用户排行榜页面 + 修复 checkpointer 连接与前端依赖
- 新增公开排行榜页面与后端 public_leaderboard 路由
- 完善 skills/agents 路由
- checkpointer Postgres 改用连接池(自愈), 解决连接关闭后定时任务连环失败
- 修复前端 mermaid 依赖未声明导致 Vite 解析失败 (新增 pnpm-lock)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 17:09:28 +08:00
董宏凯 c05e7df48e Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-08 16:31:00 +08:00
董宏凯andClaude Opus 4.8 834df64650 feat(roundtable): 业务链条流程图改弹窗 + 每阶段「本阶段目标」注入总控
- 业务链条配置页流程图从底部内嵌改为按钮 + Dialog 弹窗查看
- 每个 Stage 新增可选「本阶段目标」文本框,告诉总控本阶段要产出
  什么、如何依赖上一阶段产出(仅分层 DAG 生效)
- StageGroups 重构为 StageGroup[]({seats, goal?}),goal 随 stage
  在增删改/重排中自动跟随;新增 stageGoals 持久化(与 stages 同下标对齐)
- 运行时注入:buildDagStageLeaderTask(总控派活,主)+ pickDagSeatTask
  (席位任务,兜底)
- 后端 roundtable_chains 加 stage_goals 列 + 校验 + Alembic 20260608_04
- 老链条/草稿无该字段时不注入,行为不变

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:10:46 +08:00
吉鑫升 8113b822c5 docs: add product knowledge base plan 2026-06-08 16:02:43 +08:00
AdministratorandClaude Opus 4.8 a53e565e5a feat: 管理菜单增加「用户排行榜」入口
侧边栏综合管理与右上角工作区下拉菜单新增「用户排行榜」(admin only),
指向 /page/strategy/admin/user-leaderboard,并默认展开综合管理分组。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:47:15 +08:00
AdministratorandClaude Opus 4.8 d4a71ce384 feat: 浏览器扩展支持交互式页面操作 (browser_act)
在原有只读抓取 (browser_fetch_page) 基础上,新增 observe→act 循环,
让 Agent 能在用户的 Chrome 中实际操作网页:点击/输入/滚动/等待/页内跳转。

后端:
- 新工具 browser_act,按 session 复用标签页,返回带编号的可交互元素清单+正文
- browser_context 任务队列扩展 kind/session_id/action 与 observation 结果
- /api/browser-context 路由下发 act 任务、接收 observation
- BrowserContextConfig 增加 actions_enabled 等开关,tools.py 两级门控
- 接线 app.py 路由挂载、app_config.py 配置字段、config.yaml 工具注册

前端:
- ChatPage 处理「发送当前页」回跳的 browser_context query 参数并自动提交

扩展 (browser-extension/deer-web-clipper):
- shared.js 自包含注入函数 deerObservePage / deerPerformAction
- background.js 按 kind 分发任务,session→tab 映射存 chrome.storage.session

测试:tests/test_browser_act.py(队列往返 + 工具校验 + 模拟扩展成功路径,8 passed)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:47:00 +08:00
g zy 004853f030 Merge branch 'gzy_iframedf' into 'master'
feat: 登录token回传至宿主

See merge request knowledge-base-bj/deerflow-server!102
2026-06-08 04:35:35 +00:00
ZyGuo 37be59b0dd feat: 登录token回传至宿主 2026-06-08 12:33:24 +08:00
董宏凯 273503ddb9 Merge branch 'dhk-1' into 'master'
样式修改

See merge request knowledge-base-bj/deerflow-server!101
2026-06-07 15:54:16 +00:00
董宏凯 ce431ee155 样式修改 2026-06-07 23:53:52 +08:00
董宏凯 12844e341c Merge branch 'dhk-1' into 'master'
feat(roundtable): 业务链条「发布为公共」+ 我的/公共筛选

See merge request knowledge-base-bj/deerflow-server!100
2026-06-07 14:56:48 +00:00
董宏凯andCursor eaf1e075f2 fix(roundtable): 本地 SQLite 路径与离线并行席位禁用 web_search
将 backend 配置中的 SQLite/checkpointer 改为相对路径以便本地开发,并在离线部署下禁止并行席位使用 web_search,统一走技能检索。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-07 22:55:50 +08:00
董宏凯andClaude Opus 4.8 7affaaf7c0 feat(roundtable): 业务链条「发布为公共」+ 我的/公共筛选
后端:roundtable_chains 加 is_public 列;list_chains 支持 scope=mine|public(public=所有已发布,任何账号可查看/选入研讨);get_chain 放开公共可见;响应加 is_public/is_mine;update 支持 is_public(发布/取消,owner 限定,编辑/删除仍仅 owner)。迁移 20260608_03 接在合并 head 20260608_02 之后,保证单一 alembic head(多 head 会让启动自动迁移失败、静默降级 create_all → 列缺失 500)。

前端:listChains(scope) + setChainPublic;BusinessChain 加 isPublic/isMine;列表弹窗与研讨选择器加「我的/公共」筛选 tab;列表卡片发布/取消发布 + 公共徽标(别人的只读);配置页头部加发布按钮(已保存且本人)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 22:30:23 +08:00
董宏凯 90f3564d0b Merge branch 'dhk-1' into 'master'
fix(roundtable): 后台任务临时跳过 Step3 报告生成

See merge request knowledge-base-bj/deerflow-server!99
2026-06-07 13:28:21 +00:00
董宏凯 05d14bb364 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-07 21:25:54 +08:00
董宏凯andClaude Opus 4.8 7b8c11852e feat(roundtable): 圆桌 Step2 分层 DAG 编排(并行/沙箱双模式 + 流程图 + 按需取全文)
数据模型/编辑器:链条加 stages 分层(前后端 + alembic 20260607_03);BusinessChainEditorPage 竖列 Stage 编辑 + 底部只读流程图预览;lib/dag-types + chain-stages 纯逻辑(含单测)。

调度(runDagOrchestration,方案 A 总控驱动):每个 stage 由总控经 agent_orchestration 派活给计划钉死的席位,批内 Promise.all 并行、批间 barrier 串行;末尾交回 runOrchestration 收口。抑制 leader 预广播 + 干净席位任务,根治『席位模仿派活』。

执行子模式:快速(双列·产物走正文·禁写文件 seat_parallel)/ 沙箱(单列·写 .md·沙箱跟随预览 seat);统一禁 bash(防 .py 脚本),提示词禁 .py。

显示:头像条 + 两列/单列 + ref 全量累积 + 节流 flush(仅选中渲染);DAG 流程图弹窗(按 stage 分列,节点随执行点亮,只到共识);沙箱跟随当前席位(防错位 + 修第一个席位自动开沙箱)。

按需取全文:新增 harness 只读工具 read_peer_delivery(从 run context 取网关注入的前序席位完整交付),席位默认看摘要、需要时取全文。

修:宽表溢出、并行自动下滑、data-lov-id Fragment 警告等。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 21:20:58 +08:00
董宏凯andClaude Opus 4.8 5164fd362c feat: 重新设计浏览器标签页图标(智能助手中心)
玫红渐变磁贴 + 白色对话气泡 + 气泡内 AI 闪光星 + 角落小闪光,围绕「助手 / 多种智能工具」主题;并在 index.html 补上 favicon 链接。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 21:20:58 +08:00
董宏凯andClaude Opus 4.8 2e689e4482 docs(roundtable): 圆桌 DAG 编排 + 并行执行显示分步需求文档
锁定三项设计决策:分层 Stage(非自由连线)、并行跳过 leader 前端直派、主区固定 2 列(窄屏降 1 列)。含数据模型/编辑器交互/并行调度/禁写文件/高性能流式渲染/分步实现计划(Phase 1-8)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 21:20:58 +08:00
董宏凯andCursor 1ee2e6ca0a perf(roundtable): 轻量 thread 接口降低广播与席位状态核对开销
新增 messages/append 与 last-ai-message 接口,圆桌广播和总控派活轮改走服务端轻量读写,避免 loopback 传输整份 state。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-07 21:20:58 +08:00
董宏凯andCursor 924c8f2fac fix(roundtable): 优化 Step2 总控派活稳定性与并发编排
限制总控工具白名单、关闭圆桌记忆注入、综合轮 synthesis_mode 与编排 epoch 防双发,并优化广播异步化及 Postgres checkpointer 连接池。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-07 21:20:58 +08:00
Administrator 0001f86826 feat: 完善公开任务预览和用户问答历史 2026-06-07 21:18:16 +08:00
fengxiangdebaozi 9c9c912657 refactor(strategy): 任务分析页移除演示数据并接入真实接口
舆情分析与规划任务分析看板统一改为后端任务列表拉取,去掉 mock/演示切换,并修正 running 列状态与日期筛选交互。
2026-06-06 20:23:58 +08:00
董宏凯 024c8ee5a1 Merge branch 'ji' into 'master'
feat: 重新设计浏览器标签页图标(智能助手中心)

See merge request knowledge-base-bj/deerflow-server!97
2026-06-06 01:21:19 +00:00
董宏凯 2e7985639e Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-06 09:19:15 +08:00
AdministratorandClaude Opus 4.8 e7c745a512 feat: 排行榜日快照分析 + 数据库连接池/索引调优
- 排行榜改为按天预计算快照(admin_leaderboard_daily_stats),请求只读取合并,重统计移至后台调度;过去日不可变、当天 TTL 刷新,避免在线聚合长时间占用数据库
- 为 runs/tool_call_metrics/llm_call_metrics/threads_meta 增加面向时间段+用户聚合的复合索引(model __table_args__ + migration 20260608_01)
- 连接池可调:DatabaseConfig 新增 max_overflow / pool_timeout,接入 postgres/mysql 引擎;config.yaml 上调 pool_size=20/max_overflow=20
- 新增手动执行的索引脚本 scripts/sql/leaderboard_indexes_mysql.sql(幂等,适用于已存在数据、create_all 不补索引且 alembic 关闭的部署)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 00:52:24 +08:00
董宏凯 1b75887615 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-05 23:47:07 +08:00
董宏凯andClaude Opus 4.8 a1bcc6eed4 feat: 重新设计浏览器标签页图标(智能助手中心)
玫红渐变磁贴 + 白色对话气泡 + 气泡内 AI 闪光星 + 角落小闪光,围绕「助手 / 多种智能工具」主题;并在 index.html 补上 favicon 链接。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 23:45:28 +08:00
fengxiangdebaozi 0bf6285287 fix(roundtable): 后台任务临时跳过 Step3 报告生成
后台挂起路径在真模型下仍无法稳定写出报告 HTML,先只跑完 Step2 研讨并正确设置 furthest_step;测试可通过 enable_report 覆盖验证报告链路。
2026-06-05 23:41:28 +08:00
Administrator 4df71f32a8 fix: use sqlite backend config 2026-06-05 22:44:21 +08:00
fengxiangdebaozi 44b7f9fa99 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-05 22:40:44 +08:00
fengxiangdebaozi 03329387b3 样式修改 2026-06-05 22:22:38 +08:00
吉鑫升 e5ba898fc7 hide user leaderboard entry 2026-06-05 22:11:31 +08:00
吉鑫升 a41b5a6d4c fix: improve agent handoff and leaderboard scheduling 2026-06-05 21:46:04 +08:00
董宏凯 cbbde887d4 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-05 21:17:31 +08:00
董宏凯 89724d6e4d Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!96
2026-06-05 13:17:03 +00:00
董宏凯 6d5325d444 代码修改 2026-06-05 21:16:35 +08:00
吉鑫升 db1b32612b fix: run leaderboard stats in background 2026-06-05 21:15:20 +08:00
吉鑫升 f4ccef8c70 fix: optimize leaderboard and agent handoff 2026-06-05 21:06:23 +08:00
董宏凯 99aa064e6c Merge branch 'ji' into 'master'
Ji

See merge request knowledge-base-bj/deerflow-server!95
2026-06-05 12:36:02 +00:00
吉鑫升 24a5ca0c06 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-05 20:07:03 +08:00
吉鑫升 6eda572f31 tijiaodaim 2026-06-05 20:06:55 +08:00
董宏凯 7b6dd9ba6f Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-05 19:56:51 +08:00
董宏凯 1341767692 Merge branch 'dhk-1' into 'master'
feat: 多智能体会商草稿分享(import 复制 / view 公开结果页)

See merge request knowledge-base-bj/deerflow-server!94
2026-06-05 11:48:08 +00:00
董宏凯andClaude Opus 4.8 f845805706 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1
解决 StrategyRoutes.tsx import 冲突:保留双方各自唯一的页面导入(AgentsPage/ChatPage/ChatsPage + AdminUserLeaderboardPage/SettingsPage),去掉与下方重复的 13 个 import。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 19:46:19 +08:00
董宏凯andClaude Opus 4.8 b2132dd668 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1
解决 artifact 预览组件冲突:mermaid 渲染(dhk-1) 与 markdown 锚点跳转(master) 取并集;package-lock.json 按 master 删除(项目用 pnpm)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 19:43:02 +08:00
fengxiangdebaozi fc5eaa2941 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-05 19:28:19 +08:00
fengxiangdebaozi 045bb11abf 样式修改 2026-06-05 19:28:09 +08:00
董宏凯 9a31155581 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-05 19:00:28 +08:00
董宏凯andCursor 9e510ce088 feat: 优化会商公开分享页,展示总控结论与各席位交付
公开分享页拆分为落地页与独立报告页,后端补充 consensus_text 与 seat_deliveries 字段。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-05 19:00:13 +08:00
fengxiangdebaozi a642ba91fa Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-05 18:58:37 +08:00
fengxiangdebaozi b0fdeab995 代码修改 2026-06-05 18:58:28 +08:00
吉鑫升 1bf1fc6512 增加依赖 2026-06-05 17:36:53 +08:00
吉鑫升 392373b4b7 chore: add qwen model config 2026-06-05 17:32:53 +08:00
吉鑫升 f3def88342 feat: add sqlite checkpoint fallback switch 2026-06-05 17:28:44 +08:00
吉鑫升 690d09a3d1 feat: add workspace view mode settings 2026-06-05 17:21:49 +08:00
吉鑫升 9471e72171 feat: add checkpoint postgres migration admin 2026-06-05 17:16:31 +08:00
g zy 9ebde3b315 Merge branch 'gzy_iframedf' into 'master'
feat: iframe传 文件进入

See merge request knowledge-base-bj/deerflow-server!93
2026-06-05 07:10:59 +00:00
吉鑫升andClaude Opus 4.8 eaa061dd06 feat: 新增技能置顶功能
- 后端:新增 PUT /skills/custom/{name}/featured 接口,在 usage 中实现 set_featured 与 featured 字段(与 pinned 正交,仅影响排序)
- 前端:新增 setSkillFeatured API、置顶/取消置顶操作及中英文文案
- ScheduledTasksPage:优化助手选择下拉框的宽度与文本换行
- config.yaml:整理 log_system 配置块

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 15:02:50 +08:00
ZyGuo 5f6ab41798 feat: iframe传 文件进入 2026-06-05 14:15:42 +08:00
xuhdandClaude Sonnet 4.6 9adb0fee28 fix(notebook): preserve selected notebook/docs when switching material source with studioToken
- Initialize materialSource via WritingFormProvider initialMaterialSource prop
- Don't clear selectedNotebookId/selectedDocumentIds on source switch when studioToken is set

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:58:34 +08:00
xuhdandClaude Sonnet 4.6 c577833e7c fix(notebook): default material source to notebook when studioToken or initialNotebookId is set
Replace useEffect-based approach with synchronous effectiveMaterialSource
derived value to avoid first-render flash and timing issues.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:53:10 +08:00
xuhdandClaude Sonnet 4.6 d57bcd9aa2 feat(notebook): lock material source to notebook when studioToken is provided
- Auto-switch materialSource to 'notebook' on mount when initialNotebookId is set
- Replace material source dropdown with static label when studioToken is present

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:45:24 +08:00
xuhdandClaude Sonnet 4.6 0e7149eec3 feat(notebook): load notebook space via token and pre-select docs/sources
- NotebookAIWritingPage reads `token` from URL, fetches space data from
  notebook-token API (search_space_id, doc_ids, user_token) and space
  name from searchspaces API; keep-alive ping every 50s resets Redis TTL
- Pass user_token as studioToken through AIWritingPage → AIWritingLayout
  → WritingFormPanel → AIWritingPanel → AIWritingForm to skip
  getTokenByEmail when studio token is already available
- useStudioNotebooks accepts enabled flag; useNotebookSources accepts
  overrideToken to bypass the internal token fetch
- AIWritingForm hides notebook selector when studioToken is provided
  (notebook is pre-locked) and pre-selects initialDocumentIds

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:38:08 +08:00
xuhd e53c1a0f7b feat(notebook): pre-select notebook source when notebook_id is in URL 2026-06-05 13:35:35 +08:00
xuhd e689493723 feat(notebook): add /page/notebook/ai-writing route for 索财笔记 view 2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 e6d3226c47 feat(studio): replace notes source upload with multi-tab popup
- Add document-upload-popup.tsx with tabs for B系统/A系统/Y系统/XWT/upload
- Add network-actor.tsx for XWT search tab
- Add empty.tsx for empty state
- Refactor SourcesDialog: left panel becomes single "上传来源" button that opens new popup
- Wire DocumentUploadDialogProvider around StudioNotebookDetailPage

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 2c2650ff07 feat(skill-evolution): expose model_name as per-user configurable field
前端恢复模型选择器,后端允许 model_name 写入 per-user skill_evolution.json。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 603d667608 fix(skill-evolution): strip non-user-configurable fields from per-user overrides
load_user_overrides 只保留 interval_hours/stale_after_days/archive_after_days,
过滤掉老文件中的 enabled、model_name 等字段,防止旧数据覆盖全局开关。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 e9125b0900 test(curator): add scheduler startup non-blocking and execution tests
验证 curator 调度器不阻塞启动、启动延迟后真实执行、无锁时跳过。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 d0c696e523 refactor(skill-evolution): simplify config UI to 3 user-editable fields
前端配置页只保留运行间隔、陈旧阈值、归档阈值三个字段,
其余配置(enabled、model_name 等)走 config.yaml 全局默认。
后端 PUT /api/curator/config 仅保存这三个字段到 per-user skill_evolution.json。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhd 6f9afcdba2 修复技能审核agent提示词 2026-06-05 13:32:19 +08:00
xuhd 705de81c78 fix(skill-review): use uuid per review run to avoid checkpoint context bleed 2026-06-05 13:32:19 +08:00
xuhd 335bc3cf48 fix(skill-review): propagate user_id through review chain for correct DB ownership 2026-06-05 13:32:19 +08:00
xuhd 857798ff2f fix(skill-review): pass RunnableConfig with thread_id to satisfy ThreadDataMiddleware 2026-06-05 13:32:19 +08:00
xuhd 3955bd72b5 refactor(skill-review): use create_agent with skill_evolution disabled to allow autonomous skill creation 2026-06-05 13:32:19 +08:00
xuhd b5d80025e9 fix(skill-review): lower CREATE threshold and log agent decision 2026-06-05 13:32:19 +08:00
xuhd 5b5e4f8ff0 fix(thread-data): guard runtime.context None on line 110 2026-06-05 13:32:19 +08:00
xuhd ad5bd22c5e refactor(skill-review): use make_lead_agent instead of create_react_agent
Reuses the full middleware chain (ToolErrorHandlingMiddleware,
LLMErrorHandlingMiddleware, etc.) so tool errors like 'already exists'
and invalid SKILL.md are converted to ToolMessages by the middleware,
not silently swallowed or crashing the review task.
2026-06-05 13:32:19 +08:00
xuhd b2ed6f1acf fix(skill-review): add strict SKILL.md format spec to review prompt 2026-06-05 13:32:19 +08:00
xuhd 2a8364e902 fix(skill-review): use runtime.context to get thread_id 2026-06-05 13:32:19 +08:00
xuhd 23a18ec318 fix(skill-review): after_agent must be sync, not async 2026-06-05 13:32:19 +08:00
xuhd d713f0209d feat(curator): restrict per-user config to archiving thresholds only 2026-06-05 13:32:19 +08:00
xuhd 0a21d37146 chore(config): enable skill_evolution, review_worker, and curator (24h) in config.yaml 2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 c645142f82 feat(skill-evolution): register SkillReviewMiddleware in lead agent chain
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 0e7a1de4db feat(skill-evolution): add SkillReviewMiddleware to trigger post-turn review
Implements SkillReviewMiddleware that hooks into after_agent to call
maybe_start_review() as a background task after each agent turn, without
blocking the HTTP response. Exceptions are caught and logged only.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 ef3ef433c1 feat(skill-evolution): add SkillReviewWorker for passive post-turn skill creation
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhd 0da91be9b1 test(skill-evolution): fix unused import and add max_messages assertion 2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 69454ada69 feat(skill-evolution): add ReviewWorkerConfig to SkillEvolutionConfig
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
xuhdandClaude Sonnet 4.6 1126fedea8 chore(env): 添加我的笔记相关环境变量配置
- VITE_AIPI_FRONTEND_URL: 我的笔记前端地址
- VITE_STUDIO_ENABLED: 控制侧边栏我的笔记入口显示

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 13:32:19 +08:00
董宏凯 69c28e3563 代码修改 2026-06-05 13:04:44 +08:00
吉鑫升andClaude Opus 4.8 b117bb1dc2 Revert skill list layout and tune leaderboard report
- Revert skill settings to vertical list layout with pinned sorting
- Default leaderboard range 30d -> 7d, hide stats while report generating
- Reframe leaderboard report prompt as user-behavior analysis (cache v5)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 11:34:39 +08:00
董宏凯 9c9330114f Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-05 11:20:22 +08:00
董宏凯andCursor 0fd314632a feat: 多智能体会商草稿分享(import 复制 / view 公开结果页)
支持会商草稿生成分享码、导入副本与公开只读结果页,并在侧边栏展示最近会商记录。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-05 11:19:09 +08:00
吉鑫升 0d91c74289 style: enlarge leaderboard report dialog 2026-06-05 11:17:09 +08:00
吉鑫升 d59f9e218f feat: enhance leaderboard AI report 2026-06-05 11:00:08 +08:00
fengxiangdebaozi 9bbd04d6cf 后台挂起功能优化 2026-06-05 10:59:56 +08:00
吉鑫升 22be6325a8 Resolve merge conflicts 2026-06-05 10:28:45 +08:00
吉鑫升 e96cc97462 Merge origin/master into ji 2026-06-05 10:04:11 +08:00
Administrator 92f5cb8fe3 enhance admin leaderboard and previews 2026-06-05 01:51:48 +08:00
Administrator a5897caec4 enhance leaderboard reporting and grouping 2026-06-05 00:02:05 +08:00
Administrator 88c83b4dd7 refine admin leaderboard experience 2026-06-04 23:41:19 +08:00
Administrator fe0ede178e polish admin leaderboard analytics 2026-06-04 21:09:36 +08:00
fengxiangdebaozi cca3d8eb41 字体大小修改 2026-06-04 20:49:32 +08:00
Administrator 5590f7d85a style: polish admin user leaderboard 2026-06-04 20:22:37 +08:00
fengxiangdebaozi 90bced3ed2 第二次生成结果后台挂起 2026-06-04 20:18:34 +08:00
fengxiangdebaozi 19399482e1 后台挂起 2026-06-04 20:00:58 +08:00
吉鑫升 7657c45aae Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-04 19:37:19 +08:00
吉鑫升 e6e0832c8a chore: commit local changes 2026-06-04 19:35:56 +08:00
Administrator 8f80b7c1ef feat: add admin user leaderboard analytics 2026-06-04 19:35:11 +08:00
董宏凯 c766e3fa3b Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!92
2026-06-04 11:10:18 +00:00
fengxiangdebaozi 788118ce3d 下载图片 2026-06-04 19:08:52 +08:00
fengxiangdebaozi 77f8ded1e6 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-04 18:50:50 +08:00
fengxiangdebaozi 9d863f63e5 代码提交 2026-06-04 18:50:31 +08:00
Administrator 1e4ef070cf fix: 调整提示词和 agent 管理入口 2026-06-04 18:45:16 +08:00
吉鑫升 c1336ad5b3 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	frontend-web/src/components/workspace/settings/memory-settings-page.tsx
#	frontend-web/src/core/auth/sync.tsx
2026-06-04 17:49:26 +08:00
吉鑫升 143e0478ef Merge remote-tracking branch 'origin/ji' into ji 2026-06-04 17:46:50 +08:00
吉鑫升 cbd07c9d1b chore: update ji branch work 2026-06-04 17:46:11 +08:00
AdministratorandClaude Opus 4.8 e3b0958c23 fix: drive logout from real 401s, not local storage changes
apiFetch now redirects to login only on a genuine backend 401 (auth endpoints excluded, only when previously logged in). AuthSyncWatcher no longer treats localStorage.clear()/unrelated writes as a logout, fixing spurious sign-outs (e.g. when uploading skills).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:41:46 +08:00
g zy b843ab6542 Merge branch 'gzy_iframedf' into 'master'
feat: 中断回复

See merge request knowledge-base-bj/deerflow-server!91
2026-06-04 09:03:00 +00:00
ZyGuo dccce9355d feat: 中断回复 2026-06-04 17:00:56 +08:00
吉鑫升 6c30e649e3 Merge remote-tracking branch 'origin/ji' into ji 2026-06-04 16:59:05 +08:00
吉鑫升 bcebc8d5fb feat: 支持智能体置顶配置 2026-06-04 16:58:42 +08:00
AdministratorandClaude Opus 4.8 225398972d fix: add missing axios dependency to frontend-web
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 16:53:07 +08:00
AdministratorandClaude Opus 4.8 87f764bfa9 feat: improve markdown rendering, artifact file preview, and public scheduled task page
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 16:52:30 +08:00
fengxiangdebaozi 47217e9158 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-04 15:41:03 +08:00
fengxiangdebaozi 10334ddfe1 feat: AI writing history, Word export, roundtable dispatch chain 2026-06-04 15:40:15 +08:00
董宏凯 002e71f971 Merge branch 'dhk-1' into 'master'
样式修改

See merge request knowledge-base-bj/deerflow-server!89
2026-06-04 06:55:59 +00:00
吉鑫升andClaude Opus 4.8 1f2b1e3b8a feat: 删除提问时级联删除其回答,并移除回答上的删除按钮
- 删除按钮只保留在用户提问气泡上;AI 回答不再单独提供删除
- 后端 DELETE /messages/{id} 改为按整轮删除:从提问删到下一条提问之前,
  返回实际删除的 deleted_ids,保持 checkpoint 合法(无孤立工具结果/回答)
- 前端隐藏后端返回的整批 id,删除后即时消失
- 更新删除相关中英文案

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 14:34:52 +08:00
吉鑫升andClaude Opus 4.8 5d12616211 chore: 将登录失败次数上限从 5 提高到 100
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 14:34:42 +08:00
吉鑫升 9704eff9f7 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-04 14:28:22 +08:00
吉鑫升andClaude Opus 4.8 362a8268e8 feat: 支持删除单条聊天消息(用户提问与模型回答)
- 后端新增 DELETE /api/threads/{thread_id}/messages/{message_id},从最新 checkpoint 的 messages 通道过滤掉指定 id 并写回新 checkpoint
- 前端 useDeleteMessage 钩子 + DeleteMessageButton(带确认框)组件
- 在用户问题气泡与助手回答工具栏上各加删除按钮,仅对已落库消息显示
- MessageList 本地隐藏已删消息并在切换会话时重置;只读/分享场景禁用删除
- 新增 deleteMessage 相关中英文案

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 14:28:11 +08:00
fengxiangdebaozi c0e3c5d692 样式修改 2026-06-04 14:19:53 +08:00
AdministratorandClaude Opus 4.8 94c02ded2a feat: add user preferences, agent name desensitization and related improvements
- Add user preferences persistence (model, migration, router, frontend core)
- Add agent name desensitization config
- Add agent_id to user custom prompts with migration
- Enhance agents persistence (base, memory, model, sql) and scheduler service
- Improve frontend agent cards/gallery, scheduled tasks, custom prompt menu
- Add pagination UI component; remove stale package-lock.json

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:40:18 +08:00
董宏凯 998bd0ce06 Merge branch 'zhujingyi' into 'master'
'feat:技能样式改成卡片式'

See merge request knowledge-base-bj/deerflow-server!87
2026-06-04 03:13:33 +00:00
fengxiangdebaozi 6b6465b5e3 Merge remote branch into zhujingyi 2026-06-04 11:12:45 +08:00
董宏凯 57da50b8d6 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!88
2026-06-04 03:10:18 +00:00
fengxiangdebaozi f87f6031de Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-04 11:09:29 +08:00
fengxiangdebaozi 5b686824c5 样式修改 2026-06-04 11:08:42 +08:00
g zy 95487d362f Merge branch 'gzy_iframedf' into 'master'
feat: 从iframe对接模型配置

See merge request knowledge-base-bj/deerflow-server!86
2026-06-04 03:05:26 +00:00
ZyGuo f496546cc0 feat: 从iframe对接模型配置 2026-06-04 11:03:50 +08:00
zjy 9423d7e892 'feat:技能样式改成卡片式' 2026-06-04 10:44:55 +08:00
fengxiangdebaozi 062f984262 ai写作位置调整 2026-06-04 10:40:16 +08:00
吉鑫升andClaude Opus 4.8 925675ab54 chore: update ji local changes
- frontend: scheduled tasks pages, system-settings api, workspace nav menu
- backend: system_settings router, app_config, log_system_config, config.yaml

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 09:18:32 +08:00
董宏凯 c05513ae1e Merge branch 'dhk-1' into 'master'
fix(roundtable): 文件卡截断、Step3 完整 HTML 与跨标签页登录体验

See merge request knowledge-base-bj/deerflow-server!85
2026-06-03 13:46:33 +00:00
fengxiangdebaozi f257ccb682 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-03 21:45:21 +08:00
fengxiangdebaozi d5b0bd4d31 fix(roundtable): 文件卡截断、Step3 完整 HTML 与跨标签页登录体验
第二步消息列表长文件名不再溢出卡片;第三步绘制结束后从沙箱回灌完整 HTML(修复 append 续写 stub 被截短),进入第三步时关闭第二步沙箱;HTML 预览与提示词强调 utf-8/中文。跨标签页切换账号改为 toast 提示而非强制刷新;方案总结智能体 SOUL 去掉「AI 自动生成」标签要求。
2026-06-03 21:44:46 +08:00
董宏凯 5026bd1887 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-03 21:07:17 +08:00
董宏凯 b0b0cf7b9e 地址修改 2026-06-03 21:07:12 +08:00
fengxiangdebaozi bf96cf4cb4 接口地址修改 2026-06-03 19:12:30 +08:00
吉鑫升 aeef1dca59 Merge remote-tracking branch 'origin/ji' into ji 2026-06-03 19:01:56 +08:00
吉鑫升 a1d460e220 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	frontend-web/src/components/workspace/messages/message-list-item.tsx
#	offline-backend-20260512/backend/app/gateway/app.py
#	offline-backend-20260512/backend/packages/harness/deerflow/runtime/scheduler/html_page.py
#	offline-backend-20260512/backend/packages/harness/deerflow/runtime/scheduler/service.py
2026-06-03 19:01:45 +08:00
吉鑫升 e2a962de32 chore: update ji local changes 2026-06-03 18:57:49 +08:00
董宏凯 dbf1f46fa1 Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!84
2026-06-03 10:57:34 +00:00
fengxiangdebaozi ce07a27b8d Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-03 18:54:45 +08:00
fengxiangdebaozi 8f6e08eb2f Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-03 18:54:26 +08:00
董宏凯 a4b14e4911 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!78
2026-06-03 09:38:24 +00:00
fengxiangdebaozi 56114562cb fix: ²¹Æë Step3 ɳÏä²Ù×÷²¢Îȶ¨д×÷³ÎÇåÁ÷³Ì
Ϊ roundtable µÚÈý²½ɳÏ䲹»ØÐ´°¿ڴò¿ªÓëÏÂÔزÙ×÷£¬²¢ÐÞÕýд×÷ÅäÖóÎÇåµÄÌύÁ÷³ÌÓëĬÈÏËزÄÀ´Դ£¬±ÜÃâÓû§Ôڶ࿨Ƭ³¡¾°ÏÂÌáǰÌύ»ò½øÈ벻·ûºÏԤÆڵļìË÷·¾¶¡£
2026-06-03 17:36:52 +08:00
董宏凯 ba7834f222 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-03 17:27:18 +08:00
董宏凯andClaude Opus 4.8 d49406d2f1 Merge branch 'master' into dhk-1
解决 8 处冲突:
- app.py:同时挂载 public_embed + html_page_favorites 两个 router
- .env:保留 dhk-1 的 CORS 配置(含 5174、ALLOW_ALL=0)
- message-list.tsx:并入双方新增(onSetupWriting* 解构 + contentClassName/fitMessageRowsToContent 类型)
- WorkspaceRoutes.tsx:采用 master 的路由结构(含 chats_iframe/IframeChatPage),补回 dhk-1 的 BusinessChainEditorPage 导入与 roundtable/chains 路由
- LoginPage.tsx:合并两套登录(master 的 token 换登录 + dhk-1 的 online-ticket),并集依赖数组
- ScheduledTasksPage.tsx:采用 master 的 HTML 定时任务表单(isHtmlTask 分支)
- AIWritingForm.tsx:保留 dhk-1 的 useWritingForm 重构,补回 master 的笔记来源 useState;WritingFormContext.materialSource 扩展支持 'notebook'
- useAIWritingStream.ts:保留 dhk-1 重构(仅 reducer/helpers,useAIWriting 已移至 AIWritingContext),不并入 master 在此文件的旧实现

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 17:26:52 +08:00
fengxiangdebaozi a81d8adc90 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-03 16:34:25 +08:00
fengxiangdebaozi 3eae4a0f45 代码修改 2026-06-03 16:34:17 +08:00
董宏凯 016f921cf0 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-03 16:28:34 +08:00
董宏凯 9c8230a867 跨域修改 2026-06-03 16:28:29 +08:00
董宏凯andCursor aea7724cdb 修复 embed 跨域并持久化圆桌 Step3 结果
- Gateway 默认 CORS 白名单增加 5174,embed 文档补充跨域配置说明
- 圆桌草稿新增 step3 快照字段与迁移,结果绘制 HTML 可随草稿恢复

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-03 16:27:42 +08:00
fengxiangdebaozi 79d87ad661 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-03 16:22:51 +08:00
fengxiangdebaozi ad4b27b7ca feat: 无界 ticket 登录、AI 写作配置确认与定时任务弹窗修复
无界 onlineTicket 对接 MaxKey 与 consumer 接口并用 sub 登录;新增 setup_writing 写作配置确认流;定时任务创建弹窗限制多行高度并支持滚动。
2026-06-03 16:20:45 +08:00
董宏凯andCursor 40ba81ee6a 新增 iframe 结果接口与圆桌 Step3 结果绘制
- 公开 API:GET /api/public/embed/sessions/{sessionId}/result 返回 messages、generated_text、generated_files
- 圆桌 Step3:内置 roundtable-report 智能体、report/init 与结果绘制 UI

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-03 13:57:37 +08:00
xu hd d0e71a8104 Merge branch 'xuhd' into 'master'
技能详情对话框新增文件浏览面板:支持预览、编辑、下载、复制路径

See merge request knowledge-base-bj/deerflow-server!83
2026-06-03 04:36:31 +00:00
xuhd f2d7d43e38 Merge remote-tracking branch 'origin/master' into xuhd 2026-06-03 11:55:44 +08:00
g zy d7cb19ee96 Merge branch 'gzy_iframedf' into 'master'
Gzy iframedf

See merge request knowledge-base-bj/deerflow-server!82
2026-06-03 03:51:09 +00:00
ZyGuo 9d425a19e8 fix: 去掉iframe页顶部栏 2026-06-03 11:49:18 +08:00
xuhdandClaude Sonnet 4.6 48f37df3d5 chore(env): 更新本地开发环境配置
- 开启 GATEWAY_CORS_ALLOW_ALL=1(本地开发跨域放行)
- 更新前端 .env.development

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-03 11:45:54 +08:00
fengxiangdebaozi ab876fc7d8 feat(ai-writing): 支持用户粘贴已有大纲并按结构生成
表单可提交 userOutline,后端解析/归一用户大纲并关联素材;补充大纲测试用例与右侧编辑器滑词/段落菜单文档。
2026-06-03 11:43:44 +08:00
xuhdandClaude Sonnet 4.6 712326387f merge: 合并 origin/xuhd,解决 message-list-item 和 WorkspaceRoutes 冲突
- message-list-item: 保留 EmbeddedPageContext + 消息内联编辑两套功能
- WorkspaceRoutes: 保留 IframeChatPage + NotebookDetailPageWithKey

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-03 11:41:49 +08:00
AdministratorandClaude Opus 4.8 133054e2dd feat(skills/settings): 技能复制 + 设置持久化等会话前改动
- 技能复制:新增 POST 复制接口(_rewrite_skill_frontmatter_name 重写 frontmatter name + 校验 + 去重),前端 skills api/hooks 与技能设置页配套
- 设置持久化:lastAgentId、线程 RAG 模式锁(settings/index、local)
- i18n(en/zh/types)、agent-card/input-box/message-list 等页面文案与交互微调
- scheduler/element.py 小修

(本批为会话前已存在的工作区改动,按要求一并提交;构建产物 backend.zip 未提交)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 11:38:47 +08:00
AdministratorandClaude Opus 4.8 adcc5a358b feat(scheduled-tasks): 新增 HTML 页面定时任务(生成/预览/收藏/技能)
后端:
- 新增 task_kind=html_page 任务类型,与普通定时任务并存,配置存 execution_context(无需迁移)
- 执行流水线:智能体检索数据 -> 选定模型渲染 HTML -> 清洗/校验 -> 失败自动修复 -> 完整性闸门(缺 doctype/html/head/body/title 或残留脚本即失败) -> 归档 index.html -> 落库
- 新增 scheduled_html_pages / html_page_favorites 表与 store;收藏去重(不可重复)、可删除、收藏时提取可复用风格
- HTML 预览接口(鉴权 + 公开)、收藏接口
- 渲染注入已启用的 HTML 技能(metadata.kind=html_page);全程使用用户所选模型,去除硬编码 GLM-5
- 定时任务跳过 TitleMiddleware,避免标题生成回退默认模型

前端:
- 创建/编辑弹窗增加任务类型与 HTML 配置(页面要求/限制/参考收藏页/模型下拉)
- 运行详情页与公开页 iframe 沙箱预览 HTML;收藏按钮(已收藏禁用)
- 参考收藏页可选可删

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 11:35:38 +08:00
AdministratorandClaude Opus 4.8 5c2379577b fix(auth): token 登录将令牌放入 Authorization: Bearer 头
token 换登录调上游 getTokenInfo 时参数传错:原来发静态头
Authorization: Bearer admin + 令牌放 access_token cookie。上游实际
从 Authorization: Bearer <token> 头读取令牌。

- 鉴权头改为 "Bearer "+前端传入 token,删除 access_token cookie
- service_authorization 配置项弃用(保留兼容,不再参与请求)
- 新增回归测试 test_token_login_upstream_call.py
- 同步更新 AUTH_LOGIN.md / CLAUDE.md / config.yaml 注释 / login_config 文档

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 11:35:38 +08:00
AdministratorandClaude Opus 4.8 c5352f2ee7 本地启动环境修复与配置
- config.yaml: checkpointer 连接串改为相对路径(原为他机绝对路径,本地无法创建)
- frontend-web: 补充缺失的 dayjs 直接依赖(lockfile 已有,package.json 缺失)
- .gitignore: 忽略 backend/uv.lock 并取消其跟踪

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 11:35:38 +08:00
ZyGuo 5574364438 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy_iframedf 2026-06-03 11:33:50 +08:00
ZyGuo cb0b30690e fix: 去掉用户气泡中<>的显示 2026-06-03 11:33:23 +08:00
g zy 8442e6ec8d Merge branch 'gzy_iframedf' into 'master'
fix: 传图修复

See merge request knowledge-base-bj/deerflow-server!80
2026-06-03 03:12:40 +00:00
ZyGuo 8ba3a67401 fix: 传图修复 2026-06-03 11:12:10 +08:00
g zy f2dc03b51e Merge branch 'gzy_iframedf' into 'master'
Gzy iframedf

See merge request knowledge-base-bj/deerflow-server!79
2026-06-03 03:08:10 +00:00
ZyGuo 5d39aa55bd feat: 支持传图 2026-06-03 10:51:42 +08:00
xuhdandClaude Sonnet 4.6 22574d3ada fix(setup_agent): 限制技能数量最多 5 个
- middleware 拦截阶段静默截断 skills[:5],超出不报错不中断流程
- 工具执行阶段同样截断,双重兜底

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-03 10:48:13 +08:00
董宏凯 0727b4564b 圆桌规划第3步修改 2026-06-03 10:01:10 +08:00
董宏凯 6521218308 样式修改 2026-06-03 09:54:11 +08:00
ZyGuo 34a9f15cb4 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy_iframedf 2026-06-03 09:41:14 +08:00
ZyGuo a5b65f4087 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy_iframedf 2026-06-03 09:41:09 +08:00
AdministratorandClaude Opus 4.8 f590f672be feat(skills/settings): 技能复制 + 设置持久化等会话前改动
- 技能复制:新增 POST 复制接口(_rewrite_skill_frontmatter_name 重写 frontmatter name + 校验 + 去重),前端 skills api/hooks 与技能设置页配套
- 设置持久化:lastAgentId、线程 RAG 模式锁(settings/index、local)
- i18n(en/zh/types)、agent-card/input-box/message-list 等页面文案与交互微调
- scheduler/element.py 小修

(本批为会话前已存在的工作区改动,按要求一并提交;构建产物 backend.zip 未提交)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 23:48:19 +08:00
AdministratorandClaude Opus 4.8 d9afaca51f feat(scheduled-tasks): 新增 HTML 页面定时任务(生成/预览/收藏/技能)
后端:
- 新增 task_kind=html_page 任务类型,与普通定时任务并存,配置存 execution_context(无需迁移)
- 执行流水线:智能体检索数据 -> 选定模型渲染 HTML -> 清洗/校验 -> 失败自动修复 -> 完整性闸门(缺 doctype/html/head/body/title 或残留脚本即失败) -> 归档 index.html -> 落库
- 新增 scheduled_html_pages / html_page_favorites 表与 store;收藏去重(不可重复)、可删除、收藏时提取可复用风格
- HTML 预览接口(鉴权 + 公开)、收藏接口
- 渲染注入已启用的 HTML 技能(metadata.kind=html_page);全程使用用户所选模型,去除硬编码 GLM-5
- 定时任务跳过 TitleMiddleware,避免标题生成回退默认模型

前端:
- 创建/编辑弹窗增加任务类型与 HTML 配置(页面要求/限制/参考收藏页/模型下拉)
- 运行详情页与公开页 iframe 沙箱预览 HTML;收藏按钮(已收藏禁用)
- 参考收藏页可选可删

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 23:46:20 +08:00
董宏凯 3b5525a0a5 ai写作修改 2026-06-02 22:55:22 +08:00
董宏凯 fdfb888be9 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-02 21:26:21 +08:00
fengxiangdebaozi 02eee4bd3e 页面修改 2026-06-02 21:25:44 +08:00
董宏凯 b257963551 ai写作 2026-06-02 21:22:31 +08:00
fengxiangdebaozi fb43c036f6 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-02 21:15:53 +08:00
fengxiangdebaozi 9ae6184dc1 业务链条 2026-06-02 21:15:46 +08:00
董宏凯 7efedc7b44 ai写作修改 2026-06-02 20:36:22 +08:00
AdministratorandClaude Opus 4.8 e1e9be8daa fix(auth): token 登录将令牌放入 Authorization: Bearer 头
token 换登录调上游 getTokenInfo 时参数传错:原来发静态头
Authorization: Bearer admin + 令牌放 access_token cookie。上游实际
从 Authorization: Bearer <token> 头读取令牌。

- 鉴权头改为 "Bearer "+前端传入 token,删除 access_token cookie
- service_authorization 配置项弃用(保留兼容,不再参与请求)
- 新增回归测试 test_token_login_upstream_call.py
- 同步更新 AUTH_LOGIN.md / CLAUDE.md / config.yaml 注释 / login_config 文档

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 19:33:38 +08:00
Administrator 247ff86f2f Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-06-02 19:06:42 +08:00
吉鑫升 89cb5ab2f1 Merge remote-tracking branch 'origin/master' into ji 2026-06-02 17:40:56 +08:00
吉鑫升andClaude Opus 4.8 c484481964 登录鉴权:新增用户名口令门 + token 换登录两种模式
- config 新增 auth_login 段(login_config.py):
  - username_login.require_password 开启后,用户名直登必须带 ?password=,口令留空默认 123ewq
  - token_login 用上游 token 调 getTokenInfo 换用户名再登录,用户名不在库自动注册;含 verify_ssl/ca_cert_path 处理 HTTPS 自签证书
- auth.py:口令门、/login/token 端点、共享 _get_or_create_user_by_username 与 _fetch_username_from_token;登录类报错文案改中文
- auth_middleware:/login/token 加入免鉴权白名单
- 前端 api.ts/LoginPage:透传 ?password=、?authToken=;修复错误体为对象时显示 [object Object] 的问题
- 文档:backend/CLAUDE.md + docs/AUTH_LOGIN.md 接口说明

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 17:39:56 +08:00
xuhdandClaude Sonnet 4.6 613cece224 fix(studio): 笔记切换页面不刷新 + 侧边栏错误提示友好化
- WorkspaceRoutes 给 StudioNotebookDetailPage 加 key={notebookId},切换笔记时强制重新挂载
- createSearchSpace 接口失败时解析响应体 detail 字段,直接展示服务端错误信息

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-02 17:24:08 +08:00
吉鑫升andClaude Opus 4.8 5aa1fdca04 识图与文件上传/预览:可配置视觉模型 + 修复上传与回显
后端:
- 新增可配置识图模型(config: vision.model_name/prompt/max_tokens)。配置后 view_image 委托该模型识别并返回文字结果,文本主模型也能“看图”;未配置时回退到主模型自带视觉能力。新增 deerflow/models/vision.py 与 VisionConfig。
- 修复 Windows 上传全部报 unsafe:open_upload_file_no_symlink 不再强制要求 POSIX 专有的 O_NOFOLLOW,缺失时降级(仍用 lstat/fstat 防符号链接),Windows 追加 O_BINARY。
- 修复 normalize_input 丢弃 human 消息 additional_kwargs:保留 files/client_ts 等,使上传文件能回传到 UI 并被 UploadsMiddleware 识别。
- 约束 agent 行为:上传图片时引导只用 view_image,禁止用 read_file/grep/bash/python 解析图片字节;view_image 工具说明同步加固。
- 启用文档转换(uploads.auto_convert_documents),PDF/Word/Excel/PPT 自动转 Markdown 供 read_file/grep 读取。
- 订正若干模型错误的 supports_vision 标记。

前端:
- 修复上传文件不回显:parseUploadedFiles 不再因 "(empty)" 提前返回。
- 修复 artifact 401 破图:改用带 Authorization 头的 apiFetch 取 blob 显示(新增 useAuthedObjectUrl)。
- 新增上传文件预览弹窗:点击卡片可查看图片/文本/Markdown、Office(读转换后的 .md)、PDF;文件卡片改为可点击。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 16:43:53 +08:00
xuhdandClaude Sonnet 4.6 73700cca54 fix(ai_writing): 笔记来源素材使用真实检索分数并打印请求日志
- 笔记 chunk 的 relevance_score 改用接口返回的 score 字段(向量相似度/RRF),接口无分数时降级为位置估算
- _search_notebook 增加 INFO 级日志,输出每次请求的 payload 和响应 status/body,便于调试

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-02 16:31:57 +08:00
ZyGuo 3c92e87156 feat: 标题去除特殊tag 2026-06-02 16:24:01 +08:00
ZyGuo 0122d3e361 feat: 生成中状态 2026-06-02 16:18:00 +08:00
董宏凯 30410b0a93 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!77
2026-06-02 07:19:19 +00:00
fengxiangdebaozi 5c5632967c 样式修改 2026-06-02 15:16:39 +08:00
fengxiangdebaozi d872f4e177 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-02 14:11:24 +08:00
fengxiangdebaozi 677faab273 代码提交 2026-06-02 11:50:22 +08:00
董宏凯 d40ee80680 Merge branch 'zhujingyi' into 'master'
Zhujingyi

See merge request knowledge-base-bj/deerflow-server!76
2026-06-02 03:49:25 +00:00
董宏凯 79dd6b9be0 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!75
2026-06-02 03:48:56 +00:00
ZyGuo 49cfc687f9 fix: 对话区域显示问题修复 2026-06-02 11:26:28 +08:00
fengxiangdebaozi f0ccd6fb09 代码提交 2026-06-02 11:04:25 +08:00
zjy 372d4f7933 'feat:暗色模式样式修改' 2026-06-02 11:01:07 +08:00
fengxiangdebaozi 6621519f11 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-02 10:47:29 +08:00
fengxiangdebaozi 1777a0171b d 2026-06-02 10:47:01 +08:00
fengxiangdebaozi 93e702f9ca fix(frontend): show raw chat messages and improve roundtable draft saves 2026-06-02 10:45:20 +08:00
fengxiangdebaozi 0d8cdf3afb Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-01 22:17:44 +08:00
fengxiangdebaozi fa41d620fd 字号调整 2026-06-01 22:17:39 +08:00
AdministratorandClaude Opus 4.8 93543919d4 本地启动环境修复与配置
- config.yaml: checkpointer 连接串改为相对路径(原为他机绝对路径,本地无法创建)
- frontend-web: 补充缺失的 dayjs 直接依赖(lockfile 已有,package.json 缺失)
- .gitignore: 忽略 backend/uv.lock 并取消其跟踪

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 20:29:29 +08:00
董宏凯 001b04ac5a Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-01 20:00:46 +08:00
董宏凯 417ec01fb2 代码修改 2026-06-01 20:00:05 +08:00
fengxiangdebaozi 0c5938a5a3 代码代码修改 2026-06-01 19:54:45 +08:00
ZyGuo 2e6eff43ad feat: 去掉demo按钮 2026-06-01 18:13:23 +08:00
xuhdandClaude Sonnet 4.6 c714351819 feat: 我的笔记列表与详情页 UI 重构(Gemini 风格)
- StudioNotebooksPage: 卡片改为灰底无边框圆角网格,hover 显示三点菜单,支持重命名(PATCH)和删除(DELETE)
- StudioNotebookDetailPage: 详情页背景改为主题色渐变,内容垂直居中,输入框内联布局,模型选择器移至右侧,历史对话限显 5 条可展开/滚动
- api.ts: 新增 deleteSearchSpace、renameSearchSpace、uploadSourceText 接口
- 来源 Dialog:新增「复制的文字」面板,支持粘贴文本上传

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 17:36:42 +08:00
董宏凯 e9c56f8635 部署 2026-06-01 17:33:40 +08:00
ZyGuo 5f88efb2c9 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy_iframedf 2026-06-01 17:29:30 +08:00
ZyGuo e6af567206 iframe 页面优化 2026-06-01 17:27:57 +08:00
吉鑫升 43cbcd86be Merge remote-tracking branch 'origin/master' into ji 2026-06-01 17:11:08 +08:00
董宏凯 44931f8205 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!74
2026-06-01 09:01:23 +00:00
吉鑫升 bc7622b0bd Merge remote-tracking branch 'origin/master' into ji 2026-06-01 16:59:56 +08:00
xuhd 1a1d22d6ee 添加环境变量我的笔记的前端地址 2026-06-01 16:59:09 +08:00
xuhdandClaude Sonnet 4.6 ab9034633a feat: StudioNotebookDetailPage 添加「我的笔记」跳转
- 聊天视图顶栏和列表视图右上角均新增「我的笔记」链接
- 点击跳转目标系统 callback 页面并携带 token 和 redirect 参数
- 来源弹窗仅保留「上传文件」和「复制的文字」两个选项
- VITE_AIPI_BACKENP_URL 用于 Studio API 调用,VITE_AIPI_FRONTEND_URL 用于页面跳转
- useStudioNotebooks 新增 token 返回值供页面直接使用

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 16:55:39 +08:00
吉鑫升andClaude Opus 4.8 c860ee85f7 技能展示适配:支持多结果集(result sets)渲染
- 后端 extensions_config 新增 SkillDisplayResultSetConfig,SkillDisplayConfig 增加 resultSets 字段
- threads 引用响应增加 resultSetKey / resultSetLabel,runtime/references 适配多结果集
- 前端 skill-display 适配器/运行时/类型支持多结果集渲染,聊天框、消息组、技能展示面板相应更新

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 16:42:39 +08:00
ZyGuo 16adb90653 feat: 登陆后跳转位置增加iframe判断 2026-06-01 16:13:47 +08:00
fengxiangdebaozi a5d877207e Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-06-01 15:11:14 +08:00
fengxiangdebaozi 685abb6aa9 深蓝色ui 2026-06-01 15:11:05 +08:00
xuhdandClaude Sonnet 4.6 7f0a0d92a3 feat: 素材来源新增「我的笔记」选项
- materialSource 枚举新增 notebook 值
- 选择「我的笔记」时展开笔记本 + 文档多选选择器
- 切换其他来源自动清空笔记选择
- 只有 notebook 模式才向后端传笔记参数

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 14:30:16 +08:00
xuhdandClaude Sonnet 4.6 e4983be9d7 fix: 解决 merge 冲突,恢复笔记来源字段
合并 master 时冲突导致 notebook_search_space_id / notebook_source_ids
被覆盖,现补回;同时兼容 master 新增的 material_source / model_name 字段。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 14:22:55 +08:00
xuhd e30b44dae1 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-06-01 14:21:20 +08:00
ZyGuo 0922c8299f feat: iframe page 2026-06-01 14:16:13 +08:00
董宏凯 8adb4d5cef 一键部署 2026-06-01 13:53:57 +08:00
董宏凯 5198f6c4df Merge branch 'dhk-1' into 'master'
圆桌草稿持久化:localStorage 迁至后端 MySQL

See merge request knowledge-base-bj/deerflow-server!73
2026-06-01 04:59:24 +00:00
董宏凯andClaude Opus 4.8 5d0bafd651 AI写作:新增素材来源选项(知识库/技能检索)
写作表单新增「素材来源」下拉:知识库(默认 web/intranet 检索)/
技能检索(用已启用技能编排检索)。用户选择后素材收集专家首次检索
据此决定检索方式。

- state 新增 material_source 通道(缺省 knowledge_base,兼容老 session)
- researcher 首次检索(无干预)时按来源决定 is_skill_search;
  PAUSE-1「启用技能检索」按钮仍独立有效
- 前端 AIWritingRequest.materialSource + 表单下拉 + hook 提交 material_source

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 12:58:50 +08:00
xuhdandClaude Sonnet 4.6 b749c78efa feat: AI写作集成笔记来源,支持多文档多选检索
- 前端 AIWritingForm 新增笔记来源选择器(笔记本单选 + 文档多选 checkbox)
- AIWritingRequest 类型新增 noteSearchSpaceId / noteSourceIds 字段
- AIMaterial.sourceType 新增 notebook 类型
- useAIWritingStream startWriting 时自动获取 notebook_token 并携带笔记参数
- 后端 AIWritingState 新增 notebook_search_space_id / notebook_source_ids 字段
- researcher 节点新增 _search_notebook,解析 API 返回的 documents/chunks,
  每个 chunk 作为独立素材(source_type=notebook)混入素材包

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 11:47:37 +08:00
xuhd 22b93e32eb Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-06-01 10:49:53 +08:00
ZyGuo c767566cb6 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-06-01 10:29:39 +08:00
ZyGuo a2cc1832f2 chore: ignore 2026-06-01 10:27:31 +08:00
fengxiangdebaozi 169346cdbd 样式修改 2026-06-01 10:06:28 +08:00
董宏凯 ea50540bd5 样式修改 2026-05-31 18:23:34 +08:00
董宏凯 8e909ef1c1 ui规范 2026-05-31 18:11:17 +08:00
董宏凯 7ad42ccf16 ui规范 2026-05-31 16:48:43 +08:00
董宏凯andCursor 633a350bfc AI写作:技能检索进度反馈与超时兜底
检索等待时 SkillStepsCard 显示 spinner;单技能检索 25s 超时避免卡死;前后端增加 skill-timing 调试日志。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-31 14:42:51 +08:00
董宏凯andCursor 23d6f9efc2 圆桌 Step1:支持多澄清实时展示与合并提交
流式解析 ask_clarification 逐题渲染澄清卡;草稿恢复 selectedAgents 修复参与角色;Step3 隐藏左侧栏让报告区全宽。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-31 14:23:43 +08:00
董宏凯andCursor 838cae0d2d 圆桌草稿持久化:localStorage 迁至后端 MySQL
新增 /api/roundtable-drafts 草稿 CRUD 与会话级推荐历史;前端 useDraftPersistence 改走 api/drafts,删除本地 drafts.ts。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-31 00:23:25 +08:00
董宏凯 24e92c437d ai写作bug修改 2026-05-29 22:16:19 +08:00
董宏凯 7d45c89d72 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-29 20:56:43 +08:00
董宏凯 8e931c5acc 代码 2026-05-29 20:56:07 +08:00
fengxiangdebaozi be37779472 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-29 20:17:07 +08:00
fengxiangdebaozi 27cfd53c06 样式修改 2026-05-29 20:16:41 +08:00
吉鑫升 00e74a5e45 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	offline-backend-20260512/backend/app/gateway/services.py
2026-05-29 18:36:29 +08:00
fengxiangdebaozi c890ae5a15 样式修改 2026-05-29 18:17:08 +08:00
fengxiangdebaozi 786ddaa38f 代码修改 2026-05-29 18:07:45 +08:00
董宏凯 d162e5533f Merge branch 'zhujingyi' into 'master'
'feat:智能体暗色模式样式修改'

See merge request knowledge-base-bj/deerflow-server!72
2026-05-29 07:30:17 +00:00
董宏凯 e68b726f9a Merge branch 'dhk-1' into 'master'
圆桌 Step2:固定协调员单例、优化调度性能、修正研讨中状态

See merge request knowledge-base-bj/deerflow-server!71
2026-05-29 07:29:17 +00:00
fengxiangdebaozi 8ed3b0eb91 路由样式修改 2026-05-29 15:26:41 +08:00
fengxiangdebaozi a9332c0ab0 技能联调 2026-05-29 15:22:28 +08:00
xuhd 423abf4fde 上传文件添加 2026-05-29 15:15:29 +08:00
fengxiangdebaozi 07ad87365f 作家写作 2026-05-29 11:42:30 +08:00
吉鑫升andClaude Opus 4.7 2c136c1fde 参考文献模式合并为单一 referenceBatch 并统一连续编号
将同一轮检索结果合并为一个 referenceBatch,由系统统一从 [1] 连续编号,避免每个检索词各自重新编号;提示词引导优先并行检索后再作答。智能体列表接口并发加载技能等轻量信息以渲染卡片徽章,并新增参考文献相关测试。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 11:31:31 +08:00
fengxiangdebaozi 1a122eb7fd 代码修改 2026-05-29 11:19:58 +08:00
xuhdandClaude Sonnet 4.6 4a63399363 feat: 新增工作室展示开关 VITE_STUDIO_ENABLED
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 10:47:50 +08:00
zjy ee8e2b3225 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into zhujingyi 2026-05-29 09:56:12 +08:00
zjy 8aa52e7e3c 'feat:智能体暗色模式样式修改' 2026-05-29 09:51:44 +08:00
董宏凯andCursor de597b602a 圆桌 Step2:固定协调员单例、优化调度性能、修正研讨中状态
将 roundtable-coordinator 改为内置单例避免重复创建;legacy sync 加 TTL 减少 runs/stream 延迟;前端仅当前发言者显示研讨中。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-28 23:23:40 +08:00
董宏凯 2371364911 代码优化 2026-05-28 22:35:05 +08:00
董宏凯 214e794451 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-28 21:22:54 +08:00
董宏凯 ab902f948a 代码合并 2026-05-28 21:22:49 +08:00
fengxiangdebaozi ce1e36f4fd 样式修改 2026-05-28 21:15:45 +08:00
fengxiangdebaozi 72eb5204ff Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-28 20:18:43 +08:00
xuhd e4da5bec8d 22222 2026-05-28 18:56:11 +08:00
xuhd 6102963624 000 2026-05-28 18:43:20 +08:00
xuhd b152cb43fc 222 2026-05-28 18:37:48 +08:00
xuhdandClaude Sonnet 4.6 ebe1678b30 Merge origin/master into xuhd
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 18:31:16 +08:00
fengxiangdebaozi 8a0962681a 代码修改 2026-05-28 18:29:50 +08:00
fengxiangdebaozi 9778f9521e 接口地址修改 2026-05-28 18:29:50 +08:00
fengxiangdebaozi 4a3cfb9dfa 任务理解修改 2026-05-28 18:29:50 +08:00
董宏凯 1cfa93e855 点击后打开沙箱 2026-05-28 18:29:50 +08:00
董宏凯 4fab13c728 文件浏览 2026-05-28 18:29:50 +08:00
fengxiangdebaozi a3c69dab07 代码修改 2026-05-28 18:29:50 +08:00
董宏凯 e3dd430e68 按钮修改 2026-05-28 18:29:44 +08:00
董宏凯 d018ecd805 速度优化 2026-05-28 18:29:44 +08:00
fengxiangdebaozi a4b7ab5e9d 代码修改 2026-05-28 18:29:37 +08:00
董宏凯 ef1481be63 智能体查询优化 2026-05-28 18:29:37 +08:00
董宏凯 3a2b5d5ccd 代码修改 2026-05-28 18:29:32 +08:00
吉鑫升andClaude Opus 4.7 78f6e37f76 新增智能体收藏、定时任务必须生成MD校验、问答时间显示及账号绑定的常用提示词
- 智能体支持从广场收藏到「我的」(新增 agent_favorites 表与收藏/取消收藏接口)
- 定时任务新增「必须生成Markdown文件」开关:注入提示词并校验生成的 .md 文件且正文超过100字,否则记为失败(存于 execution_context,无需迁移)
- 聊天问答展示时间(年月日 时分):问题在右下角、回答在左下角
- 常用提示词改为与账号绑定(新增 user_custom_prompts 表与 /api/user-prompts 接口),仅在首页输入框上方以居中标签 + 轮播展示,齿轮置于最右侧管理

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:29:32 +08:00
xuhdandClaude Sonnet 4.6 1ea521abab 前端优化:chat-box、消息列表、rehype 及 Studio 相关交互改进
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 18:29:10 +08:00
xuhd b8a97f2138 xxx 2026-05-28 18:29:10 +08:00
吉鑫升andClaude Opus 4.7 dac5ff38db 技能展示配置持久化并适配引用来源,新增技能文件预览组件
- 后端将技能展示适配配置存入数据库,引用批次按持久化映射进行适配
- 前端新增技能文件预览弹窗与文件树组件,完善技能来源展示
- 修正 .gitignore 中宽泛的 skills/ 规则误忽略前端组件目录的问题

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:29:10 +08:00
董宏凯 ac98d2f585 ai写作默认模型 2026-05-28 18:29:10 +08:00
董宏凯 37a9cca82d 代码修改 2026-05-28 18:29:10 +08:00
董宏凯 8c53594df7 多智能体会商沙箱 2026-05-28 18:29:10 +08:00
hkdongandClaude Opus 4.7 eec7567ac6 修复总控智能体共识后仍被错判为继续派活的死循环
_find_dispatch_message 原实现会一路向前翻历史,直到撞到任意一条带
tool_calls 的 AIMessage,导致本轮 LLM 即使共识(tool_calls=[]),也会
被上一轮的派活 AI 翻出来再用一次,前端因此把同样的 task 又发给子智能体,
形成"嘴上共识、手上派活"的死循环。

改成只看最新一条 AIMessage(跳过末尾 skill_stop / clarification ack
ToolMessage 即可),让 tool_calls 是否为空作为本轮的唯一权威信号。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 18:29:10 +08:00
fengxiangdebaozi 920fde9cd0 代码提交 2026-05-28 18:29:10 +08:00
董宏凯 742bbdf3ac 点击确认 2026-05-28 18:29:10 +08:00
董宏凯 4da8a1301e 报告沙箱 2026-05-28 18:29:10 +08:00
董宏凯 3bd5cfab9d 代码修改 2026-05-28 18:29:10 +08:00
董宏凯 4f8b0f1c67 ai写作修改 2026-05-28 18:29:10 +08:00
fengxiangdebaozi c59819f6dc 开发文档 2026-05-28 18:29:10 +08:00
fengxiangdebaozi 96d0f4ae73 接口修改 2026-05-28 18:29:03 +08:00
吉鑫升 a35aeee6a2 代码提交 2026-05-28 18:28:57 +08:00
吉鑫升 2688cda6b5 忽略RAG调试日志 2026-05-28 18:28:57 +08:00
吉鑫升 f668133297 实现RAG参考文献显示模式 2026-05-28 18:28:57 +08:00
吉鑫升andClaude Opus 4.7 89bd07be92 管理员智能体/技能管理 + 跨标签登录同步 + 上游响应异常重试
- 「设置和更多」新增「智能体管理」「技能管理」入口,与定时任务管理同级;
  独立的 AdminAgentsPage/AdminSkillsPage 复用 AgentCard/SkillRow,
  管理员可查看并编辑/删除所有用户的智能体与技能。
- 后端 /api/agents、/api/skills 增加 ?admin=true 越权列表;agents 端
  放宽 _get_editable_or_raise 让管理员可编辑/删除任意智能体;新增
  list_all/update_any/delete_any(agents)与 list_all(skills)。
- 新增 AuthSyncWatcher:监听 localStorage["deerflow.auth"] 的 storage
  事件,user_id 变化时自动 reload,修复多标签切换登录后老页面点击
  「新对话」偶发 404 的问题。
- LLMErrorHandlingMiddleware 将 bad_response_status_code / JSON
  decode 等上游网关乱码识别为可重试的 upstream 类故障。
- 侧边栏「任务管理」改名为「定时任务」。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:28:49 +08:00
吉鑫升andClaude Opus 4.7 a5fb806028 轮换 LLM 凭证与默认模型(DeepSeek → zai-org/GLM-5-FP8)
- backend/config.yaml、config.yaml 把默认模型从 deepseek-chat 切到
  zai-org/GLM-5-FP8(modal endpoint),并轮换对应 API key / Bearer
- .env 同步更新

注意:这些文件包含真实凭证,应用部署时务必通过 .env 或私有 config
覆盖,不要把仓库里的版本直接用于生产。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:28:49 +08:00
吉鑫升andClaude Opus 4.7 83714f628b 私密/公开互斥兜底 + 智能体搜索按显示后名称匹配 + 多处小修
- 后端 update_agent / set_agent_private 增加兜底:is_private=true 时强制
  published=false,杜绝同时落在公开+私密两个广场的灰色态
- agent-card 编辑弹窗暴露 editIsPrivate 开关,与公开发布开关在前端互斥校验
- agent-gallery 智能体模糊搜索改为前端针对 desensitize() 后的名字比对,
  解决脱敏显示与原始名字不一致导致看似搜索失效的问题
- useUpdateAgent 在 onSuccess 立刻把新数据 patch 进所有 ["agents"] 列表
  缓存,卡片在后台 refetch 完成前先行 re-render,避免「切换私密/发布后
  好像没反应」的体感延迟
- useGlobalShortcuts 对 event.key 为 undefined(IME 合成 / 扩展注入)做
  容错,否则会抛 TypeError 把后续所有快捷键吃掉

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:28:49 +08:00
吉鑫升andClaude Opus 4.7 ae3e2fb4e8 默认主题改为浅色 + 管理员可配置全局默认主题
- system_settings 新增 AppearanceSettings(default_theme),默认为 light,
  对应 GET /api/system-settings/appearance(任何人可读)+ PUT(admin 可写)
- App.tsx 把 NextThemesProvider 的 defaultTheme 从 dark 改为 light,并把
  QueryClientProvider 提到 ThemeProvider 外层以便后者使用 useQuery
- ThemeContext 新增 localStorage 标志 strategy-theme-user-set:用户调用
  toggleTheme / setTheme 时打标;每次启动若标志未设,则跟随 admin 配置的
  default_theme 同步主题,admin 改动用户刷新即生效;标志一旦存在永远尊重
  用户个人选择
- legacy 'theme' 键迁移视为用户显式选择,避免老用户被新默认覆盖
- frontend system-settings api/hook 增 appearance 拉取与更新

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:28:49 +08:00
吉鑫升 650102cedb feat: improve citation display and skill persistence 2026-05-28 18:28:45 +08:00
吉鑫升andClaude Opus 4.7 61babbdf7d 技能展示样本运行器 + 参考文献来源过滤调整
- skills 路由新增 _run_skill_python_sample,按本地 Python 候选实际执行
  技能脚本,作为展示适配器的真实样本来源
- skill-display 运行时与适配器调整,参考文献收集放宽起始消息约束

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:28:41 +08:00
吉鑫升andClaude Opus 4.7 3734b6a05f 新增智能体私密广场(is_private + 管理员密码门控)
- agents 表新增 is_private 列与迁移 20260526_01;列表 filter 拆分为公开
  广场用的 _listing_filter(剔除私密)与单条访问用的 _visible_filter(保留可达)
- system_settings 增 PrivateSquareSettings(enabled + password_hash),
  对应 GET/PUT /api/system-settings/private-square 由管理员管理
- /api/agents 接口:列表/创建/更新新增 is_private 字段;新增
  POST /api/agents/private-square/list(密码校验后返回私密智能体)与
  PUT /api/agents/{id}/private(管理员跨用户搬动智能体)
- 前端「智能体」页签新增「私密广场」入口(密码校验 + sessionStorage 缓存 +
  锁定按钮),卡片增加紫色私密徽章与盾牌切换按钮(owner 自助 / 管理员跨用户),
  「广场」与首页推荐候选均剔除私密智能体
- 新增管理员配置页 /settings/private-square 与侧边栏入口

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:28:41 +08:00
吉鑫升andClaude Opus 4.7 0256d527f0 技能展示适配持久化 + 参考文献收集与新对话流式修复
- 后端新增 skill_display_adapters 表,持久化每个技能的 display 配置与 sample
  payload;/api/skills 列表、详情、设置接口同步读写
- 新增 /api/skills/{name}/display-sample 端点,编辑器优先加载库中样例
- 前端展示适配面板改为从后端加载持久样例,无样例时提示"自动识别"
- 参考文献收集修复:仅在 bash/shell/python 等执行类工具上从参数推断技能
  名,避免 read_file / web_fetch 误匹配;引用列表纳入最新一条助手消息
- ChatBox 改用「最新 human → 最新 ai」窗口收集引用,并仅保留 citation
  模式
- 修复「新对话」点击后已发消息消失:useThreadStream 只在 threadId 切回
  空值时重置/中止 SSE,避免 onCreated 分配 id 时把刚开始的流打断;
  ChatPage 在 landing 状态隐藏 MessageList,移除 KeyedChatPage remount
- 技能详情对话框:所有者可查看源码与文件 tab(不再要求管理员)
- LocalSandbox:Windows PowerShell 5 路径下把 && 重写为 ;,并以
  UTF-8 解码 subprocess 输出,避免中文乱码
- knowledge-search-v2 mock 样例改为中文固定测试数据

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:28:41 +08:00
吉鑫升 7adb93fb8e 修复「新对话」流式中无法重置 + 参考文献开关默认关闭并加对勾
- 流式回答过程中点「新对话」:URL 同路径导致 react-router navigate 静默 no-op,
  下游 hook 收不到事件;改为显式 navigate(..., {replace:true, state:{resetAt}})
  保证每次点击刷新 location.key,并让 useThreadChat 监听 location.key 触发重置
- useThreadStream 在 threadId 变化时 stop() 掉上一条 SSE,避免旧流继续派发事件
- 引入 KeyedChatPage 用 location.key 作 ChatRuntime key,真正的导航触发整树 remount,
  解决 useStream 内部 stream.values 残留导致欢迎页底下还能看到旧消息的过渡帧问题
- 「参考文献」开关默认关闭(local.ts),开启态在文字前额外多一个 ✓ 对勾
2026-05-28 18:28:33 +08:00
吉鑫升 97f24f17eb 新增 RAG 引用展示模式:支持技能结果按编号引用/列表/表格渲染
- 前端新增 skill-display 适配层(runtime/display-adapter)与可视化适配面板,
  支持从技能返回 JSON 自动识别字段并配置 citation/list/table/card 展示
- 正文 [[N]] 编号渲染为可点击徽章,点击不跳 URL 而是定位到右侧参考文献面板;
  参考卡片样式重做(圆形编号、悬停高亮、过滤掉 "result" 占位类型)
- bash 工具调用按命令中的 skills/{public,custom}/<name>/ 路径反查展示适配,
  解决调用名为 "bash" 时无法匹配到具体技能的问题
- 工具结果 JSON 解析放宽:能从 stderr/exit code 噪声尾巴里抢救出 JSON 主体
- 展示适配自动识别接入 LLM:读 SKILL.md 让模型推断真实返回结构,失败回退 mock
- 展示适配面板修复保存回显:保存后表单跟随服务端最新值刷新,样例文本不再被抹掉
- 设置页加 "RAG 引用模式" 开关(默认开),关联 lead-agent prompt 注入引用规则
2026-05-28 18:28:33 +08:00
吉鑫升andClaude Opus 4.7 96b0bae6ca 技能详情对话框新增文件浏览面板:支持预览、编辑、下载、复制路径
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:27:12 +08:00
董宏凯 3632b0d726 代码合并 2026-05-28 17:49:18 +08:00
吉鑫升 6792b4f4c4 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji
# Conflicts:
#	frontend-web/src/components/workspace/chats/chat-box.tsx
#	offline-backend-20260512/backend/app/gateway/routers/agents.py
2026-05-28 17:29:36 +08:00
吉鑫升andClaude Opus 4.7 10e35055e0 新增智能体收藏、定时任务必须生成MD校验、问答时间显示及账号绑定的常用提示词
- 智能体支持从广场收藏到「我的」(新增 agent_favorites 表与收藏/取消收藏接口)
- 定时任务新增「必须生成Markdown文件」开关:注入提示词并校验生成的 .md 文件且正文超过100字,否则记为失败(存于 execution_context,无需迁移)
- 聊天问答展示时间(年月日 时分):问题在右下角、回答在左下角
- 常用提示词改为与账号绑定(新增 user_custom_prompts 表与 /api/user-prompts 接口),仅在首页输入框上方以居中标签 + 轮播展示,齿轮置于最右侧管理

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 17:16:15 +08:00
董宏凯 7548620683 样式修改 2026-05-28 17:14:01 +08:00
董宏凯 d5e12e3506 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!70
2026-05-28 07:58:17 +00:00
fengxiangdebaozi 23b9d401b7 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-28 15:56:58 +08:00
董宏凯 44894765b6 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!69
2026-05-28 07:54:20 +00:00
fengxiangdebaozi c2568f4be9 代码修改 2026-05-28 15:50:31 +08:00
董宏凯 90adb9dfa3 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-28 15:48:15 +08:00
董宏凯 d2f3eba434 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1
# Conflicts:
#	frontend-web/src/components/workspace/chats/chat-box.tsx
#	frontend-web/src/pages/StrategyRoutes.tsx
#	offline-backend-20260512/backend/app/gateway/routers/agents.py
2026-05-28 15:36:11 +08:00
fengxiangdebaozi 2fe058e0ee 接口地址修改 2026-05-28 15:24:00 +08:00
吉鑫升andClaude Opus 4.7 4410acaee8 技能展示配置持久化并适配引用来源,新增技能文件预览组件
- 后端将技能展示适配配置存入数据库,引用批次按持久化映射进行适配
- 前端新增技能文件预览弹窗与文件树组件,完善技能来源展示
- 修正 .gitignore 中宽泛的 skills/ 规则误忽略前端组件目录的问题

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 15:16:56 +08:00
fengxiangdebaozi d03f5fbbc0 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-28 15:10:25 +08:00
fengxiangdebaozi ae1c2f95a7 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-28 14:25:54 +08:00
fengxiangdebaozi 381547ec78 任务理解修改 2026-05-28 14:25:44 +08:00
董宏凯 f4672ea6b8 点击后打开沙箱 2026-05-28 13:56:05 +08:00
董宏凯 51a270a2f7 文件浏览 2026-05-28 13:52:25 +08:00
fengxiangdebaozi f3c8f2e1ab 代码修改 2026-05-28 11:45:25 +08:00
xuhd e2b676caaa 修复 2026-05-28 10:00:40 +08:00
董宏凯 68ac49259c 按钮修改 2026-05-28 09:09:02 +08:00
董宏凯 d94c0aae4b 速度优化 2026-05-27 23:12:02 +08:00
董宏凯 047e700d09 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-27 22:23:44 +08:00
董宏凯 9ccc473982 智能体查询优化 2026-05-27 22:23:37 +08:00
董宏凯 4142029f48 代码修改 2026-05-27 21:25:15 +08:00
fengxiangdebaozi dbf2cc8d80 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-27 20:57:19 +08:00
吉鑫升 f200972c00 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-05-27 20:28:38 +08:00
董宏凯 3033597f02 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!68
2026-05-27 12:28:25 +00:00
董宏凯 a16dd889cf Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-27 20:28:05 +08:00
董宏凯 dab6ecbf9a ai写作默认模型 2026-05-27 20:28:00 +08:00
董宏凯 8bdbf6ab15 代码修改 2026-05-27 19:43:28 +08:00
fengxiangdebaozi 8f75e12871 代码修改 2026-05-27 19:43:15 +08:00
xuhd 36311e6cef 999 2026-05-27 19:30:54 +08:00
fengxiangdebaozi 8f5af46ec2 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-27 19:15:19 +08:00
fengxiangdebaozi aeebf53739 api 2026-05-27 19:15:09 +08:00
吉鑫升 1d81ee9ed0 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji 2026-05-27 19:12:27 +08:00
董宏凯 e1c9d24aa4 Merge branch 'dhk-1' into 'master'
多智能体会商沙箱

See merge request knowledge-base-bj/deerflow-server!67
2026-05-27 11:12:07 +00:00
董宏凯 b7da062a4c 多智能体会商沙箱 2026-05-27 19:11:36 +08:00
吉鑫升 6fd6d564eb Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji
# Conflicts:
#	frontend-web/src/components/workspace/messages/message-list-item.tsx
#	frontend-web/src/components/workspace/messages/message-list.tsx
#	offline-backend-20260512/backend/packages/harness/deerflow/agents/lead_agent/agent.py
#	offline-backend-20260512/backend/packages/harness/deerflow/agents/lead_agent/prompt.py
2026-05-27 19:10:27 +08:00
吉鑫升 106f1d1794 代码提交 2026-05-27 19:02:19 +08:00
董宏凯 3809d7f3e7 Merge branch 'tjl' into 'master'
修复总控智能体共识后仍被错判为继续派活的死循环

See merge request knowledge-base-bj/deerflow-server!66
2026-05-27 10:08:50 +00:00
hkdongandClaude Opus 4.7 c769dd20f7 修复总控智能体共识后仍被错判为继续派活的死循环
_find_dispatch_message 原实现会一路向前翻历史,直到撞到任意一条带
tool_calls 的 AIMessage,导致本轮 LLM 即使共识(tool_calls=[]),也会
被上一轮的派活 AI 翻出来再用一次,前端因此把同样的 task 又发给子智能体,
形成"嘴上共识、手上派活"的死循环。

改成只看最新一条 AIMessage(跳过末尾 skill_stop / clarification ack
ToolMessage 即可),让 tool_calls 是否为空作为本轮的唯一权威信号。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 18:07:30 +08:00
董宏凯 445865e422 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!65
2026-05-27 09:48:13 +00:00
fengxiangdebaozi 24d4934c27 代码提交 2026-05-27 17:47:20 +08:00
吉鑫升 fe7cdba07e 忽略RAG调试日志 2026-05-27 17:44:02 +08:00
吉鑫升 c56db15a03 实现RAG参考文献显示模式 2026-05-27 17:40:10 +08:00
董宏凯 deb9993a64 点击确认 2026-05-27 17:25:10 +08:00
董宏凯 1ff8860b98 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-27 17:20:47 +08:00
董宏凯 198fc18c50 报告沙箱 2026-05-27 17:20:41 +08:00
董宏凯 621fdc9244 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!64
2026-05-27 08:02:37 +00:00
fengxiangdebaozi 9ece6213a9 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-27 16:02:12 +08:00
fengxiangdebaozi 35c313b689 开发文档 2026-05-27 16:02:07 +08:00
董宏凯 d6b88b842d Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-27 15:31:00 +08:00
董宏凯 ff90cac755 代码修改 2026-05-27 15:30:51 +08:00
董宏凯 8f93606c81 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-27 14:19:18 +08:00
董宏凯 95baa44a1c ai写作修改 2026-05-27 14:19:11 +08:00
ZyGuo fa65e67069 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-05-27 12:07:07 +08:00
xu hd 066d5032f9 Merge branch 'xuhd' into 'master'
修复一下

See merge request knowledge-base-bj/deerflow-server!63
2026-05-27 03:44:16 +00:00
xuhd 3f8a520624 修复一下 2026-05-27 11:40:41 +08:00
fengxiangdebaozi 6ab6695be7 接口修改 2026-05-27 11:37:07 +08:00
吉鑫升andClaude Opus 4.7 eda0ccffdb 管理员智能体/技能管理 + 跨标签登录同步 + 上游响应异常重试
- 「设置和更多」新增「智能体管理」「技能管理」入口,与定时任务管理同级;
  独立的 AdminAgentsPage/AdminSkillsPage 复用 AgentCard/SkillRow,
  管理员可查看并编辑/删除所有用户的智能体与技能。
- 后端 /api/agents、/api/skills 增加 ?admin=true 越权列表;agents 端
  放宽 _get_editable_or_raise 让管理员可编辑/删除任意智能体;新增
  list_all/update_any/delete_any(agents)与 list_all(skills)。
- 新增 AuthSyncWatcher:监听 localStorage["deerflow.auth"] 的 storage
  事件,user_id 变化时自动 reload,修复多标签切换登录后老页面点击
  「新对话」偶发 404 的问题。
- LLMErrorHandlingMiddleware 将 bad_response_status_code / JSON
  decode 等上游网关乱码识别为可重试的 upstream 类故障。
- 侧边栏「任务管理」改名为「定时任务」。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 11:13:29 +08:00
xu hd 1d399c3c21 Merge branch 'xuhd' into 'master'
feat: 笔记本 Studio 模块 — RAG 聊天、引用弹窗、侧边栏工作室

See merge request knowledge-base-bj/deerflow-server!62
2026-05-27 03:10:13 +00:00
ZyGuo cfd0faf5e7 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-05-27 10:01:35 +08:00
ZyGuo ffee030548 chore: ignore 2026-05-27 10:01:15 +08:00
董宏凯 9d81858ff4 Merge branch 'dhk-1' into 'master'
代码提交

See merge request knowledge-base-bj/deerflow-server!61
2026-05-27 01:16:50 +00:00
fengxiangdebaozi f791210e70 代码提交 2026-05-27 09:16:25 +08:00
xuhdandClaude Sonnet 4.6 794ff93fa9 chore: 更新 .env 配置(notebook API 地址、数据库连接)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 23:56:14 +08:00
xuhdandClaude Sonnet 4.6 ff8eb930f7 feat: 笔记本 Studio 模块 — RAG 聊天、引用弹窗、侧边栏工作室
- 新增 Studio 笔记本列表页与详情页(RAG 流式聊天、历史线程切换)
- 修复 streamSubgraphs: true 使 AI 流式消息正常展示
- 引用圆圈 [[cite:N]] 渲染 + 点击弹窗显示文档 chunk 内容
- 侧边栏「工作室」区域支持折叠/展开,笔记本过滤 is_owner=true
- 后端 lead_agent 支持 notebook_source_ids / notebook_token 参数
- 线程 metadata 改为 thread_type=notebook,侧边栏过滤同步

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 23:55:08 +08:00
董宏凯 d71a21ca8b Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!60
2026-05-26 15:25:32 +00:00
fengxiangdebaozi 2bd23dd374 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-26 23:21:13 +08:00
fengxiangdebaozi a501463ac7 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-26 23:20:58 +08:00
fengxiangdebaozi 9bd049923e 多智能体页面结构修改 2026-05-26 23:20:50 +08:00
董宏凯 67152f1c83 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-26 21:10:33 +08:00
董宏凯 8ca3fdec75 ai写作 2026-05-26 21:10:27 +08:00
fengxiangdebaozi 8e7fc54548 代码修改 2026-05-26 21:09:02 +08:00
吉鑫升 1642c3e694 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	frontend-web/src/contexts/ThemeContext.tsx
#	offline-backend-20260512/backend/config.yaml
2026-05-26 19:34:43 +08:00
董宏凯 d738c13e9e Merge branch 'dhk-1' into 'master'
智能体列表

See merge request knowledge-base-bj/deerflow-server!59
2026-05-26 11:32:35 +00:00
fengxiangdebaozi 45eb46c3f3 智能体列表 2026-05-26 19:31:59 +08:00
吉鑫升andClaude Opus 4.7 7b629d0697 轮换 LLM 凭证与默认模型(DeepSeek → zai-org/GLM-5-FP8)
- backend/config.yaml、config.yaml 把默认模型从 deepseek-chat 切到
  zai-org/GLM-5-FP8(modal endpoint),并轮换对应 API key / Bearer
- .env 同步更新

注意:这些文件包含真实凭证,应用部署时务必通过 .env 或私有 config
覆盖,不要把仓库里的版本直接用于生产。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 19:31:10 +08:00
吉鑫升andClaude Opus 4.7 89a1fa5042 私密/公开互斥兜底 + 智能体搜索按显示后名称匹配 + 多处小修
- 后端 update_agent / set_agent_private 增加兜底:is_private=true 时强制
  published=false,杜绝同时落在公开+私密两个广场的灰色态
- agent-card 编辑弹窗暴露 editIsPrivate 开关,与公开发布开关在前端互斥校验
- agent-gallery 智能体模糊搜索改为前端针对 desensitize() 后的名字比对,
  解决脱敏显示与原始名字不一致导致看似搜索失效的问题
- useUpdateAgent 在 onSuccess 立刻把新数据 patch 进所有 ["agents"] 列表
  缓存,卡片在后台 refetch 完成前先行 re-render,避免「切换私密/发布后
  好像没反应」的体感延迟
- useGlobalShortcuts 对 event.key 为 undefined(IME 合成 / 扩展注入)做
  容错,否则会抛 TypeError 把后续所有快捷键吃掉

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 19:30:00 +08:00
吉鑫升andClaude Opus 4.7 c9c59b761f 默认主题改为浅色 + 管理员可配置全局默认主题
- system_settings 新增 AppearanceSettings(default_theme),默认为 light,
  对应 GET /api/system-settings/appearance(任何人可读)+ PUT(admin 可写)
- App.tsx 把 NextThemesProvider 的 defaultTheme 从 dark 改为 light,并把
  QueryClientProvider 提到 ThemeProvider 外层以便后者使用 useQuery
- ThemeContext 新增 localStorage 标志 strategy-theme-user-set:用户调用
  toggleTheme / setTheme 时打标;每次启动若标志未设,则跟随 admin 配置的
  default_theme 同步主题,admin 改动用户刷新即生效;标志一旦存在永远尊重
  用户个人选择
- legacy 'theme' 键迁移视为用户显式选择,避免老用户被新默认覆盖
- frontend system-settings api/hook 增 appearance 拉取与更新

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 19:29:45 +08:00
吉鑫升 8b2f398015 feat: improve citation display and skill persistence 2026-05-26 19:27:03 +08:00
董宏凯 5c5bf7a60e Merge branch 'dhk-1' into 'master'
提示词修改

See merge request knowledge-base-bj/deerflow-server!58
2026-05-26 06:49:51 +00:00
fengxiangdebaozi 6cf4404243 提示词修改 2026-05-26 14:48:06 +08:00
ZyGuo 56ff310f29 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-05-26 14:40:01 +08:00
吉鑫升 b671b49725 Merge remote-tracking branch 'origin/master' into ji 2026-05-26 14:25:02 +08:00
吉鑫升andClaude Opus 4.7 d3d7db1f34 技能展示样本运行器 + 参考文献来源过滤调整
- skills 路由新增 _run_skill_python_sample,按本地 Python 候选实际执行
  技能脚本,作为展示适配器的真实样本来源
- skill-display 运行时与适配器调整,参考文献收集放宽起始消息约束

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 14:24:47 +08:00
吉鑫升andClaude Opus 4.7 26a388e3bf 新增智能体私密广场(is_private + 管理员密码门控)
- agents 表新增 is_private 列与迁移 20260526_01;列表 filter 拆分为公开
  广场用的 _listing_filter(剔除私密)与单条访问用的 _visible_filter(保留可达)
- system_settings 增 PrivateSquareSettings(enabled + password_hash),
  对应 GET/PUT /api/system-settings/private-square 由管理员管理
- /api/agents 接口:列表/创建/更新新增 is_private 字段;新增
  POST /api/agents/private-square/list(密码校验后返回私密智能体)与
  PUT /api/agents/{id}/private(管理员跨用户搬动智能体)
- 前端「智能体」页签新增「私密广场」入口(密码校验 + sessionStorage 缓存 +
  锁定按钮),卡片增加紫色私密徽章与盾牌切换按钮(owner 自助 / 管理员跨用户),
  「广场」与首页推荐候选均剔除私密智能体
- 新增管理员配置页 /settings/private-square 与侧边栏入口

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 14:24:29 +08:00
董宏凯 6a9d8e903e Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!57
2026-05-26 06:19:16 +00:00
董宏凯 daba5c0599 代码修改 2026-05-26 14:18:00 +08:00
董宏凯 d1e6cd5a8f 多智能体协作修改 2026-05-26 13:01:01 +08:00
fengxiangdebaozi eeb7f30585 代码修改 2026-05-26 11:47:47 +08:00
董宏凯 29fdb06cea Merge branch 'dhk-1' into 'master'
修改

See merge request knowledge-base-bj/deerflow-server!56
2026-05-26 01:52:02 +00:00
fengxiangdebaozi 6d02e2c89e ai写作修改 2026-05-26 09:50:24 +08:00
fengxiangdebaozi cf8c17d08b 敏感词修改 2026-05-26 09:15:32 +08:00
吉鑫升andClaude Opus 4.7 ad5d55220c 技能展示适配持久化 + 参考文献收集与新对话流式修复
- 后端新增 skill_display_adapters 表,持久化每个技能的 display 配置与 sample
  payload;/api/skills 列表、详情、设置接口同步读写
- 新增 /api/skills/{name}/display-sample 端点,编辑器优先加载库中样例
- 前端展示适配面板改为从后端加载持久样例,无样例时提示"自动识别"
- 参考文献收集修复:仅在 bash/shell/python 等执行类工具上从参数推断技能
  名,避免 read_file / web_fetch 误匹配;引用列表纳入最新一条助手消息
- ChatBox 改用「最新 human → 最新 ai」窗口收集引用,并仅保留 citation
  模式
- 修复「新对话」点击后已发消息消失:useThreadStream 只在 threadId 切回
  空值时重置/中止 SSE,避免 onCreated 分配 id 时把刚开始的流打断;
  ChatPage 在 landing 状态隐藏 MessageList,移除 KeyedChatPage remount
- 技能详情对话框:所有者可查看源码与文件 tab(不再要求管理员)
- LocalSandbox:Windows PowerShell 5 路径下把 && 重写为 ;,并以
  UTF-8 解码 subprocess 输出,避免中文乱码
- knowledge-search-v2 mock 样例改为中文固定测试数据

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 23:16:51 +08:00
董宏凯 2ecd50f5dc Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!55
2026-05-25 14:52:19 +00:00
董宏凯 48d22e0d42 ui规范 2026-05-25 22:51:38 +08:00
董宏凯 096e85fbc3 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-25 22:39:56 +08:00
董宏凯 e3d8e534f6 样式修改 2026-05-25 22:39:50 +08:00
fengxiangdebaozi acadc246cb Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-25 21:22:09 +08:00
fengxiangdebaozi fd2c8d1d64 ui规范 2026-05-25 21:21:54 +08:00
董宏凯 f7575e4ddb Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!54
2026-05-25 12:35:09 +00:00
董宏凯 114ee8f6ac 代码修改 2026-05-25 20:34:46 +08:00
董宏凯 b91a45639f 模型下拉框 2026-05-25 20:23:33 +08:00
吉鑫升 c4277f8566 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	frontend-web/src/components/workspace/messages/message-list-item.tsx
2026-05-25 19:50:17 +08:00
吉鑫升 b7aa8b06ca 修复「新对话」流式中无法重置 + 参考文献开关默认关闭并加对勾
- 流式回答过程中点「新对话」:URL 同路径导致 react-router navigate 静默 no-op,
  下游 hook 收不到事件;改为显式 navigate(..., {replace:true, state:{resetAt}})
  保证每次点击刷新 location.key,并让 useThreadChat 监听 location.key 触发重置
- useThreadStream 在 threadId 变化时 stop() 掉上一条 SSE,避免旧流继续派发事件
- 引入 KeyedChatPage 用 location.key 作 ChatRuntime key,真正的导航触发整树 remount,
  解决 useStream 内部 stream.values 残留导致欢迎页底下还能看到旧消息的过渡帧问题
- 「参考文献」开关默认关闭(local.ts),开启态在文字前额外多一个 ✓ 对勾
2026-05-25 19:47:55 +08:00
董宏凯 26097b7cfe Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!53
2026-05-25 11:39:59 +00:00
董宏凯 6addf507cb 样式修改 2026-05-25 19:39:31 +08:00
董宏凯 f0bf29ba08 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-25 19:38:23 +08:00
董宏凯 6ef7701805 样式修改 2026-05-25 19:38:16 +08:00
fengxiangdebaozi 70814b1026 脱敏 2026-05-25 19:30:36 +08:00
fengxiangdebaozi ca1d7e77ba 脱敏 2026-05-25 19:30:26 +08:00
吉鑫升 a800baf8ae Merge remote-tracking branch 'origin/master' into ji 2026-05-25 18:59:32 +08:00
fengxiangdebaozi 2f7f07467e Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-25 18:20:50 +08:00
fengxiangdebaozi f472bba9f0 敏感词 2026-05-25 18:20:40 +08:00
董宏凯 48de418d21 Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!52
2026-05-25 10:19:58 +00:00
吉鑫升 8892637b97 新增 RAG 引用展示模式:支持技能结果按编号引用/列表/表格渲染
- 前端新增 skill-display 适配层(runtime/display-adapter)与可视化适配面板,
  支持从技能返回 JSON 自动识别字段并配置 citation/list/table/card 展示
- 正文 [[N]] 编号渲染为可点击徽章,点击不跳 URL 而是定位到右侧参考文献面板;
  参考卡片样式重做(圆形编号、悬停高亮、过滤掉 "result" 占位类型)
- bash 工具调用按命令中的 skills/{public,custom}/<name>/ 路径反查展示适配,
  解决调用名为 "bash" 时无法匹配到具体技能的问题
- 工具结果 JSON 解析放宽:能从 stderr/exit code 噪声尾巴里抢救出 JSON 主体
- 展示适配自动识别接入 LLM:读 SKILL.md 让模型推断真实返回结构,失败回退 mock
- 展示适配面板修复保存回显:保存后表单跟随服务端最新值刷新,样例文本不再被抹掉
- 设置页加 "RAG 引用模式" 开关(默认开),关联 lead-agent prompt 注入引用规则
2026-05-25 18:19:52 +08:00
董宏凯 8c55d4b55d 文档修改 2026-05-25 18:19:16 +08:00
董宏凯 dffb8a955b 暂停修改 2026-05-25 17:56:40 +08:00
董宏凯 86e3b4de06 Merge branch 'dhk-1' into 'master'
接口联调

See merge request knowledge-base-bj/deerflow-server!51
2026-05-25 09:50:01 +00:00
董宏凯 525218f9a7 多智能体协作 2026-05-25 17:48:59 +08:00
董宏凯 9a70329db2 代码提交 2026-05-25 16:08:18 +08:00
吉鑫升andClaude Opus 4.7 9a63a4b7ca 技能详情对话框新增文件浏览面板:支持预览、编辑、下载、复制路径
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 14:17:39 +08:00
董宏凯 357f245aec Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-25 14:14:39 +08:00
董宏凯 8f9451a24b 接口修改 2026-05-25 14:14:31 +08:00
fengxiangdebaozi 6396ccc701 接口修改 2026-05-25 14:14:01 +08:00
董宏凯 9361c069db Merge branch 'dhk-1' into 'master'
代码修改

See merge request knowledge-base-bj/deerflow-server!50
2026-05-24 14:16:58 +00:00
董宏凯 0b5cc2d639 代码修改 2026-05-24 22:16:25 +08:00
董宏凯 61358b6233 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!49
2026-05-24 13:13:48 +00:00
董宏凯 05815d9475 多智能问答 2026-05-24 21:13:19 +08:00
董宏凯 77db1a6297 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-23 23:36:55 +08:00
董宏凯 21254a060a 接口联调 2026-05-23 23:36:41 +08:00
董宏凯 f049936ec4 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!48
2026-05-23 15:05:37 +00:00
董宏凯 8673eb5eca 接口联调 2026-05-23 23:05:01 +08:00
董宏凯 43df9175df 修改 2026-05-23 17:46:31 +08:00
董宏凯andCursor 7fcf22de90 Merge origin/dhk-1: resolve config.yaml database backend conflict
Use sqlite as temporary fallback while MySQL is unavailable; keeps
local persistence instead of in-memory backend.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 17:44:52 +08:00
董宏凯 6f9d81ca68 样式修改 2026-05-23 17:43:46 +08:00
董宏凯 267ce81be2 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!47
2026-05-23 09:42:11 +00:00
fengxiangdebaozi 3987ee7ee3 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-23 17:23:22 +08:00
fengxiangdebaozi 87c9986b33 接口联调 2026-05-23 17:23:15 +08:00
fengxiangdebaozi a85f1571a0 接口修改 2026-05-23 10:49:16 +08:00
董宏凯 d6ff00226a Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-22 21:41:52 +08:00
董宏凯 7f1f34e34f 样式修改 2026-05-22 21:41:26 +08:00
fengxiangdebaozi edb3238f3e 接口修改 2026-05-22 20:40:36 +08:00
吉鑫升andClaude Opus 4.7 67d5e43ec4 标题生成强制关闭 think 模式,回答速度指示器默认开启
- TitleMiddleware 给模型实例注入 extra_body 关 think(覆盖 Zhipu GLM 与 Qwen/vLLM 两套写法),并兜底剥离不闭合/残留的 <think> 标签,避免 GLM5 起标题时长时间思考与标签泄漏。
- 前端 streamSpeedMeterEnabled 默认改为 true,设置项描述同步为"默认开启"。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:03:24 +08:00
吉鑫升andClaude Opus 4.7 f8e3a3e5b4 公开定时任务页:每条记录标题前加 M月D日 前缀
同名任务多次执行后列表全是同一行,加上日期前缀方便扫描;
用 muted-foreground + text-xs + font-normal 弱化,不喧宾夺主。
Tooltip / title / 删除确认弹窗内的文案也同步带上日期。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 16:38:44 +08:00
吉鑫升 ef410e298d Merge remote-tracking branch 'origin/master' into ji 2026-05-22 16:23:11 +08:00
吉鑫升andClaude Opus 4.7 80fc2a9240 新增技能目录重新扫描接口与分页,关掉技能安全扫描的配置开关
- 后端新增 POST /api/skills/reconcile-custom:扫描 custom 目录,把磁盘存在但 DB 无记录的技能登记到调用者名下(published=false),附 4 个单元测试
- 前端技能列表加"重新扫描技能目录"按钮,列表分页每页 10 条
- SkillsConfig 新增 security_scan.enabled(默认 true)用于关闭 LLM 安全扫描;scan_skill_content 在开关关闭时直接放行
- 智能体卡片/对话页长名 truncate 显示 + loading 占位

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 16:22:42 +08:00
xu hd 3ae1202536 Merge branch 'xuhd' into 'master'
feat: 统一 Admin 用户中心 + 修复默认对话记忆存储路径

See merge request knowledge-base-bj/deerflow-server!46
2026-05-22 08:05:32 +00:00
xuhdandClaude Sonnet 4.6 2c0bb2041b feat: 统一 Admin 用户中心 + 修复默认对话记忆存储路径
## 前端
- 新增 AdminUserHub 页面,合并用户管理/审计/记忆三个页面为统一中心(左侧用户列表 + 右侧 Tab)
- 旧三条 admin 路由重定向到新 /admin 路由
- 侧边栏导航菜单合并为单一入口"用户中心"
- memory-settings-page: 默认助手下拉选项传 agent=default(后端识别为全局哨兵)

## 后端
- memory.py: 将 "default" 加入全局哨兵 _GLOBAL_AGENT_VALUES,?agent=default 读全局记忆文件
- memory_middleware.py: _resolve_agent_id() 无 agent 上下文时返回 None,默认对话写入 users/{id}/memory.json
- manager.py: 移除 agent_id or "default" 回退,让 None 透传给 V1 provider
- admin_users.py: Admin 记忆 API 将"默认助手"桶改为读全局文件(agent_id=None)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 16:04:49 +08:00
董宏凯 ab6b6876aa 样式修改 2026-05-22 15:26:20 +08:00
董宏凯 284445e0c9 样式修改 2026-05-22 15:20:59 +08:00
董宏凯 05729505d8 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-22 15:13:44 +08:00
董宏凯 4004fb908b 接口地址 2026-05-22 15:13:28 +08:00
董宏凯 19660e49d2 样式修噶 2026-05-22 14:56:59 +08:00
吉鑫升 b6a2c9336e Merge remote-tracking branch 'origin/master' into ji 2026-05-22 14:25:23 +08:00
吉鑫升andClaude Opus 4.7 ba2bc46042 智能体对话选 Agent 直达、澄清问题批量提交、LLM 错误中文化等
- 前端:新会话选 Agent 后直接跳转并自动发送,智能体页输入框宽度与首页对齐
- 前端:澄清卡片支持多选+多问题合并提交,消除单题逐一发送的割裂感
- 前端:定时任务弹窗 Agent 下拉支持长描述截断,避免撑破布局
- 后端:ask_clarification 支持同回合多次调用以提多个独立问题
- 后端:LLM 错误处理与定时任务失败提示统一改为中文

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:24:29 +08:00
wg he ad8f74c964 Merge branch 'hwg' into 'master'
修改数据库连接

See merge request knowledge-base-bj/deerflow-server!45
2026-05-22 06:10:44 +00:00
wghe ded3123af2 修改数据库连接 2026-05-22 14:09:03 +08:00
董宏凯 e076abe759 ui规范 2026-05-22 12:34:11 +08:00
xu hd c1bb4864ab Merge branch 'xuhd-2' into 'master'
feat: V1记忆系统支持、管理员记忆编辑及对话记忆注入开关

See merge request knowledge-base-bj/deerflow-server!44
2026-05-22 04:34:07 +00:00
xuhdandClaude Sonnet 4.6 b3a39cbdf7 feat: V1记忆系统支持、管理员记忆编辑及对话记忆注入开关
- 新增 V1 记忆系统(memory.json)支持:提取结果强制中文、历史字段修复为增量累积日志
- 用户设置页面:V1 模式下新增 agent 选择器,可查看各 agent 的私有记忆
- 管理员记忆页面:区分 V1/V2 渲染,V1 支持完整 CRUD(用户画像/历史摘要/事实记录)
- 后端新增 V1 记忆 CRUD API(sections/facts),前端同步添加对应 hooks 和 API 调用
- 新建专家页面:标记 bootstrap 线程类型,跳过记忆保存,侧边栏过滤该类线程
- 输入框工具栏新增「记忆」开关:关闭时 V1/V2 均不注入,开启时按 config.yaml 版本正常注入
- 修复 agent 目录不存在时的 FileNotFoundError,回退至默认配置

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 12:32:47 +08:00
董宏凯 d59e0514b3 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!43
2026-05-22 03:12:49 +00:00
董宏凯 6e88c5a1c5 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-22 11:11:57 +08:00
吉鑫升 c74be2b789 Merge branch 'master' into ji 2026-05-22 10:58:20 +08:00
吉鑫升andClaude Opus 4.7 a258122e22 定时任务:修复智能体执行 422、新增描述字段、公开页删除按钮等
- 定时任务执行时按 agent.id 解析智能体,老数据中存的中文显示名会回退按 name 查找,避免 422
- scheduled_tasks 表新增 description 字段(迁移 20260522_01),创建/编辑表单支持,公开页标题下显示
- 公开页(/public/scheduled-tasks/{id})新增删除单次执行记录入口,使用样式化 Dialog 确认
- 公开页左侧标题区精简:去掉 schedule/timezone/最近状态两行;执行列表标题剥离尾部时间戳,"计划"改为"执行时间"
- 工作区定时任务列表:超长标题改为按字符换行不再截断;按 created_at 倒序(新建任务在前)
- 启动 Alembic 升级加超时与单独线程,MySQL 缺库时自动 CREATE DATABASE
- vite build 增加 8GB 内存上限

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 10:55:59 +08:00
董宏凯 a01d7123d7 来源新增修改 2026-05-22 10:43:12 +08:00
董宏凯 7652db4601 样式修改 2026-05-21 22:26:25 +08:00
董宏凯 433c540ee2 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!42
2026-05-21 12:49:11 +00:00
董宏凯 37e1f7104f 代码提交 2026-05-21 20:47:45 +08:00
董宏凯 6467c8a870 样式修改 2026-05-21 20:42:57 +08:00
吉鑫升andClaude Opus 4.7 a892f55cb2 Merge branch 'master' into ji
冲突解决:
- frontend-web/src/pages/AgentChatPage.tsx: 保留 HEAD 的 isLandingState +
  AgentWelcome 欢迎页扩展,丢弃 master 的旧版 InputBox 风格
- offline-backend-20260512/backend/config.yaml: 保留 HEAD 的对齐注释格式;
  master 引入的中文 bank_mission / bank_retain_mission 已自动合入

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 20:31:49 +08:00
吉鑫升 ac4424bab2 代码修改 2026-05-21 20:19:44 +08:00
wg he 99992c951d Merge branch 'hwg' into 'master'
feat: 智能体精选排序与新对话智能体选择器

See merge request knowledge-base-bj/deerflow-server!41
2026-05-21 11:49:54 +00:00
wghe c516b74b75 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into hwg 2026-05-21 19:44:15 +08:00
xu hd da53b81bf9 Merge branch 'xuhd' into 'master'
22

See merge request knowledge-base-bj/deerflow-server!37
2026-05-21 11:43:01 +00:00
xuhd f730924572 222 2026-05-21 19:42:46 +08:00
董宏凯 0fb69a38cd Merge branch 'dhk-1' into 'master'
笔记本页面

See merge request knowledge-base-bj/deerflow-server!39
2026-05-21 11:41:20 +00:00
董宏凯 125e8b271b 笔记本页面 2026-05-21 19:40:54 +08:00
董宏凯 8c2ab6b860 Merge branch 'dhk-1' into 'master'
意图理解

See merge request knowledge-base-bj/deerflow-server!38
2026-05-21 10:48:46 +00:00
董宏凯 d639b24c2d 意图理解 2026-05-21 18:48:15 +08:00
wghe 6ebbf3aa32 Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into hwg 2026-05-21 18:35:56 +08:00
wghe b97548f8d6 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into hwg 2026-05-21 18:30:28 +08:00
wghe 87eff3e133 22 2026-05-21 18:29:55 +08:00
xuhd 2e6ce67b64 22 2026-05-21 18:04:45 +08:00
吉鑫升andClaude Opus 4.7 843eda6fea fix: 公开接口豁免 CSRF 校验
/api/public/ 命名空间下的匿名 PUT/POST 请求没有会话 cookie,
被 CSRF 中间件拦在 403。auth 中间件已放行该前缀,CSRF 这里补齐豁免,
让公开定时任务页的编辑保存能正常调用。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 17:45:54 +08:00
吉鑫升 643f9b2c76 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	frontend-web/src/pages/AgentChatPage.tsx
2026-05-21 17:44:09 +08:00
董宏凯 2089f5e8ee Merge branch 'dhk-1' into 'master'
配置参数修改

See merge request knowledge-base-bj/deerflow-server!36
2026-05-21 09:38:12 +00:00
董宏凯 7e98d7dc52 配置参数修改 2026-05-21 17:37:39 +08:00
xu hd a514b2fe79 Merge branch 'xuhd' into 'master'
feat: 记忆配置改为数据库存储,用户只可配置召回模式

See merge request knowledge-base-bj/deerflow-server!35
2026-05-21 09:34:48 +00:00
xuhdandClaude Sonnet 4.6 d56230e04d feat: 记忆配置改为数据库存储,用户只可配置召回模式
- 新增 persistence/memory_config/ 模块:UserMemoryConfigRow ORM 模型 +
  SqlUserMemoryConfigRepository + MemoryUserMemoryConfigStore(内存兼容)
- 新增 Alembic 迁移脚本 20260521_01 创建 user_memory_configs 表
- memory_config.py:USER_WRITABLE_FIELDS 从 3 个缩减为 1 个
  (hindsight.recall_budget),移除文件 IO,改为进程内 cache + async DB 对接函数
- Gateway lifespan 启动时批量预热 recall_budget cache
- memory router PATCH/DELETE 改用 DB 存储,支持 400 校验非法 budget 值

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 17:34:25 +08:00
董宏凯 03e0d8248d Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!34
2026-05-21 09:23:14 +00:00
董宏凯 065bd8f28a 样式修改 2026-05-21 17:22:40 +08:00
董宏凯 ca13a9199f 样式修改 2026-05-21 16:39:48 +08:00
董宏凯 b59d476c2d Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!32
2026-05-21 08:31:57 +00:00
董宏凯 c69486556a Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-21 16:31:27 +08:00
董宏凯 bfd75da308 功能迁移,页面整体样式修改 2026-05-21 16:30:11 +08:00
吉鑫升andClaude Opus 4.7 53bbb9b15b feat: 公开定时任务页支持正文/MD 切换与内联编辑
- 公开查看器右侧改为 Tabs:MD 附件优先、然后是「正文」;标签使用文件名(去后缀)
- 新增内联编辑:正文与 MD 文件均可编辑保存,每个 Tab 支持 Word 下载
- 后端新增公开 PUT 端点(/runs/{run_id}/files/{i}、/runs/{run_id}/body),服务层提取 _apply_run_file_edit 并新增 admin_update_run_file / admin_update_run_body
- 列表过滤:仅展示 succeeded 且有正文或可用 MD 的执行记录;后端在响应中标记每个文件 available,前端隐藏磁盘已缺失的 MD Tab
- 左侧任务名与右侧执行记录标题均改为可换行 + Tooltip 显示完整内容
- .gitignore 增加 frontend-web/dist

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 15:53:43 +08:00
吉鑫升 f1d58983c2 feat: 智能体精选排序与新对话智能体选择器
- 后端新增 featured_order 字段及精选排序 API(/agents/selector、/agents/{id}/featured、/agents/featured/order),移除 user_agent_pin 表
- 前端新对话页 (ChatPage) 与输入框 (InputBox) 接入 agent-selector,选中后跳转 AgentChatPage 并通过 sessionStorage 透传首条消息
- 新增管理员智能体管理弹窗 (agent-manage-dialog) 支持精选添加/移除/上下移动
2026-05-21 14:39:12 +08:00
ZyGuo 38b59cc198 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into gzy 2026-05-20 13:42:37 +08:00
ZyGuo 043a1aab21 update git ignore 2026-05-19 16:12:12 +08:00
3905 changed files with 934843 additions and 53856 deletions

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "md-viewer-frontend",
"runtimeExecutable": "npx",
"runtimeArgs": ["ng", "serve", "--port", "4200"],
"port": 4200,
"cwd": "F:\\angular\\md-viewer\\frontend"
}
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"permissions": {
"allow": [
"PowerShell(uv --version)",
"PowerShell(netstat -ano)",
"PowerShell(Get-NetTCPConnection -LocalPort 8001 -ErrorAction SilentlyContinue)",
"PowerShell(Get-Process -Id 20560 -ErrorAction SilentlyContinue | Select-Object Id,ProcessName,Path,StartTime; try { \\(Invoke-WebRequest -Uri \"http://127.0.0.1:8001/health\" -UseBasicParsing -TimeoutSec 5\\).Content } catch { \"health check failed: $_\" })",
"Bash(curl -s -X POST -H \"Content-Type: application/json\" -d '{\"username\":\"demo\"}' http://localhost:8001/api/v1/auth/login/username)"
]
}
}
+20
View File
@@ -0,0 +1,20 @@
import os
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(
"119.254.86.251",
port=22322,
username="root",
password=os.environ["TARGET_SSH_PASSWORD"],
timeout=15,
auth_timeout=15,
banner_timeout=15,
)
_, stdout, stderr = client.exec_command(os.environ["TARGET_SSH_COMMAND"], timeout=30)
print(stdout.read().decode(errors="replace"), end="")
print(stderr.read().decode(errors="replace"), end="")
client.close()
+37
View File
@@ -0,0 +1,37 @@
# Never send source-control history, local dependencies, runtime state, or
# credentials to the Docker daemon. The offline images are built from the
# repository root by deploy/1panel-offline/Dockerfile.*.
.git
.runtime
.history
tmp
dist
# Credentials and environment-specific configuration are supplied at runtime
# through the offline delivery package, never copied into an image layer.
**/.env
**/.env.*
**/.worker-pool
**/worker-control
offline-backend-20260512/backend/.deer-flow
offline-backend-20260512/backend/logs
offline-backend-20260512/backend/docker-data
offline-backend-20260512/backend/dist
offline-backend-20260512/backend/wheelhouse
offline-backend-20260512/backend/offline-wheels
offline-backend-20260512/backend/.venv
offline-backend-20260512/backend/.pytest_cache
offline-backend-20260512/backend/.ruff_cache
# Reproducibly install frontend dependencies inside the image instead.
frontend-web/node_modules
frontend-web/dist
frontend-web/.vite
frontend-web/.offline-pack-build
frontend-web/.offline-extract-test
frontend-web/node_modules-offline-*.tar.gz
# Editor and operating-system metadata.
**/__pycache__
**/*.py[cod]
**/.DS_Store
+264 -4
View File
@@ -1,15 +1,23 @@
# Workspace/editor
.vscode/
.vscode/*
!.vscode/launch.json
!.vscode/tasks.json
!.vscode/extensions.json
!.vscode/settings.json
frontend-web/.vscode/
node_modules/
# Claude Code local-only settings (per-user permissions, not shared)
.claude/settings.local.json
# Local runtime logs and pid files
.runtime/
logs/
offline-backend-20260512/backend/logs/
# Frontend local/runtime artifacts
frontend-web/.env
frontend-web/.env.local
frontend-web/.env.*.local
frontend-web/node_modules/
frontend-web/.pnpm-store/
frontend-web/tsconfig.tsbuildinfo
@@ -24,8 +32,9 @@ frontend-web/src.zip
frontend-web/src9.zip
frontend-web/src-v1.zip
frontend-web/src-*.rar
frontend-web/dist
# Frontend build artifacts
frontend-web/dist/
frontend-web/dist-scheduled-check/
# Offline backend bundles and local deployment artifacts
@@ -48,6 +57,7 @@ offline-backend-20260505/bundle/stop_backend.sh
# offline-backend-20260512 runtime artifacts (large files, local config, data)
offline-backend-20260512/.env.example
offline-backend-20260512/.env
offline-backend-20260512/DEPLOY_BACKEND_OFFLINE_ZH.md
offline-backend-20260512/SHA256SUMS
offline-backend-20260512/config.yaml.example
@@ -59,6 +69,9 @@ offline-backend-20260512/wheelhouse/
offline-backend-20260512/backend/.deer-flow/data/*.db
offline-backend-20260512/backend/.deer-flow/data/*.db-*
offline-backend-20260512/backend/.deer-flow/*
offline-backend-20260512/backend/.env
offline-backend-20260512/backend/.env.local
offline-backend-20260512/backend/.extensions_config.json.lock
offline-backend-20260512/start_backend.sh
offline-backend-20260512/stop_backend.sh
offline-backend-20260512/check_backend.sh
@@ -72,7 +85,254 @@ offline-backend-20260512/backend/.deer-flow/*
# Per-user skill_evolution overrides — runtime data written by the API
offline-backend-20260512/backend/skill_evolution.json
# Automatic config.yaml backups written by the admin models page on every save
offline-backend-20260512/backend/.model-config-backups/
skills/
hermes-agent-main/
.gitignore
offline-backend-20260512/backend/tests/*
offline-backend-20260512/backend/tests/*
!offline-backend-20260512/backend/tests/test_large_file_safety.py
!offline-backend-20260512/backend/tests/test_account_authentication.py
!offline-backend-20260512/backend/tests/test_agent_skill_migration.py
!offline-backend-20260512/backend/tests/test_html_runtime_addresses.py
!offline-backend-20260512/backend/tests/test_app_identity.py
!offline-backend-20260512/backend/tests/test_roundtable_room_limit.py
!offline-backend-20260512/backend/tests/test_admin_audit_retention_control.py
# Seeder-owned Agent Skills are product source; keep them out of the broad
# runtime `skills/` ignore above.
!offline-backend-20260512/backend/app/gateway/routers/_*_seed_assets/skills/
!offline-backend-20260512/backend/app/gateway/routers/_*_seed_assets/skills/**
# Keep startup seed completeness and task-report conversion regressions versioned.
!offline-backend-20260512/backend/tests/test_seed_assets.py
!offline-backend-20260512/backend/tests/test_latency_diagnosis_seed.py
!offline-backend-20260512/backend/tests/test_query_slowdown_diagnosis_seed.py
!offline-backend-20260512/backend/tests/test_elasticsearch_offline_ops_seed.py
!offline-backend-20260512/backend/tests/test_task_report_convert.py
!offline-backend-20260512/backend/tests/test_task_deeplink_details.py
!offline-backend-20260512/backend/tests/test_offline_docs.py
!offline-backend-20260512/backend/tests/test_migration_compatibility.py
# Keep the admin catalog hidden-switch (agent / business chain) store regressions versioned.
!offline-backend-20260512/backend/tests/test_roundtable_chain_hidden.py
# Keep the business-chain seat enrichment (available/live_name) regressions versioned.
!offline-backend-20260512/backend/tests/test_roundtable_chain_seat_enrichment.py
# Keep the dedicated taskId + goPath history Gateway contract versioned.
!offline-backend-20260512/backend/tests/test_task_deeplink_threads_api.py
!offline-backend-20260512/backend/tests/test_thread_clear.py
# Keep project-scoped cross-conversation memory regressions versioned.
!offline-backend-20260512/backend/tests/test_analysis_project_memory.py
!offline-backend-20260512/backend/tests/test_analysis_project_memory_integration.py
!offline-backend-20260512/backend/tests/test_analysis_project_memory_runtime.py
!offline-backend-20260512/backend/tests/test_analysis_project_memory_store.py
# Keep answer-level feedback persistence, scoring, resolver, and migration regressions versioned.
!offline-backend-20260512/backend/tests/test_answer_feedback.py
# Keep wx common-agent category configuration regressions versioned.
!offline-backend-20260512/backend/tests/test_wx_common_agents.py
# Keep the built-in public-document seed regressions versioned.
!offline-backend-20260512/backend/tests/test_gongwen_agent_seed.py
!offline-backend-20260512/backend/tests/test_gongwen_documents.py
# Keep the openGauss URL/dialect/schema compatibility regression coverage versioned.
!offline-backend-20260512/backend/tests/test_gauss_database.py
!offline-backend-20260512/backend/tests/test_gauss_mysql_compat.py
!offline-backend-20260512/backend/tests/test_chat_history_migration_seed.py
!offline-backend-20260512/backend/tests/test_gauss_data_adaptation_seed.py
!offline-backend-20260512/backend/tests/test_llmwiki_weknora.py
!offline-backend-20260512/backend/tests/test_llmwiki_knowledge_management.py
!offline-backend-20260512/backend/tests/test_llmwiki_smart_reasoning.py
!offline-backend-20260512/backend/tests/test_smart_reasoning_retrieval_middleware.py
!offline-backend-20260512/backend/tests/test_knowledge_retrieval_settings.py
!offline-backend-20260512/backend/tests/test_wiki_generation_config.py
!offline-backend-20260512/backend/tests/test_wiki_directory_constraints.py
!offline-backend-20260512/backend/tests/test_llmwiki_parent_directory_routing.py
!offline-backend-20260512/backend/tests/test_llmwiki_loading.py
!offline-backend-20260512/backend/tests/test_weknora_embed_script.py
!offline-backend-20260512/backend/tests/test_weknora_static.py
!offline-backend-20260512/backend/tests/test_llmwiki_advanced_retrieval.py
!offline-backend-20260512/backend/tests/test_knowledge_live_embedding.py
!offline-backend-20260512/backend/tests/test_health_auth_bypass.py
# Keep formal Word OOXML and embedded-font regression coverage versioned.
!offline-backend-20260512/backend/tests/test_word_export.py
# Keep generated-file library aggregation and filtering regression coverage versioned.
!offline-backend-20260512/backend/tests/test_artifact_library.py
# Keep Web App site artifact (multi-page site) regression coverage versioned.
!offline-backend-20260512/backend/tests/test_web_app_sites.py
# Keep the model configuration regression coverage versioned even though
# this deployment repository otherwise ignores newly added backend tests.
!offline-backend-20260512/backend/tests/test_model_management.py
# Keep the model-stream truncation event (persistence + classification) coverage versioned.
!offline-backend-20260512/backend/tests/test_stream_truncation.py
# Keep the forced-research agent runtime gate and sandbox-policy regressions versioned.
!offline-backend-20260512/backend/tests/test_forced_research_agent.py
# Keep strategy-selection built-in agent seed and safety-contract regressions versioned.
!offline-backend-20260512/backend/tests/test_strategy_selection_seed.py
# Keep fixed-question exact-match and streaming regression coverage versioned.
!offline-backend-20260512/backend/tests/test_fixed_questions.py
# Keep configurable es_query system-prompt routing regression coverage versioned.
!offline-backend-20260512/backend/tests/test_es_query_routing_prompt.py
# Keep the local LLMWiki vector-index and external API regression coverage versioned.
!offline-backend-20260512/backend/tests/test_llmwiki_local_index_repository.py
!offline-backend-20260512/backend/tests/test_llmwiki_vector_search.py
!offline-backend-20260512/backend/tests/test_llmwiki_wiki_sync.py
!offline-backend-20260512/backend/tests/test_llmwiki_incremental_sync_contract.py
!offline-backend-20260512/backend/tests/test_llmwiki_encoder_runtime.py
!offline-backend-20260512/backend/tests/test_external_llmwiki_search.py
!offline-backend-20260512/backend/tests/test_llmwiki_wiki_retrieval.py
!offline-backend-20260512/backend/tests/test_public_llmwiki_embed.py
# Keep assistant-source snapshot publication atomic across re-import jobs.
!offline-backend-20260512/backend/tests/test_assistant_snapshot_pointer_contract.py
# Deep-research reliability regression coverage.
!offline-backend-20260512/backend/tests/test_deep_research_persistence.py
!offline-backend-20260512/backend/tests/test_deep_research_event_sink.py
!offline-backend-20260512/backend/tests/test_deep_research_executor_reliability.py
!offline-backend-20260512/backend/tests/test_deep_research_start_job.py
!offline-backend-20260512/backend/tests/test_summarization_human_message.py
!offline-backend-20260512/backend/tests/test_llmwiki_title_ranking.py
!offline-backend-20260512/backend/tests/test_menu_overrides.py
!offline-backend-20260512/backend/tests/test_compact_menu_overrides.py
# Keep database-backed upload-policy, enforcement and bounded-preview regressions versioned.
!offline-backend-20260512/backend/tests/test_upload_policy.py
!offline-backend-20260512/backend/tests/test_uploads_policy_enforcement.py
!offline-backend-20260512/backend/tests/test_upload_responsiveness.py
!offline-backend-20260512/backend/tests/test_conversion_responsiveness.py
!offline-backend-20260512/backend/tests/test_async_agent_entrypoints.py
!offline-backend-20260512/backend/tests/test_async_tool_initialization.py
!offline-backend-20260512/backend/tests/test_artifact_preview.py
# Independent enterprise-research persistence, HTTP and race regressions.
!offline-backend-20260512/backend/tests/test_enterprise_research_tasks.py
# Position-roundtable per-turn write/present cap (weak-model duplicate artifacts).
!offline-backend-20260512/backend/tests/test_position_artifact_cap.py
# Roundtable coordinator/seat capability isolation regressions.
!offline-backend-20260512/backend/tests/test_roundtable_role_boundary.py
# Workflow Studio: schemas / definitions / engine / run-lifecycle regressions
# plus the concurrency remediation suite (atomic resume, draft CAS, publish
# counter, event seq) — required in CI per docs/WORKFLOW_STUDIO_BACKEND_REMEDIATION_ZH.md P1-06.
!offline-backend-20260512/backend/tests/test_workflow_schemas.py
!offline-backend-20260512/backend/tests/test_workflow_definitions.py
!offline-backend-20260512/backend/tests/test_workflow_engine.py
!offline-backend-20260512/backend/tests/test_workflow_runs.py
!offline-backend-20260512/backend/tests/test_workflow_concurrency.py
!offline-backend-20260512/backend/tests/test_workflow_schema_rebuild.py
# Per-account question recommendation preferences.
!offline-backend-20260512/backend/tests/test_user_preferences.py
# Writing-mode first-report pipeline enforcement regressions.
!offline-backend-20260512/backend/tests/test_writing_mode_report_middleware.py
!offline-backend-20260512/backend/tests/test_writing_rewrite_prompt.py
# LLM call timeout retry classification regression coverage.
!offline-backend-20260512/backend/tests/test_llm_error_handling_middleware.py
# Adaptive context recovery, large-payload and real-adapter streaming regressions.
!offline-backend-20260512/backend/tests/test_context_recovery.py
!offline-backend-20260512/backend/tests/test_context_recovery_transport.py
!offline-backend-20260512/backend/tests/test_summarization_multiturn.py
# Writing-mode pipeline conversation-material regressions.
!offline-backend-20260512/backend/tests/test_deep_research_report_tool.py
# Report collaboration (RC-BE-000–018) regression coverage.
!offline-backend-20260512/backend/tests/test_report_collaboration_*.py
!offline-backend-20260512/backend/tests/test_ensure_orm_columns_sync.py
deploy
.history
# Cloned third-party repos (local only)
git-clone/
# Repo-root offline dependency pack (local only)
/dist/
# Frontend offline pack working directories
frontend-web/.offline-pack-build/
frontend-web/.offline-extract-test/
frontend-web-node_modules-offline-*.tar.gz
/deerflow-frontend-dist-*.zip
# Local dependency caches and backend scratch archives
/.pnpm-store/
/offline-backend-20260512/backend/backend*.zip
# Local offline bundles and scratch tooling
/*.tar.gz
/offline-backend-20260512/*.zip
/tmp/
.codegraph
codegraph.mdc
docs/aidev-docs
docs/backups
# Frontend skills components must be tracked (excluded from the broad skills/ ignore above)
!frontend-web/src/components/workspace/skills/
# Built-in analysis mind-map skill is product source, not a per-user runtime skill.
!offline-backend-20260512/backend/skills/
offline-backend-20260512/backend/skills/*
!offline-backend-20260512/backend/skills/public/
offline-backend-20260512/backend/skills/public/*
!offline-backend-20260512/backend/skills/public/_shared/
!offline-backend-20260512/backend/skills/public/_shared/**
!offline-backend-20260512/backend/skills/public/analysis-mindmap/
!offline-backend-20260512/backend/skills/public/analysis-mindmap/SKILL.md
!offline-backend-20260512/backend/skills/public/facebook-page-generator/
!offline-backend-20260512/backend/skills/public/facebook-page-generator/**
!offline-backend-20260512/backend/tests/test_facebook_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/x-page-generator/
!offline-backend-20260512/backend/skills/public/x-page-generator/**
!offline-backend-20260512/backend/tests/test_x_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/tiktok-page-generator/
!offline-backend-20260512/backend/skills/public/tiktok-page-generator/**
!offline-backend-20260512/backend/tests/test_tiktok_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/youtube-page-generator/
!offline-backend-20260512/backend/skills/public/youtube-page-generator/**
!offline-backend-20260512/backend/tests/test_youtube_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/threads-page-generator/
!offline-backend-20260512/backend/skills/public/threads-page-generator/**
!offline-backend-20260512/backend/tests/test_threads_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/cnn-page-generator/
!offline-backend-20260512/backend/skills/public/cnn-page-generator/**
!offline-backend-20260512/backend/tests/test_cnn_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/bbc-page-generator/
!offline-backend-20260512/backend/skills/public/bbc-page-generator/**
!offline-backend-20260512/backend/tests/test_bbc_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/xinhua-page-generator/
!offline-backend-20260512/backend/skills/public/xinhua-page-generator/**
!offline-backend-20260512/backend/tests/test_xinhua_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/white-house-page-generator/
!offline-backend-20260512/backend/skills/public/white-house-page-generator/**
!offline-backend-20260512/backend/tests/test_white_house_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/manila-times-page-generator/
!offline-backend-20260512/backend/skills/public/manila-times-page-generator/**
!offline-backend-20260512/backend/tests/test_manila_times_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/gma-news-page-generator/
!offline-backend-20260512/backend/skills/public/gma-news-page-generator/**
!offline-backend-20260512/backend/tests/test_gma_news_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/yahoo-japan-page-generator/
!offline-backend-20260512/backend/skills/public/yahoo-japan-page-generator/**
!offline-backend-20260512/backend/tests/test_yahoo_japan_page_generator_skill.py
!offline-backend-20260512/backend/skills/public/yomiuri-news-page-generator/
!offline-backend-20260512/backend/skills/public/yomiuri-news-page-generator/**
!offline-backend-20260512/backend/tests/test_yomiuri_news_page_generator_skill.py
!offline-backend-20260512/backend/tests/test_fast_page_generator_specs.py
!offline-backend-20260512/backend/tests/test_sync_builtin_skills.py
# Built-in skill-creator ported from bytedance/deer-flow (product source too).
!offline-backend-20260512/backend/skills/public/skill-creator/
!offline-backend-20260512/backend/skills/public/skill-creator/**
# uv lockfile (not tracked per project preference)
offline-backend-20260512/backend/uv.lock
!offline-backend-20260512/backend/tests/test_wiki_package_roundtrip.py
!offline-backend-20260512/backend/tests/test_llmwiki_incremental_sync_scheduler.py
!offline-backend-20260512/backend/tests/test_worker_pool.py
!offline-backend-20260512/backend/tests/test_chat_step_limit.py
!offline-backend-20260512/backend/tests/test_worker_storage.py
!offline-backend-20260512/backend/tests/test_worker_discovery.py
!offline-backend-20260512/backend/tests/test_worker_diagnostics.py
!offline-backend-20260512/backend/tests/test_worker_deferred_admission.py
!offline-backend-20260512/backend/tests/test_db_loop_isolation.py
!offline-backend-20260512/backend/tests/test_chat_archive_postgres_integration.py
# Local-only scratch directory (not committed)
0622/
# Python bytecode cache
__pycache__/
# misc
.DS_Store
.worker-pool/
+6
View File
@@ -0,0 +1,6 @@
{
"recommendations": [
"ms-python.python",
"ms-python.debugpy"
]
}
+66
View File
@@ -0,0 +1,66 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "DeerFlow: Backend FastAPI (8001)",
"type": "debugpy",
"request": "launch",
"module": "uvicorn",
"args": [
"app.gateway.app:app",
"--host",
"0.0.0.0",
"--port",
"8001"
],
"cwd": "${workspaceFolder}/offline-backend-20260512/backend",
"python": "${workspaceFolder}/offline-backend-20260512/backend/.venv/Scripts/python.exe",
"envFile": "${workspaceFolder}/offline-backend-20260512/.env",
"env": {
"PYTHONPATH": "${workspaceFolder}/offline-backend-20260512/backend;${workspaceFolder}/offline-backend-20260512/backend/.deer-flow/python-vendor",
"GATEWAY_CORS_ORIGINS": "http://localhost:5174,http://127.0.0.1:5174,http://localhost:8080,http://127.0.0.1:8080",
"UV_LINK_MODE": "copy",
"WEKNORA_ADMIN_PASSWORD": "1qaz@WSX"
},
"console": "integratedTerminal",
"redirectOutput": true,
"justMyCode": false,
"subProcess": true
},
{
"name": "DeerFlow: Frontend Vite (5174)",
"type": "node-terminal",
"request": "launch",
"command": "npm.cmd run dev -- --host 0.0.0.0 --port 5174",
"cwd": "${workspaceFolder}/frontend-web",
"env": {
"VITE_BACKEND_BASE_URL": "http://127.0.0.1:8001",
"VITE_LANGGRAPH_BASE_URL": "http://127.0.0.1:8001/api"
},
"serverReadyAction": {
"pattern": "Local:\\s+(https?://[^\\s]+)",
"uriFormat": "%s",
"action": "openExternally"
}
},
{
"name": "DeerFlow: Open Frontend in Chrome",
"type": "node-terminal",
"request": "launch",
"preLaunchTask": "DeerFlow: VS Code Start",
"command": "powershell.exe -NoProfile -ExecutionPolicy Bypass -Command \"Start-Process 'http://127.0.0.1:5174/'\"",
"cwd": "${workspaceFolder}"
}
],
"compounds": [
{
"name": "DeerFlow: Full Stack (Backend + Frontend)",
"preLaunchTask": "DeerFlow: Stop Full Stack",
"configurations": [
"DeerFlow: Backend FastAPI (8001)",
"DeerFlow: Frontend Vite (5174)"
],
"stopAll": true
}
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"python.defaultInterpreterPath": "${workspaceFolder}/offline-backend-20260512/backend/.venv/Scripts/python.exe",
"python.terminal.activateEnvironment": true,
"typescript.tsdk": "frontend-web/node_modules/typescript/lib",
"npm.packageManager": "npm"
}
+175
View File
@@ -0,0 +1,175 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "DeerFlow: VS Code Start",
"type": "process",
"command": "powershell.exe",
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}/scripts/vscode-start.ps1",
"-OpenBrowser"
],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always",
"panel": "dedicated",
"clear": true
},
"problemMatcher": []
},
{
"label": "DeerFlow: Start Full Stack and Wait",
"type": "process",
"command": "powershell.exe",
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}/scripts/start-all-and-wait-frontend.ps1"
],
"problemMatcher": []
},
{
"label": "DeerFlow: Start Full Stack",
"type": "process",
"command": "powershell.exe",
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}/scripts/start-all.ps1"
],
"problemMatcher": []
},
{
"label": "DeerFlow: Stop Full Stack",
"type": "process",
"command": "powershell.exe",
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}/scripts/stop-all.ps1"
],
"problemMatcher": []
},
{
"label": "DeerFlow: Status",
"type": "process",
"command": "powershell.exe",
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}/scripts/status.ps1"
],
"problemMatcher": []
},
{
"label": "DeerFlow: Check Local Dev Environment",
"type": "shell",
"command": "$backendPython = '${workspaceFolder}\\offline-backend-20260512\\backend\\.venv\\Scripts\\python.exe'; if (-not (Test-Path -LiteralPath $backendPython)) { throw 'Backend virtual environment is missing. Run uv sync in offline-backend-20260512/backend first.' }; & $backendPython -c \"import uvicorn; print('Backend Python OK')\"; npm --prefix '${workspaceFolder}\\frontend-web' exec vite -- --version",
"options": {
"shell": {
"executable": "powershell.exe",
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-Command"
]
}
},
"problemMatcher": []
},
{
"label": "DeerFlow: Install Frontend Dependencies",
"type": "process",
"command": "npm",
"args": [
"ci",
"--no-audit",
"--no-fund"
],
"options": {
"cwd": "${workspaceFolder}/frontend-web"
},
"problemMatcher": []
},
{
"label": "DeerFlow: Frontend Typecheck",
"type": "process",
"command": "npm",
"args": [
"run",
"typecheck"
],
"options": {
"cwd": "${workspaceFolder}/frontend-web"
},
"problemMatcher": "$tsc"
},
{
"label": "DeerFlow: Frontend Build",
"type": "process",
"command": "npm",
"args": [
"run",
"build"
],
"options": {
"cwd": "${workspaceFolder}/frontend-web"
},
"problemMatcher": []
},
{
"label": "DeerFlow: Backend Tests",
"type": "process",
"command": "${workspaceFolder}/offline-backend-20260512/backend/.venv/Scripts/python.exe",
"args": [
"-m",
"pytest",
"tests/",
"-v"
],
"options": {
"cwd": "${workspaceFolder}/offline-backend-20260512/backend",
"env": {
"PYTHONPATH": ".",
"WEKNORA_ADMIN_PASSWORD": "1qaz@WSX"
}
},
"problemMatcher": []
},
{
"label": "DeerFlow: WeKnora Backend Tests",
"type": "process",
"command": "${workspaceFolder}/offline-backend-20260512/backend/.venv/Scripts/python.exe",
"args": [
"-m",
"pytest",
"tests/test_llmwiki_weknora.py",
"-v"
],
"options": {
"cwd": "${workspaceFolder}/offline-backend-20260512/backend",
"env": {
"PYTHONPATH": ".",
"WEKNORA_ADMIN_PASSWORD": "1qaz@WSX"
}
},
"problemMatcher": []
}
]
}
@@ -0,0 +1,61 @@
# 深度研究第三轮:检索稳定性修复 + 参考文献确定性 + 页面对齐 AI 写作改造
## A. 两个 bug 的排查结论与修复
### A1. 第二次检索「网络波动」——确认是真问题(DDG 限流 + 错误语义混淆 + 零重试)
**排查结论**(用户判断"确实是网络波动"基本正确,但代码层面放大了它):
- 「网络波动」文案不存在于任何代码中——是收集员 LLM 看到 `{"error": "No results found"}` 信封后自己编的解释
- 真实根因:DDG html 端点对同 IP 快速连续请求限流(403/429 挑战页)→ `DDGSException` → `ddg_search/tools.py::_search_text` 把异常吞成 `[]` → 上层把「被限流」和「真没结果」混成同一个错误信封;工具层完全没有重试
**修复**(`packages/harness/deerflow/community/ddg_search/tools.py`):
1. `_search_text` 对异常加 2 次重试 + 指数退避(约 1.5s / 3s + 抖动)
2. 错误信封区分场景:真无结果 → `no results`;多次尝试仍失败 → `web search failed after N attempts (rate limited or network), 换一组检索词稍后重试`——让模型不再瞎猜「网络波动」
3. 收集员 SOUL.md 行为准则加一条(同步改种子资产 + 已安装副本 `.deer-flow/agents/deep-research-collector/`):搜索返回 error 信封时先换检索词重试一轮,而不是直接告知用户网络异常
### A2. 参考文献缺失——代码确有隐患(当前是模型自发行为,时有时无)
**排查结论**:后端没有任何「参考来源」追加逻辑;四个 runner 的报告 prompt 只要求内联 `[N]` 引用。出现过的参考列表是模型看到上下文头 `[N] 标题(URL)` 后**自发**补写的——弱模型下不可靠,与"信息够不够"无必然关系。
**修复**(prompt 指示 + 确定性兜底双保险):
1. 四个 runner(basic / detailed / deep / multi_agent)的报告 prompt 各加一条:报告最后附「## 参考来源」,按 `[N] 标题. URL` 列出正文实际引用过的来源
2. `basic.py` 新增共享函数 `ensure_reference_section(report, context_list, materials)`:报告缺少参考小节时,解析正文引用的 `[N]` 编号,按压缩上下文顺序生成编号列表追加(无编号时列全部来源,封顶 20 条;已有参考小节则不重复追加)。在各 runner 最终 `write_text("report.md", ...)` 前调用(约 7 个调用点,跳过零材料 fallback)
3. 新增测试 `tests/test_deep_research_references.py`:helper 单测(正常追加/编号映射/不重复追加/无 URL 来源)+ runner 集成断言
## B. 页面改造(核心需求):左列复用 AI 写作对话形态,右列改真沙箱
### B1. 左列 = AI 写作式对话收集面板(仿 WritingSetupChat)
- **空状态欢迎屏**(无消息时隐藏头部,展示欢迎卡片,WritingWelcome 式)+ 有消息后 `MessageList`(沿用现有绑 collector 线程的接线)+ 首 token 前「正在整理…」占位条
- **输入框换成白卡片 PromptInput 套件**(与 AI 写作完全同款组件):卡片内一行「当前对话模型」Select(沿用 ModelNameSelect)+ 高级配置入口;下方 PromptInputTextarea + PromptInputFooter + PromptInputSubmit(`status` ready/streaming,流式中变停止按钮)。经典模式入口保留在高级配置对话框
- **配置卡片进对话流**(对标 AI 写作「识别出意图后出现表单」):
- `message-list.tsx` 最小扩展(约 15 行):新增分组 `assistant:research-approval`(识别 `additional_kwargs.setup_research_approval`)+ 可选 prop `researchApprovalSlot?: ReactNode`;不传 slot 或无该载荷时零行为变化——普通对话/AI 写作完全不受影响
- workbench:收集回合结束(awaiting_report,即"意图识别完成")时向 `displayThread` 尾部注入一条虚拟 ai 消息(WritingSetupChat 的 displayThread 同款手法),slot 传现有 `ReportConfigCard` → 卡片作为助手下一轮出现在对话流里
- 写作进度卡、完成卡、摘要气泡、追问列表保留在列表下方卡片区(报告正文移到右侧沙箱)
### B2. 右列 = 工作区真沙箱(Step2SandboxLayout 的 stub 线程模式)
- 新建 `deep-research/ResearchSandboxPanel.tsx`(约 100 行,含关闭/重开)+ `useReportSandbox.ts` hook(仿 `useStep3Report` 的 stub 机制):
- threadStub:`messages = [{type:'ai', tool_calls:[{name:'write_file', args:{path:'/mnt/user-data/outputs/report.md', content: <流式报告>}}]}]`,`isLoading = job 运行中 && phase !== 'summarizing'`
- `report_delta` 首帧 → `openArtifact(write-file: 虚拟URL)` 自动展开右栏;`run.report` 每帧 upsert stub(带防抹空守卫);刷新/切换会话用 `session.reportMarkdown` 重建
- `ArtifactFileDetail` 自带能力全部免费获得:**流式期 code 视图自动滚底 → 报告写完 isLoading 翻 false 自动切 preview + 脉冲提示**(正是「生成完直接切预览」)、Streamdown 渲染的 Markdown(比现在的好看)、另存 Word/复制/下载、默认走展示层脱敏
- 布局:ResizablePanelGroup chat 60 / sandbox 40(对齐 ChatBox/圆桌),沙箱可关闭、头部按钮重开
- **删除自定义 `ResearchSandbox` 组件**;legacy 会话与经典模式共用同一右栏(`run.report` 数据源相同,行为一致)
- 已知小限制(可接受):报告配图模式下沙箱内图片可能无法经 artifacts API 解析(配图默认关闭;真需要时后续把产物落 thread artifacts)
### B3. 验证
- 后端:`PYTHONPATH=. uv run --no-sync pytest tests/ -k deep_research -q --ignore=tests/test_notification_templates.py` 全绿 + ruff;改完配置/SOUL 后 touch 触发 dev 服务重载
- 前端:`pnpm typecheck` 零新增错误(基线 51)
- 手动走查:连续两次检索不再误报、弱模型报告末尾必带参考来源、页面全流程(欢迎屏 → 对话收集 → 流内配置卡 → 沙箱流式 → 自动预览 → 摘要/追问)
## 涉及文件
**后端**:`community/ddg_search/tools.py`、`deep_research/runners/{basic,detailed,deep,multi_agent}.py`、收集员 SOUL.md(种子 + 已安装副本)、`tests/test_deep_research_references.py`(新)
**前端**:`components/workspace/messages/message-list.tsx`(可选 slot 分组)、`pages/deep-research/DeepResearchWorkbench.tsx`(大改)、`pages/deep-research/ResearchSandboxPanel.tsx`(新)、`pages/deep-research/useReportSandbox.ts`(新)
## 明确不动
- AI 写作 / 普通对话现有组件行为(message-list.tsx 仅加可选分组,缺省零变化)
- 报告写作管线的写作逻辑本身(prompt 加一条要求 + 末尾确定性追加参考小节,均为附加式)
- 深度研究后端会话/任务/事件模型(本轮不动)
@@ -0,0 +1,113 @@
# Web App 产物模式:多页面站点 / 流程图 / 地图(可降级 + 独立页面风格)
## 总体架构
让智能体在沙箱里产出**完整多页面站点**(site.json 清单 + src/pages + public 数据),平台统一构建(预置 node_modules,永不 npm install)与受控静态托管,前端新注册一个**风格独立**的「站点预览」路由页。
**两条铁律(本次新增的核心原则)**:
1. **零侵入**:新页面不复用现有工作台风格/布局组件,走独立路由 + 独立样式表;对已有代码的修改仅限「一个带开关的入口按钮」。
2. **可降级**:沙箱/模板/node/构建链任何一环部署失败,Web App 功能整体退回"不可用"状态并优雅提示,智能体回退到现有单页 HTML 模式,**现有功能零影响**。
```
智能体(技能 web-app)
0. 检查可用性:/mnt/web-app-template 缺失 → 回退现有单页 HTML 模式(行为与今天完全一致)
1. scaffold → outputs/my-site/(排除 node_modules/dist)
2. 写 src/pages/*.tsx、public/data.geojson、编辑 site.json
3. build_site.py build → 软链/junction 预置 node_modules → vite build → dist/(失败自修复 ≤3 次)
4. present_files site.json
平台(Gateway,全部能力探测 + 开关保护)
GET /api/web-app/capability # 可用性探测(配置/模板/node_modules/node 四项检查)
GET /api/threads/{tid}/sites # 站点列表 + 构建状态
POST /api/threads/{tid}/sites/{name}/build # 触发构建
GET /api/threads/{tid}/sites/{name}/build-status
POST /api/threads/{tid}/sites/{name}/preview-url → 签发短时效签名 URL
GET /api/public/site-preview/{token}/{path} # 静态托管 dist/
前端(独立路由 + 独立风格)
#/sites/:threadId/:siteName # SiteStudioPage:全新视觉风格,无现有 chrome
产物面板 site.json →「打开站点预览」按钮(仅 capability 可用时渲染)
```
已确认决策:混合构建(技能自修复 + 平台按钮兜底);预览工作台先行;GeoJSON 优先 + 可配置底图。
---
## 一、页面风格:独立设计系统(不用现有风格)
新页面 `SiteStudioPage` 做成**深色"预览工作室"**风格,视觉上与现有工作台完全区隔:
- **独立路由**:直接注册在 `App.tsx` 顶层(`/share/:shareCode`、`/login` 同款先例),**不进** `PageLayout`/`WorkspaceLayout`/`Header`/`PageSidebar`——零现有 chrome 继承,零布局耦合。
- **独立样式**:新建 `src/pages/site-studio/site-studio.css`(自建 design tokens:深空灰底 `#0f1117` 系、靛蓝/青渐变强调色、玻璃拟态面板、细腻边框与阴影、系统字体栈),所有类名 `site-studio-` 前缀,**只被该页面 import**,不碰 tailwind 配置、全局 CSS、主题 provider。
- **布局**:
- 顶部悬浮工具栏:站点标题 + 构建状态胶囊(成功/构建中/失败三态,带呼吸灯动画)+ 设备切换分段控件(桌面/平板/手机)+ 刷新/重新构建/新窗口打开;
- 左侧窄导航栏:site.json 的页面列表(图标 + 标题,点击设 iframe hash 切页),可折叠成纯图标模式;
- 中央:**浏览器壳**造型(圆角 + 顶部仿 URL 地址条 + 红黄绿窗控点缀)内嵌 iframe,设备切换时宽度平滑过渡动画;
- 底部可折叠**构建控制台**(等宽字体日志、错误红色高亮、构建时长);
- 加载/失败/未启用态都有设计过的插画式空状态(纯 CSS/SVG,不引组件库新依赖)。
- 登录守卫:轻量检查 stored auth,缺失跳 `#/login`(复用既有跳转工具,不动鉴权体系)。
## 二、降级与故障隔离矩阵(部署失败不影响已有功能)
| 故障点 | 行为 | 对现有功能影响 |
|---|---|---|
| config `web_app.enabled: false`(默认关) | capability 返回不可用;入口按钮不渲染;技能第 0 步探测失败即回退单页 HTML | 无 |
| 模板目录/node_modules 未预置(发版遗漏) | 同上:capability 四项检查(配置/模板/依赖/node 二进制)逐项报告原因 | 无 |
| sandbox.mounts 加了模板挂载但目录缺失 | 已核实 `local_sandbox_provider.py:81-90` 对不存在宿主路径**静默跳过仅告警**;Aio provider 同样按"存在才挂"实现 | 无(沿用既有容错语义) |
| vite build 失败/超时 | 子进程隔离(`asyncio.to_thread` + 超时强杀 + 每站点并发锁),错误收进 JSON;预览页显示日志;智能体读报错自修复 | 无(不进 gateway 请求主链路) |
| 签名 URL 过期/伪造 | 403 JSON,页面自动重签 | 无 |
| 前端新页面任何异常 | 独立路由独立样式,最坏就是该页白屏,error boundary 兜底 | 无 |
| 产物面板入口按钮 | 唯一改动点:capability 请求失败/不可用 → 按钮不渲染,**原 UI 一字不变** | 无 |
| 新 router 注册 | 纯增量 include_router,异常全部在路由内转结构化响应 | 无 |
技能回退语义(关键):SKILL.md 第 0 步强制探测 `ls /mnt/web-app-template/scripts/build_site.py`——探测失败时明确指示"改用现有方式产出单个 xxx.html",保证部署不完整时智能体产物质量与今天一致。
## P1 站点模板(`offline-backend-20260512/backend/templates/web-app-template/`,源码入库,node_modules gitignore 由发版仓库预置)
- Vite + React + react-router-dom(**HashRouter**:静态托管路径下无需服务端 fallback)+ **纯 CSS design tokens**(不用 Tailwind v4,规避 oklch 在 chrome100 老内核失效)+ build target es2018。
- 依赖:react 系、@xyflow/react、maplibre-gl、echarts、mermaid、pmtiles、vite/@vitejs/plugin-react(lockfile 锁死版本)。
- 内置组件:`AppShell`(读 site.json 导航)、`FlowCanvas`(xyflow 流程图封装,自动分层布局)、`GeoMap`(**默认无底图模式**:背景 + GeoJSON 点线面离线开箱即用;site.json 可配 tilesUrl/PMTiles)、`ChartPanel`(echarts)、`MermaidBlock`(静态图)。
- `router.tsx` 用 `import.meta.glob('../pages/*.tsx')` 自动注册路由——智能体丢页面文件即生效,零手动接线。
- `site.json`:`{ title, description, nav[], map:{tilesUrl?, tilesType?, pmtiles?}, theme? }`。
- Makefile 加 `make webapp-template`(开发机一次性 pnpm install);发版仓库构建脚本负责镜像内预置 node_modules(文档写明)。
- config.yaml `sandbox.mounts` 增模板只读挂载(`templates/web-app-template → /mnt/web-app-template`,缺失自动跳过已验证);AioSandboxProvider `_get_thread_mounts` 小扩展:同样"存在才挂"地补读 config 自定义 mounts。
## P2 构建脚本 + 技能包(`skills/public/web-app/`)
- `SKILL.md`:触发词(多页面网站/站点/web app/带流程图或地图的网页);工作流 = ①可用性探测(失败即回退单页 HTML)②scaffold ③配置 site.json ④写页面 ⑤数据放 public/ ⑥build(失败读 JSON 报错修复重试 ≤3)⑦present_files site.json ⑧引导点「站点预览」;硬约束:不手写 dist、一律 `/mnt/user-data/...` 虚拟路径。
- `scripts/build_site.py`(纯标准库):`check`(能力探测 JSON)/ `scaffold`(copytree 忽略 node_modules、dist)/ `build`(定位 node → 软链 node_modules 进站点:Linux symlink、Windows `mklink /J` junction 免管理员 → `node vite.js build` → 结构化 JSON 输出,180s 超时)/ `status`。
- 模板定位顺序:env `DEERFLOW_WEBAPP_TEMPLATE` → `/mnt/web-app-template`(沙箱内)→ 后端相对路径(宿主侧)。
## P3 后端:纯引擎 + 路由(全部能力开关保护)
- `packages/harness/deerflow/webapp/`(纯引擎,不 import app.*,对齐 `address_scan.py` 先例):站点发现(outputs/* 下 site.json + dist 状态)、构建执行(子进程 + 锁 + 超时)、HMAC token(`tid|site|exp`,密钥首用生成持久化 `{base_dir}/.web-app-secret` 0600)。
- `app/gateway/routers/sites.py`(app.py 注册):
- `GET /api/web-app/capability`:enabled + 模板 + node_modules + node 四项检查,逐项给原因(前端与技能共用);
- 列表/build/build-status/preview-url:`@require_permission("threads", "read", owner_check=True)`,能力不可用时返回结构化 `{"available": false, "reason"}` 而非 5xx;
- `GET /api/public/site-preview/{token}/{path}`:验签 + 过期 → `aresolve_thread_virtual_path` 且**限定站点 dist/ 根**(复用遍历防护)→ 正确 MIME(.js/.mjs→text/javascript、.geojson→application/json、.wasm)→ **HTML inline** + `CSP: default-src 'self' data: blob:; worker-src 'self' blob:`(maplibre worker 需要)+ `X-Content-Type-Options: nosniff` + `Cache-Control: no-cache` + ETag(mtime)。
- config.yaml + `deerflow/config/configuration.py` 加 `web_app:`(enabled **默认 false**、build_timeout、token_ttl、template_dir、node 覆盖)——与 `workflows` 同款总开关模式。
- 测试 `tests/test_web_app_sites.py`:capability 降级路径、token 签发/过期/伪造、路径穿越拒绝、MIME、站点发现(构建子进程 mock)。
## P4 前端
- `src/core/sites/api.ts`:capability/sites/build/status/mintPreviewUrl + TanStack Query hooks(照 `light-apps.ts` 模式)。
- `src/pages/site-studio/SiteStudioPage.tsx` + `site-studio.css` + `App.tsx` 注册顶层路由 `/sites/:threadId/:siteName`(独立风格见第一节;iframe `sandbox="allow-scripts allow-forms allow-popups"` 无 allow-same-origin,延续既有安全契约;token 过期自动重签;设备切换;重新构建 → 轮询 build-status → cache-bust 刷新)。
- `artifact-file-detail.tsx` **唯一既有文件改动**:产物路径以 site.json 结尾且 capability 可用时渲染「打开站点预览」按钮(navigate 到新路由);capability 请求失败/超时一律不渲染,原 UI 不变。
- token URL 构造等纯函数补单测;`pnpm typecheck` 通过。
## P5 测试与文档
- 后端 `make test` + ruff;前端 typecheck + 单测;`build_site.py` 本机真实跑通 scaffold→build→静态服务器自测 dist。
- 文档:AGENTS.md 增「Web App 产物」小节(含降级矩阵);发版文档补 node_modules 预置说明。
## 安全边界
短时效签名 URL(默认 2h)只覆盖该站点 dist/ 静态读;dist/ 根限定 + 复用 `aresolve_thread_virtual_path` 遍历防护;HTML inline 仅在 site-preview 路径开放(不影响 artifacts 接口既有强制 attachment);CSP + nosniff + iframe sandbox 三重纵深。
## 二期(本期不做)
源码编辑 + 保存即重建;跨对话站点 gallery;PMTiles 底图资产打包;`visualizations/` 内联图表(进行中,互补不冲突)的底图配置统一(其 map-renderer.tsx 硬编码 Google 瓦片属离线隐患,另行处理)。
## 风险
- Windows 开发机 junction 链接免管理员,node 前端机必有;生产镜像已含 nodejs+npm。
- Aio provider 自定义 mounts 扩展是小改动,按"存在才挂"实现即可,不影响现有挂载。
- dist/ 出现在产物目录扫描(文件噪音)——一期保持现状,二期优化。
@@ -0,0 +1,64 @@
# 业务链选链去掉每次 `listAgents()` 查询
## 背景与思路
选链各环节展示只用到 seat 的 `agent_id + name`(快照已随链条落库,编辑器保存时刷新),额外全量拉 `/api/agents` 只为两件事:**席位存活判断**(existingIds)和**最新改名**(nameById)。存活是实时状态、无法落库保鲜,因此方案是:
- **后端**在返回链条(list/get 等)时,用一次批量 SQL(`agent_store.list_by_ids`,与 `/api/agents` 同一套可见性过滤)给每个 seat 附带 `available: bool` + `live_name: string | null` 两个**只读计算字段**(不落库,seats JSON 存储结构零变化、零迁移);
- **前端**选链全链路改用这两个字段,删除所有选链路径上的 `listAgents()` 调用;左栏点选一条链变为**零网络请求**(链条数据本就在内存里);选链弹窗打开只剩 1 个 `listChains` 小请求。
「只映射目前展示的这些」:仅 name + 存活状态,其他智能体字段一概不存(description 等快照维持现状,运行期配置由后端按 agent_id 自取,本就不依赖前端传参)。
## 后端改动
### 1. `offline-backend-20260512/backend/app/gateway/routers/roundtable_chains.py`
- 新增常量 `_FUNCTIONAL_AGENT_EXCLUSIONS`(`roundtable-intent` / `roundtable-recommender` / `roundtable-coordinator` / `roundtable-report` + 前缀 `roundtable-coordinator-`,与前端 `api/recommend.ts` 的 `filterRecommendCandidates` 排除集逐字对齐,保持"功能型内置智能体不可作席位"语义不变)。
- 新增纯函数 `_compute_seat_enrichment(chains, live_records) -> None`:对每条链每个 seat 写入 `available`(live 存在且不在排除集 → True)与 `live_name`(无则 None);配套薄异步封装 `_enrich_chain_seats(request, chains, user_id)`:收集去重小写 agent_id → `get_agent_store(request).list_by_ids(ids, user_id)` 一次查询(router 已 import `get_agent_store`,参照 `multi_agent.py` 的 `_get_agents_batch_direct` 写法)。
- 新增**响应专用** `ChainSeatResponseSchema(ChainSeatSchema)`,加 `available: bool | None`、`live_name: str | None`;`ChainResponse.seats` 改用之。创建/更新请求 schema 不动 → 富化字段永不被持久化(避免 create/update `model_dump()` 把默认值写进 seats JSON)。
- 在所有返回 `ChainResponse`(列表/单条/更新等)的出口调用富化。可见性语义与现状完全一致(`_listing_filter`:本人 / 内置 / 已发布、非私享、非管理员隐藏)。
### 2. 测试 `tests/test_roundtable_chain_seat_enrichment.py`(新建)
镜像 `test_roundtable_chain_stages.py` 的风格:纯函数用 dict 直接测(存活/缺失/排除集/改名刷新/混合多条链);`list_by_ids` 交互用同名小写归一化断言(stub store)。
## 前端改动(frontend-web)
### 3. `src/roundtable-planning/lib/business-chain.ts`
- `ChainSeat` 增加可选 `available?: boolean`(undefined = 旧后端未标注 → 视为存活,与现有"查询失败不判删"降级语义一致)和 `live_name?: string | null`,附注释说明来源与回退顺序。
- `buildChainSeatSelection(chain, candidates?)`:`candidates` 改**可选**;不传时存活 = `seat.available !== false`、名称 = `live_name ?? name ?? agent_id`;传入时保持现行为(测试兼容)。
### 4. `src/roundtable-planning/components/BusinessChainPicker.tsx`
加载 effect 只留 `listChains(scope)`;删 `listAgents()`、`filterRecommendCandidates` 及 `existingIds`/`nameById` state——存活判断用 `seat.available !== false`,tag 名称用 `live_name ?? seat.name ?? agent_id`;已删置灰/删除线/「存活不足 2 个」等 UI 保持不变(改由 `available` 驱动)。`handleUse` 的 `nameOf` 同步改。
### 5. `src/roundtable-planning/components/BusinessChainListDialog.tsx`
`BusinessChainListBody` 删除挂载时的 `listAgents()` effect 与 `nameById` map;`ChainSeatsFlow` 的 seatTag 标签改 `seat.live_name ?? seat.name ?? agentId`。
### 6. `src/roundtable-planning/pages/RoundtablePlanningPage.tsx`(3 处调用点)
- **L486 固定链 effect(8BF 等)**:`Promise.all([getChain, listAgents])` → 仅 `getChain`;席位不足提示改为按 `seat.available === false` 计算(文案不变)。
- **L1356 `handleSelectChainFromSidebar`(左栏点选,本次体验痛点核心)**:删 `listAgents()`,直接 `buildChainSeatSelection(chain)` —— 点选零请求。
- **L1503 C3 深链自动选链**:删 `listAgents()` 分支。
- 清理不再使用的 `listAgents` / `filterRecommendCandidates` import(编辑器页与「智能推荐」tab 的 `listAgents` 是选智能体池所必需,保留不动)。
### 7. 测试 `src/roundtable-planning/lib/business-chain.test.ts`(新建,node:test 风格同 `chain-stages.test.ts`)
覆盖无 candidates 分支:`available` 缺省视为存活、`available:false` 过滤、不足 2 席返回 null、`live_name` 优先于快照名、dag 分支不受影响;package.json 加 `test:business-chain` 脚本。
### 8. 文档 `frontend-web/docs/multi-agent-business-chain-dev.md`
补一段:链条响应 seat 附带 `available`/`live_name`(后端读时计算、不落库);选链前端不再调 `listAgents()`。
## 兼容性
- 新后端 + 旧前端:响应多两个字段,旧代码忽略,无影响。
- 旧后端 + 新前端:`available` undefined → 全按存活处理,行为等于现在"agents 查询失败"的降级路径;若智能体真被删,Step 2 init 的后端 404 硬校验仍兜底(现状即有)。
- 存量链条 seats JSON 无需迁移;8BF / 岗位协同 / official-task-analysis 等消费 seat 快照的模块零改动。
## 验证
- 后端:`PYTHONPATH=. uv run pytest tests/test_roundtable_chain_seat_enrichment.py tests/test_roundtable_chain_stages.py tests/test_roundtable_chain_hidden.py -v` + `make lint`(ruff)。
- 前端:`pnpm typecheck` + `node --experimental-strip-types --test src/roundtable-planning/lib/business-chain.test.ts`。
+144
View File
@@ -0,0 +1,144 @@
# AGENTS.md
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
## Project Overview
This is a customized offline deployment of **DeerFlow** — a LangGraph-based AI super agent platform. The repo contains two sub-projects:
- `offline-backend-20260512/backend/` — Python backend (FastAPI Gateway + LangGraph agent runtime)
- `frontend-web/` — Vite + React 19 frontend (TypeScript, pnpm)
Managed together via shell scripts in `scripts/`.
## Offline Release Repository
Linux AMD64 离线发版脚本、wheelhouse、`deploy.env` 模板和部署文档统一维护在
`knowledge-base-bj/deerflow-offline-deployment`,不要把离线镜像或发版资产提交到
本业务源码仓库。正式发版从该仓库执行 `scripts/build-latest-master.sh`,脚本会读取
本仓库最新 `master` 的干净源码快照。
## Commands
### Full Application (from repo root)
```bash
./scripts/start-all.sh # Start backend + frontend as background daemons
./scripts/stop-all.sh # Stop both
./scripts/restart-all.sh # Restart both
./scripts/status.sh # Check running status
```
Logs and PID files are written to `.runtime/logs/` and `.runtime/pids/`.
### Backend Only (from `offline-backend-20260512/backend/`)
```bash
make install # Install Python dependencies (uv)
make dev # Run Gateway API with hot-reload on port 8001
make gateway # Run Gateway API without reload
make test # Run all tests: PYTHONPATH=. uv run pytest tests/ -v
make lint # Lint with ruff
make format # Format with ruff
```
Run a single test file:
```bash
PYTHONPATH=. uv run pytest tests/test_<feature>.py -v
```
### Frontend Only (from `frontend-web/`)
```bash
pnpm install # Install dependencies
pnpm dev # Start Vite dev server on port 5174
pnpm build # Production build
pnpm typecheck # TypeScript type checking (tsc --noEmit)
```
## Service Ports
| Service | Port | Notes |
|---------|------|-------|
| Backend (Gateway API) | 8001 | FastAPI + LangGraph runtime |
| Frontend (Vite) | 5174 | React SPA |
Frontend connects to backend via env vars `VITE_BACKEND_BASE_URL` and `VITE_LANGGRAPH_BASE_URL` (injected by `scripts/start-frontend.sh`).
## Architecture
### Backend
The backend (`offline-backend-20260512/backend/`) is split into two layers:
- **`packages/harness/deerflow/`** — publishable agent framework (`deerflow.*` imports): LangGraph lead agent, middleware chain, sandbox, tools, MCP, memory, models, skills. **Never imports from `app.*`.**
- **`app/`** — application layer (`app.*` imports): FastAPI Gateway routers, IM channel integrations (Feishu, Slack, Telegram, DingTalk).
The **Lead Agent** (`deerflow/agents/lead_agent/`) is the single LangGraph graph entry point. It wraps a middleware chain (~18 middlewares assembled in strict order) around LLM calls, handling: thread isolation, sandbox lifecycle, uploads, memory, plan mode, vision, subagent delegation, and loop detection.
**Middleware order matters** — middlewares are appended in a fixed sequence; `ClarificationMiddleware` must always be last. See `offline-backend-20260512/backend/AGENTS.md` for the full ordered list.
**Harness → App import firewall** is enforced by `tests/test_harness_boundary.py` (runs in CI).
**Workflow Studio** (`deerflow/workflows/` + `/api/workflows*`) is a second, independent execution path beside the lead agent: a persisted DAG scheduler that runs published workflow graphs, streams a durable event log over SSE, and supports human-input pauses, cancellation, and crash recovery via lease reclaim. Coze Studio supplies the canvas UI only; LangGraph is used only *inside* an `agent`/`skill` node. Master switch and all limits live in `config.yaml` → `workflows`. See the backend `AGENTS.md`/`CLAUDE.md`「Workflow Studio」and `docs/WORKFLOW_STUDIO_BACKEND_DEV_ZH.md`.
### Frontend
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)
- **智能体对话跳转**: 创建页、智能体管理编辑框和问答页详情面板都可以给智能体配置「对话跳转」链接、打开方式(新窗口 / 当前窗口)和路由参数(登录参数、主题参数,解析方式与应用管理相同)。配置保存在该智能体 `config.yaml` 的 `chat_link`,并镜像到 `agent_extras.chat_link` 供列表读取。留空时智能体管理的「对话」按钮仍进入本系统问答;填了地址后,按钮按解析后的链接跳转。
- **模型流完整性检测 + 截断记录 (stream truncation)**: 模型配置页(`/page/workspace/admin/models`,`ModelManagementPage.tsx`)每张模型卡片新增「流完整性检测」开关 — `PUT /api/admin/models/strict-stream-integrity/{name}` 写 config.yaml 的 `strict_stream_integrity: true/false`(`app/gateway/routers/model_management.py`,仅 OpenAI 兼容 Chat Completions 模型可开;显式 `false` 也会覆盖 qwen3.8-flash-next 的自动开启;卡片显示值 = 显式配置 ?? qwen3.8-flash-next 自动规则,前端 `isAutoStrictIntegrityModel` 复刻后端判定)。开启后上游流未发终止帧就结束时抛可重试 `IncompleteChatStreamError`(`chat_stream_state.py`),LLM 错误中间件按 upstream 重试,避免半截回答静默入库。同时每次流异常结束都由 `patched_openai.py` 的 `_ToolCallStreamDiagnostics._record_truncation_event` 落库 `stream_truncation_events`(分类:`silent_no_terminal` 静默截断 / `incomplete_stream_error` 完整性拦截 / `length_truncated` / `content_filter` / `midstream_error`;write_file 兼容桥故意提前收流与用户取消不计;经 `fire_and_forget_db_write` 从任意 loop/thread 安全写入,store 在 `deerflow/persistence/stream_truncation/`,**每次写入顺手删除 30 天前的行,硬上限一个月**)。查看页 `pages/StreamTruncationLogPage.tsx`(路由 `/page/workspace/admin/stream-truncations`,admin gate 同模型配置页;简洁模式「设置和更多」下拉的「模型截断记录」入口在 `workspace-nav-menu.tsx`),client `core/stream-truncation-log/api.ts`;后端 API `GET /api/admin/stream-truncations`(分页 + 模型/类型过滤)与 `/breakdown`(按模型汇总,`app/gateway/routers/stream_truncations.py`)。测试 `tests/test_stream_truncation.py`、`tests/test_model_management.py`。配套「保留中间正文」(管理员设置弹窗同名分区,`GET/PUT /api/system-settings/retry-keep-partial`,默认开启,关闭即恢复旧行为):①正常路径——原先「消息带可见工具调用就不给正文气泡」的分组规则会把步骤条执行中已流出的正文清掉;现 `groupMessages` 新增 `keepIntermediateText` 选项(MessageList 按开关传入):本轮全部过程正文**合并成一个气泡**挂在步骤条正下方(合成消息剥思考/工具调用,组 id 加 `:keep-text` 后缀避免 React key 冲突),步骤条保持一条不被拆开(正文气泡对工具消息/后续轮次的累积「透明」,`lastOpenGroup`/`lastNonKeepBubbleGroup` 向前跳过),分组完成后把合并气泡**重排到 present-files/subagent/document-rewrite 附属组之后**(正文块与最终回答相邻、不被文件卡片隔开),仅本轮「最终正文消息」(回扫到的最后一条有正文且无可见工具调用的 ai 消息)保留独立气泡;②重试路径——LLM 错误中间件静默重试时,上一次尝试已流出的半截正文从未进 checkpoint、会被前端 values 对账清掉,`core/threads/hooks.ts` 在收到 `llm_retry` 事件时快照在途消息,被丢弃后按原位插回(纯函数 `core/threads/retry-kept-messages.ts`,快照只在本轮流式期间有效,刷新即失)。测试 `tests/test_strategy_project_settings.py` 尾部、`src/core/messages/utils-group.test.ts`、`src/core/threads/retry-kept-messages.test.ts`(`pnpm test:retry-kept`)。
- **知识库深度研究(普通知识库限定问答)**: 每个可读知识库从卡片或详情页进入 `/page/workspace/knowledge/:noteId/research`。它不复用原“深度研究”流程,而是把普通 Lead Agent 问答在服务端强制绑定到单个知识库、经典检索并关闭工具/记忆;私有会话与草稿仅创建者可见。首个完整回答自动成为 Markdown 草稿,后续回答须显式“应用为文档”。可写用户保存时在该知识库 Wiki 下创建保留根目录「深度研究」,用独立 publication id 的稳定 slug 创建/覆盖文章;文件名独立于问答标题。书架文章随知识库读权限共享,但“更多”及原问答仅创建者可见;只读用户可问答和整理草稿,不能发布。前端核心页 `pages/KnowledgeResearchPage.tsx`,client `strategy-components/api/knowledge-research.ts`;后端 REST 在 `app/gateway/routers/llmwiki.py`,运行时约束 `app/gateway/knowledge_research.py`,持久化 `deerflow/persistence/knowledge_research.py`。
- **AI 写作·对话版(对话驱动写作台)**: a **parallel new entry** beside the classic AI-writing page (classic page/routes untouched) — route `/page/canvas/ai-writing-chat`, sidebar 「问答管理 → 课题研究(对话版)」. Page `open-canvas/pages/AIWritingChatPage.tsx` reuses the engine (`AIWritingContext` + `useStream` + `AIWritingDraftPanel`); **idle keeps the classic setup layout** (`WritingSetupChat` + collapsible form) and switches to the chat workbench once writing starts; left panel `components/ai-writing-chat/WritingChatPanel.tsx` = **unified chronological feed** (`ChatFlowTimeline.tsx`, chat bubbles anchor-interleaved into the progress timeline so triggered events render below the user's message) + button-only intervention cards (`ChatInterventionCards.tsx`, inline textareas removed) + bottom unified smart composer. Intent resolution: frontend fast path + `POST /api/ai-writing/sessions/{id}/intent` → `deerflow/agents/ai_writing/intent_router.py` (per-pause action whitelist, high-cost confidence gates, payload cleaning); supports QA bypass, clarify follow-ups, control intents, and material-stage auto re-search + pending-intent resume. Tests `tests/test_ai_writing_intent.py`; plan doc `frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md`. **素材检索技能池限定白名单**:`researcher_node` 通用检索的候选池 = **ai-writing-researcher 智能体 config.yaml `skills` 白名单里的启用技能**(管理员在智能体管理页增删,内置 `knowledge-base-search` 保底且始终排最前),不再列全部启用技能——300+ 技能部署把选择提示词撑爆导致素材检索不可用;容错兜底 `_fallback_candidate_skills` 同样限定白名单;白名单未配置/加载失败回退仅内置知识库检索。实现 `deerflow/agents/ai_writing/nodes/researcher.py::_load_candidate_skills/_researcher_skill_whitelist`,测试 `tests/test_ai_writing_knowledge_base.py`。
- **轻应用中心 (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 defaults + personal layouts)**: `MenuManagementPage` (`pages/MenuManagementPage.tsx`) is available from「设置和更多」and the global Header account dropdown. Administrators edit the shared default menu; ordinary users edit only their own full/compact menu snapshot. For users with a saved snapshot, known node ids keep the personal `label`/`disabled`/`parentId`/`sortOrder` (or compact placement/order), while administrator defaults for node ids absent from that snapshot flow through—so newly-added code menus and iframe light apps follow the current default without overwriting older personal choices. Temporarily absent dynamic nodes are preserved when an unrelated personal edit is saved;「恢复默认」deletes only that user's snapshot. The static tree (`core/page-layout/sidebar-menu.ts`) remains the source of icons/routes and administrator defaults remain sparse per-node deltas. Merge/snapshot helpers live in `core/page-layout/menu-overrides.ts` and `compact-menu-overrides.ts`; full-menu writes carry the complete effective parent hierarchy for cycle/strict three-level validation while persisting only the sparse admin delta or full personal snapshot. Backend `/api/menu-overrides` uses `menu_overrides` (default) + `user_menu_override_configs` (per-user snapshot); `/api/compact-menu-overrides` uses `compact_menu_overrides` (type `A` / `B` defaults) + `user_compact_menu_override_configs` (per-user/type snapshots). Each website selects its compact type via `runtime-config.js` `VITE_COMPACT_MENU_TYPE`; `CompactToolbox` renders `toolbox` items.
- **生成网页标识 (Generated Page Branding, admin-only write)**: 管理员在设置弹窗「生成网页标识」中填写网页展示名称、上传 PNG/JPG/WebP Logo(≤10MB)、单独移除 Logo 或整体清除配置。配置保存在 runtime `system_settings.json -> generated_page_branding`,图片保存在 runtime `generated-page-branding/`,`GET /api/system-settings/generated-page-branding` 全员可读,`PUT/DELETE` 仅管理员;生成 HTML 通过公开只读 `/api/public/html-runtime/generated-page-logo` 获取图片。**只有网页展示名称非空且 Logo 文件真实存在时功能才启用**;缺少任意一项(含单独移除 Logo)都不注入任何内容,完全保持原有网页生成逻辑。该配置只约束后续生成的 HTML 网页内容,不修改 DeerFlow 自身的系统名称、主导航、欢迎区、工作区标题或 Logo。启用时,HTML 写入与 `page_report_template validate` 会由 `html_runtime/generated_page_chrome.py` 确定性注入平台套壳:页头**通栏全宽、贴顶、无圆角**,**背景直接用全量模式导航栏设计图**(`html_runtime/assets/topbar-light.svg` 浅色红调 / `topbar-dark.svg` 深色深蓝,已注册进网关 `html_runtime.py` 的 `_STATIC_ASSETS` 白名单以 `/api/public/html-runtime/topbar-*.svg` 提供;页头运行时按 body 明暗 tone 自动切图),**只注入页头、不注入页脚**;设置弹窗不再提供「品牌位置」选择,新配置默认使用 `center`:「Logo+系统名称」居中锁孔(26px 白色金属渐变字 + 深浅辉光,落在设计图中央发光基座上)+ 页面导航**分列两侧**白字页签(当前项白色加粗 + 白色墨条)。`generated_page_branding.header_layout` 字段继续兼容存量配置,既有 `left` 仍按品牌居左 + 导航居中单行渲染。页签均为通栏等高下划线式(当前项主色 + 底部渐变墨条),多页强制首个逻辑页初始可见。开关 `chrome_enabled` **默认开启**;明确关闭时完全回归无注入:不注入页头、也不对页面提任何品牌要求(校验不检查品牌,模型不会被迫自写)。页脚与「网页页脚文字」设置项均已按需求移除(`FOOTER_MARKER` 常量仅为旧页面兼容保留)。模板套件的兜底导航条同款(品牌左 + 导航中、通栏贴顶),平台注入时经 `body:has([data-df-generated-header])` + 兜底脚本双保险自动隐藏。后处理会隐藏旧的多页导航、移除模型写入的 `data-df-brand` 重复标识且保持幂等;lead prompt 只让模型生成正文和逻辑页。注入点共四处且全部**账号无关**(admin 配置对全部账号生效,非 admin 仅无配置入口):**`page_report_template prepare`(工作副本创建时即预注入页头,模型从第一秒起编辑的就是带品牌导航的页面,brief 的 `platform_branding.pre_injected` 标记此状态)**、`write_file`/`str_replace`(`sandbox/tools.py` 的 `maybe_fix_generated_html`)、`page_report_template validate`、以及 `present_files` 交付兜底(`present_file_tool._ensure_generated_html_chrome`,覆盖模型经 bash 等旁路写出的 HTML;幂等,>4MB 跳过);注入时还会**归一化 body/html 顶部 padding/margin(清零)**(防弱模型为自想页头留白)并**隐藏模型自写的顶部 nav/header**(仅正文首个内容容器之前的,正文内导航不受影响);品牌配置每次实时读取 `system_settings.json`,无缓存无账号隔离。
- **生成网页默认明暗模式 (Generated Page Theme)**: `ChatPage` 与 `AgentChatPage` 每次发送只把当前界面的明暗模式作为 `presentation_theme=light|dark` 上下文传入。用户未明确指定网页主题时,自由生成 HTML、显式模板的 `auto` 选择以及平台注入的品牌页眉/页脚按该明暗模式生成;用户明确指定浅色、深色或其他配色时以用户要求为准。不得跟随系统的红、蓝、绿等主题主色或自定义主色,网页强调色由页面内容与可读性决定;科技、数据、看板、驾驶舱或地图题材本身不得再触发深色默认。
- **系统名称与 Logo(与生成网页标识分开)**: 管理员在设置弹窗「系统名称」里填写本系统导航、侧栏和欢迎区使用的名称,并可上传一张 PNG/JPG/WebP Logo。配置在 `system_settings.json -> app_identity`,图片在运行目录 `app-identity/`,接口 `GET/PUT/DELETE /api/system-settings/app-identity`(写仅管理员),图片地址 `GET /api/public/app-identity/logo`。名称留空继续用「CM业务中心」/「CM 助手」;未上传 Logo 继续用各主题静态图片和既有 `runtime-config.js` 覆盖。不读写 `generated_page_branding`,也不改已生成的 HTML。
- **平台模板套件 (Bootstrap page-template-suite 技能)**: 内置技能 `skills/public/page-template-suite`(public 类,缺省启用)让「画页面」走平台预制 Bootstrap 模板而不是从零手写。**套件只提供多页面门户(最低 2 个逻辑页),不做单页面 HTML**(单页请求自动回落共享响应式文档模板):5 套设计 × 明暗两版共 10 个 `deerflow/page_reports/assets/report-bootstrap-*-template.html`(图表门户 3 页 / 甘特双页「进度总览+里程碑风险」/ 瓦片地图门户 3 页 / 文字杂志双页「正文论述+脉络结论」/ 研判简报双页「核心结论+风险行动」),profile 注册于 `page_reports/templates.py`(id `bootstrap-charts-portal-{light,dark}`、`bootstrap-gantt-{light,dark}`、`bootstrap-map-portal-{light,dark}`、`bootstrap-text-magazine-{light,dark}`、`bootstrap-text-briefing-{light,dark}`)。显式 `template_id` 时**页数以模板为准**(prepare 会把 brief 的页数对齐到模板页数,技能无需依赖用户说出「多页」)。模板源文件用 `__DF_HTML_RUNTIME_BASE__` 占位符引用 Gateway 运行库(Bootstrap/Alpine/ECharts/Leaflet/deerflow-runtime.js),`page_report_template prepare` 在会话副本中替换为设置里保存的 HTML 运行库地址,部署无关;图表走 `data-df-chart` 严格 JSON(甘特 = 时间轴 + 阶段重叠柱 `barGap:-100%`),地图门户走 `data-df-map` Leaflet 瓦片契约(瓦片地址来自设置里保存的地图瓦片地址,需管理员在「外观设置 → HTML 地图」选择「地图网页」引擎,引擎不符时 prepare 的 brief 会带 `map_engine_warning`)。prepare 的 brief 还带 `platform_branding`(管理员「生成网页标识」的名称/Logo/页脚文字与注入规则,正文禁止自写品牌)和 `runtime_base_url`;`_choose_page_profile` 现在**显式 `template_id` 优先**(单页文档模式也能选中套件模板,此前单页一律回落共享文档模板),未显式指定时旧选择行为不变。多页门户模板自带锚点切页兜底脚本(检测 `data-df-generated-header` 让位平台套壳,勿用 `data-df-generated-chrome` 字面量——会被注入幂等检查误判)。测试 `tests/test_page_template_suite.py`(10 模板 prepare→validate 全绿 + 品牌注入 + 居左/居中布局 + 引擎门控)。
- **Docker 内置技能同步**: Linux Docker 启动时不能让旧的持久化 `/app/skills` 遮住当前版本的 `backend/skills/public`。共享实现 `app/builtin_skill_sync.py` 会把 bundled public 覆盖同步到 live public 根、保留 `custom/`,并强制校验 Facebook/X/TikTok/YouTube/Threads/CNN/BBC/新华社/白宫官网/马尼拉时报/GMA News/雅虎日本/读卖新闻共 13 个硬路由页面技能;它使用跨进程文件锁和必需包内容摘要,多 worker 首次只复制一次,后续相同版本只校验跳过。两个受支持启动脚本仍在 Gateway 前调用 `backend/scripts/sync_builtin_skills.py`,把当前源码 `backend/skills` 只读挂载为 `/app/bundled-skills`、live skills 读写挂载到 `/app/skills`;同时 Gateway lifespan 在加载配置后、技能 ownership 迁移/MySQL 目录投影/提示词缓存之前再次调用同一共享实现,所以镜像默认入口、Compose 或外部发版脚本绕过 Shell 时也会自动补齐。任一硬路由技能缺失会 fail-fast 并打印名单,不能静默启动成“技能不可用”。
- **Facebook 页面生成技能**: 内置公共技能 `skills/public/facebook-page-generator` 只在用户明确要求 Facebook/Facebook 风格网页时触发;`lead_agent/prompt.py` 的普通问答 HTML 分流会强制读取该技能,并排除通用 `page-report-generation`、模板套件和从零手写 HTML。单账号单动态场景强制只写小型中文规格 JSON,再调用一次 `scripts/fast_single_post.py --spec`;脚本可将总评论数与实际展示数分离,按 `commentTopics` 自动补齐最多 100 条中文热评,也接受用户指定的逐条评论,并在一次进程内完成七模块 JSON、内部校验和 HTML 渲染。用户已提供素材或明确不搜索时禁止联网、图像生成、读模板/脚本源码和临时构建脚本;动态与评论正文必须为简体中文。多帖子场景仍使用 `scripts/render_facebook_page.py` 的 `init → validate → render` 流程确定性注入 `assets/facebook-template.html`,模型不得重写模板 DOM/CSS;渲染器拒绝覆盖已有文件并对 `</script>` 注入做转义。最终单文件 HTML 保留右上角设置按钮、分模块 JSON 编辑弹窗、实时校验与「应用并渲染」,以及响应式、深浅主题、发布/点赞/评论/搜索交互;浏览器缓存键包含初始 JSON 的 FNV-1a 指纹,同一制品刷新保留手动编辑,不同新制品不会再被沙箱同源旧 JSON 覆盖。测试 `tests/test_facebook_page_generator_skill.py`。
- **X 页面生成技能**: 内置公共技能 `skills/public/x-page-generator` 只在用户明确要求 X 平台、Twitter/推特或 X 风格社交时间线网页时触发;专用路由会强制读取技能并绕开通用 HTML 生成器。单账号单推文场景强制只写小型中文规格 JSON,再调用一次 `scripts/fast_single_post.py --spec`;脚本可将总回复数与实际展示数分离,按 `replyTopics` 自动补齐最多 100 条中文热评,也接受用户指定的逐条回复,并在一次进程内完成六模块 JSON、内部校验和 HTML 渲染。用户已提供素材或明确不搜索时禁止联网、图像生成、读模板/脚本源码和临时构建脚本;推文与回复正文必须为简体中文。多帖子场景仍通过 `scripts/render_x_page.py` 的 `init → validate → render` 流程注入固定三栏模板与内联运行时。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、实时校验和「应用并渲染」,保留深浅主题、发布、回复、点赞、转发、收藏、搜索、关注与响应式移动布局;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_x_page_generator_skill.py`。
- **TikTok 页面生成技能**: 内置公共技能 `skills/public/tiktok-page-generator` 只在用户明确要求 TikTok、抖音国际版或 TikTok 风格短视频信息流网页时触发。默认只写小型六模块补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_tiktok_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、实时校验和「应用并渲染」,保留滚动吸附、播放/暂停、双击点赞、静音、收藏、关注、评论、分享、搜索、方向键切换和移动端全屏布局;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_tiktok_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **YouTube 页面生成技能**: 内置公共技能 `skills/public/youtube-page-generator` 只在用户明确要求 YouTube 或 YouTube 风格视频门户、视频首页、频道页时触发。默认只写小型七模块补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_youtube_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、分类筛选、搜索、响应式视频网格、Shorts 横向列表、观看弹窗、点赞、收藏、订阅和评论;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_youtube_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **Threads 页面生成技能**: 内置公共技能 `skills/public/threads-page-generator` 只在用户明确要求 Threads 或 Threads 风格串文首页、文本社交信息流时触发。默认只写 `accountName`、`postText`、`topic`、`displayReplyCount` 等高层规格 JSON,并调用一次专用 `scripts/fast_page.py --spec`;脚本自动映射六模块、补齐作者/统计/中文热评、保留示例视觉并一次完成校验与渲染,禁止模型猜测 `$set` 深层路径或读取默认数据。只有结构改造才回退 `scripts/render_threads_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、深浅主题、发帖、搜索、点赞、回复、转发、分享、关注、动态面板和移动端导航;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_threads_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **CNN 页面生成技能**: 内置公共技能 `skills/public/cnn-page-generator` 只在用户明确要求 CNN 或 CNN 风格全球新闻门户、新闻首页时触发。默认只写以 `topic` 为核心、可选 `headline`/`breaking`/栏目标题数组的高层规格 JSON,并调用一次专用 `scripts/fast_page.py --spec`;脚本自动生成完整中文十模块与明确标注的非实时示意数据,禁止模型猜测 `$set` 深层路径、读取生成后的合并数据或探路后二次渲染。只有结构改造才回退 `scripts/render_cnn_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、突发条、搜索、直播弹窗、字幕切换、收藏、分享、移动菜单、市场快照和订阅表单;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_cnn_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **BBC 页面生成技能**: 内置公共技能 `skills/public/bbc-page-generator` 只在用户明确要求 BBC 或 BBC 风格国际公共新闻门户、新闻首页时触发。默认只写小型十模块补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_bbc_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、搜索、快讯、直播弹窗、字幕切换、音频进度、移动抽屉、新闻排行、地区天气和订阅反馈;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_bbc_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **新华社页面生成技能**: 内置公共技能 `skills/public/xinhua-page-generator` 只在用户明确要求新华社、新华网或新华社风格中文通讯社门户、新闻首页时触发。默认只写小型十模块中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_xinhua_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、多语种顶栏、报道专集、焦点图、要闻分类、名专栏、专题、记者工作室、地方切换、行业频道、媒体矩阵、直播字幕和订阅反馈;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_xinhua_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **白宫官网页面生成技能**: 内置公共技能 `skills/public/white-house-page-generator` 只在用户明确要求白宫官网、White House 风格政府首页或美国行政机构门户时触发。技能把材料整理为 `site/navigation/hero/notice/updates/priorities/administration/calendar/participation/footer` 十模块 JSON;键名、`id`、锚点和视觉枚举保留英文技术值,所有读者可见内容强制使用简体中文,英文来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_white_house_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、透明转吸顶导航、建筑主视觉、公告、官方动态、优先事项、行政团队、公共日历、全屏菜单搜索、直播字幕和订阅反馈;默认内容明确为概念模板,不冒充政府官网,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_white_house_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **马尼拉时报页面生成技能**: 内置公共技能 `skills/public/manila-times-page-generator` 只在用户明确要求马尼拉时报、The Manila Times 或其风格的菲律宾大报门户时触发。技能把材料整理为 `site/navigation/ticker/lead/pulse/regions/opinion/sections/media/footer` 十模块 JSON;键名、`id`、锚点、视觉和涨跌枚举保留英文技术值,所有读者可见内容强制使用简体中文,英文或菲律宾语来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_manila_times_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、菲律宾旗色带、衬线报头、三栏头条、地区切换、评论、商业体育、视频弹窗、数字报翻页和订阅反馈;默认内容明确为概念模板,不冒充官方网站,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_manila_times_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **GMA News 页面生成技能**: 内置公共技能 `skills/public/gma-news-page-generator` 只在用户明确要求 GMA News、GMA 新闻或菲律宾广播新闻门户风格页面时触发。技能把材料整理为 `site/navigation/justIn/lead/news/services/broadcast/channels/media/footer` 十模块 JSON;键名、`id`、锚点和视觉枚举保留英文技术值,品牌缩写 `GMA` 可保留,其余读者可见内容强制使用简体中文,英文或菲律宾语来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_gma_news_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、即时新闻条、天气切换、吸顶导航、头条视频、最新/热门/地方切换、公共服务、电视直播字幕、频道卡片、播客、彩票开奖和订阅反馈;默认内容明确为概念模板,不冒充官方网站,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_gma_news_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **雅虎日本页面生成技能**: 内置公共技能 `skills/public/yahoo-japan-page-generator` 只在用户明确要求雅虎日本、Yahoo! JAPAN、Yahoo Japan 或日本综合门户风格页面时触发。技能把材料整理为 `site/search/services/news/account/weather/utilities/shopping/pulse/footer` 十模块 JSON;键名、`id`、锚点和视觉枚举保留英文技术值,品牌 `Yahoo! JAPAN` 可保留,其余读者可见内容强制使用简体中文,日文或英文来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_yahoo_japan_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、多类型搜索、服务展开、分类新闻、推荐轮换、演示登录、城市天气、路线查询、市场切换、商品收藏、体育比分、实时热榜、移动抽屉和返回顶部;默认内容明确为概念模板,不冒充官方网站,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_yahoo_japan_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **读卖新闻页面生成技能**: 内置公共技能 `skills/public/yomiuri-news-page-generator` 只在用户明确要求读卖新闻、读买新闻、Yomiuri、Yomiuri Shimbun 或日本全国大报风格页面时触发。技能把材料整理为 `site/navigation/breaking/lead/edition/features/news/opinion/media/footer` 十模块 JSON;键名、`id`、锚点和视觉枚举保留英文技术值,品牌罗马字 `YOMIURI ONLINE` 可保留,其余读者可见内容强制使用简体中文,日文或英文来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_yomiuri_news_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、字号切换、速报展开、三栏头条、文章收藏、吸顶导航、全屏菜单、搜索、演示登录、数字报翻页、专题与分类切换、社论、视频字幕和邮件订阅;默认内容明确为概念模板,不冒充官方网站,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_yomiuri_news_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
- **舆情分析智能体(前端虚拟智能体)**: 智能体管理页新增「舆情分析」类型 tab,固定一张虚拟智能体卡片(名称/简介可编辑,存 localStorage)。对话页 `pages/SentimentAgentChatPage.tsx`(路由 `agents/sentiment-analysis/chats/:thread_id`)复用普通问答布局 + `MessageList`,**输入框只有发送按钮**;问答经 Gateway `POST /api/sentiment-agent/stream` 转发外部 AG-UI 网关(不经过 LangGraph),会话仅存 sessionStorage。接口地址 + Basic Auth 在 `runtime-config.js` 配置(`VITE_SENTIMENT_AGENT_API_URL` / `_AUTH_USERNAME` / `_AUTH_PASSWORD`)并随请求传给后台;后台按传入地址转发、关闭 TLS 校验,失败时把完整错误回传。核心模块 `src/core/sentiment-agent/`。
- **简洁模式用户引导 (Compact-mode onboarding tour)**: 简洁模式(外观设置的「全量/简洁」= compact,无全局导航栏 + 页面侧边栏)新增 TDesign React `Guide` 组件驱动的分步引导。组件 `components/workspace/compact-mode-guide.tsx`(挂在 `ChatPage`):9 步 —— 欢迎弹窗(dialog 模式)→ 左侧功能导航 → 聊天记录 → 设置和更多 → 换肤 → 界面模式(切回全量)→ 常用提示词栏 → 提示词管理弹窗 → 输入框;高亮目标由各组件上的 `data-compact-guide` 标记定位(`workspace-nav-chat-list` / `recent-chat-list` / `workspace-nav-menu` / `appearance-controls` / `custom-prompt-menu.tsx` 的 `CustomPromptBar`(提示词栏,仅新对话落地态渲染)与其 `ManagePromptsDialog`(`prompt-dialog` 锚点)/ ChatPage 输入框容器),**启动时按目标是否存在过滤步骤**(如新用户无聊天记录、侧栏收起时自动剔除该步 —— Guide 对缺失元素会抛错,不能盲传)。**提示词管理弹窗步骤是动态目标**:弹窗平时不渲染,引导切到该步前先广播 `PROMPT_DIALOG_GUIDE_EVENT`(`custom-prompt-menu.tsx` 导出)让 `CustomPromptBar` 打开 `ManagePromptsDialog` 并**接管**(`owner: true` 期间 ESC/点遮罩不关闭,防止高亮目标消失导致 Guide 报错),轮询锚点真正挂载后才切步;离开该步 / 跳过 / 完成 / 中途卸载时以 `owner: false` 收回弹窗,4 秒打不开则跳过该步防卡死。**TDesign Guide × Radix 模态互操作**:Radix 模态弹窗打开时会把 `body` 置 `pointer-events:none`(滚动锁定),Guide 直接挂在 body 下的遮罩/高亮/弹层会一并继承失活(引导按钮点不动),`styles/tdesign-theme.css` 末尾对 `.t-guide__overlay/__highlight/__popup/__wrapper` 显式 `pointer-events:auto` 兜底。触发:① 自动 —— 简洁模式新对话落地页自动演示,直到用户显式点「完成」或「跳过」才写 localStorage `deerflow.compact-guide-finished` 记忆(浏览器级);**中途刷新/离开不记忆,下次进入还会再演示**。② 手动 —— 「设置和更多」下拉新增「界面使用引导」(该下拉仅存在于简洁模式工作区侧栏 footer):已在问答页时广播 `compact-guide:start` 窗口事件直接启动,否则写 sessionStorage 请求并导航 `/chats/new` 由挂载的引导消费(消费在定时器真正启动时才执行,规避 StrictMode effect 双跑吞请求)。`eligible` 排除 embed=1 / hideChrome=1 / chats_iframe / FORCE_COLLAPSED_SIDEBAR(无界)等同样无全局 chrome 的特殊环境;启动延迟 800ms 等侧栏宽度过渡稳定后再测量高亮框。
- **智能体使用引导 (Agent onboarding tour, 三段式)**: 智能体「浏览管理 → 创建与配置 → 发起问答」全流程分步引导,组件 `components/workspace/agents/agent-guide.tsx`(同一 TDesign `Guide` 封装模式,与简洁模式引导共享记忆语义:**仅显式点「完成/跳过」才写 localStorage** `deerflow.agent-guide.<stage>.finished`,中途刷新/离开不记忆)。**自动演示仅 create / chat 两段**(进智能体列表页不弹引导,点「创建智能体」进入新建页时才自动演示;list 段的 `AgentGuide` 传 `autoStart={false}`,只能由头部「使用引导」按钮手动触发)。三段各自挂载、各自记忆:① `list`(`agent-gallery.tsx`,/page/workspace/agents)——分区 Tabs、搜索排序、智能体卡片操作、右上「创建智能体」按钮;**完成/跳过就地结束(不跳转创建页,与 create 段无联动)**,最后一步仅提示进入创建页后会有配置引导;② `create`(`NewAgentPage.tsx`,/page/workspace/agents/new)——左侧对话式创建输入区、基本信息、运行模型+入库模板名、知识空间、SOUL.md、技能穿梭框、保存按钮(9 步);③ `chat`(`AgentChatPage.tsx`,agents/:id/chats)——左栏切换与历史、常用问题 chips、输入框(落地态/会话态两个挂点同一 `chat-input` 标记)、右侧详情面板;`eligible` 限定普通智能体对话页(`showAgentList && !isEmbedded && !taskCtxOn`,即排除通用问答原地嵌入与任务深链工作区),三段共用 `isAgentGuideEnvironment()` 排除 embed/hideChrome/无界环境。高亮锚点 `data-agent-guide`:列表页 `tabs`/`search`/`agent-card`(卡片+列表两种布局的根元素)/`new-agent-btn`,创建页 `create-chat-input`/`create-basic`/`create-model`/`create-knowledge`/`create-soul`/`create-skills`/`create-save-btn`,对话页 `chat-sidebar`/`chat-questions`/`chat-input`/`chat-detail`;同样**启动时按目标存在性过滤步骤**(新用户无卡片/无预设问题时自动剔除)。手动重放:三个页面头部各有「使用引导」按钮(列表页创建按钮左侧、创建页 header 右侧、对话页 header),广播 `agent-guide:start:<stage>` 窗口事件强制重放(忽略已看过记忆)。
- **敏感词管理 (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.
- **技能上下线 (Skill Availability, owner/admin)**: the global `Skill.enabled` flag is the online/offline switch. Taking a skill offline persists `skills.<name>.enabled=false` in `extensions_config.json` but does **not** delete its directory or remove it from existing agent/workflow configurations; the row remains visible and bringing it online restores those references. Administrators may toggle every skill from 「技能管理」; ordinary users may toggle only their own non-built-in `custom` skills from 「技能 → 技能列表 → 我的」. Offline skills must be absent from every model-facing skill catalogue (`lead` prompt, `search_skills`, `skill_list`, `skill_view`, subagents, AI writing/deep research/roundtable and Workflow run-start validation), from agent skill pickers, and from direct sandbox access: `read_file`/`ls`/`glob`/`grep`/`bash` reject offline, unknown, root-wide and category-wide `/mnt/skills` paths. The backend mutation is `PUT /api/skills/{name}`, authorizes either an administrator or the persisted owner of the target custom skill, patches the raw document so MCP placeholders and unrelated extension fields survive, uses atomic replacement when supported plus a Docker single-file-bind fallback, and refreshes the skill prompt cache. Launchers keep the runtime extensions file in a writable persisted directory. Existing agent/strategy-agent references stay visible as 「已下线」 and may be removed but not newly selected.
- **技能地址管理 (Skill Address Management, admin-only)**: 扫描运行中的技能(`skills/{public,custom}` 下所有 `.md`/`.py`)里的 **http(s) URL 与 IP/IP:端口**,按唯一地址聚合全部出现位置(跨 .md/.py),支持**批量替换**(如把 UAT 地址一次性改成生产)。主体抽成可复用组件 `SkillAddressesPanel`(`pages/SkillAddressesPage.tsx` 导出,默认导出 `SkillAddressesPage` 仍保留旧路由 `/page/strategy/admin/skill-addresses` 作直链回退),**作为「技能地址管理」标签页嵌入管理员「技能管理」页 `pages/AdminSkillsPage.tsx`**(该页加 Tabs:「技能列表」+「技能地址管理」;入口在「设置和更多」下拉的「技能管理」`workspace-nav-menu.tsx` → `/page/workspace/admin/skills`,不再单列于 `components/page-sidebar.tsx` 左下角设置下拉):打开自动扫描并带**进度条**(扫描逐技能 / 应用逐文件 X/N,应对 150+ 技能),URL/IP 类型过滤 + 搜索 + 「片段批量套用」(如所有 `uat.4.cn` → `prod.4.cn`)、每地址「替换为」输入框(可展开看 `file:line` 片段)、内联**预览**、**应用**、**多关键词检索**(空格分隔全部命中),以及**修改记录**面板——每次应用生成一条记录(显示时间/改了哪些地址 from→to/文件数/处数),可**针对单次记录回退**(二次确认)。client + NDJSON 流式解析在 `strategy-components/api/skill-addresses.ts`。后端 `/api/skill-addresses`(**仅管理员**):所有文件 IO 走 `asyncio.to_thread` 不阻塞事件循环;`GET /scan`(+`/scan/stream`)、`POST /preview`、`POST /apply`(+`/apply/stream`)、`GET /backups`、`POST /rollback/{id}`;**子串安全替换**(基于 token span,不会误伤子串)、`expected_total` 乐观锁(409)、写前自动磁盘备份到 `{skills_root}/.address-edits/`(同时写一份 `{id}.manifest.json` 记录本次替换明细,供修改记录展示)、应用后刷新技能系统提示缓存。纯引擎 `deerflow/skills/address_scan.py`,router `app/gateway/routers/skill_addresses.py`,tests `tests/test_skill_addresses.py`。范围仅运行中技能,不动 `deploy/minimal/skills/`。
- **按钮管理 (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). **`host`(宿主路由)** asks the embedding parent to navigate: `runTaskButton` sends `window.parent.postMessage({ type:'HOST_NAVIGATE', path, queryParams:{ [idParam]: Number(taskId) } }, hostOrigin)` — `target` is the host route, `appendTaskId`/`idParam` become numeric `queryParams` (task id, or action id when `idKind:"action"` — same selector as url buttons, xdfx only), origin from `runtime-config.js` `VITE_HOST_NAVIGATE_ORIGIN` (else ancestorOrigins/referrer; never `*`). **`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 **or host** 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`.
- **HTML 模板管理 (HTML Template Management, admin-only)**: 定时任务「HTML 模板」库的可视化管理——列表/预览(iframe srcDoc sandbox)/在线编辑/上传 .html 覆盖/新建/删除/重置内置,改完**即时生效**(调度器每次执行直接读文件,无需重启)。模板从纯代码注册表升级为**文件型存储**:harness 纯引擎 `deerflow/runtime/scheduler/template_store.py`(`{base_dir}/html-templates/<id>/{template.html,meta.json}`,gitignored),app.py lifespan 把随包 `scheduler/templates/` 的全部内置模板(目前 27 个)seed 进存储——**目录缺失才复制,绝不覆盖管理页/线上修改**;`template_fill.py` 的 `get_template/list_templates/read_template_text` 改为存储优先、随包注册表兜底,写操作后 `invalidate_cache()` 清引擎 lru_cache。**convertible 自动探测**:上传/编辑正文时检测单行 `const DATA={…};` 注入行(当前引擎唯一注入点,`const MANIFEST=` 同理),带注入行即「可转换填充」(定时任务 JSON 转换管线零代码接入),否则「只展示」;数据存 `<script type="application/json">` 元素或 `let DATA`/带空格写法的模板仍探测为只展示。内置模板可编辑/覆盖/重置回随包原版但**不可删除**(防引用它的任务挂掉),自建模板可删。页面 `pages/HtmlTemplatesPage.tsx`(入口**仅官方 DeerFlow 入口**:`OfficialDeerFlowEntry.tsx` 侧栏「模板管理」→ `#/official/workspace/task-analysis/html-templates`,页面 id `html-templates` 的路径判断必须先于 `task-analysis-detail` 的 `/:id` 正则,仅 admin 可见;主应用的简洁/全量模式**不加侧栏入口**,仅保留直链路由 `/page/strategy/admin/html-templates` 作回退,admin-gated),client+hooks `strategy-components/api/html-templates.ts`。后端 `/api/html-templates`(读开放、写仅 admin;`app/gateway/routers/html_templates.py`),旧端点 `GET /api/scheduled-tasks/html-templates` 不变(内部同样读存储),定时任务表单的下拉自动看到新建模板。测试 `tests/test_html_templates_admin.py`。
- **单智能体任务深链聊天记录(2026-10-19)**: `3qfx` / `rwfx` / `xdfx` 的会话历史使用独立 `task_deeplink_threads` 索引表及 `GET /api/task-deeplink-threads?task_id=&go_path=`,前端由 `useTaskDeeplinkThreads` 读取,不再筛选通用聊天列表。LangGraph thread/checkpoint 仍是消息权威数据;专用表仅按 `(task_id, go_path)` 定位 thread。`3qfx/rwfx` 按任务 id,`xdfx` 按 URL 原始行动 id;新 thread 写 `metadata.{taskRecordId,taskGoPath,thread_type:"task_deeplink"}` 并自动登记,通用最近对话默认隐藏。迁移 `20261019_01` 只建表、**不迁移/回填旧数据**。
- **上下文与对话轮数(管理员全局设置)**: 「设置 → 上下文管理」可开启 `system_settings.json -> conversation_context.recent_turn_window_enabled`(默认关闭),并调整 `max_conversation_rounds`(单个普通对话的真实用户提问上限,默认 20,范围 1–50);统一走 `GET/PUT /api/system-settings/conversation-context`,PUT 仅管理员。轮数上限由 `ChatPage` 读取,达到后禁止继续发送并引导新建对话;旧配置缺字段时仍按 20。近 3 轮模式开启后,`RecentTurnsMiddleware` 只改变单次模型请求,保留含当前轮在内的最近 3 个真实用户回合及其 assistant/tool 链;checkpoint 与前端完整聊天记录不删。该模式优先于聊天框「上下文压缩」,且不会调用摘要模型;关闭后沿用原压缩行为。实现 `deerflow/agents/middlewares/recent_turns_middleware.py`,回归 `tests/test_summarization_multiturn.py` / `tests/test_prompt_prefix.py`。
- **输入框选项按窗口隔离(per-tab composer options)**: 输入框工具条的「写作 / 文件 / 参考文献 / 上下文压缩」开关与「模型 / 快速(模式) / 思考强度」选择器原本存 `localStorage`(`deerflow.local-settings`)且 store.ts 监听 `storage` 事件跨窗口同步——一个窗口切换、所有窗口生效。现这 7 个字段拆入 `sessionStorage`(`deerflow.composer-session`):纯函数拆分/合并/解析在 `core/settings/composer-scope.ts`,`core/settings/local.ts` 的 `getLocalSettings`/`saveLocalSettings` 负责路由(全局文档读写时强制剥离这 7 个字段,历史残留值失效)。**每个浏览器窗口独立**——复制链接新开的窗口从默认值开始、互不影响;同一窗口刷新保留;`useLocalSettings` API 与全部使用方(input-box / chat-box / message-list / hooks / IframeChatPage 等)零改动。「选择 Agent」的新对话预选 `deerflow.last-agent-id` 同样改 sessionStorage。其余 LocalSettings(字号 / 布局模式 / composer 宽度等外观偏好)保持浏览器全局并继续跨窗口同步;一次性迁移标志 `deerflow.composer-session.migrated` 把升级前旧值搬进升级后第一个打开的窗口。「经典检索/智能检索」与「知识空间」选择本来就是页面 state + 线程 metadata,天然按窗口隔离,未改动。测试 `pnpm test:composer-session`(`core/settings/composer-scope.test.ts`)。
- **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/taskType`; opening text maps `taskType` 1/2/3 to 打击/塑势/防御) 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). **xdfx additionally partitions its chat records by 行动id (action_id), NOT by task_id**: `resolveTaskDeeplinkTarget` sets `partitionByAction:true` + keeps the raw action_id as `TaskContext.actionId`, so new threads are tagged `metadata.{taskId,actionId}` (taskId kept only to preserve the backend「任务深链对话全局共享」semantics, which keys off `metadata.taskId`) and the conversation list filters by `actionId` (+`agent_id`) — different actions of the same task get separate lists. xdfx's first-question opening text also appends `行动id(action_id)为…` (see `buildOpeningText` / `taskThreadMetadata`). 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, actionId?)` — filtered by **both** `metadata.taskILine truncated
- **agentfx 任务深链(新系统 iframe 嵌入的智能体问答,3qfx 单智能体 lite 模式的独立复制)**: goPath=`agentfx`(`${loginBase}?password=…&taskId=…&goPath=agentfx&embed=1&hideJump=1&theme=dark-blue`)。与 3qfx 的差异:①任务详情不走外部 consumer,改调**本系统 Gateway** `GET {backend}/taskAnalyseSearch/cop-task-detail?taskId=`(`apiFetch` 带刚登录的 DeerFlow 态;任务数据来自 TaskCOP 任务表,与任务列表/报告导入同一份);②**固定使用内置智能体** `agentfx-analyst`(不走业务映射);③路由 `task-management/plan-task-agentfx/agent/:agent_id/chats`,页面为独立复制的 `AgentFxWorkspace.tsx`(`AgentFxWorkspace`/`AgentFxIndexResolver`/`AgentFxChat` —— 左「当前任务」卡 + 1:N 对话列表 + 新建对话,`AgentChatPage taskBind` 自动发开场白;无 TaskJumpBar/清除记录/闸门/xdfx 行动卡)。模块 `core/auth/agentfx-deeplink.ts`(`isAgentfxGoPath`/`fetchAgentfxTaskDetail`/`resolveAgentfxDeeplinkTarget`);任务详情整包仍存共享键 `login.copTaskDetail`(按标签页隔离),`AgentChatPage` 的 taskBind 自恢复对 agentfx 生效。`LoginPage` 在既有深链分支前用 `isAgentfxGoPath` 分流。**内置「任务研判报告助手」**:后端 seeder `app/gateway/routers/_agentfx_seed.py` + `_agentfx_seed_assets/`(config.yaml + SOUL.md,目录存在不覆盖;app.py lifespan 在 `_sync_legacy_agents` 之前调用,自动进 agents 表 user_id IS NULL)——SOUL 规定工作流「搜集信息(`web_search`,**首步不可跳过**)→ 每次检索 JSON 原样落盘 `/mnt/user-data/workspace/hits/qN.json` → **一条命令** `task-report-build`(group `all`)技能函数转换成 14 类 `task-reports.json`(模型禁止手写该 JSON;分页技能 `task-report-{enemy,our,env,judge}` 仅用于事后补跑单页;五者都是共享引擎 `task-report-lib/convert_lib.py` 的瘦 CLI,`resolve_hit_files` 对虚拟绝对路径读空的情况自动回退到相对写法并在 `warnings` 里列出尝试过的路径,免得智能体自己写脚本排查)→ `write_file` 生成 `/mnt/user-data/outputs/report.md` → 聊天总结 → 引导入库」,硬性约束:categoryType 逐字用 14 个全称(禁缩写自造如「DQ关键事件」)、JSON 直接写汉字禁 `\uXXXX` 转义、每类必须有实质内容不许空数组/纯占位、文件一律用 `/mnt/user-data/...` 虚拟路径(防宿主路径泄漏进 tool args)。**检索依赖 `config.yaml tools.web_search`(DDG,enabled 已开;内网需换 configurable_search 时改回并填 endpoint)**。任务工作区输入框在 `taskCtxOn` 时隐藏「写作/记忆/参考文献」(InputBox `hideContextTools` prop)与「知识空间」(不传 knowledgeSelector);消息流里 write_file 文件卡片只显示文件名(`artifactDisplayName` 收敛宿主/虚拟路径)。**入库两条路径**:(a) **前端协助卡** —— `AgentChatPage`(taskBind 且非 taskGate)检测线程 artifacts 出现 `task-reports.json`(按文件名后缀匹配,兼容本地沙箱记录的宿主路径)且流式结束时,向 displayThread 尾部注入 `additional_kwargs.task_report_import_approval` 虚拟 ai 消息(`core/messages/utils.ts` 分组 `assistant:task-report-import` + `MessageList` 的 `taskReportImportSlot` 插槽渲染 `TaskReportImportCard`),点「开始入库」前端校验(`strategy-components/lib/agentfx-report-schema.ts`,14 类 + contentJson 合法 JSON + **\u 转义归一化还原为汉字**,与技能脚本同规则)后 `importTaskReport`(`strategy-components/api/task-reports.ts`)POST 导入接口整体替换;任务已有详情**不抑制**卡片(入库即整体替换,卡片文案说明覆盖语义),导入成功按 thread 记 sessionStorage(刷新不重复询问)、「暂不入库」为会话内记忆;(b) **入库技能** `task-report-import`(seeder 一并复制到 `skills/public/`,public 类技能 extensions_config 缺省即启用)—— 用户聊天里说「入库」时智能体按 SKILL.md 用 bash 跑 `scripts/task_report_import.py`(纯标准库:同样的校验规则 + 转义归一化;**默认关闭 SSL 证书校验** `ssl._create_unverified_context` + 忽略代理,适配内网自签证书;鉴权 `--token`/env `AGENTFX_IMPORT_TOKEN`→`DEERFLOW_AUTH_TOKEN`→`TOOLS_TOKEN` 优先,缺省经公共端点 `POST /api/parallel-agents/auth/token` 以 `agentfx-import` 用户现签 token——内网既有鉴权旁路;gateway 地址 env `AGENTFX_GATEWAY_URL` 或 `http://127.0.0.1:{DEER_FLOW_GATEWAY_PORT}`);`--strict` 可要求 14 类齐全,默认允许部分导入并在 stdout JSON 的 `missing_categories` 里列缺。入库成功后任务 TaskCOP 状态自动置 25(已完成分析)。**入库成功通知宿主**(iframe 嵌入场景):两条路径成功后都会 `window.top.postMessage({source: "magent-web", type: "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 提示。
- **Web App 产物模式(多页面站点 / 流程图 / 地图,默认关闭、全链路可降级)**: 让智能体产出**完整站点**而非单个 xxx.html。沙箱技能 `skills/public/web-app` 用模板(`backend/templates/web-app-template`,经 `config.yaml sandbox.mounts` 只读挂载到 `/mnt/web-app-template`,目录缺失自动跳过)脚手架到 `outputs/<site>/`(site.json 清单 + `src/pages/*.tsx` 文件名即路由 + `public/` 数据),再跑 `scripts/build_site.py build` 用**预置 node_modules**(symlink/junction 链接,离线永不 npm install)执行 vite build 出 `dist/`;内置组件 `FlowCanvas`(@xyflow/react)/`GeoMap`(MapLibre,默认无底图 GeoJSON 模式,site.json 可配 tilesUrl/PMTiles)/`ChartPanel`(ECharts)/`MermaidBlock`。平台侧 `app/gateway/routers/web_app_sites.py` + 纯引擎 `deerflow/webapp/`(发现/子进程构建/HMAC 签名):`GET /api/web-app/capability`(enabled/模板/依赖/node 四项探测)、`GET|POST /api/threads/{tid}/sites[...]{build,build-status,preview-url}`,静态托管走 `GET /api/public/site-preview/{token}/{path}`(`/api/public/` 免鉴权命名空间,**唯一允许 HTML inline 的出口**——签名令牌 + dist/ 根限定 + 按请求真实 origin 显式声明的 CSP(iframe sandbox 不透明 origin 下 'self' 失效)+ nosniff;artifacts 接口既有的强制 attachment 不变)。前端:**独立风格**预览工作台 `pages/site-studio/SiteStudioPage.tsx`(顶层路由 `#/sites/:threadId/:siteName`,`App.tsx` 注册,不进 PageLayout/WorkspaceLayout;自带 site-studio.css 深色设计体系,零全局样式污染;iframe `sandbox="allow-scripts allow-forms allow-popups allow-modals"` 无 allow-same-origin)+ 产物面板 `artifact-file-detail.tsx` 里 site.json 的「站点预览」按钮(capability 可用才渲染,唯一既有文件改动)。**降级铁律**:默认**完全关闭**(`sandbox.mounts` 的模板挂载条目与文件末尾的 `web_app:` 段在 config.yaml 里**均为注释状态**);开启需**同时放开两处**(挂载让沙箱技能可探测 `/mnt/web-app-template`,`web_app.enabled: true` 开平台 API——只开一处会得到"生成了看不了"或"看不了也不生成"的中间态)。`build_site.py check` 在宿主侧会读 config.yaml 的 `web_app.enabled`(env `DEERFLOW_WEBAPP_ENABLED`/`DEERFLOW_WEBAPP_CONFIG` 可覆盖;沙箱内读不到配置时"挂载即视为开")。任何一环(配置/模板/node_modules/node)缺失 → capability 不可用 + 技能第 0 步探测失败即**回退单页 HTML 模式** + 入口按钮不渲染 + 构建失败只收进任务状态,现有功能零影响。配置 `web_app:`(enabled/template_dir/build_timeout_seconds/preview_token_ttl_seconds/node_path);测试 `tests/test_web_app_sites.py`;开发机 `make webapp-template` 预置依赖,离线发版由 deerflow-offline-deployment 仓库在 CI 预置 node_modules 进镜像。
### Configuration
Backend config lives in `offline-backend-20260512/backend/config.yaml`. Values starting with `$` resolve as environment variables (e.g., `$OPENAI_API_KEY`). MCP servers and skills are configured in `extensions_config.json` in the same directory.
## Detailed Backend Reference
The backend has its own comprehensive documentation at:
- `offline-backend-20260512/backend/AGENTS.md` — architecture, middleware chain, all API routes, config schema, sandbox/memory/subagent systems
- `offline-backend-20260512/backend/README.md` — setup guide, technology stack
+65 -1
View File
@@ -1,5 +1,40 @@
# CLAUDE.md
## Retrieved files in chat (2026-10-07)
The shared `MessageGroup` renders `RetrievedFileList` below its reasoning/tool
timeline, so retrieved originals remain visible when old tool steps collapse and
do not depend on a model calling `present_files` or enabling reference mode.
The file list starts collapsed, keeps the latest retrieved file visible with the
total count, and expands the remaining files in reverse retrieval order.
`core/messages/retrieved-files.ts` derives these cards only from completed skill
invocations (a known skill tool name or a skill script path in an execution tool).
Generic reads, listings, report generation tools, uploads and outputs are excluded;
workspace paths require a structured retrieval/file container and exclude paths
written in the same message group. It accepts structured file links and WeKnora identifiers such as `knowledge_id` and
`document_file_name`. It handles JSON wrappers, MCP text blocks and bounded JSON
following console logs, deduplicates by file identity and caps one group at 100
files / 2,000 visited payload nodes. Do not extract file cards from assistant prose,
failed tool calls, arbitrary document text or `/mnt/skills` / host filesystem paths.
The admin-only Settings → Appearance switch「技能检索文件展示」persists globally as
`citation_display.retrieved_files_enabled` (default true). The existing citation-display
PUT endpoint enforces administrator authorization. The UI waits for the setting
before collecting files, shares its query cache, and refreshes active clients every
60 seconds/on stale window focus. Disabling it hides retrieved cards, not normal artifacts.
Thread files reuse the authorized artifact endpoints and uploaded-file reader;
knowledge files reuse the authorized LLMWiki original-file API and
`WeKnoraSourceDrawer`. `/api/llmwiki/sources/resolve` maps provider knowledge-base
ids to local mapping ids only after checking the viewer's existing read access.
External links use HTTP(S) only, credential-free fetches for
inline preview, and a native original-file link for download/fallback; never send
the DeerFlow bearer token to them. External download behavior depends on the
source's response headers and browser cross-origin rules. Unknown formats or
unavailable Office sidecars fall back to downloading the original. Public shares
use their existing file route and do not query private knowledge document APIs.
Closing the shared preview dialog aborts in-flight requests and releases blob URLs.
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
@@ -73,19 +108,48 @@ The **Lead Agent** (`deerflow/agents/lead_agent/`) is the single LangGraph graph
**Harness → App import firewall** is enforced by `tests/test_harness_boundary.py` (runs in CI).
**Workflow Studio** (`deerflow/workflows/` + `/api/workflows*`) is a second, independent execution path beside the lead agent: a persisted DAG scheduler that runs published workflow graphs, streams a durable event log over SSE, and supports human-input pauses, cancellation, and crash recovery via lease reclaim. Coze Studio supplies the canvas UI only; LangGraph is used only *inside* an `agent`/`skill` node. Master switch and all limits live in `config.yaml` → `workflows`. See the backend `CLAUDE.md`「Workflow Studio」and `docs/WORKFLOW_STUDIO_BACKEND_DEV_ZH.md`.
### Frontend
- **账号登录、自主注册与单点登录**:`/login` 提供用户名/邮箱与密码登录,`/register` 提供自主注册。管理员在「设置 → 登录与注册」管理 `system_settings.json.authentication` 的四个开关:账号密码登录、自主注册、单点登录(同一账号仅一处在线)默认关闭;既有外部系统免登 `sso_enabled` 默认开启。已保存配置保持不变。开启密码登录后,私有页面先经 `/api/v1/auth/me` 验证,后端 Gateway/LangGraph 同步拒绝旧免密 JWT;合法登录在 JWT 写入 `auth_method`。未设置个人密码的账号使用配置中的系统口令,未自定义时为 `123ewq`;修改密码也须验证当前个人密码或默认口令。开启 `single_session_enabled` 后,每次成功登录原子递增 `token_version`,旧会话下一次请求即失效;前端每 15 秒及窗口激活时检查并退出,失效页禁止自动重登录,避免互踢。关闭单处限制时允许多个登录会话。外部免登参数兼容 hash 前后两种位置(hash 参数优先)。公开配置 `GET /api/v1/auth/options`,管理员读写 `GET/PUT /api/system-settings/authentication`。个人信息下提供修改密码;`LoginWhitelistPage.tsx` 提供管理员重置。密码与口令共用,更新后旧密码/链接失效并撤销旧会话;当前用户改密或管理员重置自身须保存返回的新 Bearer token。新密码不在用户列表回传明文,管理员仅在本次重置后临时复制链接。注册与新建外部账号均为普通用户,禁止依据名称自动授予管理员权限。
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)
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
- **智能体对话跳转**: 创建页、智能体管理编辑框和问答页详情面板都可以给智能体配置「对话跳转」链接、打开方式(新窗口 / 当前窗口)和路由参数(登录参数、主题参数,解析方式与应用管理相同)。配置保存在该智能体 `config.yaml` 的 `chat_link`,并镜像到 `agent_extras.chat_link` 供列表读取。留空时智能体管理的「对话」按钮仍进入本系统问答;填了地址后,按钮按解析后的链接跳转。
- **普通问答地图可视化**: shared `MarkdownContent` recognizes only dedicated `map-json` fences and otherwise preserves the legacy Markdown/Streamdown path byte-for-byte. `components/workspace/visualizations/` validates the bounded map contract with Zod after recovering common marker/line aliases (`coords`, `from`/`to`, `lng`/`lat`) and dropping unusable lines so markers still render; markers accept per-point `color`; lines are emitted only when the user explicitly asks to connect places, then render as colored SVG arrows that loop along the path (honoring `prefers-reduced-motion`); it lazy-loads MapLibre, and provides loading/error/text fallbacks so malformed or unreachable maps never blank the message. The lead-agent prompt emits `map-json` only when the user explicitly asks for a map; flowcharts and other graphics continue through the existing Markdown/Mermaid path. The raster tile template comes from the single post-build setting `runtime-config.js` → `VITE_MAP_TILE_URL` (Google by default); replace it with the intranet `{z}/{x}/{y}` endpoint for disconnected deployments.
- **HTML 成品离线绘图运行时**: 新生成的 `.html` 源码直接引用 Gateway `/api/public/html-runtime/` 下的浏览器版 `g6.min.js`、`echarts.min.js`、`leaflet.js/css` 和 `deerflow-runtime.js`;文件随后台源码存放于 `vendor/html-runtime/`,不再依赖前端 Vite/node_modules 产物或公网 CDN。设置 → 外观的「HTML 运行地址」保存在 `system_settings.json -> html_runtime`(`GET|PUT /api/system-settings/html-runtime`,管理员可写):`base_url` 是写入新 HTML 的浏览器可访问绝对地址,`map_tile_url` 是地图网页模式读取的瓦片模板。未保存时才回退到旧的 `config.yaml`,最后才用本机默认地址。设置 → 外观的管理员选项「HTML 地图」可选 `echarts`(本地 GeoJSON,`data-df-geo`,默认)或 `leaflet`(地图网页,`data-df-map`);运行时同时保留两种初始化,已生成页面不因切换失效。用户上传的栅格图若要作为页面背景,使用同一 Gateway 源下的签名地址 `/api/public/html-images/{token}` 写入 `background-image`。流程图使用 `data-df-flow` + G6(不用 Mermaid),图表使用 `data-df-chart`。普通问答保持独立:消息列表 `map-json` 继续由前端原逻辑渲染,普通流程图/图表仍走 Markdown/Mermaid。
- **系统名称与 Logo**: 管理员在设置弹窗「系统名称」里填写本系统导航、侧栏和欢迎区使用的名称,并可上传一张 PNG/JPG/WebP Logo。配置在 `system_settings.json -> app_identity`,图片在运行目录 `app-identity/`,接口 `GET/PUT/DELETE /api/system-settings/app-identity`(写仅管理员),图片地址 `GET /api/public/app-identity/logo`。名称留空继续用「CM业务中心」/「CM 助手」;未上传 Logo 继续用各主题静态图片和既有 `runtime-config.js` 覆盖。不改已生成的 HTML。
- **定时任务「JSON → HTML 模板填充」(模板数据转换器)**: a third scheduled-task execution mode. In the create/edit dialog (`ScheduledTasksPage.tsx`), selecting the built-in agent **「模板数据转换器」** (`execution_agent_name === "template-json-builder"`, `TEMPLATE_BUILDER_AGENT_ID`) reveals a 「HTML模板」 select (`useHtmlTemplates` → `GET /api/scheduled-tasks/html-templates`) + a **.json 上传** button (reads the file's text into the prompt box) and **hides** the 必须生成 HTML/Markdown switches (this mode always outputs HTML). The chosen template persists as `execution_context.template_config.template_id` (`TemplateFillConfig` in `core/scheduled-tasks/types.ts`). At run time the backend converts the source JSON (the task prompt) into that template's `DATA` structure, validates (retry-on-fail), fills the template, and stores an HTML page previewable via the existing run-detail HTML preview. The source can be **pure JSON, plain text, or text-with-embedded-JSON** — the backend pre-extracts any embedded JSON and the agent's `SOUL.md` maps it (or the plain text's semantics) to the template's schema skeleton. **Chat-page debug entry (only this agent's `AgentChatPage`)**: when `agent_id === "template-json-builder"`, the chat header shows a 「页面模板」 select + a 「渲染预览」 button — after a normal Q&A run, the button takes the **latest AI reply**, POSTs it to `POST /api/scheduled-tasks/template-fill/render` (`renderTemplateFill`), and pops a dialog rendering the filled HTML in a `sandbox="allow-scripts"` iframe plus the structure-validation status/errors/gaps — for debugging the agent's conversion effect without creating a scheduled task. Gated strictly on the agent id, so other agents' chat pages are untouched. See the backend CLAUDE.md「Template-fill mode」for the engine (`deerflow/runtime/scheduler/template_fill.py`), agent seed, dispatch, and the render API.
- **AI 写作·对话版(对话驱动写作台)**: a **parallel new entry** beside the classic AI-writing page (classic page/routes untouched) — route `/page/canvas/ai-writing-chat` (`OpenCanvasRoutes.tsx`), sidebar 「问答管理 → 课题研究(对话版)」. Page `open-canvas/pages/AIWritingChatPage.tsx` fully **reuses the engine** (`AIWritingContext` state machine + LangGraph `useStream`, `AIWritingHistoryProvider`, right-side `AIWritingDraftPanel`) but replaces the presentation: left = `components/ai-writing-chat/WritingChatPanel.tsx` (timeline + **button-only intervention cards** `ChatInterventionCards.tsx` — the five pause cards copied from `InterventionCard.tsx` with all inline textareas removed, confirm/action buttons kept — plus a bottom **unified smart composer**). Free text goes through two-level intent resolution (`open-canvas/api/ai-writing-intent.ts`): deterministic short-phrase fast path (确认/继续/重新搜索/重写大纲…; high-cost actions never fast-pathed) then `POST /api/ai-writing/sessions/{id}/intent` — the backend reads the graph checkpoint (authoritative pause point from the pending interrupt) and routes via `deerflow/agents/ai_writing/intent_router.py` (LLM + strict per-pause action whitelist aligned to the graph's real resume actions, confidence gates: finalize/force_finalize/覆盖式 re_search need ≥0.85 else clarify, payload key-whitelist cleaning). Results map to `submitIntervention`/control (暂停/继续/后台挂起)/QA bypass (`answer` rendered as a chat bubble, never touches graph state)/clarify (amber follow-up bubble with multi-turn context). **Two-state layout**: idle (未开始写作) renders the **classic setup experience unchanged** — `WritingSetupChat` + collapsible `AIWritingPanel` form under `WritingFormProvider` (same as `AIWritingPage`'s idle branch); once writing starts (or history view opens) it switches to the chat workbench. **Unified chronological feed** (`ChatFlowTimeline.tsx`): intent-layer chat bubbles are interleaved INTO the progress-event timeline by anchor (= `progressEvents.length` at message creation), so events triggered by a user message render **below** it (Google-AI-Studio-style single stream, not timeline-above/chat-below); composer-driven interventions suppress the duplicate 「我的要求」card (`suppressedRequirementIndices`). **素材不足自动续跑** only at `material_confirm` (the only pause the graph supports re-search from): needResearch caches the payload as a pending intent, submits `re_search + userQuery`, and auto-submits the pending intent when the new material-confirm pause arrives (cancellable pill). Stage chips + per-stage placeholder + 「当前交互对象」status badge. Backend tests `tests/test_ai_writing_intent.py`. Plan doc: `frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md`.
- **策略优选**: route `/page/strategy/qa/strategy-selection`, sidebar 「问答管理 → 策略优选」. The standalone `src/strategy-selection/` workbench has two horizontal split stages: Step 1 keeps intent-understanding conversation cards on the left and an editable task draft plus angle selection on the right; Step 2 keeps multiplexed parallel strategy cards and automatic judging on the left while the right stays dedicated to the selected-strategy basket and final Markdown synthesis. It consumes the existing `POST /api/parallel-agents/run/stream` protocol, isolates output by stable agent id, supports expanded per-agent dialogs, user selection, Markdown editing/copy/download, and shared server-side DOCX export. A clearly marked neutral Taiwan-Strait risk-management demo is loaded by default for offline UI acceptance. Administrators can edit the SOUL and skills of the nine built-in functional agents through the page dialog; the backend seeds `strategy-selection-{intent,angle-*,judge,solution}` only when their directories are missing, preserving later admin changes. Pure parsing/SSE tests live in `src/strategy-selection/lib.test.ts`; backend seed tests live in `tests/test_strategy_selection_seed.py`.
- **轻应用中心 (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). **简介模式** left-nav is a separate overlay: `/api/compact-menu-overrides` stores two independent sets (type `A` / `B`); each website picks one via `runtime-config.js` `VITE_COMPACT_MENU_TYPE`.
- **白名单管理 (Login Whitelist, admin-only)**: gates **who may log in**, run as a **blocklist (黑名单模式)**. Two pieces: a global master switch (`system_settings.json → login_whitelist.enabled`, surfaced by **admin-only** `GET|PUT /api/system-settings/login-whitelist`) + a per-user **放行** flag (`users.approved` column, migration `20260625_02`). Users **self-register** as usual and **every new account defaults to `approved=True`** — so a user who has never logged into this system before is allowed straight through; the switch only blocks users an admin has explicitly **取消放行** (`approved=False`). (`create_user`/`User`/`UserRow` all default `approved=True`; admins are always approved; existing rows are backfilled `True`.) Login interception is the single helper `enforce_user_approved(user)` in `app/gateway/routers/auth.py`, called in all three login endpoints (`/login/{local,username,token}`) **after** the account is resolved/created and **before** the JWT is issued: switch off → everyone passes; `system_role=="admin"` → always passes (anti-lockout); else `approved=False` (admin-revoked) → 403 `{code:"PENDING_APPROVAL"}` (the frontend's `extractErrorMessage` surfaces the message and login throws before writing any auth state, so no half-login). Admin approves on `pages/LoginWhitelistPage.tsx` (route `/page/strategy/admin/login-whitelist`, entry「白名单管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both sidebar modes): a top master-switch + a list of all registered users (`GET /api/v1/auth/users`, now carrying `approved`) with a per-row 放行 Switch (`PUT /api/v1/auth/users/{id}/approval`, admin-only; revoking only blocks the **next** login — `token_version` is left untouched, existing sessions are not force-killed). Client/hooks: switch in `strategy-components/api/login-whitelist.ts`, user list + approval in `core/auth/{api,hooks}.ts` (`useSetUserApproval`). Backend tests: `tests/test_login_approval.py`. **账号级登录口令与密码**已统一,个人口令优先于系统共享口令;新密码保存哈希,旧明文口令兼容校验。管理员重置使用 `PUT /api/v1/auth/users/{id}/login-password`(别名 `/reset-password`),同时更新两种历史凭据字段并撤销旧会话,不再支持清空密码或读取新密码明文。未设置个人密码时使用配置共享口令(默认 `123ewq`);登录开关关闭时保留旧入口兼容行为,开启后禁止免密进入。详见上方「账号登录、自主注册与单点登录」。
- **敏感词管理 (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.
- **技能地址管理 (Skill Address Management, admin-only)**: 扫描运行中的技能(`skills/{public,custom}` 下所有 `.md`/`.py`)里的 **http(s) URL 与 IP/IP:端口**,按唯一地址聚合全部出现位置(跨 .md/.py),支持**批量替换**(如把 UAT 地址一次性改成生产)。主体抽成可复用组件 `SkillAddressesPanel`(`pages/SkillAddressesPage.tsx` 导出,默认导出 `SkillAddressesPage` 仍保留旧路由 `/page/strategy/admin/skill-addresses` 作直链回退),**作为「技能地址管理」标签页嵌入管理员「技能管理」页 `pages/AdminSkillsPage.tsx`**(该页加 Tabs:「技能列表」+「技能地址管理」;入口在「设置和更多」下拉的「技能管理」`workspace-nav-menu.tsx` → `/page/workspace/admin/skills`,不再单列于 `components/page-sidebar.tsx` 左下角设置下拉):打开自动扫描并带**进度条**(扫描逐技能 / 应用逐文件 X/N,应对 150+ 技能),URL/IP 类型过滤 + 搜索 + 「片段批量套用」(如所有 `uat.4.cn` → `prod.4.cn`)、每地址「替换为」输入框(可展开看 `file:line` 片段)、内联**预览**、**应用**、**多关键词检索**(空格分隔全部命中),以及**修改记录**面板——每次应用生成一条记录(显示时间/改了哪些地址 from→to/文件数/处数),可**针对单次记录回退**(二次确认)。client + NDJSON 流式解析在 `strategy-components/api/skill-addresses.ts`。后端 `/api/skill-addresses`(**仅管理员**):所有文件 IO 走 `asyncio.to_thread` 不阻塞事件循环;`GET /scan`(+`/scan/stream`)、`POST /preview`、`POST /apply`(+`/apply/stream`)、`GET /backups`、`POST /rollback/{id}`;**子串安全替换**(基于 token span,不会误伤子串)、`expected_total` 乐观锁(409)、写前自动磁盘备份到 `{skills_root}/.address-edits/`(同时写一份 `{id}.manifest.json` 记录本次替换明细,供修改记录展示)、应用后刷新技能系统提示缓存。纯引擎 `deerflow/skills/address_scan.py`,router `app/gateway/routers/skill_addresses.py`,tests `tests/test_skill_addresses.py`。范围仅运行中技能,不动 `deploy/minimal/skills/`。
- **按钮管理 (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, openMode, loginParams, appendAuth, authTokenParam, authNameParam, 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). **`host`(宿主路由)** asks the embedding parent to navigate: `runTaskButton` sends `window.parent.postMessage({ type:'HOST_NAVIGATE', path, queryParams:{ [idParam]: Number(taskId) } }, hostOrigin)` — `target` is the host route (e.g. `/task/item-aiceh/step-analysis-audience`), `appendTaskId`/`idParam` become numeric `queryParams` (task id only), origin from `runtime-config.js` `VITE_HOST_NAVIGATE_ORIGIN` (else ancestorOrigins/referrer; never `*`). Independent-tab clicks toast and do nothing. **`url` buttons support two independent, coexisting login-append mechanisms**: (1) **`loginParams` (追加登录参数, like 应用管理/Light App Center)** — a list of `{key, source, customValue}` resolved at click time: `runTaskButton` reads `userInfo` (via `readUserInfo` from `strategy-components/lib/light-app`, embed-isolated through `authStorage`) and appends `?{key}={value}` for each (`source` = a userInfo field such as `accessToken`/`yUserId`, or `other` → literal `customValue`); empty list = nothing appended. Reuses `LOGIN_SOURCE_OPTIONS` from light-app; stored as JSON column `task_buttons.login_params_json` (`PortableJSON`, migration `20260625_01`). (2) **`appendAuth` (追加登录态)** — appends `?{authTokenParam}={token1}&{authNameParam}={username}` (default param names `token`/`username`) so the跳转目标外部系统 can identify the current user — e.g. `…/action/sentiment?token=<JWT>&username=lizhaoxing`. **Gated on token login**: `token1` = the `?authToken=` used by token-exchange login; `username` = the raw login name the backend resolved from `getTokenInfo`. Both are stashed at login by `persistLoginCredentials` into `login.token1`/`login.username` (`core/auth/login-credentials.ts`, scoped via [[scoped-storage]] so嵌入/独立会话隔离 + 随独立会话迁移). Only token login writes them → a non-token-login session has no `token1`, so `runTaskButton` silently skips the auth append (the jump still works, just without those two params). The frontend reads `username` straight from the new `UsernameLoginResponse.username` field (the stored email local-part is lossy — lowercased/normalized — so not used), **not** by decoding the JWT. Stored as columns `task_buttons.{append_auth, auth_token_param, auth_name_param}` (migration `20260625_02`). The admin page renders both editors for `url` buttons (loginParams 虚线框 + 追加登录态 switch). **`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. **Bottom 快捷跳转 bar groups by prev/next**: `TaskJumpBar` renders only「上一步/下一步」-type buttons in the bottom bar — a `prev` group (id 含 `prev` 或文案「上一步」, 描边次要样式 + ←图标) rendered **左侧**, then a `next` group (id 含 `next` 或文案「下一步」, 实心主色) on the **右侧** (container `justify-end`); everything else goes to the right-edge floating menu. The default 上一步 button (`rwfx-prev`, `url`, target = `DASHBOARD_AGENT_ROUTE` `/page/strategy/dashboard-agent`, `appendTaskId` + `idParam=taskId` → `?taskId=任务id`, `openMode=self`) 默认指向**应用内**「大屏绘制」Line truncated
- **实时并发监控 (Concurrency / System-Pressure Monitor, admin-only)**: a live panel mounted at the **top of the admin 排行榜 page** (`components/workspace/admin/concurrency-monitor.tsx` `ConcurrencyMonitorPanel`, rendered in `pages/AdminUserLeaderboardPage.tsx`) showing **当前并发的大模型调用数 + 列表(用户/智能体/类型/已运行时长)**, each row with a 「停止」button (and a 「全部停止」) that **truly aborts** that run's in-flight model stream via `RunManager.cancel` (`POST /api/admin/active-runs/{run_id}/cancel`) — to relieve pressure when 使用人数过多. Two line charts (minute/hour toggle): **并发量折线图** (peak/avg, `GET /api/admin/active-runs/concurrency`, fed by a lightweight background sampler into `concurrency_samples`) and **大模型出字速度折线图** (tokens/sec, `GET /api/admin/active-runs/token-speed`, aggregated from `llm_call_metrics`) so a dip pinpoints where the bottleneck is. A **「后台采样」Switch** (`system_settings.json → concurrency_monitor.enabled`, **default off / opt-in**, `GET|PUT /api/admin/active-runs/settings`) turns the background sampling on/off **at runtime, no restart** (the live concurrency count + 「停止」 work even while sampling is off — only the 并发量 history chart needs it on); everything is designed to **never impact production** (one tiny INSERT/15s, retention-purged, best-effort). Client/hooks: `core/admin/active-runs.ts` + `core/admin/hooks.ts` (`useActiveRuns`/`useConcurrencySeries`/`useTokenSpeedSeries`/`useCancel*`/`useMonitorSettings`). See the backend CLAUDE.md「Admin Concurrency Monitor」.
- **会话冲突与模型工具流恢复**: when a user submits a new question while the previous turn is still streaming, the backend's `RunManager.create_or_reject` rejects with HTTP 409 (`services.py` returns the Chinese detail「当前对话还在生成回答…」). `core/threads/hooks.ts` detects the conflict and routes it through `confirmOrRejoin`. Run-creation SSE responses expose `Content-Location` plus the SDK `Location` reconnect endpoint; `core/api/api-client.ts` records the last consumed event id, so an in-page rejoin resumes after that cursor instead of replaying tool arguments from `-1`. `write_file` argument updates carried by `messages-tuple` count as business activity. A known active run is probed only after 90 seconds without a business frame; the watchdog hides `lg:stream`, stops only the old browser reader, and rejoins without cancelling the backend run. Clean EOF, transport errors, 409 and watchdog recovery share one single-flight Promise to prevent duplicate joins/finalization. The backend `PatchedChatOpenAI` separately normalizes confirmed cumulative argument snapshots and bounded compatible response shapes while preserving standard deltas; its content-free diagnostics never log prompts, arguments or file bodies.
- **React #185 与流式刷新保护**: every direct LangGraph `useStream` surface (main/agent chat, AI writing, Canvas and Studio notebook) uses shared `STREAM_RENDER_BATCHING = true`. The installed SDK implements numeric `throttle: 16` as a trailing debounce, which can indefinitely postpone UI updates during a continuous fast stream; `true` retains asynchronous next-task batching without requiring 16ms silence. `stream-error-classification.ts` detects `Maximum update depth exceeded` / production `#185` through bounded, cycle-safe wrappers. Main chat filters the SDK's stored error and duplicate submit rejection; `react-ui-error.ts` gives each send at most one automatic UI recovery, then pauses rejoin without cancelling the server run. Token activity must not reset that budget. The top-level `ReactUiErrorBoundary` catches only this render/commit error, shows a static friendly reload panel, and never automatically remounts the failing tree. Other errors are not swallowed. Shared toasts are deduplicated for 30 seconds; diagnostics retain error type, recovery phase, thread/run identifiers and component stack but never message/tool content. Real SDK SSE replay covers partial reasoning and write_file Markdown before generation ends; the browser boundary check triggers a real production React layout-effect loop and requires manual reload to recover. These safeguards do not prove the unknown production component loop is fixed.
- **流式游标作用域**: resumable cursors belong to the current SDK message accumulator, not a module-global map. `createStreamAPIClient` isolates same-reader recovery; newly mounted chats and real thread switches must replay the retained prefix instead of borrowing another reader's consumed position. Clearing replaces the cursor map so late old-reader events cannot pollute the new scope. The shared `getAPIClient` does not rewrite replay-from-start cursors. `stream-cursor-replay.test.ts` uses the real SDK to protect against both duplicate tool arguments on reconnect and missing prefixes on reopening.
- **单智能体任务深链聊天记录(2026-10-19)**: `3qfx` / `rwfx` / `xdfx` 已不再通过 `useTaskThreads` 扫描、过滤通用 `threads_meta` 列表;`TaskFxWorkspace` / `TaskFxIndexResolver` 统一调用 `useTaskDeeplinkThreads` → `GET /api/task-deeplink-threads?task_id=&go_path=`,读取独立表 `task_deeplink_threads` 的 `(task_id, go_path)` 索引,再按 `thread_id` 关联 canonical `threads_meta` 标题/状态(消息与 checkpoint 仍由 LangGraph 管理)。新会话 metadata 写 `taskRecordId`、`taskGoPath`、`thread_type=task_deeplink` 并由 thread-meta 仓储同事务登记;`3qfx/rwfx` 的 `taskRecordId` 是任务 id,`xdfx` 是 URL 原始行动 id(真实任务 id 仍保留在 `metadata.taskId` 维持共享访问语义)。普通聊天记录默认隐藏该 thread type;显式 taskId 查询仍可读取。迁移 `20261019_01` **只建表、不回填旧数据**,因此上线前旧深链会话不会出现在新列表。`/api/open/3qfx/ask` 同样写专用索引。Tests: `packages/harness/tests/test_task_deeplink_threads.py`, `src/core/auth/task-purpose-metadata.test.ts`, `src/core/threads/hidden-chats.test.ts`。
- **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/taskType`; opening text maps `taskType` 1/2/3 to 打击/塑势/防御) 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). **xdfx additionally partitions its chat records by 行动id (action_id), NOT by task_id**: `resolveTaskDeeplinkTarget` sets `partitionByAction:true` + keeps the raw action_id as `TaskContext.actionId`, so new threads are tagged `metadata.{taskId,actionId}` (taskId kept only to preserve the backend「任务深链对话全局共享」semantics, which keys off `metadata.taskId`) and the conversation list filters by `actionId` (+`agent_id`) — different actions of the same task get separate lists. xdfx's first-question opening text also appends `行动id(action_id)为…` (see `buildOpeningText` / `taskThreadMetadata`). 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, actionId?)` — filtered by **both** `metadata.taskILine 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`。(2.5) **`?hideChrome=1`** — **仅**去全局 chrome(Header 导航栏 + PageSidebar 侧边栏),**不**强制主题、**不**隔离鉴权(区别于 `embed`:只想要一个干净全屏页面,如「大屏绘制」`/page/strategy/dashboard-agent?taskId=…&hideChrome=1`)。新增 `EmbedSession.hideChrome` 字段 + `readHideChromeParam()` + `isChromeHidden()`(取 `embed || hideChrome` 之并),与 `hideJump` 完全对称;`PageRoutes.tsx` 的 `PageLayout` 把 `chromeHidden`(`isChromeHidden() || readHideChromeParam(location.search)==="on"`)并入 `pageSidebarAllowed`,且其**优先级高于** dashboard-agent 路由原本的强制全局 chrome(`forceChromeForDashboardAgent`)。`hideChrome=0` 可显式关闭。(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 提示。
- **操作日志(Y-Log)上报** — 用户的关键操作(登录登出/查询/查看/增删改/启停/导入导出/问答等)成功后,**前端直连**外部接口 `POST {write_url}`(默认 `https://ch1.b.uat.4.cn/api/y-log/write`)记一条审计日志。核心模块 `src/core/log/`:`y-log.ts`(`writeYLog(params)` + `OptType` 枚举 0/1/3..12;**异步即发即忘、永不 await、永不抛错、失败静默**,自动把完整 url 转相对路径去 ip/host、对象入参/返回自动 `JSON.stringify` + 50k 裁剪、`optResult` 恒 0 只报成功),`y-log-config.ts`(从公开只读 `GET /api/public/config/y-log` 拉 `{enabled, writeUrl}`,模块级缓存 + 去重 + 默认兜底;`App.tsx` `AppProviders` 启动预热 `fetchYLogConfig()`),`y-log-token.ts`(token1 = token 登录的 `?authToken=`,经 [[scoped-storage]] 的 `authStorage*` 存取,嵌入态自动隔离)。**双门控**:仅当①存在 token1(即用 token 登录,`LoginPage` 成功后 `persistYLogToken(authToken)`,登出 `account-settings-page.tsx` 先报后清 token1)且②配置 `enabled && writeUrl` 才上报;否则一律不发。`optDetail` 统一「CM助手-全量-…」(**禁内部框架名**)。埋点**广覆盖**各 API client 的成功路径——原则是「一个用户操作(查看/查询/新增/编辑/删除/启停/导入导出)= 一条日志」,每个 API client 的**单条详情 GET(查看→view 4)/ 列表查询 GET(search 3)/ 新增 POST(create 9)/ 改 PUT·PATCH(edit 5)/ 删 DELETE(delete 6)/ 启停(enabled 11 / disabled 10)/ 导入导出(import 7 / export 8)**都各落一条,仅跳过高频 typeahead/状态轮询/纯 bootstrap config 读。覆盖文件:`strategy-components/api/{sensitive-words,menu-overrides,task-buttons,skill-addresses,light-apps,business-mapping}.ts`、`roundtable-planning/api/{drafts,task-drafts,roundtable-jobs,recommend,chains,multi-agent,dashboard-sessions}.ts`、`core/{agents,scheduled-tasks,knowledge,positions,tags,studio,system-settings,memory,mcp,models,custom-prompts,user-preferences,notifications,recommended-questions,user-qa,curator,admin,thread-shares,roundtable-draft-shares,tool-metrics,llm-metrics,note,artifacts}/api.ts`、`core/api/markdown-docx-export.ts`。**问答(Q&A)改为「一次大模型调用 = 一条日志」**:在共享的 `core/threads/hooks.ts` `useThreadStream` 的 `onLangChainEvent` 里监听 `on_chat_model_end`,每次模型调用结束就上报一条(optType 12,`reqParam` 取本次 input 的最后一条 user 文本 + 模型名,`returnParam` 取本次输出文本)——一个问答轮次里 lead agent / 子代理的**每次** LLM 调用都各记一条,覆盖所有走 `useThreadStream` 的页面(`ChatPage`/`AgentChatPage`/创建智能体/iframe/会商等);`ChatPage`/`AgentChatPage` 的 `onFinish` 仍额外保留一条轮次汇总。后端仅新增公开只读配置:`deerflow/config/y_log_config.py`(`YLogConfig{enabled,write_url}`)挂到 `AppConfig.y_log`,`app/gateway/routers/public_config.py` 加 `GET /api/public/config/y-log`,地址写在 `config.yaml` 的 `y_log` 段(mtime 热重载,前端无需重建);**不做后端代理**。Tests:`tests/test_y_log_config.py`。
### Configuration
普通问答与智能体问答的 `write_file` 流式展示:`namedStreamingWriteFilePath` 统一判断路径是否可用;缺少路径、路径尚未完整或只有占位名时,不生成虚拟文件来自动打开沙箱,而由 `message-group.tsx` 在步骤内用绿色小字展示正文。步骤参数合并 `tool_calls` 与 `tool_call_chunks`,后续收到真实路径时复用原工具调用 ID 恢复正常文件预览;`outputs` 下真实文件的自动打开和沙箱流式预览保持原流程。
沙箱文件正在生成时,ArtifactsProvider 的 `select` / `openStreamedArtifact` 阻止切到其他文件;手动操作提示「当前文件正在生成,请稍等片刻,完成后就可以切换查看其他文件。」,自动选择静默跳过。ChatBox 按选中文件的未完成 write_file 和运行状态注册锁,预览组件同时覆盖流式写入及全文改写;完成、停止或卸载时移除所属锁。同一个文件的虚拟预览和真实路径视为同一目标。
Backend config lives in `offline-backend-20260512/backend/config.yaml`. Values starting with `$` resolve as environment variables (e.g., `$OPENAI_API_KEY`). MCP servers and skills are configured in `extensions_config.json` in the same directory.
## Detailed Backend Reference
+739
View File
@@ -0,0 +1,739 @@
# DeerFlow 接口卡顿独立诊断脚本使用说明
配套脚本:[`diagnose_deerflow_latency.py`](./diagnose_deerflow_latency.py)
## 0. 最简单的用法(推荐)
把脚本复制到 DeerFlow 所在服务器,然后直接运行:
```bash
python3 diagnose_deerflow_latency.py
```
脚本会显示中文向导。你只需要:
1. 粘贴卡顿接口 URL;
2. 选择普通 GET、登录 POST 或 Agent SSE;
3. 登录/Agent POST 时再提供请求 JSON 文件;
4. 根据提示选择是否需要 Bearer Token 或 Cookie。
5. 确认脚本是否运行在实际部署服务器上,避免把个人电脑的 CPU/内存误认为服务器指标。
脚本会显示 `[1/5]` 到 `[5/5]` 的进度,最后直接输出“**一键判断**”,告诉你当前证据更偏向:
- Nginx/入口代理;
- MySQL/数据库;
- DeerFlow 并发或热点路径;
- CPU、内存、磁盘等服务器资源;
- DNS、TCP、TLS 等网络问题。
如果只是普通 GET,也可以一行执行:
```bash
python3 diagnose_deerflow_latency.py 'https://你的域名/卡顿接口'
```
一行模式只请求目标接口一次,不自动压测、不跟随重定向、不复制请求到本机直连地址。需要登录态时,可使用专门的诊断环境变量:
```bash
export DEERFLOW_DIAG_TOKEN='你的测试 Token'
export DEERFLOW_DIAG_ON_SERVER=1
python3 diagnose_deerflow_latency.py 'https://你的域名/api/skills?sort=time_desc'
unset DEERFLOW_DIAG_TOKEN DEERFLOW_DIAG_ON_SERVER
```
Token 值不会显示或写入报告。不要使用生产管理员的长期 Token。
## 1. 工具定位
这是一个可以单独复制、单独运行的诊断脚本,不是 DeerFlow 后端补丁。
- 不需要重新发布或替换后端。
- 不需要把脚本放进 DeerFlow 源码目录。
- 不需要安装 Python 第三方包。
- 不会修改 Nginx、MySQL、Docker 或 DeerFlow 配置。
- 默认只进行 HTTP 测量和只读状态采集。
- 支持 Python 3.9 及以上版本。
建议把脚本复制到发生卡顿的 Linux 服务器,在卡顿正在发生时运行。只有从服务器本机运行,才能同时采集 CPU、内存、磁盘、连接队列、Nginx、Docker 等现场信息。
> 登录接口和 Agent 接口通常是 POST,请求本身可能创建会话或任务。脚本默认只发送一次,不会自动压测。请使用测试账号和测试数据。
## 2. 能排查什么
脚本从以下层次收集证据:
1. **网络和 HTTPS**
- DNS 解析时间
- TCP 建连时间
- HTTP 代理 CONNECT 时间
- TLS 握手时间
- 请求上传时间
- 请求发完到首响应的等待时间
- 响应体读取时间
2. **Nginx 和系统连接容量**
- 公网入口与 `127.0.0.1:8001` 直连的耗时差异
- 监听队列与 TCP 状态
- Nginx worker 数量、`worker_connections` 和文件句柄限制
- 可选的 Nginx `stub_status`
- 502、503、504、upstream timeout、too many open files 等日志模式
3. **MySQL**
- TCP 建连
- 多次新连接执行 `SELECT 1` 的耗时
- `Threads_connected`、`max_connections` 等状态
- 活动时间较长的会话数量
- 数据锁、元数据锁等待
- performance schema 聚合信息
MySQL 检查仅执行预置的只读查询,不保存 SQL 正文。
4. **DeerFlow 请求排队和热点路径**
- `/api/health`
- `/api/v1/auth/options`
- 登录态下的 `auth/me`、Agents、Skills 接口
- 慢接口执行期间健康接口是否同时变慢
- 可选的管理员活动运行数和模型并发限制
- Agent SSE 首包时间
5. **服务器和容器容量**
- CPU、load、iowait、steal
- 内存、Swap、Linux PSI
- 磁盘忙碌度和剩余空间
- 进程 CPU、RSS、线程数、FD 使用率
- cgroup/Docker CPU 和内存限制
- Docker OOM、重启次数
## 3. 准备脚本
把单个 Python 文件复制到目标服务器:
```bash
scp diagnose_deerflow_latency.py user@server:/tmp/
```
登录服务器后检查 Python:
```bash
python3 --version
python3 /tmp/diagnose_deerflow_latency.py --help
```
脚本可以在任意目录执行。只有使用 `--config` 时才需要知道 DeerFlow 的 `config.yaml` 路径。
## 4. 第一次运行:只测一个接口
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/health' \
--count 5 \
--server-checks \
--output /tmp/deerflow-latency.json
```
终端会显示中文摘要,完整脱敏结果写入 `/tmp/deerflow-latency.json`。
Linux 上默认会自动启用服务器检查;显式写上 `--server-checks` 更清楚。普通用户权限不足时,部分 Nginx、Docker 或进程信息会显示为“未完成检查”,但不会导致整个诊断失败。
默认还会对目标 origin 的 `/health`、`/api/health` 和 `/api/langgraph/health` 各进行一次安全 GET 探测。如果不希望产生这些额外请求,增加 `--no-health-baselines`。
## 5. 推荐排查顺序
### 第一步:测公网入口
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/skills?sort=time_desc' \
--count 5 \
--server-checks \
--output /tmp/01-public.json
```
### 第二步:同时对比 Gateway 本机直连
确保两条 URL 的路径、查询参数和业务行为一致:
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/skills?sort=time_desc' \
--compare-url 'http://127.0.0.1:8001/api/skills?sort=time_desc' \
--count 5 \
--server-checks \
--output /tmp/02-public-vs-direct.json
```
如果请求带 Token、Cookie、任意自定义 header、`--query-env`、请求体,或使用 POST,向不同 origin 发送这些内容前必须明确增加:
```text
--allow-cross-origin-compare
```
该参数意味着你已经确认比较地址可信。POST 登录和 Agent 请求不建议使用 `--compare-url`,应分两次各运行一次,避免重复创建状态。
### 第三步:增加 DeerFlow 基线接口
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/skills?sort=time_desc' \
--count 5 \
--deerflow-suite \
--server-checks \
--output /tmp/03-deerflow-suite.json
```
未提供登录凭据时,只检查公开的 health 和 auth/options。提供 Bearer Token 或 Cookie 后,才会增加 `auth/me`、Agents、Skills 等登录态基线。
### 第四步:安全 GET 接口使用干扰探针
下面的命令会在慢接口执行期间,每 0.25 秒探测一次 `/api/health`:
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/skills?sort=time_desc' \
--count 5 \
--deerflow-suite \
--interference \
--server-checks \
--output /tmp/04-interference.json
```
如果慢接口执行时 health 也明显变慢,更偏向 Gateway worker、事件循环、CPU 或 IO 被阻塞。如果 health 始终很快,更偏向该请求自身的数据库、模型或下游服务等待。
`--interference` 会额外请求一次目标接口,仅建议用于 GET/HEAD/OPTIONS 等无副作用接口。
### 第五步:检查 MySQL
先做不带账号的 TCP 连通性检查:
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/health' \
--server-checks \
--mysql-host '10.0.0.20' \
--mysql-port 3306 \
--output /tmp/05-mysql-tcp.json
```
若需查询连接、锁和 performance schema,请参见“经过认证的 MySQL 只读检查”。
### 第六步:卡顿时再运行一次
间歇性问题恢复后再执行,只能反映恢复后的状态。最好在下面任一现象出现时立即运行:
- 登录等待很久;
- Skills/Agents 页面一直转圈;
- Agent 长时间没有返回 SSE 响应实体字节;
- 出现 429、502、503 或 504;
- 所有页面同时变慢。
## 6. 鉴权接口
### 6.1 Bearer Token
不要把 Token 直接写进命令行。使用环境变量:
```bash
read -rsp 'Bearer Token: ' DF_TOKEN
export DF_TOKEN
echo
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/skills?sort=time_desc' \
--bearer-env DF_TOKEN \
--count 5 \
--deerflow-suite \
--server-checks \
--output /tmp/skills-auth.json
unset DF_TOKEN
```
Token 值不会写入报告。
### 6.2 Cookie
```bash
read -rsp 'Cookie header value: ' DF_COOKIE
export DF_COOKIE
echo
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/protected/path' \
--cookie-env DF_COOKIE \
--count 5 \
--output /tmp/cookie-request.json
unset DF_COOKIE
```
环境变量值应为 Cookie header 的值,例如 `session=...; other=...`,不要包含 `Cookie:` 前缀,也不要把真实值发给其他人。
### 6.3 自定义请求头
普通非敏感头:
```text
--header 'Accept: application/json'
```
敏感头使用环境变量:
```bash
read -rsp 'API key: ' DF_API_KEY
export DF_API_KEY
echo
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/path' \
--header-env 'X-API-Key=DF_API_KEY'
unset DF_API_KEY
```
### 6.4 URL 查询参数中的敏感值
不要把 ticket、token、password 等直接写进 URL。使用:
```bash
read -rsp 'Ticket: ' DF_TICKET
export DF_TICKET
echo
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/login/callback' \
--query-env 'ticket=DF_TICKET' \
--count 1 \
--output /tmp/ticket-request.json
unset DF_TICKET
```
报告中的 URL 查询参数值会统一脱敏。
## 7. 登录 POST 接口
登录请求可能创建登录会话,所以默认只发送一次。先准备请求体文件,并限制权限:
```bash
umask 077
vi /tmp/login-request.json
chmod 600 /tmp/login-request.json
```
例如请求体可能是:
```json
{
"username": "diagnosis-user",
"password": "请填写测试账号密码"
}
```
实际字段应以你的登录接口为准。运行:
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/v1/auth/login' \
--method POST \
--header 'Content-Type: application/json' \
--data-file /tmp/login-request.json \
--count 1 \
--read-mode full \
--first-byte-timeout 60 \
--total-timeout 90 \
--server-checks \
--output /tmp/login-diagnosis.json
```
完成后删除临时请求体:
```bash
rm -f /tmp/login-request.json
```
注意:
- 请求体内容不会写入 JSON 报告。
- 不要为登录 POST 增加 `--interference`。
- 不要同时使用 `--compare-url`,公网和直连应分别执行一次。
- 不要增加 `--count` 或 `--concurrency`,除非确认可以重复登录并明确加上 `--allow-unsafe-replay`。
如果 HTTP 状态很快返回 401/403,这仍然说明链路和服务响应很快;它不代表登录业务验证成功。请结合 `status_counts` 判断。
## 8. Agent SSE 首包诊断
Agent 请求通常是 POST,并返回 `text/event-stream`。使用 `first-byte` 模式,只等待首个响应实体字节,不等待整个 Agent 任务结束:
```bash
read -rsp 'Bearer Token: ' DF_TOKEN
export DF_TOKEN
echo
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/实际Agent流式接口' \
--method POST \
--header 'Content-Type: application/json' \
--header 'Accept: text/event-stream' \
--bearer-env DF_TOKEN \
--data-file /tmp/agent-request.json \
--count 1 \
--read-mode first-byte \
--first-byte-timeout 180 \
--total-timeout 240 \
--server-checks \
--output /tmp/agent-first-byte.json
unset DF_TOKEN
```
请使用测试会话。客户端在收到首个响应实体字节后会关闭连接,但服务端任务是否继续运行取决于实际接口实现。
`first-byte` 不解析 SSE 协议边界,因此这个字节不等于一个完整 SSE 事件,也不一定代表模型已经开始生成。它可能来自 SSE 注释、心跳、代理填充,甚至 JSON/HTML 错误正文;必须同时检查 HTTP 状态码和响应 `Content-Type`。
重点看:
- `response_wait` 很高:服务端迟迟没有返回响应头,可能在排队、鉴权、数据库、worker 或上游连接阶段等待;
- 响应头很快,但首个响应实体字节很慢:可能在 Agent、模型并发或模型供应商阶段等待;
- 返回 429:优先检查 DeerFlow 模型并发限制或上游配额;
- 返回 502/503/504:结合 Nginx error log 和本机直连结果。
首个响应实体字节的精确耗时位于 JSON 单样本的 `hops[].timings_ms.first_body_after_upload`;`response_wait` 表示请求上传完成到收到首个响应字节,通常对应响应头开始返回。
## 9. Skills 接口专项诊断
```bash
read -rsp 'Bearer Token: ' DF_TOKEN
export DF_TOKEN
echo
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/skills?sort=time_desc' \
--compare-url 'http://127.0.0.1:8001/api/skills?sort=time_desc' \
--allow-cross-origin-compare \
--bearer-env DF_TOKEN \
--count 5 \
--deerflow-suite \
--interference \
--server-checks \
--config '/实际路径/config.yaml' \
--output /tmp/skills-diagnosis.json
unset DF_TOKEN
```
该组合可以同时判断:
- 公网/Nginx 是否比 Gateway 直连慢;
- Skills 是否比 health、auth 和 Agents 更慢;
- Skills 执行期间 health 是否也被拖慢;
- 技能目录文件量和仅元数据遍历是否异常;
- CPU、iowait、磁盘是否同时出现压力。
## 10. Nginx 连接数专项诊断
脚本在 Linux 上会尝试执行只读的 `nginx -T`、`ss` 和 `/proc` 检查。如果已经配置仅本机可访问的 `stub_status`,可增加:
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/health' \
--server-checks \
--nginx-status-url 'http://127.0.0.1/nginx_status' \
--output /tmp/nginx-diagnosis.json
```
主要证据:
- `active_connections` 接近 `worker_processes × worker_connections`;
- `Recv-Q` 接近监听 backlog;
- 大量 `SYN-RECV`;
- Nginx 日志命中 `worker_connections are not enough`;
- 进程 FD 使用率接近上限;
- 公网明显慢于 `127.0.0.1:8001` 直连。
仅看到大量 ESTABLISHED 或 Waiting 连接,不能单独证明连接数耗尽。SSE 和 keepalive 本身就会保持连接,应结合理论槽位、FD、队列和错误日志判断。
## 11. 经过认证的 MySQL 只读检查
服务器需要安装 `mysql` 命令行客户端。建议为诊断创建权限受限的只读账号,并使用单独的 client 配置文件:
```ini
[client]
host=10.0.0.20
port=3306
user=diagnosis_ro
password=替换为诊断账号密码
database=deerflow
protocol=TCP
ssl-mode=REQUIRED
```
保存后限制权限:
```bash
chmod 600 /secure/path/diagnosis.cnf
```
运行:
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/health' \
--server-checks \
--mysql-defaults-file '/secure/path/diagnosis.cnf' \
--mysql-probes 3 \
--output /tmp/mysql-diagnosis.json
```
TCP 认证要求配置 `ssl-mode=REQUIRED`、`VERIFY_CA` 或 `VERIFY_IDENTITY`。如果 MySQL 只允许本机 Unix Socket,可使用:
```ini
[client]
user=diagnosis_ro
password=替换为诊断账号密码
database=deerflow
protocol=SOCKET
socket=/var/run/mysqld/mysqld.sock
```
普通业务库只读权限通常足以执行 `SELECT 1`,但查看完整 processlist、全局状态以及 `performance_schema` 的锁和 digest 聚合可能需要额外的只读可见权限。权限不足时脚本会保留已完成的检查,并把其余项目标记为部分不可用;请查看报告的 `coverage.unavailable` 和 `server.mysql` 错误字段。不要为了消除这些提示授予写权限或管理员权限,应由 DBA 按最小权限补充所需的监控可见性。
也可以把 MySQL URL 放入环境变量:
```bash
read -rsp 'MySQL URL: ' DF_MYSQL_URL
export DF_MYSQL_URL
echo
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/health' \
--server-checks \
--mysql \
--mysql-url-env DF_MYSQL_URL \
--output /tmp/mysql-diagnosis.json
unset DF_MYSQL_URL
```
TCP URL 必须带 `ssl-mode=REQUIRED`、`VERIFY_CA` 或 `VERIFY_IDENTITY`。不要把数据库密码直接写到命令行。
用户名、密码、数据库名中的特殊字符需要按 URL 规则进行 percent-encoding。
## 12. DeerFlow 活动运行数和并发限制
如果当前账号具有管理员权限,可以读取活动运行数和模型并发配置:
```bash
read -rsp 'Admin JWT: ' DF_ADMIN_TOKEN
export DF_ADMIN_TOKEN
echo
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/health' \
--admin-token-env DF_ADMIN_TOKEN \
--server-checks \
--output /tmp/concurrency-diagnosis.json
unset DF_ADMIN_TOKEN
```
如果管理员 API 使用另一个可信 origin:
```text
--admin-origin 'https://gateway.example.com' --allow-cross-origin-admin
```
报告只保存活动数量、最长运行时间、模型聚合及并发限制,不保存任务正文。
## 13. 小规模并发退化测试
`--concurrency` 是主动并发请求,会增加生产压力。应先使用单并发建立基线:
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/skills?sort=time_desc' \
--count 10 \
--concurrency 1 \
--output /tmp/concurrency-1.json
```
在经过确认的低峰窗口,最多先升到 2:
```bash
python3 /tmp/diagnose_deerflow_latency.py \
--url 'https://example.com/api/skills?sort=time_desc' \
--count 10 \
--concurrency 2 \
--output /tmp/concurrency-2.json
```
不要对登录、创建任务、发送消息等 POST 接口进行并发测试。脚本会拒绝重复或并发执行有副作用的方法,除非显式增加 `--allow-unsafe-replay`。
## 14. 如何读报告
### 14.1 HTTP 时间字段
| 字段 | 含义 | 主要怀疑方向 |
|---|---|---|
| `dns` | DNS 解析 | DNS 服务器、解析链路 |
| `tcp_connect` | TCP 建连 | 网络、防火墙、SYN/backlog、连接压力 |
| `proxy_connect` | HTTP 代理建立隧道 | 前向代理 |
| `tls_handshake` | TLS 握手 | TLS 终止层、证书链、中间设备、CPU |
| `request_upload` | 发送请求头和请求体 | 客户端到服务器上传链路 |
| `response_wait` | 请求发完到收到首个响应字节 | Nginx 上游排队、Gateway、DB、文件扫描、下游服务 |
| `headers_complete_after_upload` | 请求发完到响应头完整 | 响应头返回阶段 |
| `body_read` | 读取响应体 | 大响应、SSE、网络吞吐、代理缓冲 |
| `total` | 单次总耗时 | 整体体验 |
脚本使用新的 HTTP/1.1 连接测量,不等同于浏览器复用 HTTP/2/keepalive 的真实行为。
### 14.2 四类怀疑的判断矩阵
| 观察结果 | 更可能的方向 |
|---|---|
| 公网慢,本机 `127.0.0.1:8001` 快 | Nginx、负载均衡、TLS、入口网络 |
| 公网和直连都慢,health 也同时慢 | Gateway worker/事件循环、CPU、内存、磁盘 IO、整机压力 |
| health 快,但 auth/me、Agents 等多个 DB 路径慢 | MySQL、连接池、锁、数据库磁盘 |
| 只有 Skills 慢,且执行时 health 也慢 | 同步技能目录扫描、慢盘/NFS、单 worker 阻塞 |
| Agent 首包慢,但 health 快 | 模型并发、模型供应商、工具调用或该请求下游 |
| 429 | DeerFlow 并发限制、上游配额或其他限流 |
| 502/503/504 | Nginx 到上游失败、上游超时或服务不可用 |
| TCP 慢且监听队列/SYN-RECV 高 | 连接洪峰、backlog 或处理能力不足 |
| Nginx active 接近理论槽位,FD 也高 | Nginx 连接/文件句柄容量风险 |
| MySQL `Threads_connected` 接近 `max_connections` | DB 连接容量或连接泄漏 |
| MySQL 存在锁等待/长会话 | 锁、长事务或慢 SQL |
| CPU busy/load/PSI 高 | 服务器算力不足或进程热点 |
| iowait/磁盘 util 高 | MySQL、SQLite、技能目录或日志所在存储慢 |
| MemAvailable 很低、Swap/OOM 明显 | 内存不足或容器限制过低 |
单个指标不能直接定根因。脚本的“优先结论”会把多项证据组合起来,并给出下一步建议。
`successful_transport` 只表示 HTTP 传输流程完成。HTTP 401、403、429、500、502 等仍可能计入传输成功,必须同时检查 `status_counts` 和报告中的优先结论。
## 15. 常用参数
| 参数 | 说明 |
|---|---|
| `--url URL` | 目标地址,可重复 |
| `--url-env ENV` | 从环境变量读取目标 URL |
| `--compare-url URL` | 同一请求的另一路径,例如 Gateway 直连 |
| `--method GET/POST` | HTTP 方法 |
| `--bearer-env ENV` | 从环境变量读取 Bearer Token |
| `--cookie-env ENV` | 从环境变量读取 Cookie |
| `--header-env HEADER=ENV` | 从环境变量读取敏感请求头 |
| `--query-env KEY=ENV` | 从环境变量读取查询参数值 |
| `--data-file PATH` | 请求体文件,`-` 表示 stdin |
| `--count N` | 请求次数;GET 默认 5,POST 默认 1 |
| `--concurrency N` | 并发数,默认 1 |
| `--read-mode MODE` | `auto`、`headers`、`first-byte`、`full` |
| `--connect-timeout SEC` | DNS/TCP/TLS 相关连接超时 |
| `--first-byte-timeout SEC` | 等待响应头或首个响应实体字节的超时 |
| `--read-timeout SEC` | 正文空闲读取超时 |
| `--total-timeout SEC` | 单请求硬性总超时 |
| `--deerflow-suite` | 检查 DeerFlow 基线接口 |
| `--interference` | 慢 GET 执行期间持续测 health |
| `--server-checks` | 收集 Linux/Nginx/Docker/日志/数据库状态 |
| `--config PATH` | DeerFlow `config.yaml` 路径 |
| `--log PATH` | 增加一个待扫描日志,可重复 |
| `--nginx-status-url URL` | Nginx stub_status 地址 |
| `--mysql-host HOST` | 只做 MySQL TCP 测量 |
| `--mysql-defaults-file PATH` | 进行 MySQL 认证只读检查 |
| `--admin-token-env ENV` | 管理员只读并发检查 |
| `--output PATH` | JSON 报告路径 |
| `--no-output` | 不生成 JSON 文件 |
| `--json-stdout` | 将完整 JSON 输出到终端 |
查看全部参数:
```bash
python3 /tmp/diagnose_deerflow_latency.py --help
```
## 16. TLS、代理和重定向
- HTTPS 默认校验证书。
- 内部 CA 使用 `--ca-file /path/to/ca.pem`。
- `--insecure` 会关闭证书校验,仅用于明确了解风险的临时诊断,报告会记录安全警告。
- 默认不使用系统 `HTTP_PROXY`/`HTTPS_PROXY`,需要时显式增加 `--use-env-proxy`。
- 也可以使用 `--proxy` 或更安全的 `--proxy-env`。
- 默认不跟随重定向;`--follow-redirects` 只允许同 origin 跳转,跨 origin 会被拒绝。
- 带凭据、环境变量查询值或请求体时,非本机明文 HTTP 会被拒绝。优先使用 HTTPS,不建议使用 `--allow-insecure-http`。
`--allow-unsafe-replay`、`--allow-cross-origin-compare`、`--allow-cross-origin-admin`、`--allow-insecure-http` 和 `--insecure` 都是明确的风险开关,不应放进日常默认命令。
## 17. 日志和权限
脚本会尝试自动发现常见的 Nginx、Gateway 和运行日志,也可以显式提供:
```text
--log /var/log/nginx/error.log --log /path/to/gateway.log
```
报告只保存错误模式的命中次数,不保存完整日志行,避免把业务内容带入报告。
建议先以普通部署用户运行。权限不足时,报告会明确列出缺失项。不要为了方便直接把数据库密码或 Token 写进 `sudo` 命令行;如确需更高权限读取 Nginx/进程信息,应在受控 shell 中重新设置所需环境变量。
## 18. 报告安全
脚本不会保存:
- 请求体和响应体;
- Token、Cookie、密码或敏感请求头值;
- URL 查询参数值;
- MySQL SQL 正文;
- 原始日志行。
报告仍可能包含:
- IP、端口和路径;
- 容器名、模型名、数据库主机名;
- Nginx 和系统容量信息;
- 接口路径和状态码。
把报告发给其他人之前仍应人工检查和脱敏。不要公开上传到互联网。
## 19. 常见问题
### 报告显示“未完成检查”
通常是权限不足、命令不存在或功能未配置。例如:
- 没有 `ss`;
- 当前用户无法运行 `nginx -T`;
- 没有 Docker socket 权限;
- 没有安装 mysql client;
- 没有配置 Nginx stub_status;
- 管理员 Token 权限不足。
这不会使已经采集到的其他证据失效。
### 接口返回 401 或 403
检查 Bearer/Cookie 是否正确,以及接口是否需要特殊请求头。401/403 是 HTTP 响应,不属于 DNS/TCP/TLS 传输失败。
### 公网和直连业务不一致
某些 Nginx 配置依赖原始 `Host`。如果直接访问 `127.0.0.1:8001` 与公网执行的不是同一业务,则两者耗时不能直接比较。可根据实际配置增加非敏感 Host header:
```text
--header 'Host: example.com' --allow-cross-origin-compare
```
仅在确认后端确实需要该 Host 时使用。自定义 `Host` 会同时应用到公网目标和直连目标;不同 origin 的比较存在任意自定义 header 时,脚本要求显式使用 `--allow-cross-origin-compare`。
### 脚本没有抓到问题
间歇性卡顿通常需要在问题发生时运行。可以保留同一套命令,在用户反馈卡顿时立即执行,并同时记录准确时间,之后与 Nginx、Gateway、MySQL 监控对齐。
## 20. 提交结果供分析
建议提供以下信息:
1. 脱敏后的 JSON 报告;
2. 卡顿发生的准确时间和时区;
3. 目标 URL 路径,不需要 Token、Cookie 或密码;
4. 请求方法 GET/POST;
5. 是否经过 Nginx、负载均衡或网关;
6. 后端是否为 Docker 部署;
7. 公网和本机直连是否都慢;
8. 当时大约同时在线或执行 Agent 的人数。
不要提供真实账号密码、Token、Cookie、数据库密码或未经检查的完整业务日志。
Binary file not shown.
Submodule _skills_src/ai-skills added at cde1c8385e.
Submodule _skills_src/anthropics-skills added at 5754626092.
Submodule _skills_src/awesome-claude-skills added at 92568c1eda.
Submodule _skills_src/ce-kit added at d4973c4827.
+1
Submodule _skills_src/csm added at 3fa16a94e0.
Submodule _skills_src/superpowers added at 6fd4507659.
Submodule _skills_src/tapestry-skills added at 80e1dc56df.
+33
View File
@@ -0,0 +1,33 @@
# 批量人物蒸馏 → llmwiki
一个**完全独立的单文件脚本 + 内置定时器**:读 Excel 名单,串行调用线上 DeerFlow 服务问答接口,
复用「女娲 / huashu-nuwa」技能逐个蒸馏人物,**由脚本抓取回复并保存**成 llmwiki 风格 markdown。
- **不联网**:只用已配置的知识库查询技能(`knowledge-search-v2`)检索资料。
- **定时执行**:每天 **23:00 ~ 次日 08:00** 自动跑,到点暂停、次日继续。
- **md 由 py 保存**:agent 只产出内容,脚本抓最终回复写成 `.md`(不让项目自己写文件)。
## 你只需要做两件事
1. **改一行地址**:打开 `distill_people.py`,把顶部 `BASE_URL = "..."` 改成你的线上服务地址。
2. **放名单**:同目录放 `people.xlsx`(或 `people.csv`),**第一列 = 人名**,其余列=可选提示。
其余(用户名 `distiller`、口令 `123ewq`、技能名、时间窗)都已内置,不用填。
## 运行
```bash
python distill_people.py # 常驻,按 23:00~08:00 窗口自动执行(推荐挂后台)
python distill_people.py --now # 忽略时间窗,立刻把名单跑完(测试用)
python distill_people.py --redo # 忽略已完成,全部重做
```
读 `.xlsx` 需要 `openpyxl`;用 `.csv` 则零额外依赖。
## 输出(都在 output/ 一个文件夹)
- `<人名>.md` —— 每个人的 llmwiki 档案
- `manifest.json` —— 执行清单(状态/耗时/run_id)
- `index.md` —— 可读清单表(谁完成/失败,点开看 md)
**断点续跑**:已完成的人自动跳过;中途往名单里加人,下个执行窗会带上。
+563
View File
@@ -0,0 +1,563 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量人物蒸馏 → llmwiki markdown(完全独立的单文件客户端 + 内置定时器)
特点
----
- 串行(一个一个来)调用正在运行的 DeerFlow 服务问答接口
- 复用线上「女娲 / huashu-nuwa」技能做提炼;**不联网**,只用已配置的
知识库查询技能(knowledge-search-v2)检索资料
- agent 只负责产出内容,**markdown 由本脚本抓取最终回复后自己保存**
- 内置时间窗:每天 23:00 ~ 次日 08:00 才执行,到点自动暂停、次日继续
- 断点续跑:已完成的人自动跳过;中途加名单也会被带上
你只需要改一处:下面的 BASE_URL(线上服务地址)。其余都不用填。
名单
----
脚本同目录放 people.xlsx 或 people.csv,**第一列 = 人名**,其余列=可选提示。
运行
----
python distill_people.py # 常驻,按 23:00~08:00 窗口自动执行
python distill_people.py --now # 忽略时间窗,立刻把名单跑完(测试用)
python distill_people.py --redo # 忽略已完成,全部重做
"""
from __future__ import annotations
import argparse
import csv
import json
import re
import sys
import time
from datetime import datetime, time as dtime
from pathlib import Path
try:
import requests
except ImportError:
sys.exit("缺少依赖 requests:pip install requests")
# ════════════════════════════════════════════════════════════════════════
# 只改这一行:你的线上服务地址(不带结尾斜杠)
# ════════════════════════════════════════════════════════════════════════
BASE_URL = "http://47.94.209.59:2026/"
# ════════════════════════════════════════════════════════════════════════
# ---- 以下都已内置,正常无需改动 ----
USERNAME = "distiller" # 免密自动注册
PASSWORD = "123ewq" # 共享口令(你们开了口令门)
NUWA_SKILL = "huashu-nuwa" # 女娲技能
KB_SKILL = "knowledge-search-v2" # 知识库查询技能(不联网,用它检索)
DEPTH = "full" # full 完整 / fast 精简
HERE = Path(__file__).resolve().parent
OUTPUT_DIR = HERE / "output"
PEOPLE_FILE_DEFAULT = HERE / "people.example.csv"
# 执行时间窗:23:00 ~ 次日 08:00(跨午夜)
WIN_START = dtime(23, 0)
WIN_END = dtime(8, 0)
PER_PERSON_TIMEOUT = 1800 # 单人最长等待(秒)
POLL_INTERVAL = 5 # 轮询间隔(秒)
HTTP_TIMEOUT = 60
TERMINAL_STATUS = {"success", "error", "timeout", "interrupted"}
# ================================ llmwiki 模板 ================================
LLMWIKI_TEMPLATE = """\
---
name: <中文名/常用名>
aliases: [<别名/英文名...>]
type: person
era: <在世 | 历史人物>
domains: [<领域1>, <领域2>]
distilled_at: <YYYY-MM-DD>
sources_count: <检索到的来源条数>
primary_source_ratio: <一手来源占比, 0~1 的小数>
confidence: <high | medium | low>
---
# <人物名>
> **一句话定位**:<此人看世界的独特方式,一句话>
## 身份卡
- **活跃年代**:
- **核心身份**:
- **自述(50字, 以其语气)**:
## 核心观点(真信念 · 反复出现的主张)
1. ...
## 心智模型(3–7 个;每个含:一句话 / 证据场景≥2 / 应用 / 局限 / 来源)
### 1. <模型名>
- **一句话**:
- **证据场景**:
- **应用方式**:
- **局限**:
- **来源**:
## 决策启发式(5–10 条 · 如果 X 则 Y,带案例)
- 若 <X> → <Y>
## 表达 DNA
| 维度 | 特征 |
|------|------|
| 句式 | |
| 高频词 | |
| 幽默 | |
| 确定性 | |
| 引用习惯 | |
## 价值观与反模式
- **价值观排序**:
- **明确反对**:
## 内在张力(≥2 对矛盾)
- <A> ↔ <B>
## 经历时间线
| 年份 | 事件 | 思想意义 |
|------|------|---------|
| | | |
## 代表语录
- “...” —(出处/年份,标一手/二手)
## 智识谱系
- **受影响于**:
- **影响了**:
## 外部评价与争议
-
## 诚实边界
- <至少 3 条具体局限,含信息截止日期>
## 调研来源
**一手(N)**:
**二手(N)**:
"""
def build_prompt(name: str, hints: str, depth: str) -> str:
depth_note = (
"本次走【完整模式】:尽量覆盖著作/对话/表达/他者评价/决策/时间线 6 个维度。"
if depth == "full"
else "本次走【精简模式】:重点覆盖核心观点、心智模型、时间线三块即可。"
)
hint_block = f"\n补充提示(来自名单其它列,可作为检索关键词):{hints}\n" if hints.strip() else ""
return f"""\
你的任务:把人物【{name}】蒸馏成一份 llmwiki 风格的人物档案 markdown。
请复用本服务中已启用的「女娲 / {NUWA_SKILL}」技能的提炼方法论
(心智模型三重验证、表达DNA分析、诚实边界)。
⚠️ 本环境**无法联网,严禁使用 WebSearch 等任何联网工具**。
所有资料**只能通过已配置的知识库查询技能「{KB_SKILL}」检索获取**。
请充分调用该知识库技能,围绕该人物多角度检索(生平、观点、著作、语录、决策、评价等),
基于检索到的内容做提炼。知识库里查不到的部分,如实在「诚实边界」标注,不要编造。
{depth_note}
{hint_block}
输出要求:
1. **不要写任何文件,不要调用 write_file / present_files**。
2. 直接在你的回复正文里输出**完整中文 markdown 全文**,严格按下面模板结构
(保留各级标题,逐项填实,不要保留尖括号占位符),**不要任何额外解说、前言或结语**:
------------------ 模板开始 ------------------
{LLMWIKI_TEMPLATE}
------------------ 模板结束 ------------------
现在开始,独立完成,不要向我提问。"""
# ================================ HTTP 客户端 ================================
class DeerFlowClient:
def __init__(self, base_url: str):
self.base = base_url.rstrip("/")
self.s = requests.Session()
self.token: str | None = None
def _headers(self) -> dict:
h = {"Content-Type": "application/json"}
if self.token:
h["Authorization"] = f"Bearer {self.token}" # 只用 Bearer,不带 cookie → 跳过 CSRF
return h
def login(self) -> bool:
url = f"{self.base}/api/v1/auth/login/username"
params = {"password": PASSWORD} if PASSWORD else None
try:
r = self.s.post(url, params=params, json={"username": USERNAME}, timeout=HTTP_TIMEOUT)
except requests.RequestException as e:
print(f" [登录] 连接失败:{e}")
return False
if r.status_code == 200:
self.token = r.json().get("access_token")
self.s.cookies.clear()
print(f" [登录] 成功,用户={USERNAME}")
return True
print(f" [登录] 返回 {r.status_code}:{r.text[:200]}")
return False
def ensure_skill_enabled(self, name: str) -> None:
try:
r = self.s.get(f"{self.base}/api/skills", headers=self._headers(), timeout=HTTP_TIMEOUT)
if r.status_code == 200:
skills = r.json().get("skills", [])
hit = next((x for x in skills if x.get("name") == name), None)
if hit is None:
print(f" [技能] 警告:服务里没找到 '{name}'")
return
if hit.get("enabled"):
print(f" [技能] '{name}' 已启用")
return
pr = self.s.put(f"{self.base}/api/skills/{name}", headers=self._headers(),
json={"enabled": True}, timeout=HTTP_TIMEOUT)
print(f" [技能] 启用 '{name}' → {pr.status_code}")
except requests.RequestException as e:
print(f" [技能] 检查 '{name}' 失败(忽略):{e}")
def create_thread(self) -> str:
r = self.s.post(f"{self.base}/api/threads", headers=self._headers(), json={}, timeout=HTTP_TIMEOUT)
r.raise_for_status()
return r.json()["thread_id"]
def start_run(self, thread_id: str, prompt: str) -> str:
body = {
"input": {"messages": [{"role": "user", "content": prompt}]},
"excluded_tools": ["ask_clarification"], # 禁澄清,无人值守不卡住
}
r = self.s.post(f"{self.base}/api/threads/{thread_id}/runs",
headers=self._headers(), json=body, timeout=HTTP_TIMEOUT)
r.raise_for_status()
return r.json()["run_id"]
def poll_run(self, thread_id: str, run_id: str) -> str:
deadline = time.monotonic() + PER_PERSON_TIMEOUT
last = ""
while time.monotonic() < deadline:
try:
r = self.s.get(f"{self.base}/api/threads/{thread_id}/runs/{run_id}",
headers=self._headers(), timeout=HTTP_TIMEOUT)
if r.status_code == 200:
st = r.json().get("status", "")
if st != last:
print(f" ...状态:{st}")
last = st
if st in TERMINAL_STATUS:
return st
except requests.RequestException as e:
print(f" 轮询出错(重试):{e}")
time.sleep(POLL_INTERVAL)
return "timeout"
def fetch_result_text(self, thread_id: str, run_id: str) -> str | None:
"""抓取该 thread 的最终 AI 回复文本(由 py 保存为 md)。
注意:本部署的 `/runs/{rid}/messages`、`/messages`、`/events` 端点都返回空
(事件库按登录用户过滤,后台 worker 写入时未带 user_id → 读不到)。
可靠来源是 LangGraph 检查点状态 `/api/threads/{tid}/state` → values.messages,
其中每条消息形如 {"type": "human"|"ai"|"tool", "content": <str | 内容块列表>, ...}。
取最后一条有正文的 ai 消息即可。
"""
try:
r = self.s.get(f"{self.base}/api/threads/{thread_id}/state",
headers=self._headers(), timeout=HTTP_TIMEOUT)
if r.status_code != 200:
print(f" 取回复返回 {r.status_code}:{r.text[:200]}")
return None
messages = (r.json().get("values") or {}).get("messages") or []
# 从后往前找最后一条「有正文」的 AI 回复(跳过只含工具调用的中间消息)
for msg in reversed(messages):
if not isinstance(msg, dict) or msg.get("type") != "ai":
continue
txt = _extract_text(msg)
if txt and txt.strip():
return txt
except requests.RequestException as e:
print(f" 取回复出错:{e}")
return None
def _extract_text(payload) -> str:
"""从一条消息的 content 里提取纯文本。
payload 可能是:
- LangChain 消息的 model_dump 字典(正文在 payload["content"])
- 直接的字符串
- 内容块列表([{"type":"text","text":"..."}, ...])
"""
if payload is None:
return ""
# 若是整条消息的 model_dump,正文在其 content 字段
if isinstance(payload, dict):
c = payload.get("content", payload.get("text", ""))
else:
c = payload
if isinstance(c, str):
return c
if isinstance(c, list):
parts = []
for b in c:
if isinstance(b, dict):
# 只取文本块,跳过 tool_use / thinking 等非文本块
if b.get("type") in (None, "text", "text_block"):
parts.append(b.get("text") or b.get("content") or "")
elif b.get("text"):
parts.append(b["text"])
elif isinstance(b, str):
parts.append(b)
return "\n".join(p for p in parts if p)
return str(c) if c else ""
def _clean_markdown(text: str) -> str:
"""去掉 agent 可能套上的 ```markdown ... ``` 围栏,并规整 YAML frontmatter。"""
t = text.strip()
m = re.match(r"^```(?:markdown|md)?\s*\n(.*)\n```$", t, re.S)
if m:
t = m.group(1).strip()
return _normalize_frontmatter(t)
def _normalize_frontmatter(text: str) -> str:
"""修复模型常见的 frontmatter 跑偏,让 YAML 能正常解析。
模型经常把字段名写成 markdown 加粗(``**name:**``)、加空行、留行尾双空格,
这些都会让 frontmatter 解析失败。这里把开头 ``---`` 到下一个 ``---`` 之间的内容
规整为干净的 ``key: value`` 形式。正文(第二个 ``---`` 之后)保持原样。
"""
if not text.startswith("---"):
return text
# 拆出 frontmatter 块:开头 --- 与下一行单独的 --- 之间
m = re.match(r"^---[ \t]*\n(.*?)\n---[ \t]*\n?(.*)$", text, re.S)
if not m:
return text
body_fm, rest = m.group(1), m.group(2)
out_lines = []
for line in body_fm.splitlines():
s = line.rstrip() # 去行尾双空格
s = s.replace("**", "") # 去 markdown 加粗标记
if not s.strip():
continue # 丢掉空行
out_lines.append(s)
return "---\n" + "\n".join(out_lines) + "\n---\n\n" + rest.lstrip("\n")
# ================================ 名单读取 ================================
def slugify(name: str) -> str:
s = re.sub(r'[\\/:*?"<>|]+', "", name).strip()
s = re.sub(r"\s+", "_", s)
return s or "unnamed"
def read_people(path: Path) -> list[dict]:
if not path.exists():
return []
rows: list[list[str]] = []
if path.suffix.lower() in (".xlsx", ".xlsm"):
try:
import openpyxl
except ImportError:
sys.exit("读取 .xlsx 需要 openpyxl:pip install openpyxl(或把名单存成 .csv)")
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
for row in wb.active.iter_rows(values_only=True):
rows.append(["" if c is None else str(c).strip() for c in row])
elif path.suffix.lower() == ".csv":
with open(path, encoding="utf-8-sig", newline="") as f:
rows = [[c.strip() for c in r] for r in csv.reader(f)]
else:
sys.exit(f"不支持的名单格式:{path.suffix}(用 .xlsx 或 .csv)")
if rows and re.search(r"(姓名|名字|人物|name)", rows[0][0] if rows[0] else "", re.I):
rows = rows[1:]
people, seen = [], set()
for r in rows:
if not r or not r[0].strip():
continue
name = r[0].strip()
if name in seen:
continue
seen.add(name)
hints = " | ".join(x for x in r[1:] if x.strip())
people.append({"name": name, "hints": hints})
return people
# ================================ 时间窗 ================================
def in_window(now: datetime | None = None) -> bool:
now = now or datetime.now()
t = now.time()
return t >= WIN_START or t < WIN_END # 跨午夜
def seconds_until_window(now: datetime | None = None) -> int:
now = now or datetime.now()
if in_window(now):
return 0
target = now.replace(hour=WIN_START.hour, minute=WIN_START.minute, second=0, microsecond=0)
return max(1, int((target - now).total_seconds()))
def sleep_interruptible(total: int) -> None:
end = time.monotonic() + total
while time.monotonic() < end:
time.sleep(min(30, max(1, int(end - time.monotonic()))))
# ================================ 蒸馏单人 ================================
def distill_one(client: DeerFlowClient, person: dict, out_dir: Path,
manifest: dict, save_manifest, depth: str) -> None:
name, hints = person["name"], person["hints"]
slug = slugify(name)
md_path = out_dir / f"{slug}.md"
t0 = time.time()
rec = {"name": name, "slug": slug, "status": "running",
"started_at": _now(), "file": f"{slug}.md"}
manifest[name] = rec
save_manifest()
try:
tid = client.create_thread()
run_id = client.start_run(tid, build_prompt(name, hints, depth))
status = client.poll_run(tid, run_id)
rec.update(thread_id=tid, run_id=run_id, run_status=status)
text = client.fetch_result_text(tid, run_id) if status == "success" else None
if status == "success" and text:
md = _clean_markdown(text)
md_path.write_text(md, encoding="utf-8")
rec["status"] = "succeeded"
rec["chars"] = len(md)
print(f" ✅ 完成 → {md_path.name}({len(md)} 字,耗时 {int(time.time()-t0)}s)")
else:
rec["status"] = "failed"
rec["error"] = f"run={status}, text={'有' if text else '无'}"
if text:
(out_dir / f"{slug}.partial.md").write_text(text, encoding="utf-8")
print(f" ❌ 失败(run={status})")
except Exception as e:
rec["status"] = "failed"
rec["error"] = str(e)
print(f" ❌ 异常:{e}")
rec["finished_at"] = _now()
rec["seconds"] = int(time.time() - t0)
manifest[name] = rec
save_manifest()
# ================================ 主流程 ================================
def main():
ap = argparse.ArgumentParser(description="批量人物蒸馏 → llmwiki(定时窗 23:00~08:00)")
ap.add_argument("excel", nargs="?", default=str(PEOPLE_FILE_DEFAULT),
help="名单文件(.xlsx 或 .csv),默认同目录 people.xlsx")
ap.add_argument("--now", action="store_true", help="忽略时间窗,立刻跑完整批(测试用)")
ap.add_argument("--redo", action="store_true", help="忽略已完成,全部重做")
args = ap.parse_args()
excel = Path(args.excel)
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
manifest_path = OUTPUT_DIR / "manifest.json"
manifest: dict = {}
if manifest_path.exists():
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except Exception:
manifest = {}
# 校验名单存在
if not read_people(excel):
sys.exit(f"名单为空或不存在:{excel}\n请放 people.xlsx(第一列写人名)。")
# --redo:一次性清掉名单里这些人的旧记录,让他们重做一遍;
# 之后本次会话内跑成功的会正常计为「已完成」,循环才会往后推进
# (否则每轮 pending() 都把已完成的人当未完成,永远卡在第 1 个人)
if args.redo:
for p in read_people(excel):
manifest.pop(p["name"], None)
client = DeerFlowClient(BASE_URL)
if not client.login():
sys.exit("登录失败。请检查 BASE_URL 是否指向正在运行的服务、口令是否正确。")
client.ensure_skill_enabled(NUWA_SKILL)
client.ensure_skill_enabled(KB_SKILL)
def save_manifest():
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
_write_index(OUTPUT_DIR, read_people(excel), manifest)
def pending() -> list[dict]:
people = read_people(excel)
out = []
for p in people:
r = manifest.get(p["name"], {})
done = r.get("status") == "succeeded" and (OUTPUT_DIR / f"{slugify(p['name'])}.md").exists()
if not done:
out.append(p)
return out
print(f"启动 | 服务={BASE_URL} | 输出={OUTPUT_DIR}")
print(f"模式={'立即跑完' if args.now else '定时窗 23:00~08:00'} | 名单={excel}")
try:
while True:
todo = pending()
if not todo:
print(f"[{_now()}] 全部已完成,待命中(每小时复查名单)...")
if args.now:
break
sleep_interruptible(3600)
continue
if not args.now and not in_window():
wait = seconds_until_window()
nxt = datetime.now().replace(hour=WIN_START.hour, minute=0, second=0, microsecond=0)
print(f"[{_now()}] 不在执行窗口,剩 {len(todo)} 人待蒸;"
f"休眠到 {nxt.strftime('%H:%M')}(约 {wait//60} 分钟)...")
sleep_interruptible(wait)
continue
# 在窗口内(或 --now):处理一个人,然后回到循环重新判断窗口/名单
p = todo[0]
idx_total = len(read_people(excel))
done_n = sum(1 for v in manifest.values() if v.get("status") == "succeeded")
print(f"[{_now()}] ({done_n}/{idx_total} 已完成) 蒸馏:{p['name']}")
distill_one(client, p, OUTPUT_DIR, manifest, save_manifest, DEPTH)
except KeyboardInterrupt:
print("\n已手动停止。重跑脚本会从未完成处继续。")
ok = sum(1 for r in manifest.values() if r.get("status") == "succeeded")
fail = sum(1 for r in manifest.values() if r.get("status") == "failed")
print(f"\n结束:成功 {ok} / 失败 {fail}")
print(f"结果目录:{OUTPUT_DIR} | 清单:{manifest_path} | 索引:{OUTPUT_DIR/'index.md'}")
def _now() -> str:
return time.strftime("%Y-%m-%d %H:%M:%S")
def _write_index(out_dir: Path, people: list[dict], manifest: dict) -> None:
lines = ["# 蒸馏执行清单", "", f"更新时间:{_now()}", "",
"| # | 人物 | 状态 | 字数 | 耗时 | 文件 |",
"|---|------|------|------|------|------|"]
badge = {"succeeded": "✅完成", "failed": "❌失败", "running": "⏳进行中"}
for i, p in enumerate(people, 1):
r = manifest.get(p["name"], {})
st = badge.get(r.get("status", ""), "⌛排队")
f = r.get("file", "")
link = f"[{f}]({f})" if r.get("status") == "succeeded" and f else "-"
lines.append(f"| {i} | {p['name']} | {st} | {r.get('chars','-')} | {r.get('seconds','-')} | {link} |")
(out_dir / "index.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()
+4
View File
@@ -0,0 +1,4 @@
姓名,领域(可选提示),资料链接或备注(可选)
查理·芒格,投资/多元思维,
理查德·费曼,物理/教学,
纳瓦尔·拉维坎特,创业/杠杆,https://nav.al/
1 姓名 领域(可选提示) 资料链接或备注(可选)
2 查理·芒格 投资/多元思维
3 理查德·费曼 物理/教学
4 纳瓦尔·拉维坎特 创业/杠杆 https://nav.al/
@@ -0,0 +1,136 @@
# zncm Web Clipper
这是给 zncm 使用的 Chrome 插件,安装后默认连接 `config.js` 中配置好的服务地址。
默认地址配置在 `browser-extension/deer-web-clipper/config.js`:
```js
globalThis.ZNCM_WEB_CLIPPER_CONFIG = Object.freeze({
defaultWebBaseUrl: "http://47.94.209.59:2026",
defaultApiBaseUrl: "http://47.94.209.59:2026",
});
```
如果部署地址变化,只需要修改 `config.js` 里的这两个字段,然后重新加载插件。
正常情况下不需要手动配置 URL,也不需要手动复制 token。
## 能做什么
1. 把当前浏览器标签页发送到 zncm,作为 Markdown 附件进入聊天。
2. 接收 zncm 聊天中由 `browser_fetch_page` 工具创建的网页抓取任务。
3. 插件在 Chrome 中打开目标网页,读取可见文本和表格,再把结果回传给 zncm。
4. 在普通网页右下角显示“zncm 页面问答”浮窗,直接把当前页面内容交给 zncm 问答。
5. 接收 zncm 的 `browser_act` 交互式操作任务:在 Chrome 中打开页面并按 zncm 的指令**操作页面**——点击、输入、滚动、等待、页内跳转,每一步把页面上的可交互元素清单和正文回传给 zncm,由 zncm 决定下一步(observe→act 循环)。
## 页面操作(browser_act)
除了只读抓取,zncm 还能驱动插件**实际操作网页**,完成登录、填表、翻页找数据等多步任务:
1. zncm 调用 `browser_act` 工具,先 `navigate` 打开页面。
2. 插件打开标签页(同一会话会复用这个标签页),扫描页面上的可交互元素,给每个元素编号后连同正文回传给 zncm。
3. zncm 根据元素编号决定下一步(点第 3 个按钮、在第 1 个输入框填字……),再次调用 `browser_act`。
4. 插件执行动作、重新扫描页面、回传新状态,如此循环,直到任务完成。
5. 任务结束时 zncm 用 `action="close"` 关闭该会话标签页。
支持的动作:`navigate`(打开/跳转 URL)、`click`(点击元素)、`type`(输入文字,可选回车提交)、`scroll`(滚动到元素或下翻一屏)、`wait`(等待某 CSS 选择器出现)、`extract`(重新读取正文)、`observe`(仅重新扫描)、`close`(关闭会话标签页)。
> 提示:页面操作能力较强(可点击任意按钮、提交表单),可在后端 `config.yaml` 用 `browser_context.actions_enabled: false` 关闭,只保留只读抓取。
## 后端启用
在 `offline-backend-20260512/backend/config.yaml` 中保持:
```yaml
browser_context:
enabled: true # 只读抓取 + 页面问答
actions_enabled: true # 交互式页面操作 browser_act(不需要可设为 false)
```
修改配置后需要重启后端。
## 安装插件
1. 打开 Chrome 的 `chrome://extensions`。
2. 开启右上角的“开发者模式”。
3. 点击“加载已解压的扩展程序”。
4. 选择目录:`browser-extension/deer-web-clipper`。
5. 安装后插件名会显示为 `zncm Web Clipper`。
## 安装即用
插件默认已经开启:
- 自动识别已打开 zncm 页面的服务地址。
- 自动同步已登录 zncm 的 token。
- 自动轮询 zncm 聊天触发的浏览器抓取任务。
- 页面问答框默认开启。
如果你打开的是 `config.js` 里配置的默认服务器,通常无需进入设置页。
如果部署地址变了,保持一个已登录的 zncm 页面打开,然后在插件设置里点击:
- `重新识别服务地址`
- `同步 token`
## 自动同步 Token
插件会自动从两个位置获取登录 token:
1. zncm API 域名下的 `access_token` Cookie,包括 HttpOnly Cookie。
2. 已登录 zncm 前端页面里的浏览器本地登录态。
切换登录账号后,插件后台每次轮询任务前都会重新同步 token;点击插件里的“同步 token”也可以立即刷新。
如果当前浏览器已经登出 zncm,且打开的 zncm 页面里没有 token,插件会清空旧 token,避免继续用上一个账号请求。
## 页面问答框
安装插件后,普通 `http` / `https` 页面右下角会出现 `AI` 按钮。点击后可以在当前网页上直接提问,例如:
```text
总结这页的核心结论
提取页面里的价格和时间
这张表里哪个指标最高?
```
插件会读取当前页面可见文本和表格,发送到 zncm,并把 zncm 的回答显示回浮窗里。多轮追问会复用同一个 zncm 会话;如果页面 URL 变化,会自动重新开始当前页会话。
是否显示问答框可以自己控制:
- 插件弹窗里勾选或取消“启用页面问答框”。
- 插件设置页里勾选或取消“启用页面问答框”。
关闭问答框只会隐藏页面浮窗,不会影响“发送当前页”和 zncm 聊天中的 `browser_fetch_page` 抓取任务。
## 手动发送当前网页
点击插件图标,选择“发送当前页”。
插件会读取当前页面的可见文本和表格,发送到 zncm,并打开一个新的 zncm 聊天页面。zncm 会把网页内容作为上传文件注入到首条问题里。
## 在 zncm 聊天中触发浏览器抓取
在 zncm 中输入带有明确 URL 的问题,例如:
```text
使用 browser_fetch_page 打开 https://example.com/report,提取页面里的关键表格数据并总结。
```
执行流程:
1. zncm 调用 `browser_fetch_page` 工具创建浏览器任务。
2. 插件后台轮询到任务。
3. 插件在 Chrome 中打开目标网页。
4. 插件提取页面文本和表格。
5. 插件把结果回传给 zncm。
6. zncm 基于回传内容回答你的问题。
这个方式适合读取需要浏览器登录态、内网权限或当前 Chrome 环境才能访问的页面。
## 注意事项
- 目标 URL 必须是明确的 `http` 或 `https` 地址。
- 插件不能读取 `chrome://` 等浏览器内部页面。
- 如果目标网站阻止扩展脚本注入,抓取可能失败。
- 后台任务默认会打开新标签页;是否抓取完成后关闭标签页,可在插件设置里配置。
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,278 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");
const vm = require("node:vm");
const { webcrypto } = require("node:crypto");
const BACKGROUND_PATH = path.join(__dirname, "background.js");
function createHarness(options = {}) {
let storageChangedListener;
let alarmCreateCount = 0;
let clock = options.now ?? Date.now();
let fetchHandler = options.fetch;
let cookieToken = "";
const localData = options.localData || {};
const fetchUrls = [];
const settings = {
apiBaseUrl: "http://localhost:8001",
webBaseUrl: "http://localhost:5174",
autoDiscoverServiceUrl: false,
accessToken: "",
tokenSyncEnabled: false,
taskPollingEnabled: true,
workerId: "test-worker",
taskPollIntervalSeconds: 5,
...options.settings,
};
const chrome = {
alarms: {
clear: async () => {},
create: async () => {
alarmCreateCount += 1;
},
onAlarm: { addListener: () => {} },
},
cookies: { get: async () => cookieToken ? { value: cookieToken } : null },
runtime: {
onInstalled: { addListener: () => {} },
onMessage: { addListener: () => {} },
onStartup: { addListener: () => {} },
},
storage: {
local: {
get: async (defaults) => ({ ...defaults, ...localData }),
set: async (updates) => Object.assign(localData, updates),
},
session: { get: async () => ({ actSessions: {} }), set: async () => {} },
sync: {
get: async () => ({ ...settings }),
set: async (updates) => Object.assign(settings, updates),
},
onChanged: {
addListener: (listener) => {
storageChangedListener = listener;
},
},
},
tabs: { query: async () => [] },
};
const context = {
chrome,
console,
fetch: async (url, init) => {
fetchUrls.push(String(url));
if (fetchHandler) return fetchHandler(url, init);
return {
ok: true,
status: 200,
json: async () => ({ enabled: true }),
};
},
importScripts: () => {},
setTimeout: () => 1,
clearTimeout: () => {},
URL,
AbortController,
TextEncoder,
crypto: webcrypto,
Date: class extends Date {
constructor(...args) { super(...(args.length ? args : [clock])); }
static now() { return clock; }
},
DEER_CLIPPER_DEFAULTS: settings,
deerNormalizeBaseUrl: (value) => String(value || "").replace(/\/+$/, ""),
deerMakeWorkerId: () => "test-worker",
deerAuthHeaders: () => ({}),
deerExtractAuthTokenFromPage: () => ({ token: "" }),
};
context.globalThis = context;
vm.runInNewContext(fs.readFileSync(BACKGROUND_PATH, "utf8"), context, {
filename: BACKGROUND_PATH,
});
return {
emitStorageChange(changes) {
storageChangedListener(changes, "sync");
},
getAlarmCreateCount: () => alarmCreateCount,
getFetchUrls: () => [...fetchUrls],
getSettings: () => context.getSettings(),
setSettings: (updates) => Object.assign(settings, updates),
getLocalData: () => ({ ...localData }),
advanceTime: (ms) => { clock += ms; },
getTime: () => clock,
setFetch: (handler) => { fetchHandler = handler; },
setCookie: (token) => { cookieToken = token; },
status: (url, settings = {}, force = false) => context.browserContextStatus(url, settings, force),
discoverServiceBases: (settings, force = false) =>
context.discoverServiceBases(settings, force),
resetAlarmCreateCount: () => {
alarmCreateCount = 0;
},
getApiCandidates: (webBase, currentApiBase) =>
vm.runInContext(`apiCandidatesForWebBase(${JSON.stringify(webBase)}, ${JSON.stringify(currentApiBase)})`, context),
};
}
const settle = () => new Promise((resolve) => setImmediate(resolve));
test("self-written sync metadata does not restart browser task polling", async () => {
const harness = createHarness();
await settle();
harness.resetAlarmCreateCount();
harness.emitStorageChange({
lastTokenSyncAt: { oldValue: "before", newValue: "after" },
});
await settle();
assert.equal(harness.getAlarmCreateCount(), 0);
});
test("polling configuration changes restart browser task polling", async () => {
const harness = createHarness();
await settle();
harness.resetAlarmCreateCount();
harness.emitStorageChange({
taskPollingEnabled: { oldValue: false, newValue: true },
});
await settle();
assert.equal(harness.getAlarmCreateCount(), 1);
});
test("service discovery prefers the API paired with the open zncm tab", async () => {
const harness = createHarness();
assert.deepEqual(
Array.from(harness.getApiCandidates("http://localhost:5174", "http://47.94.209.59:2026")),
[
"http://localhost:5174",
"http://localhost:8001",
"http://47.94.209.59:2026",
"http://localhost:8001",
].filter((value, index, values) => values.indexOf(value) === index),
);
});
test("automatic service discovery checks status once per ten minutes, not on every task poll", async () => {
const harness = createHarness();
const settings = await harness.getSettings();
settings.autoDiscoverServiceUrl = true;
await harness.discoverServiceBases(settings);
assert.equal(harness.getFetchUrls().length, 1);
await harness.discoverServiceBases(await harness.getSettings());
assert.equal(harness.getFetchUrls().length, 1);
await harness.discoverServiceBases(await harness.getSettings(), true);
assert.equal(harness.getFetchUrls().length, 1);
harness.advanceTime(30_000);
await harness.discoverServiceBases(await harness.getSettings(), true);
assert.equal(harness.getFetchUrls().length, 2);
});
test("unchanged service discovery refreshes its timestamp after TTL expiry", async () => {
const harness = createHarness();
await settle();
harness.setSettings({ autoDiscoverServiceUrl: true });
await harness.discoverServiceBases(await harness.getSettings());
const firstSync = harness.getLocalData().lastServiceSyncAt;
harness.advanceTime(10 * 60_000 + 1);
await harness.discoverServiceBases(await harness.getSettings());
assert.notEqual(harness.getLocalData().lastServiceSyncAt, firstSync);
assert.equal(harness.getFetchUrls().length, 2);
for (let i = 0; i < 20; i++) {
harness.advanceTime(3_000);
await harness.discoverServiceBases(await harness.getSettings());
}
assert.equal(harness.getFetchUrls().length, 2);
});
test("concurrent status callers share a request and successful results expire", async () => {
const harness = createHarness();
const url = "http://example.test";
const results = await Promise.all(Array.from({ length: 30 }, () => harness.status(url)));
assert.ok(results.every((result) => result.enabled));
assert.equal(harness.getFetchUrls().length, 1);
harness.advanceTime(59_000);
await harness.status(`${url}/`);
assert.equal(harness.getFetchUrls().length, 1);
harness.advanceTime(1_001);
await harness.status(url);
assert.equal(harness.getFetchUrls().length, 2);
});
test("disabled status respects Retry-After even for manual calls and later recovers", async () => {
const harness = createHarness({
fetch: async () => ({
ok: false,
status: 403,
headers: { get: () => "300" },
json: async () => ({ detail: { code: "browser_status_disabled" } }),
}),
});
const url = "http://example.test";
const status = await harness.status(url);
assert.equal(status.enabled, false);
assert.equal(status.statusAccessDisabled, true);
assert.equal(status.authenticationRequired, undefined);
harness.advanceTime(299_999);
await harness.status(url, {}, true);
assert.equal(harness.getFetchUrls().length, 1);
harness.setFetch(async () => ({ ok: true, status: 200, json: async () => ({ enabled: true }) }));
harness.advanceTime(1);
assert.equal((await harness.status(url)).enabled, true);
assert.equal(harness.getFetchUrls().length, 2);
});
test("network and server failures back off for five minutes", async () => {
for (const fetch of [
async () => { throw new Error("offline"); },
async () => ({ ok: false, status: 500, json: async () => ({ detail: "unavailable" }) }),
]) {
const harness = createHarness({ fetch });
for (let i = 0; i < 10; i++) assert.equal(await harness.status("http://example.test", {}, true), null);
assert.equal(harness.getFetchUrls().length, 1);
harness.advanceTime(300_000);
assert.equal(await harness.status("http://example.test"), null);
assert.equal(harness.getFetchUrls().length, 2);
}
});
test("status cache separates service addresses, login tokens and cookies", async () => {
const harness = createHarness();
await harness.status("http://one.test", { accessToken: "account-a" });
await harness.status("http://one.test", { accessToken: "account-b" });
await harness.status("http://two.test", { accessToken: "account-b" });
harness.setCookie("new-login");
await harness.status("http://two.test", { accessToken: "account-b" });
assert.equal(harness.getFetchUrls().length, 4);
await harness.status("http://two.test", { accessToken: "account-b" });
assert.equal(harness.getFetchUrls().length, 4);
});
test("discovery survives worker restarts but refreshes after account changes", async () => {
const harness = createHarness();
await settle();
harness.setSettings({ autoDiscoverServiceUrl: true, accessToken: "account-a" });
await harness.discoverServiceBases(await harness.getSettings());
const localData = harness.getLocalData();
assert.ok(!JSON.stringify(localData).includes("account-a"));
const restarted = createHarness({
localData,
now: harness.getTime(),
settings: { autoDiscoverServiceUrl: true, accessToken: "account-a" },
});
await restarted.discoverServiceBases(await restarted.getSettings());
assert.equal(restarted.getFetchUrls().length, 0);
restarted.setSettings({ accessToken: "account-b" });
await restarted.discoverServiceBases(await restarted.getSettings());
assert.equal(restarted.getFetchUrls().length, 1);
});
@@ -0,0 +1,9 @@
// Default deployment settings for zncm Web Clipper.
//
// Change these two values before loading or packaging the extension when the
// zncm service address changes. Users can still override them in the extension
// settings page after installation.
globalThis.ZNCM_WEB_CLIPPER_CONFIG = Object.freeze({
defaultWebBaseUrl: "http://47.94.209.59:2026",
defaultApiBaseUrl: "http://47.94.209.59:2026",
});
@@ -0,0 +1,777 @@
(() => {
if (window.top !== window || window.__zncmPageAssistantLoaded) {
return;
}
window.__zncmPageAssistantLoaded = true;
const HOST_ID = "zncm-page-assistant-host";
const state = {
enabled: true,
taskPollingEnabled: true,
webBaseUrl: "",
open: false,
busy: false,
threadId: "",
pageUrl: location.href,
messages: [],
};
let host = null;
let shadow = null;
let ui = {};
function sendRuntimeMessage(message) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, (response) => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve(response || {});
});
});
}
function makeElement(tag, className = "", text = "") {
const element = document.createElement(tag);
if (className) {
element.className = className;
}
if (text) {
element.textContent = text;
}
return element;
}
function setStatus(message) {
if (ui.status) {
ui.status.textContent = message || "";
}
}
function setBusy(busy) {
state.busy = busy;
if (ui.send) ui.send.disabled = busy;
if (ui.input) ui.input.disabled = busy;
if (ui.panel) ui.panel.classList.toggle("is-busy", busy);
}
function resetThreadIfPageChanged() {
if (state.pageUrl === location.href) {
return;
}
state.pageUrl = location.href;
state.threadId = "";
state.messages = [];
renderMessages();
setStatus("页面已变化,下一次提问会重新读取当前页面。");
}
function destroyWidget() {
if (host) {
host.remove();
}
host = null;
shadow = null;
ui = {};
}
function renderMessages() {
if (!ui.messages) {
return;
}
ui.messages.replaceChildren();
if (state.messages.length === 0) {
const empty = makeElement("div", "empty");
const emptyTitle = makeElement("strong", "", "问问当前页面");
const emptyText = makeElement("span", "", "可以提问页面里的数据、表格、段落和结论。");
empty.append(emptyTitle, emptyText);
ui.messages.appendChild(empty);
return;
}
for (const message of state.messages) {
const item = makeElement("div", `message ${message.role}`);
const avatar = makeElement("div", "avatar", message.role === "user" ? "你" : "zn");
const bubble = makeElement("div", "bubble");
const label = makeElement("div", "message-label", message.role === "user" ? "你" : "zncm");
const body = makeElement("div", "message-body", message.text);
if (message.pending) {
body.classList.add("pending");
}
bubble.append(label, body);
item.append(avatar, bubble);
ui.messages.appendChild(item);
}
ui.messages.scrollTop = ui.messages.scrollHeight;
}
function setOpen(open) {
state.open = open;
if (!ui.panel || !ui.launcher) {
return;
}
ui.panel.classList.toggle("open", open);
ui.launcher.classList.toggle("open", open);
ui.launcher.setAttribute("aria-expanded", String(open));
if (open) {
resetThreadIfPageChanged();
setTimeout(() => ui.input?.focus(), 50);
}
}
async function ask(question) {
const normalized = String(question || "").trim();
if (!normalized || state.busy) {
return;
}
resetThreadIfPageChanged();
setBusy(true);
setStatus("正在读取页面并发送给 zncm...");
state.messages.push({ role: "user", text: normalized });
const pending = { role: "assistant", text: "zncm 正在理解当前页面...", pending: true };
state.messages.push(pending);
renderMessages();
ui.input.value = "";
try {
if (typeof deerExtractCurrentPage !== "function") {
throw new Error("页面读取脚本未加载,请刷新当前页面后重试。");
}
const page = deerExtractCurrentPage();
const response = await sendRuntimeMessage({
type: "zncm-page-agent-ask",
page,
question: normalized,
threadId: state.threadId || "",
});
if (!response.ok) {
throw new Error(response.message || "zncm 没有返回答案。");
}
state.threadId = response.thread_id || state.threadId;
pending.text = response.answer || "zncm 没有返回答案。";
pending.pending = false;
setStatus(response.truncated ? "已回答。页面内容较长,本次按配置做了截断。" : "已回答。");
} catch (error) {
pending.text = error instanceof Error ? error.message : "页面问答失败。";
pending.pending = false;
setStatus("本次问答失败。");
} finally {
setBusy(false);
renderMessages();
ui.input.focus();
}
}
function buildWidget() {
host = document.createElement("div");
host.id = HOST_ID;
document.documentElement.appendChild(host);
shadow = host.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = `
:host {
all: initial;
color-scheme: light;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.launcher,
.panel {
position: fixed;
z-index: 2147483647;
font: 14px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.launcher {
right: 20px;
bottom: 20px;
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
gap: 8px;
height: 44px;
min-width: 112px;
border: 1px solid rgba(15, 118, 110, 0.28);
border-radius: 8px;
padding: 0 12px 0 10px;
background: #0f766e;
color: #fff;
box-shadow: 0 12px 34px rgba(15, 118, 110, 0.28), 0 2px 8px rgba(17, 24, 39, 0.12);
cursor: pointer;
font-weight: 750;
transition: transform 160ms ease, box-shadow 160ms ease, background 160ms ease;
}
.launcher:hover {
transform: translateY(-2px);
box-shadow: 0 16px 40px rgba(15, 118, 110, 0.32), 0 4px 12px rgba(17, 24, 39, 0.14);
}
.launcher-mark {
display: grid;
place-items: center;
width: 24px;
height: 24px;
border-radius: 7px;
background: rgba(255, 255, 255, 0.18);
font-size: 12px;
letter-spacing: 0;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);
}
.launcher.open {
background: #115e59;
}
.panel {
right: 20px;
bottom: 72px;
width: min(430px, calc(100vw - 24px));
max-height: min(640px, calc(100vh - 96px));
display: none;
grid-template-rows: auto auto minmax(180px, 1fr) auto;
overflow: hidden;
border: 1px solid #d6d8dc;
border-radius: 8px;
background: #ffffff;
color: #171717;
box-shadow: 0 24px 70px rgba(17, 24, 39, 0.2), 0 1px 2px rgba(17, 24, 39, 0.08);
}
.panel.open {
display: grid;
animation: zncm-panel-in 160ms ease-out;
}
@keyframes zncm-panel-in {
from {
opacity: 0;
transform: translateY(8px) scale(0.985);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
.header {
display: grid;
gap: 10px;
padding: 14px;
background: linear-gradient(180deg, #f4fffc 0%, #ffffff 84%);
border-bottom: 1px solid #e5e7eb;
}
.header-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.brand {
display: flex;
align-items: center;
min-width: 0;
gap: 10px;
}
.brand-mark {
display: grid;
place-items: center;
width: 34px;
height: 34px;
flex: 0 0 auto;
border-radius: 8px;
background: #0f766e;
color: #fff;
font-weight: 800;
box-shadow: 0 8px 20px rgba(15, 118, 110, 0.18);
}
.brand-copy {
display: grid;
min-width: 0;
gap: 1px;
}
.brand-copy strong {
color: #111827;
font-size: 15px;
line-height: 1.25;
}
.brand-copy span {
overflow: hidden;
color: #6b7280;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.header-actions {
display: flex;
flex: 0 0 auto;
gap: 6px;
}
.icon-button {
display: grid;
place-items: center;
width: auto;
min-width: 34px;
height: 30px;
padding: 0 8px;
border: 1px solid #dfe3e8;
border-radius: 7px;
background: #fff;
color: #374151;
cursor: pointer;
font: inherit;
font-size: 12px;
white-space: nowrap;
transition: background 140ms ease, border-color 140ms ease, color 140ms ease;
}
.icon-button:hover {
border-color: #0f766e;
color: #0f766e;
background: #f0fdfa;
}
.page-chip {
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
gap: 8px;
min-width: 0;
border: 1px solid #dbeafe;
border-radius: 8px;
padding: 8px 10px;
background: #f8fbff;
color: #334155;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8);
}
.page-chip-dot {
width: 8px;
height: 8px;
border-radius: 999px;
background: #0f766e;
}
.page-chip-text {
overflow: hidden;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.status {
min-height: 20px;
padding: 9px 14px;
border-bottom: 1px solid #f0f2f5;
color: #475569;
background: #fbfcfd;
font-size: 12px;
}
.messages {
display: grid;
align-content: start;
gap: 12px;
overflow: auto;
padding: 14px;
background: linear-gradient(180deg, #f7f8fa 0%, #f3f6f8 100%);
}
.empty {
display: grid;
gap: 5px;
padding: 16px;
border: 1px solid #dfe7ed;
border-radius: 8px;
background: linear-gradient(180deg, #ffffff 0%, #fbfefd 100%);
color: #4b5563;
box-shadow: 0 8px 20px rgba(15, 23, 42, 0.04);
}
.empty strong {
color: #111827;
font-size: 14px;
}
.empty span {
font-size: 13px;
}
.message {
display: grid;
grid-template-columns: 28px minmax(0, 1fr);
gap: 8px;
align-items: start;
}
.message.user {
grid-template-columns: minmax(0, 1fr) 28px;
}
.message.user .avatar {
grid-column: 2;
}
.message.user .bubble {
grid-column: 1;
justify-self: end;
}
.avatar {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border-radius: 8px;
background: #e6fffb;
color: #0f766e;
font-size: 11px;
font-weight: 800;
}
.message.user .avatar {
background: #111827;
color: #fff;
}
.bubble {
display: grid;
gap: 4px;
max-width: 100%;
}
.message-label {
color: #6b7280;
font-size: 11px;
}
.message.user .message-label {
text-align: right;
}
.message-body {
max-width: 330px;
padding: 10px 12px;
border: 1px solid #e5e7eb;
border-radius: 8px;
background: #fff;
color: #171717;
white-space: pre-wrap;
overflow-wrap: anywhere;
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}
.message.user .message-body {
border-color: #0f172a;
background: #0f172a;
color: #fff;
}
.message-body.pending {
color: #6b7280;
}
.message-body.pending::after {
content: "";
display: inline-block;
width: 18px;
height: 4px;
margin-left: 6px;
border-radius: 999px;
background: linear-gradient(90deg, #0f766e 0 33%, transparent 33% 100%);
background-size: 9px 4px;
animation: zncm-thinking 900ms linear infinite;
vertical-align: middle;
}
@keyframes zncm-thinking {
from {
background-position: 0 0;
}
to {
background-position: 18px 0;
}
}
.composer-wrap {
display: grid;
gap: 10px;
padding: 12px 14px 14px;
background: #fff;
border-top: 1px solid #e5e7eb;
}
.quick {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 7px;
}
.quick button {
border: 1px solid #d6d8dc;
border-radius: 8px;
padding: 8px 10px;
background: #fbfcfd;
color: #374151;
cursor: pointer;
font: inherit;
font-size: 12px;
text-align: left;
transition: background 140ms ease, border-color 140ms ease, color 140ms ease, transform 140ms ease;
}
.quick button:hover {
border-color: #0f766e;
color: #0f766e;
background: #f0fdfa;
transform: translateY(-1px);
}
.composer {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
align-items: end;
}
.composer textarea {
min-height: 46px;
max-height: 130px;
resize: vertical;
border: 1px solid #cfd6dd;
border-radius: 8px;
padding: 10px 11px;
color: #171717;
background: #fbfcfd;
font: inherit;
outline: none;
}
.composer textarea:focus {
border-color: #0f766e;
box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12);
}
.composer button {
height: 42px;
border: 0;
border-radius: 8px;
padding: 0 14px;
background: #0f766e;
color: #fff;
cursor: pointer;
font: inherit;
font-weight: 750;
box-shadow: 0 8px 18px rgba(15, 118, 110, 0.2);
transition: transform 140ms ease, background 140ms ease, box-shadow 140ms ease;
}
.composer button:hover {
background: #115e59;
transform: translateY(-1px);
box-shadow: 0 10px 22px rgba(15, 118, 110, 0.24);
}
.panel.is-busy .brand-mark,
.panel.is-busy .launcher-mark {
opacity: 0.82;
}
.composer button:disabled,
.quick button:disabled,
.icon-button:disabled {
cursor: not-allowed;
opacity: 0.6;
}
@media (max-width: 480px) {
.launcher {
right: 12px;
bottom: 12px;
min-width: 96px;
}
.panel {
right: 12px;
bottom: 64px;
width: calc(100vw - 24px);
max-height: calc(100vh - 80px);
}
.message-body {
max-width: calc(100vw - 104px);
}
.quick {
grid-template-columns: 1fr;
}
}
`;
const launcher = makeElement("button", "launcher");
launcher.type = "button";
launcher.title = "打开 zncm 页面问答";
launcher.setAttribute("aria-expanded", "false");
launcher.append(makeElement("span", "launcher-mark", "zn"), makeElement("span", "", "页面问答"));
const panel = makeElement("section", "panel");
const header = makeElement("header", "header");
const headerTop = makeElement("div", "header-top");
const brand = makeElement("div", "brand");
const brandCopy = makeElement("div", "brand-copy");
const title = makeElement("strong", "", "zncm 页面问答");
const subtitle = makeElement("span", "", "读取当前页面并回答");
brandCopy.append(title, subtitle);
brand.append(makeElement("div", "brand-mark", "zn"), brandCopy);
const actions = makeElement("div", "header-actions");
const settings = makeElement("button", "icon-button", "设置");
settings.type = "button";
settings.title = "打开插件设置";
const minimize = makeElement("button", "icon-button", "-");
minimize.type = "button";
minimize.title = "收起";
actions.append(settings, minimize);
headerTop.append(brand, actions);
const pageChip = makeElement("div", "page-chip");
const pageTitle = makeElement("span", "page-chip-text", document.title || location.hostname);
pageChip.append(makeElement("span", "page-chip-dot"), pageTitle);
header.append(headerTop, pageChip);
const status = makeElement("div", "status", "已连接当前页面。");
const messages = makeElement("div", "messages");
const composerWrap = makeElement("div", "composer-wrap");
const quick = makeElement("div", "quick");
for (const text of ["总结此页", "提取关键数据", "列出待办", "解释表格"]) {
const chip = makeElement("button", "", text);
chip.type = "button";
chip.addEventListener("click", () => ask(text));
quick.appendChild(chip);
}
const composer = makeElement("form", "composer");
const input = makeElement("textarea");
input.placeholder = "问当前页面...";
input.rows = 2;
const send = makeElement("button", "", "发送");
send.type = "submit";
composer.append(input, send);
composerWrap.append(quick, composer);
panel.append(header, status, messages, composerWrap);
shadow.append(style, panel, launcher);
ui = { launcher, panel, subtitle, pageTitle, status, messages, input, send };
renderMessages();
launcher.addEventListener("click", () => setOpen(!state.open));
minimize.addEventListener("click", () => setOpen(false));
settings.addEventListener("click", () => {
sendRuntimeMessage({ type: "zncm-open-options" }).catch((error) => {
setStatus(error instanceof Error ? error.message : "无法打开插件设置。");
});
});
composer.addEventListener("submit", (event) => {
event.preventDefault();
ask(input.value);
});
input.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
ask(input.value);
}
});
}
function ensureWidget() {
if (!state.enabled) {
destroyWidget();
return;
}
if (document.getElementById(HOST_ID)) {
return;
}
buildWidget();
}
async function loadSettings() {
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
state.enabled = Boolean(settings.pageAssistantEnabled);
state.taskPollingEnabled = Boolean(settings.taskPollingEnabled);
state.webBaseUrl = deerNormalizeBaseUrl(settings.webBaseUrl || DEER_CLIPPER_DEFAULTS.webBaseUrl);
ensureWidget();
}
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== "sync") {
return;
}
if (changes.pageAssistantEnabled) {
state.enabled = Boolean(changes.pageAssistantEnabled.newValue);
ensureWidget();
if (state.enabled) {
setStatus("页面问答框已开启。");
}
}
if (changes.taskPollingEnabled) {
state.taskPollingEnabled = Boolean(changes.taskPollingEnabled.newValue);
}
if (changes.webBaseUrl) {
state.webBaseUrl = deerNormalizeBaseUrl(changes.webBaseUrl.newValue || DEER_CLIPPER_DEFAULTS.webBaseUrl);
}
});
function isZncmPage() {
const appPath = `${location.pathname}${location.hash}`.toLowerCase();
if (
appPath.includes("/page/workspace") ||
appPath.includes("/chats/") ||
appPath.includes("#/login")
) {
return true;
}
try {
const configured = new URL(state.webBaseUrl);
return configured.origin === location.origin;
} catch {
return false;
}
}
// MV3 service workers may be suspended between their short polling timers,
// while chrome.alarms cannot reliably run more often than every 30 seconds.
// A visible zncm tab provides a cheap wake-up signal so browser_act requests
// are normally claimed within the backend/model timeout window.
setInterval(() => {
if (!state.taskPollingEnabled || !isZncmPage()) {
return;
}
chrome.runtime.sendMessage({ type: "zncm-poll-now" }).catch(() => {});
}, 3000);
setInterval(() => {
if (!state.enabled || !ui.pageTitle) {
return;
}
if (state.pageUrl !== location.href) {
resetThreadIfPageChanged();
}
ui.pageTitle.textContent = document.title || location.hostname;
}, 1200);
void loadSettings();
})();
@@ -0,0 +1,24 @@
{
"manifest_version": 3,
"name": "zncm Web Clipper",
"version": "0.2.0",
"description": "Send pages to zncm and execute browser-backed fetch tasks.",
"permissions": ["activeTab", "alarms", "cookies", "scripting", "storage", "tabs"],
"host_permissions": ["<all_urls>"],
"background": {
"service_worker": "background.js"
},
"action": {
"default_title": "zncm Web Clipper",
"default_popup": "popup.html"
},
"options_page": "options.html",
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["config.js", "shared.js", "content.js"],
"run_at": "document_idle",
"all_frames": false
}
]
}
@@ -0,0 +1,74 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>zncm Web Clipper Settings</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<main class="options">
<h1>zncm Web Clipper Settings</h1>
<label>
API 地址
<input id="apiBaseUrl" />
</label>
<label>
前端地址
<input id="webBaseUrl" />
</label>
<label class="checkbox">
<input id="autoDiscoverServiceUrl" type="checkbox" />
自动识别已打开 zncm 页面的服务地址
</label>
<div class="actions">
<button id="discoverService" type="button">重新识别服务地址</button>
</div>
<p id="serviceStatus" class="status"></p>
<label>
Access Token
<textarea id="accessToken" rows="5" placeholder="会自动从已登录 zncm 页面或 access_token Cookie 获取。也可以手动粘贴。"></textarea>
</label>
<label class="checkbox">
<input id="tokenSyncEnabled" type="checkbox" />
自动同步已登录 zncm 的 token
</label>
<div class="actions">
<button id="syncToken" type="button">Sync token now</button>
</div>
<p id="tokenStatus" class="status"></p>
<label class="checkbox">
<input id="pageAssistantEnabled" type="checkbox" />
启用页面问答框
</label>
<label>
默认首问
<textarea id="defaultPrompt" rows="4"></textarea>
</label>
<label class="checkbox">
<input id="taskPollingEnabled" type="checkbox" />
启用 zncm 聊天触发的浏览器抓取任务
</label>
<label>
Worker ID
<input id="workerId" placeholder="自动生成" />
</label>
<label>
任务轮询间隔秒数
<input id="taskPollIntervalSeconds" type="number" min="3" step="1" />
</label>
<label>
页面加载超时秒数
<input id="taskPageLoadTimeoutSeconds" type="number" min="5" step="1" />
</label>
<label class="checkbox">
<input id="closeTaskTabs" type="checkbox" />
抓取完成后关闭任务标签页
</label>
<button id="save" type="button">保存</button>
<p id="status" class="status"></p>
</main>
<script src="config.js"></script>
<script src="shared.js"></script>
<script src="options.js"></script>
</body>
</html>
@@ -0,0 +1,148 @@
const textFields = [
"apiBaseUrl",
"webBaseUrl",
"accessToken",
"defaultPrompt",
"workerId",
"taskPollIntervalSeconds",
"taskPageLoadTimeoutSeconds",
];
const checkboxFields = [
"autoDiscoverServiceUrl",
"tokenSyncEnabled",
"pageAssistantEnabled",
"taskPollingEnabled",
"closeTaskTabs",
];
function formatServiceStatus(settings) {
if (!settings.lastServiceSyncAt) {
return `当前服务地址:${settings.webBaseUrl || DEER_CLIPPER_DEFAULTS.webBaseUrl};API:${settings.apiBaseUrl || DEER_CLIPPER_DEFAULTS.apiBaseUrl}`;
}
return `当前服务地址:${settings.webBaseUrl || ""};API:${settings.apiBaseUrl || ""}\n上次识别:${settings.lastServiceSyncAt}(${settings.lastServiceSyncSource || "unknown source"})`;
}
function formatTokenStatus(settings) {
if (!settings.lastTokenSyncAt) {
return "Token 尚未自动同步。";
}
return `上次 token 同步:${settings.lastTokenSyncAt}(${settings.lastTokenSyncSource || "unknown source"})`;
}
async function loadSettings() {
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
if (!settings.workerId) {
settings.workerId = deerMakeWorkerId();
await chrome.storage.sync.set({ workerId: settings.workerId });
}
document.getElementById("apiBaseUrl").placeholder =
DEER_CLIPPER_DEFAULTS.apiBaseUrl || "在 config.js 中配置默认 API 地址";
document.getElementById("webBaseUrl").placeholder =
DEER_CLIPPER_DEFAULTS.webBaseUrl || "在 config.js 中配置默认前端地址";
for (const field of textFields) {
document.getElementById(field).value = settings[field] ?? "";
}
for (const field of checkboxFields) {
document.getElementById(field).checked = Boolean(settings[field]);
}
document.getElementById("serviceStatus").textContent = formatServiceStatus(settings);
document.getElementById("tokenStatus").textContent = formatTokenStatus(settings);
}
async function saveSettings() {
const next = {};
for (const field of textFields) {
next[field] = document.getElementById(field).value.trim();
}
for (const field of checkboxFields) {
next[field] = document.getElementById(field).checked;
}
next.apiBaseUrl = deerNormalizeBaseUrl(next.apiBaseUrl || DEER_CLIPPER_DEFAULTS.apiBaseUrl);
next.webBaseUrl = deerNormalizeBaseUrl(next.webBaseUrl || DEER_CLIPPER_DEFAULTS.webBaseUrl);
next.defaultPrompt = next.defaultPrompt || DEER_CLIPPER_DEFAULT_PROMPT;
next.workerId = next.workerId || deerMakeWorkerId();
next.taskPollIntervalSeconds = Math.max(3, Number(next.taskPollIntervalSeconds || DEER_CLIPPER_DEFAULTS.taskPollIntervalSeconds));
next.taskPageLoadTimeoutSeconds = Math.max(5, Number(next.taskPageLoadTimeoutSeconds || DEER_CLIPPER_DEFAULTS.taskPageLoadTimeoutSeconds));
await chrome.storage.sync.set(next);
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
document.getElementById("status").textContent = "已保存。";
document.getElementById("serviceStatus").textContent = formatServiceStatus(settings);
document.getElementById("tokenStatus").textContent = formatTokenStatus(settings);
}
function sendDiscoverServiceMessage() {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ type: "zncm-discover-service" }, (response) => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve(response || { ok: false, message: "服务地址识别没有返回结果。" });
});
});
}
function sendSyncTokenMessage() {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ type: "zncm-sync-token" }, (response) => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve(response || { ok: false, message: "Token 同步没有返回结果。" });
});
});
}
async function discoverServiceNow() {
const button = document.getElementById("discoverService");
button.disabled = true;
document.getElementById("serviceStatus").textContent = "正在识别服务地址...";
try {
await chrome.storage.sync.set({
autoDiscoverServiceUrl: document.getElementById("autoDiscoverServiceUrl").checked,
apiBaseUrl: deerNormalizeBaseUrl(document.getElementById("apiBaseUrl").value || DEER_CLIPPER_DEFAULTS.apiBaseUrl),
webBaseUrl: deerNormalizeBaseUrl(document.getElementById("webBaseUrl").value || DEER_CLIPPER_DEFAULTS.webBaseUrl),
});
const response = await sendDiscoverServiceMessage();
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
document.getElementById("apiBaseUrl").value = settings.apiBaseUrl || "";
document.getElementById("webBaseUrl").value = settings.webBaseUrl || "";
document.getElementById("serviceStatus").textContent = response.message || formatServiceStatus(settings);
} catch (error) {
document.getElementById("serviceStatus").textContent = error instanceof Error ? error.message : "服务地址识别失败。";
} finally {
button.disabled = false;
}
}
async function syncTokenNow() {
const button = document.getElementById("syncToken");
button.disabled = true;
document.getElementById("tokenStatus").textContent = "正在同步 zncm token...";
try {
await chrome.storage.sync.set({
tokenSyncEnabled: document.getElementById("tokenSyncEnabled").checked,
apiBaseUrl: deerNormalizeBaseUrl(document.getElementById("apiBaseUrl").value || DEER_CLIPPER_DEFAULTS.apiBaseUrl),
webBaseUrl: deerNormalizeBaseUrl(document.getElementById("webBaseUrl").value || DEER_CLIPPER_DEFAULTS.webBaseUrl),
});
const response = await sendSyncTokenMessage();
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
document.getElementById("accessToken").value = settings.accessToken || "";
document.getElementById("apiBaseUrl").value = settings.apiBaseUrl || "";
document.getElementById("webBaseUrl").value = settings.webBaseUrl || "";
document.getElementById("serviceStatus").textContent = formatServiceStatus(settings);
document.getElementById("tokenStatus").textContent = response.message || formatTokenStatus(settings);
} catch (error) {
document.getElementById("tokenStatus").textContent = error instanceof Error ? error.message : "Token 同步失败。";
} finally {
button.disabled = false;
}
}
document.getElementById("save").addEventListener("click", saveSettings);
document.getElementById("discoverService").addEventListener("click", discoverServiceNow);
document.getElementById("syncToken").addEventListener("click", syncTokenNow);
void loadSettings();
@@ -0,0 +1,31 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>zncm Web Clipper</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<main class="popup">
<h1>zncm Web Clipper</h1>
<label>
首问
<textarea id="prompt" rows="4"></textarea>
</label>
<label class="checkbox">
<input id="pageAssistantEnabled" type="checkbox" />
启用页面问答框
</label>
<div class="actions">
<button id="send" type="button">发送当前页</button>
<button id="syncToken" type="button">同步 token</button>
<button id="pollNow" type="button">检查任务</button>
<button id="options" type="button" class="secondary">设置</button>
</div>
<p id="status" class="status"></p>
</main>
<script src="config.js"></script>
<script src="shared.js"></script>
<script src="popup.js"></script>
</body>
</html>
+151
View File
@@ -0,0 +1,151 @@
function setStatus(message) {
document.getElementById("status").textContent = message;
}
async function getActiveTab() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab?.id) {
throw new Error("No readable active tab found.");
}
return tab;
}
async function captureFromActiveTab(tabId) {
const [result] = await chrome.scripting.executeScript({
target: { tabId },
func: deerExtractCurrentPage,
});
if (!result?.result?.content) {
throw new Error("The current page has no readable text to send.");
}
return result.result;
}
async function submitToZncm(page, settings, prompt) {
const apiBaseUrl = deerNormalizeBaseUrl(settings.apiBaseUrl || DEER_CLIPPER_DEFAULTS.apiBaseUrl);
const response = await fetch(`${apiBaseUrl}/api/browser-context/capture`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...deerAuthHeaders(settings),
},
body: JSON.stringify({
title: page.title,
url: page.url,
content: page.content,
content_type: page.contentType,
prompt,
}),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const detail = typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail || data);
throw new Error(detail || `HTTP ${response.status}`);
}
return data;
}
async function sendCurrentPage() {
const sendButton = document.getElementById("send");
sendButton.disabled = true;
setStatus("正在读取当前页面...");
try {
await syncToken({ silent: true });
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
const prompt = document.getElementById("prompt").value.trim() || settings.defaultPrompt || DEER_CLIPPER_DEFAULT_PROMPT;
const tab = await getActiveTab();
const page = await captureFromActiveTab(tab.id);
setStatus("正在发送到 zncm...");
const result = await submitToZncm(page, settings, prompt);
const webBaseUrl = deerNormalizeBaseUrl(settings.webBaseUrl || DEER_CLIPPER_DEFAULTS.webBaseUrl);
await chrome.tabs.create({ url: `${webBaseUrl}/${result.chat_url}`.replace(/\/#/g, "/#") });
setStatus("已发送,zncm 聊天页面已打开。");
} catch (error) {
setStatus(error instanceof Error ? error.message : "发送失败。");
} finally {
sendButton.disabled = false;
}
}
function sendSyncTokenMessage() {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ type: "zncm-sync-token" }, (response) => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve(response || { ok: false, message: "Token 同步没有返回结果。" });
});
});
}
function sendPollNowMessage() {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ type: "zncm-poll-now" }, (response) => {
const error = chrome.runtime.lastError;
if (error) {
reject(new Error(error.message));
return;
}
resolve(response || { ok: true, message: "Poll requested." });
});
});
}
async function syncToken(options = {}) {
const button = document.getElementById("syncToken");
button.disabled = true;
if (!options.silent) {
setStatus("正在同步 zncm token...");
}
try {
const response = await sendSyncTokenMessage();
if (!options.silent) {
setStatus(response.message || "Token sync finished.");
}
return response;
} catch (error) {
if (!options.silent) {
setStatus(error instanceof Error ? error.message : "Token 同步失败。");
}
return { ok: false, message: error instanceof Error ? error.message : "Token 同步失败。" };
} finally {
button.disabled = false;
}
}
async function pollNow() {
const button = document.getElementById("pollNow");
button.disabled = true;
setStatus("正在检查 zncm 浏览器任务...");
try {
await syncToken({ silent: true });
const response = await sendPollNowMessage();
setStatus(response.message || "任务检查完成。");
} catch (error) {
setStatus(error instanceof Error ? error.message : "任务检查失败。");
} finally {
button.disabled = false;
}
}
async function togglePageAssistant() {
const enabled = document.getElementById("pageAssistantEnabled").checked;
await chrome.storage.sync.set({ pageAssistantEnabled: enabled });
setStatus(enabled ? "页面问答框已开启。" : "页面问答框已关闭。");
}
async function init() {
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
document.getElementById("prompt").value = settings.defaultPrompt || DEER_CLIPPER_DEFAULT_PROMPT;
document.getElementById("pageAssistantEnabled").checked = Boolean(settings.pageAssistantEnabled);
document.getElementById("send").addEventListener("click", sendCurrentPage);
document.getElementById("syncToken").addEventListener("click", () => syncToken());
document.getElementById("pollNow").addEventListener("click", pollNow);
document.getElementById("pageAssistantEnabled").addEventListener("change", togglePageAssistant);
document.getElementById("options").addEventListener("click", () => chrome.runtime.openOptionsPage());
}
void init();
@@ -0,0 +1,389 @@
const DEER_CLIPPER_DEFAULT_PROMPT =
"\u8bf7\u57fa\u4e8e\u521a\u521a\u53d1\u9001\u7684\u7f51\u9875\u5185\u5bb9\uff0c\u5148\u7528\u4e2d\u6587\u603b\u7ed3\u8981\u70b9\uff0c\u5e76\u7b49\u5f85\u6211\u7ee7\u7eed\u63d0\u95ee\u3002";
const ZNCM_EXTENSION_CONFIG = globalThis.ZNCM_WEB_CLIPPER_CONFIG || {};
const ZNCM_DEFAULT_WEB_BASE_URL = String(ZNCM_EXTENSION_CONFIG.defaultWebBaseUrl || "").trim().replace(/\/+$/, "");
const ZNCM_DEFAULT_API_BASE_URL = String(ZNCM_EXTENSION_CONFIG.defaultApiBaseUrl || "").trim().replace(/\/+$/, "");
const DEER_CLIPPER_DEFAULTS = {
apiBaseUrl: ZNCM_DEFAULT_API_BASE_URL,
webBaseUrl: ZNCM_DEFAULT_WEB_BASE_URL,
autoDiscoverServiceUrl: true,
lastServiceSyncAt: "",
lastServiceSyncSource: "",
accessToken: "",
tokenSyncEnabled: true,
lastTokenSyncAt: "",
lastTokenSyncSource: "",
defaultPrompt: DEER_CLIPPER_DEFAULT_PROMPT,
pageAssistantEnabled: true,
taskPollingEnabled: true,
workerId: "",
taskPollIntervalSeconds: 5,
taskPageLoadTimeoutSeconds: 30,
closeTaskTabs: false,
};
function deerNormalizeBaseUrl(value) {
return String(value || "").trim().replace(/\/+$/, "");
}
function deerAuthHeaders(settings) {
const token = String(settings.accessToken || "").trim();
if (!token) {
return {};
}
return {
Authorization: /^bearer\s+/i.test(token) ? token : `Bearer ${token}`,
};
}
function deerMakeWorkerId() {
return `zncm-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
function deerExtractAuthTokenFromPage() {
const storageKeys = ["deerflow.auth"];
const tokenFieldNames = new Set(["access_token", "accessToken", "token", "id_token", "idToken"]);
function looksLikeToken(value) {
const text = String(value || "").trim();
return text.length > 20 && !/\s/.test(text);
}
function findToken(value, depth = 0) {
if (value == null || depth > 4) {
return "";
}
if (typeof value === "string") {
const text = value.trim();
if (!text) {
return "";
}
if ((text.startsWith("{") && text.endsWith("}")) || (text.startsWith("[") && text.endsWith("]"))) {
try {
return findToken(JSON.parse(text), depth + 1);
} catch {
return looksLikeToken(text) ? text : "";
}
}
return looksLikeToken(text) ? text : "";
}
if (typeof value !== "object") {
return "";
}
for (const [key, nested] of Object.entries(value)) {
if (tokenFieldNames.has(key) && looksLikeToken(nested)) {
return String(nested).trim();
}
}
for (const nested of Object.values(value)) {
const token = findToken(nested, depth + 1);
if (token) {
return token;
}
}
return "";
}
function scanStorage(storage, storageName) {
for (const key of storageKeys) {
const token = findToken(storage.getItem(key));
if (token) {
return { token, source: `${storageName}:${key}` };
}
}
for (let index = 0; index < storage.length; index += 1) {
const key = storage.key(index);
if (!key || !/(auth|token|session)/i.test(key)) {
continue;
}
const token = findToken(storage.getItem(key));
if (token) {
return { token, source: `${storageName}:${key}` };
}
}
return null;
}
try {
return scanStorage(window.localStorage, "localStorage") || scanStorage(window.sessionStorage, "sessionStorage");
} catch (error) {
return { token: "", source: "", error: error instanceof Error ? error.message : String(error) };
}
}
function deerExtractCurrentPage() {
const maxLocalChars = 220000;
function cleanText(value) {
return String(value || "")
.replace(/\s+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
}
function escapeCell(value) {
return cleanText(value).replace(/\|/g, "\\|").replace(/\n/g, " ");
}
function tableToMarkdown(table, index) {
const rows = Array.from(table.rows || []).map((row) =>
Array.from(row.cells || []).map((cell) => escapeCell(cell.innerText)),
);
if (rows.length === 0 || rows.every((row) => row.length === 0)) {
return "";
}
const width = Math.max(...rows.map((row) => row.length));
const normalized = rows.map((row) => {
const next = row.slice();
while (next.length < width) next.push("");
return next;
});
const header = normalized[0];
const divider = Array.from({ length: width }, () => "---");
const body = normalized.slice(1);
return [
`### Table ${index + 1}`,
"",
`| ${header.join(" | ")} |`,
`| ${divider.join(" | ")} |`,
...body.map((row) => `| ${row.join(" | ")} |`),
].join("\n");
}
const clone = document.body ? document.body.cloneNode(true) : null;
if (clone) {
clone.querySelectorAll("script, style, noscript, svg, canvas, iframe").forEach((node) => node.remove());
}
const title = document.title || "";
const url = location.href;
const description = document.querySelector('meta[name="description"]')?.getAttribute("content") || "";
const main = clone?.querySelector("article, main, [role='main']") || clone;
const text = cleanText(main?.innerText || document.body?.innerText || "");
const tables = Array.from(document.querySelectorAll("table"))
.map((table, index) => tableToMarkdown(table, index))
.filter(Boolean);
const parts = [];
if (description.trim()) {
parts.push(`## Meta Description\n\n${cleanText(description)}`);
}
if (text) {
parts.push(`## Page Text\n\n${text}`);
}
if (tables.length > 0) {
parts.push(`## Tables\n\n${tables.join("\n\n")}`);
}
let content = parts.join("\n\n");
if (content.length > maxLocalChars) {
content = `${content.slice(0, maxLocalChars)}\n\n[Truncated locally by zncm Web Clipper]`;
}
return { title, url, content, contentType: "markdown" };
}
// Injected into the page to build an indexed list of interactive elements plus
// the visible page text. Each interactive element is tagged with
// `data-deer-index` so a follow-up deerPerformAction call can find it by index.
function deerObservePage(maxElements) {
const limit = Math.max(10, Number(maxElements || 150));
const DEER_ATTR = "data-deer-index";
document.querySelectorAll(`[${DEER_ATTR}]`).forEach((node) => node.removeAttribute(DEER_ATTR));
function isVisible(el) {
if (!(el instanceof Element)) return false;
const rect = el.getBoundingClientRect();
if (rect.width <= 1 && rect.height <= 1) return false;
const style = window.getComputedStyle(el);
if (style.visibility === "hidden" || style.display === "none" || style.opacity === "0") return false;
if (el.disabled) return false;
return true;
}
function labelFor(el) {
const aria = el.getAttribute("aria-label");
if (aria && aria.trim()) return aria.trim();
const placeholder = el.getAttribute("placeholder");
const title = el.getAttribute("title");
const name = el.getAttribute("name");
const text = (el.innerText || el.textContent || "").trim();
if (text) return text.replace(/\s+/g, " ");
if (placeholder && placeholder.trim()) return placeholder.trim();
if (title && title.trim()) return title.trim();
if (el.value && String(el.value).trim()) return String(el.value).trim();
if (name && name.trim()) return name.trim();
const alt = el.querySelector?.("img[alt]")?.getAttribute("alt");
if (alt && alt.trim()) return alt.trim();
return "";
}
const selector = [
"a[href]",
"button",
"input:not([type=hidden])",
"select",
"textarea",
"[role=button]",
"[role=link]",
"[role=tab]",
"[role=menuitem]",
"[role=checkbox]",
"[role=radio]",
"[role=switch]",
"[contenteditable=true]",
"[onclick]",
].join(",");
const seen = new Set();
const elements = [];
let index = 0;
for (const el of document.querySelectorAll(selector)) {
if (index >= limit) break;
if (seen.has(el) || !isVisible(el)) continue;
seen.add(el);
el.setAttribute(DEER_ATTR, String(index));
const tag = el.tagName.toLowerCase();
let label = labelFor(el);
if (label.length > 200) label = label.slice(0, 200);
const entry = { index, tag, label };
const type = el.getAttribute("type") || el.getAttribute("role");
if (type) entry.type = type;
if (tag === "input" || tag === "textarea" || tag === "select") {
const value = String(el.value || "");
if (value) entry.value = value.slice(0, 80);
}
if (tag === "a") {
const href = el.getAttribute("href") || "";
if (href) entry.href = href.slice(0, 200);
}
elements.push(entry);
index += 1;
}
// Inline text extraction so this function stays self-contained when injected
// via chrome.scripting.executeScript (no dependency on other content-script fns).
let text = "";
try {
const clone = document.body ? document.body.cloneNode(true) : null;
if (clone) {
clone.querySelectorAll(`script, style, noscript, svg, canvas, iframe, [${DEER_ATTR}-skip]`).forEach((node) => node.remove());
}
const main = clone?.querySelector("article, main, [role='main']") || clone;
text = String(main?.innerText || document.body?.innerText || "")
.replace(/\s+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
} catch {
text = "";
}
return {
url: location.href,
title: document.title || "",
elements,
text,
};
}
// Injected into the page to perform a single action on the element previously
// tagged by deerObservePage (by index). Returns {status, message}.
async function deerPerformAction(action) {
const DEER_ATTR = "data-deer-index";
const type = String(action?.type || "").toLowerCase();
function findByIndex(idx) {
if (idx === undefined || idx === null || idx < 0) return null;
return document.querySelector(`[${DEER_ATTR}="${idx}"]`);
}
function fireInput(el, value) {
const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
if (setter) {
setter.call(el, value);
} else {
el.value = value;
}
el.dispatchEvent(new Event("input", { bubbles: true }));
el.dispatchEvent(new Event("change", { bubbles: true }));
}
try {
if (type === "observe" || type === "extract") {
return { status: "ok", message: type === "extract" ? "Page text re-read." : "Observed page." };
}
if (type === "scroll") {
const el = findByIndex(action.index);
if (el) {
el.scrollIntoView({ block: "center", behavior: "instant" });
return { status: "ok", message: "Scrolled element into view." };
}
window.scrollBy(0, Math.round(window.innerHeight * 0.85));
return { status: "ok", message: "Scrolled down one viewport." };
}
if (type === "wait") {
const selector = String(action.wait_for || "").trim();
const timeoutMs = Math.max(500, Number(action.timeout_ms || 8000));
if (!selector) {
await new Promise((resolve) => setTimeout(resolve, Math.min(timeoutMs, 3000)));
return { status: "ok", message: "Waited." };
}
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (document.querySelector(selector)) {
return { status: "ok", message: `Element ${selector} appeared.` };
}
await new Promise((resolve) => setTimeout(resolve, 200));
}
return { status: "timeout", message: `Element ${selector} did not appear within ${timeoutMs}ms.` };
}
if (type === "click") {
const el = findByIndex(action.index);
if (!el) return { status: "error", message: `No element with index ${action.index}. Re-observe the page.` };
el.scrollIntoView({ block: "center", behavior: "instant" });
if (typeof el.focus === "function") el.focus();
el.click();
return { status: "ok", message: `Clicked element ${action.index}.` };
}
if (type === "type") {
const el = findByIndex(action.index);
if (!el) return { status: "error", message: `No element with index ${action.index}. Re-observe the page.` };
el.scrollIntoView({ block: "center", behavior: "instant" });
if (typeof el.focus === "function") el.focus();
const value = String(action.text ?? "");
if (el.isContentEditable) {
el.textContent = value;
el.dispatchEvent(new Event("input", { bubbles: true }));
} else {
fireInput(el, value);
}
if (action.submit) {
const enterInit = { bubbles: true, cancelable: true, key: "Enter", code: "Enter", keyCode: 13, which: 13 };
el.dispatchEvent(new KeyboardEvent("keydown", enterInit));
el.dispatchEvent(new KeyboardEvent("keyup", enterInit));
const form = el.form || el.closest("form");
if (form && typeof form.requestSubmit === "function") {
try {
form.requestSubmit();
} catch {
form.submit?.();
}
}
}
return { status: "ok", message: `Typed into element ${action.index}${action.submit ? " and submitted" : ""}.` };
}
return { status: "error", message: `Unsupported action type: ${type}` };
} catch (error) {
return { status: "error", message: error instanceof Error ? error.message : String(error) };
}
}
@@ -0,0 +1,96 @@
* {
box-sizing: border-box;
}
body {
margin: 0;
color: #171717;
background: #fafafa;
font: 14px/1.5 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
h1 {
margin: 0 0 14px;
font-size: 16px;
}
.popup,
.options {
display: grid;
gap: 12px;
padding: 14px;
}
.popup {
width: 340px;
}
.options {
max-width: 720px;
}
label {
display: grid;
gap: 6px;
font-weight: 600;
}
label.checkbox {
grid-template-columns: auto 1fr;
align-items: center;
font-weight: 500;
}
label.checkbox input {
width: auto;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
input,
textarea {
width: 100%;
border: 1px solid #d4d4d4;
border-radius: 6px;
padding: 8px;
background: #fff;
color: inherit;
font: inherit;
font-weight: 400;
}
textarea {
resize: vertical;
}
button {
border: 0;
border-radius: 6px;
padding: 9px 12px;
background: #111827;
color: #fff;
cursor: pointer;
font: inherit;
font-weight: 600;
}
button.secondary {
background: #e5e7eb;
color: #111827;
}
button:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.status {
min-height: 20px;
margin: 0;
color: #525252;
white-space: pre-wrap;
}
-9
View File
@@ -1,9 +0,0 @@
# GEMINI_API_KEY: Required for Gemini AI API calls.
# AI Studio automatically injects this at runtime from user secrets.
# Users configure this via the Secrets panel in the AI Studio UI.
GEMINI_API_KEY="MY_GEMINI_API_KEY"
# APP_URL: The URL where this applet is hosted.
# AI Studio automatically injects this at runtime with the Cloud Run service URL.
# Used for self-referential links, OAuth callbacks, and API endpoints.
APP_URL="MY_APP_URL"
-20
View File
@@ -1,20 +0,0 @@
<div align="center">
<img width="1200" height="475" alt="GHBanner" src="https://ai.google.dev/static/site-assets/images/share-ais-513315318.png" />
</div>
# Run and deploy your AI Studio app
This contains everything you need to run your app locally.
View your app in AI Studio: https://ai.studio/apps/75261c35-a558-4ef8-9501-e8b7f9c98bfb
## Run Locally
**Prerequisites:** Node.js
1. Install dependencies:
`npm install`
2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
3. Run the app:
`npm run dev`
-6
View File
@@ -1,6 +0,0 @@
{
"name": "Gemini Style Assistant",
"description": "A clean, modern AI assistant interface inspired by Google Gemini with centered search, suggestion pills, and a minimalist sidebar.",
"requestFramePermissions": [],
"majorCapabilities": ["MAJOR_CAPABILITY_SERVER_SIDE_GEMINI_API"]
}
-35
View File
@@ -1,35 +0,0 @@
{
"name": "react-example",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --port=3000 --host=0.0.0.0",
"build": "vite build",
"preview": "vite preview",
"clean": "rm -rf dist server.js",
"lint": "tsc --noEmit"
},
"dependencies": {
"@google/genai": "^1.29.0",
"@tailwindcss/vite": "^4.1.14",
"@vitejs/plugin-react": "^5.0.4",
"lucide-react": "^0.546.0",
"react": "^19.0.1",
"react-dom": "^19.0.1",
"vite": "^6.2.3",
"express": "^4.21.2",
"dotenv": "^17.2.3",
"motion": "^12.23.24"
},
"devDependencies": {
"@types/node": "^22.14.0",
"autoprefixer": "^10.4.21",
"esbuild": "^0.25.0",
"tailwindcss": "^4.1.14",
"tsx": "^4.21.0",
"typescript": "~5.8.2",
"vite": "^6.2.3",
"@types/express": "^4.17.21"
}
}
-238
View File
@@ -1,238 +0,0 @@
/**
* @license
* SPDX-License-Identifier: Apache-2.0
*/
import { useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import {
MessageSquare,
Bot,
Wrench,
Brain,
ListChecks,
Settings,
Menu,
Mic,
Plus,
Sparkles,
ArrowRight,
User,
History,
LayoutGrid,
Languages,
Code2,
Music,
Database,
Search
} from 'lucide-react';
export default function App() {
const [sidebarOpen, setSidebarOpen] = useState(true);
const navItems = [
{ icon: MessageSquare, label: '对话', active: true },
{ icon: Bot, label: '智能体' },
{ icon: Wrench, label: '技能' },
{ icon: Brain, label: '记忆' },
{ icon: ListChecks, label: '任务管理' },
];
const recentChats = [
'CM助手初次问候交谈',
'Untitled',
'Untitled',
'Untitled',
'帮我写一个500字的文案',
'帮我生成一个写论文的实例',
];
const suggestions = [
{ icon: Code2, label: 'Build an Android app', color: 'text-green-600', bg: 'bg-green-50' },
{ icon: Languages, label: 'Convert text to speech', color: 'text-blue-600', bg: 'bg-blue-50' },
{ icon: Music, label: 'Generate music', color: 'text-purple-600', bg: 'bg-purple-50' },
{ icon: Database, label: 'Add database and auth', color: 'text-cyan-600', bg: 'bg-cyan-50' },
];
return (
<div className="flex h-screen w-full bg-white font-sans text-gray-900 overflow-hidden">
{/* Sidebar */}
<motion.aside
initial={false}
animate={{ width: sidebarOpen ? 280 : 0, opacity: sidebarOpen ? 1 : 0 }}
className="relative bg-gray-50 border-r border-gray-100 flex flex-col h-full"
>
<div className="p-4 flex items-center justify-between">
<div className="flex items-center gap-2 px-2 py-1.5 bg-red-50 text-red-700 rounded-lg cursor-pointer">
<Plus size={18} />
<span className="font-medium text-sm">新对话</span>
</div>
</div>
<nav className="flex-1 overflow-y-auto px-2 space-y-1">
<div className="space-y-1 pb-4">
{navItems.map((item) => (
<div
key={item.label}
className={`flex items-center gap-3 px-3 py-2 rounded-xl cursor-pointer transition-colors ${
item.active ? 'bg-white shadow-sm font-medium' : 'hover:bg-gray-100 text-gray-600'
}`}
>
<item.icon size={18} />
<span className="text-sm">{item.label}</span>
</div>
))}
</div>
<div className="pt-4 border-t border-gray-200">
<h3 className="px-3 mb-2 text-xs font-semibold text-gray-400 uppercase tracking-wider">
最近对话
</h3>
{recentChats.map((chat, idx) => (
<div
key={idx}
className="px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-lg cursor-pointer truncate"
>
{chat}
</div>
))}
</div>
</nav>
<div className="p-4 border-t border-gray-200">
<div className="flex items-center gap-3 px-3 py-2 text-gray-600 hover:bg-gray-100 rounded-xl cursor-pointer">
<Settings size={18} />
<span className="text-sm">设置和更多</span>
</div>
</div>
</motion.aside>
{/* Main Content */}
<main className="flex-1 flex flex-col relative h-full overflow-y-auto">
{/* Top bar */}
<header className="absolute top-0 w-full p-4 flex items-center justify-between z-10">
<button
onClick={() => setSidebarOpen(!sidebarOpen)}
className="p-2 hover:bg-gray-100 rounded-lg text-gray-500 transition-colors"
>
<Menu size={20} />
</button>
<div className="flex items-center gap-2">
<button className="p-2 hover:bg-gray-100 rounded-lg text-gray-500 transition-colors">
<Settings size={20} />
</button>
<div className="w-8 h-8 rounded-full bg-gradient-to-tr from-blue-400 to-purple-400 flex items-center justify-center text-white shadow-sm ring-2 ring-white cursor-pointer overflow-hidden">
<User size={16} />
</div>
</div>
</header>
{/* Center Canvas */}
<div className="flex-1 flex flex-col items-center justify-center px-4 max-w-4xl mx-auto w-full pt-16">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="text-center mb-12 relative"
>
<div className="absolute -top-16 left-1/2 -translate-x-1/2 opacity-10 blur-2xl pointer-events-none">
<Sparkles size={120} className="text-blue-500 animate-pulse" />
</div>
<h1 className="text-5xl font-display font-medium tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-gray-900 to-gray-500 mb-4 px-4">
Build your ideas with Gemini
</h1>
<Sparkles className="absolute -right-8 top-0 text-blue-200 opacity-50" size={48} />
</motion.div>
{/* Search/Input Area */}
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: 0.1 }}
className="w-full max-w-2xl relative group"
>
<div className="gemini-gradient-border gemini-shadow rounded-3xl bg-white p-2">
<div className="flex flex-col p-4 space-y-4">
<textarea
placeholder="Describe an app and let Gemini do the rest"
className="w-full bg-transparent resize-none focus:outline-none text-lg text-gray-700 min-h-[80px]"
/>
<div className="flex items-center justify-between pt-2">
<div className="flex items-center gap-2">
<button className="p-2 hover:bg-gray-100 rounded-full text-gray-400 transition-colors">
<Mic size={20} />
</button>
<button className="p-2 hover:bg-gray-100 rounded-full text-gray-400 transition-colors">
<Plus size={20} />
</button>
</div>
<button className="flex items-center gap-2 px-5 py-2.5 bg-gray-50 hover:bg-gray-100 text-gray-700 rounded-full border border-gray-200 transition-all font-medium text-sm group/btn shadow-sm">
<Sparkles size={16} className="text-blue-500" />
I'm feeling lucky
<ArrowRight size={14} className="opacity-0 -translate-x-2 group-hover/btn:opacity-100 group-hover/btn:translate-x-0 transition-all" />
</button>
</div>
</div>
</div>
</motion.div>
{/* Suggestion Chips */}
<div className="mt-8 flex flex-wrap justify-center gap-3">
{suggestions.map((suggestion, idx) => (
<motion.button
key={suggestion.label}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 + idx * 0.05 }}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
className={`flex items-center gap-2 px-4 py-2.5 rounded-2xl border border-gray-100 bg-white hover:bg-gray-50 shadow-sm transition-all text-sm font-medium group hover:border-gray-200 text-gray-700`}
>
<suggestion.icon className={`w-4 h-4 ${suggestion.color}`} />
{suggestion.label}
</motion.button>
))}
<motion.button
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.4 }}
className="flex items-center justify-center p-2 rounded-full border border-gray-100 bg-white hover:bg-gray-50 text-gray-400 shadow-sm transition-all"
>
<ArrowRight size={16} />
</motion.button>
</div>
</div>
{/* Footer info/links */}
<footer className="w-full max-w-4xl mx-auto px-4 py-12 mt-auto">
<div className="rounded-3xl border border-gray-100 bg-gray-50/50 p-8 flex items-center justify-between group hover:bg-gray-50 transition-colors">
<div>
<h2 className="text-2xl font-display font-medium text-gray-800 mb-1">
Discover and remix app ideas
</h2>
<p className="text-gray-500 text-sm italic">
(Gallery view pending implementation)
</p>
</div>
<button className="flex items-center gap-2 px-6 py-2.5 bg-white border border-gray-200 rounded-xl hover:shadow-md transition-all font-medium text-gray-700">
Browse the app gallery
<ArrowRight size={18} />
</button>
</div>
</footer>
{/* Floating Right Bar (from target image) */}
<div className="absolute right-6 top-1/2 -translate-y-1/2 flex flex-col gap-4">
<button className="p-2.5 bg-white shadow-lg border border-gray-100 rounded-xl hover:scale-110 transition-all text-gray-400">
<LayoutGrid size={22} />
</button>
<button className="p-2.5 bg-white shadow-lg border border-gray-100 rounded-xl hover:scale-110 transition-all text-gray-400">
<Languages size={22} />
</button>
</div>
</main>
</div>
);
}
-71
View File
@@ -1,71 +0,0 @@
@import "tailwindcss";
@theme {
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
--font-display: "Outfit", "Inter", sans-serif;
}
@layer base {
body {
@apply bg-white text-gray-900 antialiased;
}
}
@layer utilities {
.gemini-shadow {
box-shadow: 0 0 20px rgba(66, 133, 244, 0.08),
0 0 40px rgba(219, 68, 55, 0.04),
0 0 60px rgba(244, 180, 0, 0.04),
0 0 80px rgba(15, 157, 88, 0.04);
}
.gemini-gradient-border {
position: relative;
background: white;
border-radius: 1.5rem; /* rounded-3xl */
z-index: 0;
overflow: hidden;
}
.gemini-gradient-border::before {
content: '';
position: absolute;
width: 150%;
height: 150%;
top: -25%;
left: -25%;
background: conic-gradient(
from 0deg,
transparent 0deg,
transparent 90deg,
#4285F4 120deg,
#DB4437 150deg,
#F4B400 180deg,
#0F9D58 210deg,
transparent 240deg
);
z-index: -2;
animation: rotate 3s linear infinite;
filter: blur(15px);
}
.gemini-gradient-border::after {
content: '';
position: absolute;
inset: 1.5px; /* The "thickness" of the glow border */
background: white;
border-radius: calc(1.5rem - 1px);
z-index: -1;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
}
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Outfit:wght@400;500;600&display=swap');
-10
View File
@@ -1,10 +0,0 @@
import {StrictMode} from 'react';
import {createRoot} from 'react-dom/client';
import App from './App.tsx';
import './index.css';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);
-26
View File
@@ -1,26 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": true,
"useDefineForClassFields": false,
"module": "ESNext",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true,
"moduleResolution": "bundler",
"isolatedModules": true,
"moduleDetection": "force",
"allowJs": true,
"jsx": "react-jsx",
"paths": {
"@/*": [
"./*"
]
},
"allowImportingTsExtensions": true,
"noEmit": true
}
}
-22
View File
@@ -1,22 +0,0 @@
import tailwindcss from '@tailwindcss/vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import {defineConfig} from 'vite';
export default defineConfig(() => {
return {
plugins: [react(), tailwindcss()],
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
},
},
server: {
// HMR is disabled in AI Studio via DISABLE_HMR env var.
// Do not modify—file watching is disabled to prevent flickering during agent edits.
hmr: process.env.DISABLE_HMR !== 'true',
// Disable file watching when DISABLE_HMR is true to save CPU during agent edits.
watch: process.env.DISABLE_HMR === 'true' ? null : {},
},
};
});
+620
View File
@@ -0,0 +1,620 @@
<!DOCTYPE html>
<!--
社交信息流 · 布局样式复刻 Demo(无品牌标识版)
------------------------------------------------
- 版式/布局参考主流社交平台桌面端信息流(顶栏 + 三栏 + 信息流卡片)
- 不包含任何真实平台的商标 / Logo / 品牌元素,可放心二次修改
- 所有展示数据集中在 <script> 顶部的「数据区」,替换字段即可换数据
- 双击直接用浏览器打开,无任何外部依赖
-->
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>社交信息流 · 布局样式 Demo</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
html { color-scheme: light; }
body {
background: #f0f2f5;
color: #050505;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue",
"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
font-size: 15px;
}
button { font: inherit; border: 0; background: none; cursor: pointer; color: inherit; }
svg { display: block; }
/* ============ 顶栏 ============ */
.topbar {
position: fixed; inset: 0 0 auto 0; height: 56px; z-index: 100;
background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,.1);
display: flex; align-items: center; justify-content: space-between;
padding: 0 16px;
}
.tb-left, .tb-right { display: flex; align-items: center; gap: 8px; min-width: 280px; }
.tb-right { justify-content: flex-end; }
.logo-mark {
width: 40px; height: 40px; border-radius: 50%;
background: #1877f2; color: #fff; display: grid; place-items: center; flex: none;
}
.search-pill {
display: flex; align-items: center; gap: 8px;
background: #f0f2f5; border-radius: 20px; padding: 9px 14px;
width: 240px; color: #65676b;
}
.tb-center { display: flex; gap: 6px; }
.tb-tab {
width: 108px; height: 56px; border-radius: 8px;
display: grid; place-items: center; color: #65676b; position: relative;
}
.tb-tab:hover { background: #f2f2f2; }
.tb-tab.active { color: #1877f2; }
.tb-tab.active::after {
content: ""; position: absolute; left: 12px; right: 12px; bottom: 0;
height: 3px; border-radius: 3px 3px 0 0; background: #1877f2;
}
.icon-btn {
width: 40px; height: 40px; border-radius: 50%;
background: #e4e6eb; display: grid; place-items: center; position: relative;
}
.icon-btn:hover { background: #d8dadf; }
.notif-badge {
position: absolute; top: -3px; right: -3px;
background: #e41e3f; color: #fff; font-size: 11px; font-weight: 600;
line-height: 1; border-radius: 10px; padding: 3px 5px; border: 2px solid #fff;
}
.create-btn {
display: flex; align-items: center; gap: 6px;
background: #e4e6eb; border-radius: 8px; padding: 10px 14px; font-weight: 600;
}
.create-btn:hover { background: #d8dadf; }
/* ============ 三栏布局 ============ */
.layout {
display: flex; justify-content: center; gap: 16px;
max-width: 1240px; margin: 0 auto; padding: 72px 12px 32px;
}
.side {
width: 300px; flex: none;
position: sticky; top: 72px; align-self: flex-start;
max-height: calc(100vh - 80px); overflow-y: auto;
}
.feed { width: 590px; flex: none; }
@media (max-width: 1160px) { .side.right { display: none; } }
@media (max-width: 980px) { .side.left { display: none; } }
/* ============ 左侧导航 ============ */
.side-item {
display: flex; align-items: center; gap: 12px;
padding: 8px 12px; margin: 0 8px; border-radius: 8px;
font-size: 15px; font-weight: 500;
}
.side-item:hover { background: #e4e6eb; }
.side-item .si-ic { width: 36px; height: 36px; flex: none; color: #3a4a5c; display: grid; place-items: center; }
.side-sep { height: 1px; background: #e4e6eb; margin: 10px 16px; }
.side-title { color: #65676b; font-size: 17px; font-weight: 600; margin: 14px 16px 4px; }
.see-more { color: #65676b; }
/* ============ 快拍 ============ */
.stories { display: flex; gap: 8px; overflow-x: auto; padding: 4px 2px 12px; }
.story {
width: 112px; height: 200px; flex: none; border-radius: 12px;
position: relative; overflow: hidden; box-shadow: 0 1px 2px rgba(0,0,0,.15);
}
.story-create {
background: #fff; display: flex; flex-direction: column; justify-content: flex-end;
}
.story-create .sc-img { height: 148px; display: grid; place-items: center; color: #a8b3c4; }
.story-create .sc-label {
padding: 10px 8px 12px; text-align: center; font-size: 13px; font-weight: 600;
border-top: 1px solid #e4e6eb;
}
.story-create .sc-plus {
position: absolute; left: 50%; top: 124px; transform: translateX(-50%);
width: 36px; height: 36px; border-radius: 50%; background: #1877f2; color: #fff;
display: grid; place-items: center; border: 3px solid #fff;
}
.story-meta { position: absolute; left: 8px; right: 8px; bottom: 8px; color: #fff; }
.story-meta .sm-name {
font-size: 13px; font-weight: 600; text-shadow: 0 1px 2px rgba(0,0,0,.6);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.story-meta .avatar { border: 2px solid #fff; margin-bottom: 6px; }
/* ============ 卡片通用 ============ */
.card {
background: #fff; border-radius: 8px;
box-shadow: 0 1px 2px rgba(0,0,0,.1); margin-bottom: 16px;
}
.avatar {
width: 40px; height: 40px; border-radius: 50%; flex: none;
display: grid; place-items: center; color: #fff; font-weight: 600; font-size: 16px;
user-select: none; background: #1877f2;
}
.avatar.sm { width: 32px; height: 32px; font-size: 13px; }
/* ============ 发帖框 ============ */
.composer-top { display: flex; align-items: center; gap: 10px; padding: 12px 16px; }
.composer-input {
flex: 1; background: #f0f2f5; border-radius: 20px; padding: 10px 16px;
color: #65676b; font-size: 16px;
}
.composer-actions { display: flex; border-top: 1px solid #e4e6eb; margin: 2px 12px 0; }
.c-action {
flex: 1; display: flex; justify-content: center; align-items: center; gap: 8px;
padding: 10px; border-radius: 6px; font-weight: 600; color: #65676b;
}
.c-action:hover { background: #f2f2f2; }
.ic-video { color: #f3425f; } .ic-photo { color: #45bd62; } .ic-emoji { color: #f7b928; }
/* ============ 帖子 ============ */
.post-head { display: flex; align-items: center; gap: 10px; padding: 12px 16px 0; }
.ph-meta { flex: 1; min-width: 0; }
.ph-name { font-weight: 600; display: flex; align-items: center; gap: 4px; }
.ph-sub { color: #65676b; font-size: 13px; display: flex; align-items: center; gap: 4px; margin-top: 2px; }
.ph-more { color: #65676b; }
.post-text { padding: 12px 16px; line-height: 1.55; white-space: pre-wrap; }
.post-media { display: grid; gap: 2px; background: #fff; }
.post-media.n1 { grid-template-columns: 1fr; }
.post-media.n2 { grid-template-columns: 1fr 1fr; }
.post-media.n3 { grid-template-columns: 2fr 1fr; }
.post-media.n4 { grid-template-columns: 1fr 1fr; }
.tile { position: relative; overflow: hidden; aspect-ratio: 1.8; background: #dfe7f5; }
.post-media.n3 .tile:first-child { grid-row: span 2; aspect-ratio: auto; }
.tile img { width: 100%; height: 100%; object-fit: cover; display: block; }
.img-ph {
position: absolute; inset: 0; display: grid; place-items: center;
color: rgba(255,255,255,.9);
}
.tile-more {
position: absolute; inset: 0; background: rgba(0,0,0,.45); color: #fff;
display: grid; place-items: center; font-size: 26px; font-weight: 600;
}
.link-card {
margin: 0 16px 12px; border: 1px solid #e4e6eb; border-radius: 8px;
overflow: hidden; display: flex;
}
.link-img { width: 140px; flex: none; min-height: 120px; position: relative; background: #dfe7f5; }
.link-img .img-ph { color: rgba(255,255,255,.9); }
.link-body { padding: 10px 14px; min-width: 0; }
.link-domain { color: #65676b; font-size: 12px; text-transform: uppercase; letter-spacing: .04em; }
.link-title { font-weight: 600; font-size: 15px; margin: 3px 0 4px; }
.link-desc { color: #65676b; font-size: 13px; line-height: 1.4; }
.stats { display: flex; align-items: center; gap: 6px; padding: 10px 16px 6px; color: #65676b; }
.stats .grow { flex: 1; }
.rx {
width: 20px; height: 20px; border-radius: 50%; background: #fff;
display: grid; place-items: center; box-shadow: 0 0 0 1px rgba(0,0,0,.05);
}
.post-actions { display: flex; border-top: 1px solid #e4e6eb; margin: 4px 12px 4px; }
.p-action {
flex: 1; display: flex; justify-content: center; align-items: center; gap: 8px;
padding: 9px; border-radius: 6px; font-weight: 600; color: #65676b;
}
.p-action:hover { background: #f2f2f2; }
.p-action.liked { color: #1877f2; }
.comments { padding: 2px 16px 12px; }
.comment { display: flex; gap: 8px; margin-top: 8px; }
.c-bubble { background: #f0f2f5; border-radius: 16px; padding: 8px 12px; min-width: 0; }
.c-name { font-weight: 600; font-size: 13px; }
.c-text { font-size: 15px; line-height: 1.45; }
.c-foot { padding-left: 40px; color: #65676b; font-size: 13px; font-weight: 600; display: flex; gap: 12px; margin-top: 2px; }
/* ============ 右侧栏 ============ */
.sponsored { display: flex; gap: 12px; padding: 8px 12px; margin: 0 8px; border-radius: 8px; }
.sponsored:hover { background: #e4e6eb; }
.sq {
width: 96px; height: 96px; flex: none; border-radius: 8px; overflow: hidden;
position: relative; background: #dfe7f5;
}
.sp-title { font-weight: 500; }
.sp-domain { color: #65676b; font-size: 13px; margin-top: 2px; }
.birthday {
display: flex; gap: 10px; padding: 4px 16px; font-size: 14px; line-height: 1.45;
}
.contact-row {
display: flex; align-items: center; gap: 10px;
padding: 6px 12px; margin: 0 8px; border-radius: 8px; font-weight: 500;
}
.contact-row:hover { background: #e4e6eb; }
.contact-av { position: relative; flex: none; }
.online-dot {
position: absolute; right: 0; bottom: 0; width: 10px; height: 10px;
border-radius: 50%; background: #31a24c; border: 2px solid #fff;
}
.contacts-head {
display: flex; align-items: center; justify-content: space-between;
padding: 6px 16px 2px;
}
.contacts-head .ch-actions { display: flex; gap: 8px; color: #65676b; }
</style>
</head>
<body>
<!-- ================= 顶栏 ================= -->
<header class="topbar">
<div class="tb-left">
<div class="logo-mark" title="示例 Logo(替换成你们自己的标识)">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 11.5a8.5 8.5 0 0 1-8.5 8.5c-1.5 0-2.9-.4-4.1-1L3 20l1-5.4A8.5 8.5 0 1 1 21 11.5z"/>
</svg>
</div>
<div class="search-pill">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><line x1="16.5" y1="16.5" x2="21" y2="21"/></svg>
搜索
</div>
</div>
<nav class="tb-center">
<button class="tb-tab active" title="首页">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/></svg>
</button>
<button class="tb-tab" title="视频">
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="M15.5 10.5 21.5 7v10l-6-3.5"/></svg>
</button>
<button class="tb-tab" title="市场">
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9.5 5.2 4h13.6L20 9.5"/><path d="M4 9.5V20h16V9.5"/><path d="M10 20v-5.5h4V20"/></svg>
</button>
<button class="tb-tab" title="群组">
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8.5" r="3"/><path d="M3 20c0-3.2 2.7-5 6-5s6 1.8 6 5"/><circle cx="17" cy="9.5" r="2.3"/><path d="M16 15.3c2.9.2 5 1.8 5 4.7"/></svg>
</button>
<button class="tb-tab" title="游戏">
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="7.5" width="19" height="10" rx="4"/><path d="M7 10.5v4M5 12.5h4"/><circle cx="16" cy="11" r=".6" fill="currentColor"/><circle cx="18.5" cy="13.5" r=".6" fill="currentColor"/></svg>
</button>
</nav>
<div class="tb-right">
<button class="create-btn">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
创建
</button>
<button class="icon-btn" title="菜单">
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="5" r="1.7"/><circle cx="12" cy="5" r="1.7"/><circle cx="19" cy="5" r="1.7"/><circle cx="5" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="19" cy="12" r="1.7"/><circle cx="5" cy="19" r="1.7"/><circle cx="12" cy="19" r="1.7"/><circle cx="19" cy="19" r="1.7"/></svg>
</button>
<button class="icon-btn" title="消息">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.5 8.5 0 0 1-8.5 8.5c-1.5 0-2.9-.4-4.1-1L3 20l1-5.4A8.5 8.5 0 1 1 21 11.5z"/><path d="M12.8 8 9.3 13h2.6l-.6 3.3 3.5-5.1h-2.6z"/></svg>
</button>
<button class="icon-btn" title="通知">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M18 16v-5a6 6 0 1 0-12 0v5l-1.6 1.8h15.2z"/><path d="M10 20.2a2.1 2.1 0 0 0 4 0"/></svg>
<span class="notif-badge">3</span>
</button>
<div class="avatar" style="background:#45bd62">我</div>
</div>
</header>
<!-- ================= 三栏 ================= -->
<div class="layout">
<!-- ---- 左侧导航 ---- -->
<aside class="side left">
<div class="side-item">
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8.5" r="3"/><path d="M3 20c0-3.2 2.7-5 6-5s6 1.8 6 5"/><circle cx="17" cy="9.5" r="2.3"/><path d="M16 15.3c2.9.2 5 1.8 5 4.7"/></svg></div>
好友
</div>
<div class="side-item">
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7.5V12l3 2"/></svg></div>
回忆动态
</div>
<div class="side-item">
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5.5A2.5 2.5 0 0 1 7.5 3h9a2.5 2.5 0 0 1 2.5 2.5z"/></svg></div>
已保存
</div>
<div class="side-item">
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8.5" r="3"/><path d="M3 20c0-3.2 2.7-5 6-5s6 1.8 6 5"/><circle cx="17" cy="9.5" r="2.3"/><path d="M16 15.3c2.9.2 5 1.8 5 4.7"/></svg></div>
群组
</div>
<div class="side-item">
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="M15.5 10.5 21.5 7v10l-6-3.5"/></svg></div>
视频
</div>
<div class="side-item">
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9.5 5.2 4h13.6L20 9.5"/><path d="M4 9.5V20h16V9.5"/><path d="M10 20v-5.5h4V20"/></svg></div>
市场
</div>
<div class="side-item">
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M16 3v4M8 3v4M3 11h18"/></svg></div>
活动
</div>
<div class="side-sep"></div>
<div class="side-title">你的捷径</div>
<div class="side-item"><div class="avatar sm" style="background:#7c5cff">登</div>周末登山小队</div>
<div class="side-item"><div class="avatar sm" style="background:#12b5cb">摄</div>城市摄影交流</div>
<div class="side-item"><div class="avatar sm" style="background:#f3425f">书</div>读书会</div>
<div class="side-item see-more">
<div class="si-ic"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9l6 6 6-6"/></svg></div>
查看更多
</div>
</aside>
<!-- ---- 中间信息流 ---- -->
<main class="feed">
<!-- 快拍 -->
<div class="stories" id="stories"></div>
<!-- 发帖框 -->
<div class="card">
<div class="composer-top">
<div class="avatar" style="background:#45bd62">我</div>
<div class="composer-input">有什么新鲜事?</div>
</div>
<div class="composer-actions">
<button class="c-action ic-video">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="M15.5 10.5 21.5 7v10l-6-3.5"/></svg>
直播视频
</button>
<button class="c-action ic-photo">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10" r="1.5"/><path d="M21 15.5l-5-5-9 8"/></svg>
照片/视频
</button>
<button class="c-action ic-emoji">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M8.5 14.5s1.3 1.8 3.5 1.8 3.5-1.8 3.5-1.8"/><circle cx="9" cy="9.5" r=".6" fill="currentColor"/><circle cx="15" cy="9.5" r=".6" fill="currentColor"/></svg>
感受/活动
</button>
</div>
</div>
<!-- 帖子(由下方数据区渲染) -->
<div id="posts"></div>
</main>
<!-- ---- 右侧栏 ---- -->
<aside class="side right">
<div class="side-title" style="margin-top:4px">赞助内容</div>
<div id="sponsored"></div>
<div class="side-sep"></div>
<div class="birthday">
<span style="font-size:24px">🎂</span>
<div><b>小林</b> 和 <b>赵敏</b> 今天过生日</div>
</div>
<div class="side-sep"></div>
<div class="contacts-head">
<span style="color:#65676b;font-weight:600">联络人</span>
<span class="ch-actions">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><line x1="16.5" y1="16.5" x2="21" y2="21"/></svg>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="M15.5 10.5 21.5 7v10l-6-3.5"/></svg>
</span>
</div>
<div id="contacts"></div>
</aside>
</div>
<script>
/* ============================================================
数据区 —— 换数据只改这里
------------------------------------------------------------
FEED 帖子字段:
name 作者名 verified 是否显示认证标
time 发布时间文案 audience "公开" / "好友"
text 正文(\n 换行)
images 配图数组:"" = 灰色占位图;填图片 URL 则显示真实图片
数量 1-4 张,布局自动变化(1 大图 / 2 / 3 / 4 宫格)
link 可选链接卡片 { domain, title, desc }
likes 点赞数 shares 分享数
comments 评论数组 [{ name, text, time, likes }]
============================================================ */
const FEED = [
{
name: "张伟", time: "5 小时", audience: "公开",
text: "连续加班两周终于把项目收尾了,今天准点下班,\n路上顺手拍了一张晚霞。生活还是需要一点仪式感 🙂",
images: [""],
likes: 128, shares: 6,
comments: [
{ name: "赵敏", text: "恭喜收尾!这张晚霞拍得真好", time: "4 小时", likes: 12 },
{ name: "孙鹏", text: "下次组个饭局庆祝一下", time: "3 小时", likes: 3 },
],
},
{
name: "城市天气指南", verified: true, time: "3 小时", audience: "公开",
text: "本周天气提示:周三起冷空气过境,气温下降 6–8℃,早晚温差加大,提醒大家适当添衣。详细预报见评论区链接。",
images: ["", "", ""],
likes: 402, shares: 36,
comments: [
{ name: "吴倩", text: "收到,已经把薄羽绒翻出来了", time: "2 小时", likes: 8 },
],
},
{
name: "王强", time: "9 小时", audience: "好友",
text: "求推荐一条周末适合新手的徒步路线,最好单程 10 公里以内、交通方便的。打算这周就走,谢谢大家!",
images: [],
likes: 17, shares: 0,
comments: [
{ name: "陈晨", text: "西郊森林公园的环线不错,全程约 8 公里,坡度平缓", time: "8 小时", likes: 5 },
{ name: "周婷", text: "记得带够水,最近天气比较干", time: "7 小时", likes: 2 },
],
},
{
name: "陈晨", time: "1 天", audience: "公开",
text: "整理了一篇新手徒步装备清单,有需要的朋友自取~",
images: [],
link: { domain: "example-outdoor.com", title: "2026 秋季徒步装备清单(新手向)", desc: "从鞋服到导航设备,一份可以照着买的入门清单。" },
likes: 54, shares: 9,
comments: [],
},
];
const STORIES = ["赵敏", "孙鹏", "周婷", "吴倩", "林芳"];
const SPONSORED = [
{ title: "云端笔记 Pro", domain: "cloudnote.example.com" },
{ title: "户外装备精选", domain: "outdoor.example.com" },
];
const CONTACTS = ["刘洋", "赵敏", "孙鹏", "周婷", "吴倩", "郑凯", "林芳"];
/* ============================================================
以下为渲染逻辑,一般不用动
============================================================ */
const AV_COLORS = ["#1877f2", "#f3425f", "#45bd62", "#f7b928", "#7c5cff", "#12b5cb"];
const PH_GRADIENTS = [
"linear-gradient(135deg,#a8c5f0,#dfe7f5)",
"linear-gradient(135deg,#f8d3c5,#f7ebe4)",
"linear-gradient(135deg,#c9e5d3,#eaf5ee)",
"linear-gradient(135deg,#e2d8f7,#f0eaf9)",
"linear-gradient(135deg,#f6e3b0,#faf2df)",
];
const STORY_GRADIENTS = [
"linear-gradient(165deg,#5b8def,#8f6ee8)",
"linear-gradient(165deg,#f5a623,#ec5e8f)",
"linear-gradient(165deg,#2ec3a6,#3f8ee8)",
"linear-gradient(165deg,#8f6ee8,#5b8def)",
"linear-gradient(165deg,#ec5e8f,#f5a623)",
];
const esc = s => String(s).replace(/[&<>"]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const colorOf = name => AV_COLORS[[...name].reduce((a, c) => a + c.charCodeAt(0), 0) % AV_COLORS.length];
const avatarHtml = (name, cls = "") =>
`<div class="avatar ${cls}" style="background:${colorOf(name)}">${esc(name.slice(0, 1))}</div>`;
const ICONS = {
like: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.3a2 2 0 0 0 2-1.7l1.4-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></svg>',
likeFilled: '<svg width="14" height="14" viewBox="0 0 24 24" fill="#1877f2" stroke="#1877f2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.3a2 2 0 0 0 2-1.7l1.4-9a2 2 0 0 0-2-2.3z"/><path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></svg>',
heart: '<svg width="14" height="14" viewBox="0 0 24 24" fill="#f3425f"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 0 0-7.8 7.8l1 1L12 21.2l7.8-7.8 1-1a5.5 5.5 0 0 0 0-7.8z"/></svg>',
comment: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>',
share: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.59 13.51l6.83 3.98M15.41 6.51l-6.82 3.98"/></svg>',
globe: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a13.5 13.5 0 0 1 0 18 13.5 13.5 0 0 1 0-18z"/></svg>',
friends: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="9" cy="8.5" r="3"/><path d="M3 20c0-3.2 2.7-5 6-5s6 1.8 6 5"/><circle cx="17" cy="9.5" r="2.3"/></svg>',
dots: '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="19" cy="12" r="1.8"/></svg>',
mountain: '<svg width="46" height="46" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10" r="1.5"/><path d="M21 15.5l-5-5-9 8"/></svg>',
link: '<svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>',
check: '<svg width="14" height="14" viewBox="0 0 24 24" fill="#1877f2"><circle cx="12" cy="12" r="10"/><path d="M17.5 9.5 10.7 16 7 12.3l1.4-1.4 2.3 2.3 5.4-5.2z" fill="#fff"/></svg>',
plus: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>',
};
const audienceIcon = a => (a === "好友" ? ICONS.friends : ICONS.globe);
const isImg = v => /^(https?:|data:|\.?\/)/.test(v);
function tileHtml(v, i) {
const inner = isImg(v)
? `<img src="${esc(v)}" alt="">`
: `<div class="img-ph" style="background:${PH_GRADIENTS[i % PH_GRADIENTS.length]}">${ICONS.mountain}</div>`;
return `<div class="tile">${inner}</div>`;
}
function mediaHtml(images) {
if (!images || !images.length) return "";
const shown = images.slice(0, 4);
const cls = `n${Math.min(shown.length, 4)}`;
let html = shown.map((v, i) => tileHtml(v, i)).join("");
if (images.length > 4) {
html = html.replace(/<div class="tile">[\s\S]*<\/div>$/, m =>
m + `<div class="tile-more">+${images.length - 3}</div>`);
}
return `<div class="post-media ${cls}">${html}</div>`;
}
function linkCardHtml(link) {
if (!link) return "";
return `
<div class="link-card">
<div class="link-img"><div class="img-ph" style="background:linear-gradient(135deg,#a8c5f0,#dfe7f5)">${ICONS.link}</div></div>
<div class="link-body">
<div class="link-domain">${esc(link.domain)}</div>
<div class="link-title">${esc(link.title)}</div>
<div class="link-desc">${esc(link.desc || "")}</div>
</div>
</div>`;
}
function commentHtml(c) {
return `
<div class="comment">
${avatarHtml(c.name, "sm")}
<div style="min-width:0">
<div class="c-bubble">
<div class="c-name">${esc(c.name)}</div>
<div class="c-text">${esc(c.text)}</div>
</div>
<div class="c-foot">
<span>赞 ${c.likes}</span><span>回复</span><span>${esc(c.time)}</span>
</div>
</div>
</div>`;
}
function postHtml(p) {
const comments = (p.comments || []).map(commentHtml).join("");
const commentCount = p.comments.length;
return `
<article class="card post">
<div class="post-head">
${avatarHtml(p.name)}
<div class="ph-meta">
<div class="ph-name">${esc(p.name)}${p.verified ? ICONS.check : ""}</div>
<div class="ph-sub">${audienceIcon(p.audience)} ${esc(p.time)}</div>
</div>
<button class="ph-more">${ICONS.dots}</button>
</div>
${p.text ? `<div class="post-text">${esc(p.text)}</div>` : ""}
${mediaHtml(p.images)}
${linkCardHtml(p.link)}
<div class="stats">
<span class="rx">${ICONS.likeFilled}</span><span class="rx">${ICONS.heart}</span>
<span class="like-count" data-base="${p.likes}">${p.likes}</span>
<span class="grow"></span>
${commentCount ? `<span>${commentCount} 条评论</span>` : ""}
${p.shares ? `<span>· ${p.shares} 次分享</span>` : ""}
</div>
<div class="post-actions">
<button class="p-action act-like">${ICONS.like}<span>赞</span></button>
<button class="p-action">${ICONS.comment}<span>评论</span></button>
<button class="p-action">${ICONS.share}<span>分享</span></button>
</div>
${comments ? `<div class="comments">${comments}</div>` : ""}
</article>`;
}
function storiesHtml() {
const items = STORIES.map((n, i) => `
<div class="story" style="background:${STORY_GRADIENTS[i % STORY_GRADIENTS.length]}">
<div class="story-meta">
<div class="avatar sm" style="background:${colorOf(n)}">${esc(n.slice(0, 1))}</div>
<div class="sm-name">${esc(n)}</div>
</div>
</div>`).join("");
return `
<div class="story story-create">
<div class="sc-img">${ICONS.mountain}</div>
<div class="sc-plus">${ICONS.plus}</div>
<div class="sc-label">创建快拍</div>
</div>${items}`;
}
function render() {
document.getElementById("posts").innerHTML = FEED.map(postHtml).join("");
document.getElementById("stories").innerHTML = storiesHtml();
document.getElementById("sponsored").innerHTML = SPONSORED.map(s => `
<div class="sponsored">
<div class="sq"><div class="img-ph" style="background:linear-gradient(135deg,#c9d8ef,#e9eff8)">${ICONS.mountain}</div></div>
<div style="min-width:0">
<div class="sp-title">${esc(s.title)}</div>
<div class="sp-domain">${esc(s.domain)}</div>
</div>
</div>`).join("");
document.getElementById("contacts").innerHTML = CONTACTS.map(n => `
<div class="contact-row">
<div class="contact-av">${avatarHtml(n, "sm")}<span class="online-dot"></span></div>
${esc(n)}
</div>`).join("");
}
/* 点赞按钮可点击切换(纯前端演示) */
document.addEventListener("click", e => {
const btn = e.target.closest(".act-like");
if (!btn) return;
const count = btn.closest(".post").querySelector(".like-count");
const base = Number(count.dataset.base);
const liked = btn.classList.toggle("liked");
count.textContent = base + (liked ? 1 : 0);
});
render();
</script>
</body>
</html>
File diff suppressed because it is too large. Load diff
+36
View File
@@ -0,0 +1,36 @@
# 接口性能管理
管理员入口:**设置 → Redis 与性能**。页面集中管理 Redis 读取缓存、浏览器状态接口访问、历史统计数据定时清理。
## 控制项
- Redis 总开关及有效期:1–3600 秒,默认 300 秒。已有管理员设置优先于 YAML 默认值。
- 接口列表:15 组,支持搜索和单独开关。同组路径共用一个开关;总开关关闭时保留每组选择。列表由后端实际接入目录返回。
- 浏览器状态:允许/拒绝 `GET /api/browser-context/status`,保存后生效。为兼容现有插件,升级默认允许;关闭时返回 403,错误码 `browser_status_disabled`,并建议客户端 300 秒后重试。此开关只控制状态查询,不改变 capture/ask/task 接口的原有权限。
- 定时清理:复用原有审计清理调度及持久化暂停标记。关闭时在当前小批次完成后停止;重启保持关闭。清理范围仍是超过 90 天的工具调用、模型调用、已结束运行摘要和排行榜快照,不清理对话消息。页面仅打开时或手动刷新状态,不新增轮询。
## 缓存覆盖
智能体列表、技能列表、展示脱敏词、个人偏好、常用提示词、推荐问题、轻应用列表/侧栏/详情、完整菜单、简洁菜单、任务按钮、业务映射、HTML 模板、模型能力目录、标签及资源标签、浏览器状态。
模型配置仍按当前配置即时组装,缓存的是其数据库能力目录。智能体、技能和推荐问题保留原有可缓存请求条件。用户相关数据保持用户隔离,菜单同时按角色和菜单类型隔离。对话、流式响应和写入操作不缓存。
写入后使相关缓存失效;同键并发未命中请求合并填充。Redis 未配置、超时或不可用时回到原读取逻辑。超出大小限制的结果不缓存。
## 持久化和升级
`api_read_cache_settings` 保存总开关、有效期、逐组配置和浏览器状态开关。迁移 `20261029_01` 增加有效期,`20261029_02` 增加逐组配置、浏览器开关和缓存代次。沿用项目正常数据库迁移流程后再启动新版服务。
每次保存配置都会轮换持久化缓存代次,避免在 Redis 离线时关闭/开启缓存、随后 Redis 恢复或 Gateway 重启后重新命中旧数据。设置写入在进程内串行化,并使用数据库行锁合并更新;其他 Gateway 进程最多约 2 秒刷新设置。
浏览器扩展也应同步更新:修复服务地址不变时探测时间戳未更新的问题,成功状态短暂缓存、同地址鉴权请求合并,禁用/失败至少退避 5 分钟。旧扩展仍可能发送请求,服务端关闭开关会拒绝这些请求。
## 管理员排行榜
移除 `GET /api/admin/users/{user_id}/analytics` 及用户详情展示/调用;排行榜聚合统计和用户管理保留。旧详情 URL 返回 404。
## 回归入口
后端:`test_api_read_cache.py`、`test_api_performance_controls.py`、`test_api_performance_edge_cases.py`、`test_catalog_cache_routes.py`、`test_admin_analytics_removed.py`,以及菜单、模型管理和审计清理现有测试。
浏览器扩展:`node --test browser-extension/deer-web-clipper/background.test.cjs`。
+21
View File
@@ -0,0 +1,21 @@
# 按模型追加全局提示词
管理员打开「设置 → 模型追加提示词」,选择模型,填写提示词并开启开关,点击「保存此模型设置」。每个模型独立保存,关闭开关会保留文本。
设置按模型配置的 `name` 精确匹配,而不是显示名或供应商模型名。所有用户通过平台统一模型入口调用该模型时,都会在系统提示词末尾追加该文本;切换到其他模型不会携带它。未设置的模型保持原有行为。
设置保存在运行目录的 `system_settings.json` 的 `model_prompt_suffixes` 中,默认空、默认关闭。每次模型请求读取最新设置,已经创建的模型实例也能在下一次请求使用新值,无需重启。不会改写用户问题或持久化聊天记录,也不会修改原有智能体提示词文件。提示词用于引导回答方式,无法保证上游模型一定回答。
## 接口与实现
- `GET /api/system-settings/model-prompt-suffixes`:读取全部设置,仅管理员。
- `PUT /api/system-settings/model-prompt-suffixes/{model_name}`:保存单个模型,正文为 `{ "enabled": true, "prompt": "自定义要求" }`,仅管理员;模型名需 URL 编码,支持包含 `/` 的名称。文本最多 20000 字符,启用时不可为空。
- 统一入口 `deerflow.models.factory.create_chat_model` 保留原供应商模型的工具绑定与流式能力;OpenAI 兼容请求在传输适配提示词处理后追加,支持 Chat Completions 和 Responses;其他适配器在输入转换与批量生成入口追加。
- 外部系统自行调用模型、绕过此统一入口的调用不受该设置控制。
- 回归测试:`packages/harness/tests/test_model_prompt_suffix.py`,覆盖权限、持久化、模型隔离、重复追加防护、原始消息不变、即时更新、同步/异步/流式/批量调用及工具绑定。
## 普通问答与智能体问答的末尾顺序验证
两种页面均传递当前输入框的 `model_name`。Lead Agent 按「请求选择 → 智能体默认 → 系统默认」解析实际模型,然后调用同一 `create_chat_model`。普通问答使用通用模板,智能体问答使用其 SOUL.md 模板;主题、知识库范围、项目上下文及运行时中间件继续组装提示词。追加设置在模型请求层处理,因此位于这些内容之后。
回归测试运行两种 Lead Agent 分支的真实 LangGraph 图、模型工厂与 OpenAI 请求序列化,用模拟 HTTP 接口捕获最终请求,覆盖普通/智能体、默认/目标/其他模型、同步响应/流式响应共 12 种组合。测试注入后置系统要求和检索上下文,断言最终系统文本以管理员提示词结尾且只出现一次,用户问题保持原样。另验证 text_bridge、buffered_gateway、artifact_renderer 三种文件传输适配提示词均位于管理员提示词之前。测试不访问真实上游模型。
File diff suppressed because it is too large. Load diff
+117
View File
@@ -0,0 +1,117 @@
# Wiki 数据流转与本地编码验收(2026-09-03)
## 结论
本地 BGE-M3 小批量编码已安装、配置并实际运行。已有 Wiki 的向量化、自动沉淀、
普通库文件导出、助手库异步导入、助手库文件导出、空普通库回流及两端向量检索已实测通过。
**技能自动生成 Wiki 尚未完成验收**:WeKnora 的两个生成模型都返回 HTTP 402
`Insufficient Balance`。不能把后半段通过等同于全链路通过。
本次修改运行在本地 DeerFlow 开发服务(前端 5175、后端 8001),连接用户提供的远端
WeKnora;没有把业务代码发布到服务器,没有提交 Git,也没有直接写 WeKnora 图数据库。
## 本地编码配置
- 实现:FastEmbed / ONNX Runtime CPU,官方 `BAAI/bge-m3` 权重。
- 配置名:`bge-embedding-m3`,1024 维,每批 2 条,2 个 CPU 推理线程。
- 运行依赖:FastEmbed 随标准后端依赖安装;模型必须提前放在离线目录中,仍按需加载,不影响主服务启动。
- 权重:约 2.3 GB,持久缓存 `C:\Users\ji\.cache\deerflow\embeddings`,不进入业务仓库。
- 配置:`llmwiki.local_wiki_index.embedding.provider: local`;可用
`local_model_path` 指定离线权重目录,详见后端 README。
- 查询向量在本地实时编码。已有 Wiki 在内容哈希、模型指纹匹配且向量非空时直接复用。
不同模型或维度不能混用;导入不静默重新编码。
- 原始文档分段向量与模型生成后的 Wiki 文本不同,不能相互冒用。本次新建的是 Wiki
正文的 BGE-M3 索引,不是把既有 512 维文档向量改名为 1024 维。
## 实际数据验收
来源是已有普通知识库“图片测试111”,没有改写其 Wiki 内容。
| 阶段 | Wiki | Wiki 向量 | 实体 | 引用关系 |
| --- | ---: | ---: | ---: | ---: |
| 普通知识库导出 | 19 | 101 | 19 | 108 |
| 助手知识库导入后导出 | 19 | 101 | 19 | 108 |
| 新建普通知识库回流后导出 | 19 | 101 | 19 | 108 |
| 知识梳理总库导出(7 个来源记录) | 19 | 101 | 19 | 108 |
逐项断言通过:
1. 三份包的 Wiki slug、标题、正文、摘要、页面类型、别名、分类路径、出链一致。
2. 101 条向量的原始 float32 字节、分段编号、维度和模型指纹完全一致。
3. 将导入前后实体 ID 映射回原 Wiki slug 后,108 条关系的端点及谓词集合完全一致。
4. 总库导出没有因多个来源重复同步而重复导出同一当前页面的分段向量。
5. 元数据回归测试另覆盖 tags、目录恢复、原始文档片段不计入 Wiki 数量、原生技能无
ownership 记录时可被选中、短 Wiki 不漏向量、模型指纹不兼容时不假装向量检索。
普通包约 1.01 MB,助手包约 0.79 MB,回流包约 0.83 MB。普通包还带 2 个原始文档及
108 个原始片段;助手导出提供 Wiki、Wiki 向量和关系,不重新上传原始文档触发二次生成。
### 检索
实际查询:“军方用什么工具评估极端天气带来的风险?”
- 回流普通库 `/api/llmwiki/search` 返回 `mode=vector`,首条“国防气候评估工具”。
- 助手库 `/api/assistant-knowledge/search` 返回 `retrieval_mode=vector`,首条同上;
首个命中分段余弦相似度约 0.6343。
- 浏览器实际提交总库检索,显示“向量检索 · 余弦相似度”和相同命中;不是只检查返回字段。
- 普通库采用已有页面级聚合评分,因此页面最终分数与单分段余弦值不必相等。
- 回流的向量写入 **DeerFlow 管理的本地 Wiki 索引**。未写入 WeKnora 原生向量数据库,
本次结论适用于本系统问答检索,不能声称原生 WeKnora 自身的检索也已完成该向量导入。
### 页面
普通与助手库复用同一 Wiki 阅读组件:目录树、类型/标签筛选、分类面包屑、别名标签、
正文内链、出链、反向链接及邻接关系视图。窄窗口可收起目录。
浏览器验证了“索引 → 国防气候评估工具”、展开关系视图、助手 Wiki 跳回普通库来源,
以及普通 Wiki 的“在知识梳理中查看”反向跳转。
### 验收数据位置
- 原有普通库:`48f669dc-433e-4aab-b5ea-897b6f7a3d2f`
- 知识梳理总库:`c3fd9841-0718-44dc-860e-aae3020fd485`
- 最终助手测试库:`489be905-08c8-40fe-8d60-42ac21dd945a`
- 最终普通回流测试库:`428162aa-03f6-4c61-8994-360f2f39e0c9`
新建测试库名称均以“Wiki链路验收-0903-1826”开头,保留用于复核;未删除用户已有库。
本地 `.runtime/wiki-live-result.json` 保存验收结果,`.runtime/wiki_live_acceptance.py`
保存本次验收流程,均为忽略的运行产物,不包含认证口令。
## 这次实际修复的问题
- 内置技能只有磁盘目录、没有归属记录时,被错误判定为不存在。
- 技能应上传去代码后的知识正文,让 WeKnora 生成 Wiki,而不是伪造一个 `skill` 类型页面。
- Wiki 生成等待使用实际 stats 接口;零页结果明确失败,不无期限等待。
- 向量化完成后自动导出沉淀到总库,并阻断导出回调重复触发全量同步。
- 短摘要和短正文同时存在时,旧分段阈值会将整页过滤为零向量。
- 分类路径必须先创建 WeKnora folder 并绑定 folder_id;只传 category_path 会被服务端清空。
- Wiki 的标签/分类/别名/原始引用保留;图节点绑定真实 Wiki,避免生成重复的空实体页面。
- 保留归一化 float32 原始字节;导入中不能用 `section_index or index`,因为合法编号 0 会被改写。
- 总库多个来源保留审计,但检索与导出只使用当前 Wiki 版本对应的向量,避免旧贡献污染检索。
- 包解析改为同盘临时 SQLite,上传先落盘再异步导入,导出完成后才提供文件下载。
## 阻塞与未通过的范围
1. 技能 `knowledge-base-ingest` 已送入专门创建的普通测试库,但远端
`deepseek-v4-flash` 和 `qwen3.6-flash` 均因余额不足失败。WeKnora 即使失败也可能把
文档 parse_status 标为 completed。需恢复可用生成模型后重新运行技能全链路验收。
2. 已采用磁盘暂存和有界批处理,但本次只有约 1 MB 实测,**未做数 GB 压测、断点续传、
进程中断恢复验收**。大包部署仍需磁盘容量、代理 body size 和超时配置。
3. 当前实体去重主要按类型及规范化名称;这次没有完成跨别名、歧义实体的模型对齐及
多来源事实冲突合并验收,不能视为这一历史需求已全面完成。
4. 重复上传仍会保留独立来源记录。向量导出已消除旧版本重复,但上传身份幂等、部分远端
写入失败后的无损重试、跨实例图片资源打包仍需独立验证。
5. 当前版本已补充自动增量链路:服务启动立即补扫,之后默认每 30 秒扫描全部普通
知识库;Wiki 抽取完成后无需手工点击向量化,并自动以来源快照覆盖同步到知识梳理总库。
6. 回流当前只允许新建空 Wiki 普通库,避免覆盖已有页面。普通库现有页面列表的超大规模
分页与助手问答的最终生成回答不属于这轮通过结论。
## 自动化检查
- 后端相关测试:118 passed(assistant repository、Wiki sync、package roundtrip、
WeKnora 接口、向量检索与知识库管理)。
- 修改的 Python 功能文件 Ruff 检查通过;app.py 既有启动顺序导致的 E402 不在此次改动中处理。
- `git diff --check` 通过(只有仓库换行提示)。
- 前端完整 `pnpm typecheck` 未通过:57 个既有/本轮范围外错误,涉及 nextra 缺失、Markdown
插件类型及其他模块;本轮新建/修改的 Wiki 组件、助手 API、技能面板没有出现在错误清单中。
浏览器实际页面与跳转已验证,但不能声称全项目构建通过。
+76
View File
@@ -0,0 +1,76 @@
# 单机动态在线 Worker
## 范围与入口
管理员「设置 → 执行节点管理」配置 SSH 主机/IP、端口、账号、密码、SSH 主机指纹、源容器、Docker 网络、镜像内 Python/后端目录、节点数量、并发、队列和资源预算。也支持已有 Docker socket 挂载的本机连接,无需填写 SSH 密码。
本实现将 `/api/threads/{id}/runs`、`runs/stream`、`runs/wait` 的普通/智能体问答分发到固定会话所属的在线 Worker。分配后,该会话的状态、历史、停止、重连等 `/api/threads/{id}/…` 请求也转发到同一节点。鉴权及原有任务共享、用户隔离检查仍然执行。搜索、计数和未启用时沿用主服务。
定时任务、任务分析、研究、会商、工作流以及系统内部会话仍由唯一主服务执行;不在在线 Worker 启动它们的扫描、恢复或调度循环。无状态 `/api/runs/*`、专用写作接口等未纳入在线池。后台任务池尚未实现,不应将此版本描述为全业务分布式任务队列。
## 存储与并发
- 业务库与聊天存储独立:保留 MySQL/PostgreSQL 业务库,聊天存储支持 PostgreSQL 或 SQLite。SQLite 必须使用同机共享持久目录(不能单文件挂载或网络文件系统),开启 WAL、30 秒锁等待及跨进程初始化锁;内存存储拒绝开启。
- Worker 的运行事件使用共享业务数据库;聊天检查点沿用已有 PG/SQLite 配置,不迁移聊天记录。
- 控制器私有目录保存加密 SSH 凭证、加密密钥、实例标识和 SQLite 会话归属表。该表只保存路由,不存聊天正文。目录必须独立持久化,不能挂载给 Worker。实例标识和归属表不能单独删除或在旧容器运行时重建。
- Worker 池默认关闭。关闭时不启动控制器轮询、不申请单实例锁、不连接 Docker/SSH,也不创建亲和性或诊断数据库;原部署方式与多进程服务按原样运行。只有管理员启用 Worker 池后,控制器才申请单实例锁并开始管理容器;启用期间主服务需使用单个 Uvicorn 进程。同机同套部署的启用中主服务必须共用控制器卷。
- 执行额度绑定真实运行 Task 的生命周期;HTTP 请求结束或后台返回不提前释放额度。排队有数量和时间上限;超限返回 429/Retry-After。
- 每节点业务库连接池不允许额外溢出;检查点和 LangGraph Store 各有单独的 PG 连接池。系统按 `节点数 ×(业务库池大小 + 2 × PG 池大小)` 校验 Worker 连接预算。该预算须预先扣除主服务及其他应用的连接额度。
- Worker 在新运行开始前检查共享技能扩展配置,启停变更会刷新本进程缓存;技能文件变更按最多五秒的检查间隔刷新目录提示。CPU、模型配置等需要重启的配置仍应先排空 Worker 后更新。
- 会话归属在扩容后保持。缩容节点停止接收新运行,等待执行、排队和代理请求结束后停止,再释放归属。不自动重放失败请求。节点失联时返回 503;可确认进程停止后才允许后续重新分配。
- 重启后的旧运行读取为中断错误,不自动重试带外部副作用的工具。系统保留存储中已完成的检查点,不能承诺从任意工具执行位置无损恢复。
## 部署要求
发布仓库 `deerflow-offline-deployment` 已为标准模板增加控制器独立卷和 SSH/加密依赖清单。必须按该仓库既有流程构建包含全部依赖的离线包并部署新前后端源码。
1. Worker 池关闭时保留原部署进程数即可;启用 Worker 池后主容器使用单个 Uvicorn 进程。固定 `AUTH_JWT_SECRET` 必须在容器环境变量中。
2. 使用用户自定义 Docker 网络,主容器和新 Worker 均在该网络。数据库地址不能指向容器自身的 `localhost`。
3. 挂载全部运行目录、上传文件、技能、配置及必要的源码覆盖目录。Worker 复用其挂载,保留 ExtraHosts/DNS;不继承宿主机端口、Docker socket或特权模式。
4. `DEER_FLOW_WORKER_CONTROL_HOME` 指向独立持久卷,如 `/var/lib/deerflow-worker-control`。该卷会被自动排除,不传给 Worker;控制目录嵌在其他共享卷内时拒绝创建。
5. 当前支持不依赖 Docker socket 的执行沙箱。若业务配置需要 Worker 自行创建 Docker 沙箱,须先接入独立受控沙箱服务,不得直接复制 socket 权限。
6. 设置中默认保持关闭;填写连接参数和测试连接不会启动容器。管理员明确开启后才创建 Worker。标准离线镜像 Python 为 `/opt/venv/bin/python`,工作目录为 `/app/backend`;其他镜像按实际路径填写。
7. SSH 主机指纹可在页面读取并由管理员确认;账号需具备运行 Docker 的权限。不接受未知指纹,也不自动安装服务器软件。
容器使用源容器的精确镜像 ID,执行源码覆盖挂载与主容器相同。升级前数量设为 0,等待节点退出后升级主服务,再恢复数量;不会自动替换仍在执行的旧容器。
## 验证与容量
`tests/test_worker_pool.py` 包含凭证脱敏、模板限制、排队取消/超时、后台任务额度、归属持久化、失联不重放、缩容等待、双主进程拒绝、管理员授权,以及 70 个 HTTP 客户端分配到四个模拟 Worker 并返回 SSE 的回归。
这些是功能与模拟并发测试,不等同于真实模型、PostgreSQL、Docker 和服务器硬件的 70 人容量验收。部署后应在测试环境同时运行普通问答、文件工具和定时任务,观察首字延迟、完成时间、数据库连接数、模型限流和资源峰值;执行中的关闭浏览器、停止生成、节点重启、缩容都要验证。每节点并发数乘以节点数只是顶层运行上限,工具/子智能体仍可能产生额外模型调用,应配置模型服务总额度。
回退:将期望数量改为 0,等待全部节点消失后关闭池。主服务重新处理普通问答,聊天记录和运行目录继续保留。节点不能正常退出时不要直接删除控制器卷或归属表。
## 本次开发验证(2026-10-23)
- Worker 专项、账户鉴权、运行记录回收、执行线程池、完成超时和运行争用相关回归合计 **136 项通过**。
- 70 个模拟 HTTP 客户端进入四个模拟执行节点,分配为 18 / 18 / 17 / 17,全部收到 SSE 结束事件;另测执行额度、超时、取消及后台运行不提前释放额度。这不包含真实模型耗时。
- Python 静态检查、编译检查、改动空白检查通过;Linux 离线发布配置生成/校验通过。
- 新增前端页面及设置入口语法检查通过。全量 TypeScript 检查仍有其他模块错误,不能将前端全量检查标记为通过。
- 119 服务器检测为 32 核 CPU、128806 MB 内存;8008 实例已启动 4 个实际 Docker Worker,每节点 2 CPU / 2048 MB / 4 个同时执行额度;业务库保持 MySQL,既有聊天 SQLite 配置不变。
- 实际模型短问答:同一管理员下 70 个独立会话同时发起,70/70 完成,流式阶段约 59.59 秒;随后 70/70 历史记录读取确认回答已保存。这是短问答突发负载,不代表 70 个不同用户的复杂工具任务容量。
- Linux 上分别用 SQLite 和 PostgreSQL 执行 4 个进程各 25 次检查点/写入/Store 读写验证,各 100 次成功;PG 使用独立验收实例,未迁移业务库。
- 4→0→4 缩扩容与主服务重启后发现原有 4 个节点已验证(未重启整台服务器)。Worker 不启动定时任务调度器。
- 新增服务器探测和资源推荐:页面先读取 SSH 指纹,管理员确认后才发送密码登录;检测 Docker CPU/内存总量和其他容器资源上限,保留至少半台服务器资源,建议最多 4 个起步节点。不是实时空闲内存测量。
- 密码经 Fernet 加密保存在控制器持久卷;页面/API 不返回密码。更换服务器身份后必须重新填写密码,不能复用原服务器密码。配置和密钥卷需一起保留。
- Worker/聊天存储/跨线程数据库/资源推荐专项回归 37 项通过。
### 管理页面验收补充
2026-10-23 23:06 在 119:8008 实际页面完成保存并应用、测试已保存连接、读取服务器资源,三个请求均成功。截取资源推荐与四个就绪节点页面,保存在本次 `.runtime/worker-deploy-119/` 验收目录。前端生产构建成功。
当前运行池使用本机 Docker Socket。SSH 指纹读取已在服务器内网地址实测;SSH 账号密码认证尚需管理员在页面填写实际凭证验证。密码密文持久化、读取不回显、更换主机不复用密码、错误指纹拒绝连接均有测试覆盖。重启验证指主服务重启,未重启宿主机。
## 服务器诊断与并发验收补充(2026-10-24)
管理员诊断页 `/page/workspace/admin/server-diagnostics` 提供按开关采集的宿主机资源、MySQL/PG 连接、HTTP/SSE 分段耗时、主容器和 Worker 状态、日志读取与归档。主后端挂载 Docker Socket 和只读 `/proc`、`/sys`,Worker 不继承这些挂载。主服务日志轮转为 20 MB × 5,Worker 为 10 MB × 3;节点删除前保存有界日志归档。采样和请求摘要保存在控制器私有卷,接口不记录聊天正文、查询参数或鉴权头。
修复 Worker 执行队列阻塞流首次连接:先注册真实运行、建立流,再等待执行额度;保留额度上限和取消、超时语义。新线程默认只写元数据,首次运行再初始化检查点,保留显式初始化兼容参数;历史查询缩短 SQLite 游标持有时间。
本轮相关回归 133 项通过。119 实际 2 节点、4 节点各执行 70 路冷启动和 70 路第二轮,共 280/280 成功,两组各 70 个会话历史和状态回读通过。4 节点冷/热整轮耗时 68.851/46.287 秒,响应头 P95 为 18.141/11.548 秒;2 节点冷/热整轮耗时 115.026/74.151 秒。此为同一管理员的独立客户端短问答,不代表复杂工具容量。验收后恢复原先保存的 2 个节点。
页面实际验证了采集开关、资源和数据库卡片、主服务/Worker/归档日志,浏览器无脚本错误。119 当时 CPU 100%,独立采样 steal 约 24.6%,内存和 MySQL 连接仍有余量;需同时排查宿主机 CPU 争抢。PG/SQLite 兼容性在独立实例验证,业务 MySQL 和原聊天配置不变。
Linux AMD64/Python 3.12 增量交付包和部署说明保存在离线发版仓库;文档 `deploy/linux-docker-offline-deerflow-only/docs/14-Worker池与服务器诊断更新部署.md` 包含 Docker Socket 挂载、更新排空、依赖、资源建议和回退。交付源代码基于本次 119 验收版本,配置与数据不打入包。
@@ -0,0 +1,188 @@
# 报告协作工作台 — 交互重设计方案(v2)
> 日期:2026-09-07
> 状态:**待确认**(确认后按 §7 分期实施)
> 取代:现行「规则澄清 + 三张模板方案卡 + 画布为主」的交互
> 原则:回到最初设计 —— **协调者智能体全程与用户对话的主线**
---
## 1. 设计目标与总体形态
用户视角只有一条主线:**和一个规划师智能体对话 → 它摸清意图并规划工作流 → 确认后执行、过程在流程图上可见 → 随时插话干预、指定智能体重跑 → 最终成稿、继续对话式修改**。
```
┌─────────────────────────────────────────────────────────┐
│ 阶段1 计划模式 阶段2/3 执行+干预 阶段4 成稿 │
│ ┌───────────┐ ┌───────────┐ ┌──────────┐ │
│ │ 规划师对话 │ 确认 │ 聊天时间线 │ 审稿过 │ 对话改稿 │ │
│ │ 需求摘要卡 │ ─────→ │ +成员Tab │ ─────→ │ 版本/diff│ │
│ │ 工作流卡 │ 冻结 │ +流程图动画│ 报告卡 │ 上游重跑 │ │
│ └───────────┘ └───────────┘ └──────────┘ │
│ ↑ 回到计划模式(replan)随时可触发 ↑ │
└─────────────────────────────────────────────────────────┘
```
与现行的核心差异:
| 维度 | 现行(做偏的) | v2 |
|------|----------------|-----|
| 需求澄清 | 规则模板问句秒回 | 规划师智能体(LLM)领域化提问 |
| 工作流来源 | 3 张确定性模板 | LLM 按意图生成自定义 DAG,对话迭代修改 |
| 执行展示 | 画布为主、聊天为辅 | **聊天时间线为主**(成员 Tab 切换保留),**执行状态在流程图上动画呈现** |
| 干预 | 命令确认卡体系 | 输入框常开 → 协调者智能体分类;支持**指定智能体重跑** |
| 报告修改 | 改写候选(纯文字层) | 意图分流:润色走改写;**事实性问题触发上游节点重跑** |
---
## 2. 阶段 1:计划模式 — 需求梳理与工作流规划
### 2.1 计划模式状态
- 用户发出第一条需求消息起进入**计划模式**,Header 显示徽章「📋 计划模式」,输入框提示语切换为「梳理需求中,你可以随时补充或纠正…」。
- 计划模式在**工作流确认冻结**时结束;执行期大改可通过 replan 回到计划模式(见 §5.4)。
### 2.2 规划师对话(LLM,替换现行规则路由)
- 必须调用独立内置智能体 `report-collaboration-intent` 的真实 LangGraph thread,并原样消费 `messages-tuple` SSE;禁止用 `ainvoke()` 等待完整 JSON 后再包装成一话。
- 流式正文、思考内容和工具步骤直接进入工作台现有 `MessageList`,与普通智能体问答采用同一套步骤条 / Reasoning 展示。
- 模型:`report_collaboration.planner_model`(回退 `coordinator_model` → 默认模型,复用现有 model_resolver 冻结机制)。
- 提问是领域化的:写市场分析就问「关注整车还是供应链 / 要不要竞品对比 / 给谁看 / 篇幅」,而非固定模板问句。
- 澄清轮次上限沿用 `max_clarification_rounds`;用户随时可以说「直接开始」按默认假设推进。
### 2.3 需求摘要卡
信息足够后,规划师在对话中输出一张**结构化需求摘要卡**(业务卡插槽渲染):主题 / 目的 / 读者 / 角度清单 / 篇幅与重点 / 默认假设。用户逐项看,可在对话里继续改(「读者改成投资人」→ 卡片更新出新版)。
### 2.4 工作流生成与迭代
- 规划师判断意图信息足够后,立即按已确认意图自动生成**一份**工作流方案(不是三选一),不再要求用户额外点击“确认意图/生成方案”;方案以工作流卡(成员构成、各节点使命、预计时长/成本)+ 右侧流程图预览呈现。
- 生成约束(保证可执行):**节点类型受词表约束** — `research / verify / analyze / write / review`;自由的是结构(几条线、并行还是串行、核验深度)与每个节点的使命/角度/工具。
- 对话式修改:「把价格策略单独拆一条线」「加一个政策风险分析」→ 规划师修订后出新版工作流卡(带变更说明),再确认。
- 「开始执行」→ 冻结需求 + 工作流(含模型/预算快照,沿用现有 freeze 机制)。
---
## 3. 阶段 2:执行 — 过程在流程图上可见
### 3.1 流程图动画规格(执行状态的可视化主载体)
节点状态 → 样式(`ReportFlowCanvas` / `ReportFlowNode`,状态源 `selectNodeStatusMap`,事件源 `node.status.changed` SSE):
| 状态 | 节点样式 | 连入边 |
|------|----------|--------|
| planned / queued | 灰色常态 | 静态 |
| **running** | 主色描边 + **呼吸脉冲动画**(ring)+ 角标 spinner | **流动动画**(@xyflow 内置 `animated: true` 的 dash 流动) |
| **completed** | 绿色 + ✓ 角标,常驻 | 恢复静态实线 |
| failed | 红色 + 错误角标 | 红色虚线 |
| awaiting_input | 橙色 + ?角标 | 橙色静态 |
| interrupted / superseded | 半透明降级 | 灰 |
- 语义:**边流动 = 数据正在流入该节点**(该节点执行中);节点完成即停动画换完成样式。
- 实现成本:@xyflow 原生支持 animated 边与自定义节点 className,纯 CSS 补呼吸动画即可,无需新依赖。
### 3.2 聊天区(保留现有 Tab 切换)
- 并行成员沿用 **AgentStageSelector Tab 切换**(维持现状,不改交错时间线)。
- 每个 Tab 内是该成员的完整流式输出:思考、工具调用卡、检索过程、正文 —— 与普通智能体问答同观感(message-adapter 已具备映射能力)。
- 协调者播报(「研究线 A 完成,核心发现 X,开始交叉核验」)进入总时间线 Tab。
---
## 4. 阶段 3:干预 — 对话即干预 + 指定重跑
### 4.1 输入框常开,协调者智能体分流
执行期输入框永远可用,所有输入先到协调者(LLM 分类,规则高精度直判兜底——复用 RC-BE-014 IntentRouter 骨架,把「规则优先」反转为「LLM 优先 + 规则快路径」):
| 用户意图 | 协调者行为 | 生效时机 |
|----------|-----------|----------|
| 提问(「查到什么了?」) | 直接回答 | 立即,不打断 |
| 修正方向(「重点看下沉市场」) | 小改:在安全点注入 overlay,并回复说明 | 下个安全点 |
| **指定重跑**(见 §4.2) | 出确认卡 → 重开节点 attempt | 确认后 |
| 大改(砍线/加线) | 提议 replan → 回计划模式 | 用户确认 |
| 停止 | 直接取消 | 立即 |
### 4.2 指定智能体重跑(新增核心交互)
**场景**:用户发现某节点传给下游的信息不对(如研究线 B 的结论有误)。
两个入口,同一后端动作:
1. **对话**:「研究线 B 的结果不对,重新查,重点看价格战」→ 协调者解析出 `node_id` + 新指令;
2. **画布**:点节点 → 抽屉(NodeInspectorDrawer)加「↻ 重新执行」按钮。
**级联规则**(复用并补全 ledger 的 targeted rework):
```
重跑节点 N(attempt+1,带用户新指令作为 mission overlay)
→ N 完成 → 所有直接/间接依赖 N 产物的下游节点标记 superseded
→ 按 DAG 依赖序逐波重跑(边动画重新流动,用户全程可见)
→ 受影响章节重新生成
```
- 确认卡必须展示**影响面**:「将级联重跑 核验B / 分析 / 写作 共 3 个节点,预计 +8 分钟」。
- 成本保护:级联重跑计入 run 预算(现有 budget 机制),预算不足时明确报因。
---
## 5. 阶段 4:报告成稿与对话式修改
### 5.1 成稿
审稿通过 → 报告卡出现在时间线(点开 ReportPreviewDialog 全文),协调者播报总结(各线核心发现 → 结论如何形成)。
### 5.2 修改意图分流(协调者 LLM 判定)
| 用户说 | 判定 | 动作 |
|--------|------|------|
| 「把第二章结论写得更笃定」 | 文字润色 | 改写候选(现有 rewrite API)→ 对比预览 → apply → 新版本 |
| 「这个数据不对 / 重新收集一下」 | **事实性问题** | 定位来源节点 → **触发该节点重跑(可带新角度)→ 级联 §4.2 → 受影响章节重生成 → 新版本** |
| 「再从供应链角度补一节」 | 结构性新增 | replan:回计划模式改工作流(只增不删已完成部分) |
| 「恢复到上一版」 | 版本回退 | 现有 restore API |
- 版本链:每次 apply / restore / 级联重跑产出均产生新 head,历史完整保留(现有机制)。
- 修改对话里协调者必须先**复述理解**(「你是想让研究线 B 换个角度重查,然后重写第三章,对吗?」)再执行,避免误触发昂贵的级联。
---
## 6. 工程改造清单
### 6.1 保留(本次联调已验证)
- 持久化 13 张表 + durable SSE + `after_seq` 断线续传;幂等键 / 乐观锁 / 预算框架。
- MessageList 复用链路(message-adapter → LangGraph Message → 业务卡插槽)。
- AgentStageSelector Tab、commands 安全点骨架(RC-BE-014)、报告版本三件套(RC-BE-015)、前端 hooks/reducer/selectors 主体。
- 「清空历史」「生成候选方案」等本次新增入口。
### 6.2 后端重做 / 新建
| 项 | 说明 |
|----|------|
| 规划师智能体 | LLM 多轮澄清(替换 `requirement/intent_router.py` 规则路由)+ 需求摘要结构化 + **工作流 LLM 生成**(受 §2.4 词表约束,替换 `planning/controller.py` 三模板)+ 对话式工作流修订 |
| 协调者智能体升级 | 干预分类 LLM 优先;修改意图分流(§5.2);执行前复述确认 |
| 指定重跑 + 级联 | ledger targeted rework 补全级联 superseded/重跑波次;确认卡带影响面计算 |
| AgentScope 适配器修复 | `count_tokens` 协议缺失(上下文压缩必崩);attempt 耗尽终态化(防僵尸 run) |
| 事件补齐 | 边流动所需的节点状态事件已有;补「级联影响预告」事件 |
### 6.3 前端重做 / 新建
| 项 | 说明 |
|----|------|
| 计划模式 UI | Header 徽章、composer 提示切换、需求摘要卡、工作流卡(替换现三张模板卡) |
| 流程图动画 | running 节点呼吸动画 + 入边 `animated`、completed ✓ 样式、级联重跑时边动画重流(§3.1) |
| 节点抽屉 | 加「重新执行」按钮 → 确认卡 |
| 干预交互 | 执行期输入框常开;意图确认卡(含影响面);修改对话复述确认 |
| 布局 | 聊天为主、画布为辅的默认比例微调(不动整体两栏结构) |
---
## 7. 实施分期
| 期 | 内容 | 验收 |
|----|------|------|
| **P0 地基** | AgentScope `count_tokens` 修复;attempt 耗尽终态化;级联重跑的 ledger 补全 | 执行阶段不崩、无僵尸 run、单节点重跑级联正确(后端测试) |
| **P1 计划模式 + 执行可视化** | 规划师 LLM 对话、需求摘要卡、工作流 LLM 生成与迭代、计划模式 UI、流程图动画 | 从新会话到确认工作流全程对话完成;执行时动画正确随状态流转 |
| **P2 干预 + 成稿修改** | 协调者 LLM 分类、指定重跑(两入口 + 影响面确认卡)、报告修改意图分流、上游级联重跑 | 四类干预各自走通;「数据不对→重跑→新章节→新版本」全链路 |
每期结束跑 RC 全量测试(当前基线 233 通过)+ 前端 26 单测,不引入对其他模块的影响。
@@ -0,0 +1,719 @@
# AgentScope 2.0 多智能体报告协作工作台——前端实施计划
> 文档状态:前端代码已落地、契约冻结;联调等待后端运行中干预与报告改写
> 编写日期:2026-09-02;进度更新日期:2026-09-06
> 目标项目:`F:\react01\deeflow-code\deerflow-server\frontend-web`
> 视觉与交互参考:`F:\react01\coze-frontend\frontend\apps\coze-studio`
> 参考页面:`http://localhost:3000/work_flow?space_id=1&workflow_id=wf_88cb9f4c6642`
> 配套后端计划:`docs/agentscope-多智能体报告协作工作台-后端实施计划.md`
> 本文只规划新增页面,不修改现有多智能体会商页面,不复用旧 Workflow Studio 执行状态。
## 0. 当前进度
`frontend-web/src/report-collaboration/` 已实现两栏工作台、会话/方案/run API 客户端、mock driver、SSE reducer、`MessageList` 适配、方案卡、画布、节点抽屉、Composer、报告预览与历史。`RC-FE-001`~`013` 的页面骨架与契约层视为完成。
后端已通规划前路径(澄清 → 出方案 → 选定 → `queued` run),见后端计划 §0。前端真实执行体验仍受阻:
- `GET /runs/{id}/stream` 已挂载(`RC-BE-011`);dispatcher/租约已落地(`RC-BE-012`),默认 `worker_enabled=false` 仍不自动领取 queued run。
- 报告改写 / 恢复接口已由后端 `RC-BE-015` 挂载。
- 质量角色已由 `QualityRoleKernel` 跑通(`RC-BE-013`);真实 AgentScope 模型/`web_search` 仍待后续票。
联调顺序:先打开 `report_collaboration.enabled` 验证规划前 REST 与 `GET /runs/{id}/stream` 重放;画布自动执行需同时打开 `worker_enabled`(默认关)。
## 1. 前端目标
新增独立的「报告协作」工作台。用户可以通过对话提出任意报告需求,查看系统生成的多个协作方案,点击方案卡片在流程图中预览协作结构,确认后观察多智能体执行,并在全过程通过统一对话框提出修改意见。
前端必须满足:
1. 页面采用“左侧对话、右侧流程画布”的固定两栏布局,画布、工具栏、弹窗和抽屉参考 Coze Studio 页面风格。
2. 消息列表必须复用 DeerFlow 现有 `MessageList`,不复制 Coze 的会话消息实现。
3. 所有执行过程、AgentScope 团队消息、智能体回复、工具调用及其原始返回、错误、协助卡、返工和最终报告入口都通过现有消息协议按时间顺序显示在左侧对话区,不设置独立执行结果面板,也不另做“阶段摘要”替代实时消息。
4. 候选方案、流程节点、对话进度和报告使用同一份后端事实,不各自推断状态。
5. 用户可在规划中、运行中、等待输入和报告完成后继续对话。
6. 用户协助卡的出现和提交都不能在前端被解释为“节点已经完成”。
7. 页面刷新、SSE 断线重连、历史会话切换后能恢复到一致状态。
暂定:
- 页面名称:`报告协作`。
- 路由:`/page/workspace/report-collaboration`。
- 会话路由:`/page/workspace/report-collaboration/:sessionId`。
- 默认候选方案数量:3。
- 点击画布节点时打开覆盖式节点说明抽屉;抽屉只展示节点职责和合同,不展示节点执行结果。
---
## 2. 范围与非目标
### 2.1 本期范围
- 新建、查看、重命名、删除协作报告会话。
- 使用对话澄清报告需求。
- 显示 2~3 个候选方案卡片。
- 卡片与右侧流程图预览联动。
- 节点说明抽屉:职责、所依据的信息类型、预期产出、工具、资料要求和验收条件。
- 实时展示节点排队、运行、校验、等待用户、完成、返工、失败和取消。
- 在左侧对话时间线中直接展示每个智能体的流式文本、团队对话、工具调用和工具返回,并展示审稿意见、报告文件和报告版本。
- 并行阶段用横向的智能体选择器切换当前查看对象;选择器只控制同一份消息流的聚焦范围,不创建另一套执行结果视图。
- 运行期间发送补充要求、重新检索、重新分析、节点重跑等指令。
- 完成后进行报告问答、章节重写、全文润色和版本恢复。
- 报告模板选择、Markdown 预览、Markdown/Word 下载。
- 响应式布局、键盘操作、加载反馈和错误恢复。
### 2.2 明确不做
- 不引入 `@coze-workflow/playground` 或 `@coze-arch/coze-design`。
- 不加载 Coze workflow definition、run 或 node run。
- 不允许前端拖拽连线后直接改变执行逻辑。
- 不新增第二套消息气泡、Markdown、引用和文件卡渲染器。
- 不展示模型原始 chain-of-thought、系统/内部 prompt、密钥和被标记为内部控制信息的字段。
- 不把用户有权查看的 AgentScope TeamSay、智能体文本、工具调用或工具返回压缩成“正在检索”等摘要卡;这些原始业务消息必须进入复用的 `MessageList`。敏感字段只能按统一脱敏策略替换,不能以摘要替代。
- 不增加第三栏、常驻详情栏、节点执行结果栏或独立执行时间线。
- 节点抽屉不展示节点生成正文、工具返回、证据列表、错误堆栈或 attempt 历史;这些过程统一在左侧 `MessageList` 的原生消息/工具步骤中查看。
- 不改造现有圆桌、多智能体会商、深度研究和 AI 写作页面。
- 不把浏览器状态作为业务事实源。
---
## 3. 参考页面行为映射
| 目标行为 | Coze 参考文件 | DeerFlow 目标组件 | 说明 |
|---|---|---|---|
| 两栏骨架 | `workflow-studio-layout.tsx` 的面板比例与分隔条 | `ReportCollaborationLayout.tsx` | 左对话、右画布;只保留一条可调整分隔线 |
| 顶栏 | `workflow-studio-header.tsx` | `ReportCollaborationHeader.tsx` | 替换为会话、模板、报告、停止等操作 |
| 候选卡片 | `workflow-proposal-cards.tsx` | `ReportPlanCards.tsx` | 点击预览,明确确认后才执行 |
| 右侧画布 | `workflow-canvas.tsx` | `ReportFlowCanvas.tsx` | 使用 `@xyflow/react` 重建,不引入 Coze Playground |
| 左侧消息区 | `run-conversation-panel.tsx` | `ReportConversationPanel.tsx` | 外层风格参考 Coze,内部复用 DeerFlow `MessageList` |
| 节点说明抽屉 | Coze 节点配置面板的视觉与抽屉行为 | `NodeInspectorDrawer.tsx` | 点击画布节点打开,只展示职责与输入输出合同 |
| 全程执行反馈 | 参考其进度和状态表达 | `AgentStageSelector` + DeerFlow `MessageList` | 选择智能体后直接显示其流式消息、TeamSay、工具调用与返回;不再合成为阶段摘要 |
| 状态栏 | `connection-status.tsx` | `ConnectionStatusBar.tsx` | 展示连接、重连和事件游标 |
| 对话历史 | `left-panel-tabs.tsx` | `ConversationSidebarTabs.tsx` | 对话与历史,不增加“节点资源”Tab |
| 异步反馈 | 规划进度、运行状态 | MessageList 步骤条 + 画布状态 | 操作超过 300ms 必须有反馈 |
主要参考源:
- `F:\react01\coze-frontend\frontend\apps\coze-studio\src\workflow-standalone\components\workflow-studio-layout.tsx`
- `F:\react01\coze-frontend\frontend\apps\coze-studio\src\workflow-standalone\components\workflow-studio-composition.tsx`
- `F:\react01\coze-frontend\frontend\apps\coze-studio\src\workflow-standalone\components\workflow-studio-header.tsx`
- `F:\react01\coze-frontend\frontend\apps\coze-studio\src\workflow-standalone\components\run-conversation\workflow-proposal-cards.tsx`
- `F:\react01\coze-frontend\frontend\apps\coze-studio\src\workflow-standalone\styles.module.less`
若直接复制 Apache-2.0 源码片段或样式,必须保留版权头并维护来源说明;默认做行为映射和视觉重建。
---
## 4. 页面结构
```text
┌──────────────────────────────────────────────────────────────────────────┐
│ 返回 报告协作 / 会话标题 保存状态 模板 报告 停止/继续 更多 │
├────────────────────────────────┬─────────────────────────────────────────┤
│ 对话 / 历史 │ 协作流程图 │
│ │ │
│ DeerFlow MessageList │ @xyflow/react │
│ · 并行时:[协调者][市场][政策] │ · 节点状态与活动连线 │
│ · 用户与协调者/成员消息 │ · 缩放、适配视图、小地图 │
│ · 原生 ToolCall / ToolMessage │ · 点击节点打开覆盖式说明抽屉 │
│ · 协助卡、报告文件和版本 │ │
│ │ │
│ 统一输入框 │ │
├────────────────────────────────┴─────────────────────────────────────────┤
│ 已连接 · run_xxx · 事件 128 │
└──────────────────────────────────────────────────────────────────────────┘
```
节点抽屉覆盖在右侧画布之上,不占用第三栏:
```text
┌─────────────────────────────────────────┐
│ 节点名称 关闭 × │
│ 角色 / 当前状态 │
├─────────────────────────────────────────┤
│ 节点职责 │
│ 要根据什么:所需输入、上游类型、资料要求 │
│ 要产出什么:成果类型、格式、验收条件 │
│ 可用工具与边界 │
│ 上下游关系 │
├─────────────────────────────────────────┤
│ 在对话中对此节点提出意见 │
└─────────────────────────────────────────┘
```
抽屉明确不展示实际执行结果、生成正文、工具返回、来源明细、错误堆栈或 attempt 时间线;这些信息只在左侧原生消息流中展示。
布局默认值:
- 顶栏高度:56px。
- 左侧面板:默认 480px,最小 360px,最大 720px。
- 右侧画布:最小 480px,使用剩余空间。
- 节点说明抽屉:覆盖画布右侧,建议宽度 420px;关闭后完整归还画布空间。
- 状态栏:24~28px。
- 低于 960px:左侧对话和右侧画布改为顶部按钮切换的单面板模式;节点说明仍使用覆盖式 Drawer。
- 两栏分隔条:支持 pointer 拖动、方向键、Home、End。
### 4.1 原生消息流与并行智能体切换
“复用 `MessageList`”在本页面的含义是复用它现有的 assistant 文本、`tool_calls`、`tool` 消息、引用、文件和协助卡渲染语义;不把 AgentScope 的运行过程先解析成专用步骤条、进度摘要或阶段结果卡。
单个智能体:
- `agent.reply.started` 立即创建一条稳定的 assistant 消息;`message.delta` 持续更新同一 `messageId`,所以用户会先看到流式状态、再看到逐字回复,而不是等待节点结束。
- 工具调用创建/更新该 assistant 消息的 `tool_calls`;工具返回创建匹配 `tool_call_id` 的原生 `tool` 消息。现有 `MessageGroup` 负责把两者配对显示,不再另写工具过程渲染器。
- AgentScope TeamSay 作为带 `agentRunId` 的普通 assistant 消息进入同一流,按到达顺序显示。它不是节点完成的证据,节点状态仍由右侧画布和后端状态机决定。
并行智能体:
```text
多角度并行研究 3/4 进行中
[ 协调者 ] [ 市场规模 ✓ ] [ 品牌竞争 ● ] [ 海外市场 ● ] [ 政策风险 ! ]
└──────────────────── 当前选中智能体的原生 MessageList ────────────────────┘
```
- `AgentStageSelector` 只在并行阶段出现,横向放置在左侧对话区顶部;使用现有图标体系的头像/角色图标、名称、状态文字和非纯颜色状态标识。默认选中第一位已开始运行的成员;用户手动切换后保持选择,不因其他成员返回而抢走阅读焦点。
- 所有成员的事件都持续接收、按每个 `agentRunId` 持久化和更新,即使当前未选中;切回即可看到完整历史与正在更新的同一条消息,不丢 token、不重新请求、不把结果拼成摘要。
- 当前选择只将共享用户消息、协调者广播消息和目标成员消息组成一个 `BaseStream<AgentThreadState>` 交给同一个 `MessageList`。切换标签仅切换该视图的消息范围,不改变 run、节点或消息的后端事实。
- 某成员请求用户协助时,其标签显示“待回复”徽标,选择器显示待处理数;点击徽标切到该成员,原生协助工具消息仍由现有 `MessageList` 协助卡渲染。其他成员可继续运行。
- 节点抽屉打开某并行成员时,同步聚焦对应标签;抽屉仍只展示合同。用户从抽屉或输入框发送反馈时带 `targetNodeId`/`agentRunId`,后端在安全点生效。
这不是把完整日志另做成调试面板:对话区展示的是模型和工具的真实业务消息;只有 chain-of-thought、内部提示词及按权限必须脱敏的字段不进入该消息流。
### 4.2 页面主要状态
| 状态 | 左侧对话区 | 右侧流程画布 | 主要操作 |
|---|---|---|---|
| `empty` | 欢迎语和输入框 | 空态 | 输入需求、选模板 |
| `clarifying` | 澄清问题和协助卡 | 需求理解节点 | 回答或补充 |
| `planning` | 用户消息和规划进度 | 骨架或需求图 | 继续补充,等待安全点生效 |
| `proposal_ready` | 2~3 张方案卡 | 点击卡片预览对应图 | 切换、修改、采用 |
| `running` | 协调者与成员原生消息、工具过程和用户反馈 | 实时节点状态 | 干预、停止、在对话中要求重跑 |
| `awaiting_input` | 等待用户卡片、原因和影响 | 对应节点显示等待 | 回答、取消 |
| `reviewing` | 审稿意见和返工过程 | 评审/返工节点状态 | 接受或补充要求 |
| `completed` | 总结、报告文件卡、版本和后续对话 | 完整执行图 | 问答、改写、导出 |
| `failed` | 错误说明和恢复建议 | 失败节点 | 通过对话重试或取消 |
| `cancelled` | 已保留成果说明 | 未完成节点取消 | 从已有成果继续或新建方案 |
---
## 5. 前端目录与组件边界
建议新增:
```text
frontend-web/src/report-collaboration/
api/
client.ts
sessions.ts
plans.ts
runs.ts
reports.ts
types.ts
components/
ReportCollaborationLayout.tsx
ReportCollaborationHeader.tsx
ConversationSidebarTabs.tsx
ReportConversationPanel.tsx
AgentStageSelector.tsx
ReportComposer.tsx
ReportPlanCards.tsx
ReportFlowCanvas.tsx
ReportFlowNode.tsx
NodeInspectorDrawer.tsx
ReportPreviewDialog.tsx
InterventionCard.tsx
SessionHistoryPanel.tsx
ConnectionStatusBar.tsx
hooks/
useReportCollaborationSession.ts
useReportCollaborationStream.ts
useReportCollaborationMessages.ts
useReportPlanSelection.ts
useReportPanelLayout.ts
state/
event-normalizer.ts
event-reducer.ts
selectors.ts
message-adapter.ts
pages/
ReportCollaborationPage.tsx
styles/
report-collaboration.css
tests/
```
修改范围:
- `frontend-web/src/pages/WorkspaceRoutes.tsx`:增加页面和会话路由。
- `frontend-web/src/components/workspace/workspace-nav-chat-list.tsx`:增加导航入口。
- `frontend-web/src/components/workspace/messages/message-list.tsx`:仅允许增加一个向后兼容的通用业务卡片插槽。
- `frontend-web/src/core/messages/utils.ts`:如确需识别通用业务卡类型,只做集中式扩展。
不得把新功能放进:
- `frontend-web/src/roundtable-planning/`
- `frontend-web/src/open-canvas/`
- Coze 项目的 `workflow-standalone/`
---
## 6. 数据来源与前端状态
### 6.1 三层状态
前端状态分为:
1. 服务器快照:session、原生 messages、plans、run、nodes、artifacts、report versions;每条消息带稳定的 `agentRunId`、`nodeRunId`、`phaseId` 和可见性标记,其中 artifacts 只用于生成左侧消息卡和报告文件,不形成独立结果面板。
2. durable SSE reducer:从 `seq` 连续应用事件,更新服务器快照投影。
3. 纯展示状态:预览中的方案、选中的节点、聚焦的并行 `agentRunId`、两栏宽度、节点抽屉开关、窄屏当前视图和画布位置。
纯展示状态不能改变执行结果。点击卡片只改变 `previewPlanId`;只有点击“采用方案”才改变服务器 `selectedPlanId`。
### 6.2 前端事件包
```ts
interface CollaborationEvent<T = unknown> {
eventId: string;
sessionId: string;
runId?: string;
seq: number;
type: string;
timestamp: string;
data: T;
}
```
必须处理:
- 快照先到、事件后到。
- 事件重复。
- 事件短暂乱序。
- SSE 断线后从 `after_seq` 重放。
- 页面切换时旧连接晚到事件。
- token delta 多次更新同一消息。
- TeamSay、assistant 文本、tool-call 参数 delta、tool 返回 delta 分别更新各自稳定消息,不得等节点完成后批量生成摘要。
- 并行成员的消息可交错到达;Reducer 必须按 `agentRunId + messageId` 更新,而不是按当前被选中的标签丢弃未聚焦成员的事件。
- 节点重新打开后出现新 attempt。
Reducer 以 `sessionId + runId + seq` 去重;消息行以 `messageId`、工具结果以 `toolCallId`、标签以 `agentRunId` 使用后端稳定 ID,禁止使用数组下标。
---
## 7. 分步实施计划
### FE-0:冻结参考视觉与行为基线
任务:
1. 在 1440×900、1280×800、1024×768 打开参考页面。
2. 保存初始态、方案态、运行态和节点说明抽屉四组截图。
3. 记录顶栏、两栏比例、间距、圆角、边框、阴影、画布工具栏和状态色。
4. 形成“参考组件—目标组件—允许差异”表。
5. 明确消息列表保持 DeerFlow 原样,不纳入像素对齐。
交付物:
- 视觉基线截图。
- 视觉 token 表。
- 页面行为清单。
验收:参考的每个用户可见状态都有截图或明确说明不存在。
### FE-1:路由、菜单和静态页面骨架
任务:
1. 增加两个路由和菜单项。
2. 创建 `ReportCollaborationPage`。
3. 创建顶栏、左侧对话栏、右侧画布和底部连接栏。
4. 实现可调整宽度的两栏布局,以及“专注对话/专注画布”切换。
5. 实现窄屏单面板切换与覆盖式节点 Drawer。
验收:
- 不连接后端也能呈现完整空态。
- 375~1440px 不出现页面级横向滚动。
- 对话/画布切换不会卸载会话状态或清空输入内容。
- 键盘可以调整两栏分隔条。
### FE-2:页面设计系统与 Coze 风格重建
建立页面专用语义变量:
```text
--rc-bg-page
--rc-bg-panel
--rc-bg-canvas
--rc-border
--rc-text-primary
--rc-text-secondary
--rc-accent
--rc-running
--rc-waiting
--rc-success
--rc-danger
--rc-panel-shadow
--rc-card-radius
```
规则:
- 从 DeerFlow 主题 token 派生,不在组件中散落十六进制颜色。
- 使用 Lucide SVG 图标,不使用 emoji。
- hover/focus/展开动画控制在 150~300ms。
- 支持 `prefers-reduced-motion`。
- 交互状态不能只靠颜色表达。
- 正文对比度达到 4.5:1。
- 操作超过 300ms 显示 spinner、骨架或流式状态。
验收:除 MessageList 内部外,两栏布局、密度、卡片、画布工具栏、弹窗和节点抽屉达到参考基线。
### FE-3:API 类型和 TanStack Query 层
实现:
- session CRUD。
- messages 查询与发送。
- plan request、plans 查询、select。
- run 创建、查询、停止、重试。
- command 创建、确认、取消。
- artifacts、sources、reports、versions 查询。
每个写请求携带:
- `idempotencyKey`
- `expectedRevision`
冲突行为:
- `409`:刷新当前快照并提示用户重新确认。
- `422`:在对应操作附近显示具体错误。
- `429`:显示预算/并发限制,不自动重试。
- `5xx`:保留用户输入,允许使用同一幂等键重试。
验收:API 层不包含页面展示逻辑,类型与后端 OpenAPI 一致。
### FE-4:SSE、快照和事件 Reducer
实现 `useReportCollaborationStream`:
1. 先拉 session snapshot。
2. 使用 snapshot 的 `lastSeq` 建立 SSE。
3. 校验每个事件 session/run 身份。
4. 按 seq 应用事件并去重。
5. 出现序号缺口时暂停 live apply,补拉缺失事件。
6. 断线指数退避并支持 `Last-Event-ID`。
7. 终态后完成最后一次事件补拉再关闭连接。
Reducer 必须覆盖:
- 消息流增量。
- 计划候选和 revision。
- node/node attempt 状态。
- artifact 创建和校验。
- command 分类和执行。
- report delta 和正式版本。
- 错误、取消、接管恢复。
- AgentScope 原始可见消息和工具事件:`message.created/delta/completed`、`tool_call.created/delta/completed`、`tool_result.created/delta/completed`、`team_message.created/delta/completed`。
验收:重复事件、乱序事件和重连都不产生重复消息、重复节点或状态倒退。
### FE-5:复用 DeerFlow `MessageList`
复用:
- `frontend-web/src/components/workspace/messages/message-list.tsx`
- `frontend-web/src/components/workspace/messages/message-list-item.tsx`
- `frontend-web/src/components/workspace/messages/message-group.tsx`
- `frontend-web/src/components/workspace/messages/context.ts`
实现无损协议适配 `message-adapter.ts`:
1. 将已持久化的 `CollaborationMessage` 一对一映射为 LangGraph SDK `Message[]`,不将文本或工具结果二次概括。
2. 构造最小 `BaseStream<AgentThreadState>` 外观:`messages`、`isLoading`、`isThreadLoading`、`values`。
3. 协调者、成员 AgentScope TeamSay 和成员回复都映射为普通 assistant 消息;保留 `messageId`、文本 chunk、角色/成员名称、`agentRunId`、`nodeRunId`、`phaseId`、来源事件 ID 和完成态。
4. AgentScope 工具调用映射为该 assistant 消息的标准 `tool_calls`;调用结果映射为标准 `tool` 消息,并严格复用原有 `tool_call_id` 配对。工具参数、返回正文及增量保持原文,只有后端明确标注的脱敏字段被替换。
5. 将来源、文件、报告 Markdown delta 和正式版本继续映射为既有引用、文件卡和普通 assistant 消息;规划卡、用户确认卡和报告替换卡仍通过一个通用业务卡片插槽渲染。
6. 错误、恢复建议、命令影响范围和报告版本变化也必须进入同一时间线;错误堆栈以可读错误消息替代,但不能吞掉已发生的工具/成员消息。
7. `selectMessagesForAgentRun(allMessages, focusedAgentRunId)` 只在客户端从已同步消息中选出共享消息与目标成员消息;并行选择器不得重新拉取、重新排序或改写消息。
约束:
- 不使用 LangGraph `useThreadStream` 发送消息。
- 新页面输入框调用报告协作 API。
- 不增加多个页面专用 MessageList props。
- 普通聊天、AI 写作、深度研究等未传插槽时必须零变化。
- 不另建执行结果列表、节点结果面板或成果时间线。
- 不用“运行中”“已检索 N 条”等专用摘要替代真实消息。`MessageList` 本身的流式状态和原生工具步骤是唯一过程视图。
验收:
- 历史和流式消息使用同一行稳定更新。
- 单成员首次开始回复、每次工具启动和工具返回均在 300ms 内出现可见的原生消息行或原生工具步骤;不允许持续数秒只有静态加载圈。
- 并行标签切换后显示目标成员的完整已持久化消息和实时 delta;未选中成员持续接收,标签上的运行/待回复状态及时更新。
- 用户上翻阅读时不强制滚底。
- 用户发送新消息后滚到最新位置。
- 卡片显示成功不改变后端节点状态。
### FE-6:需求澄清和候选方案卡片
`ReportPlanCards` 展示:
- 推荐标签、策略、标题、摘要和推荐理由。
- 分析角度和参与角色。
- 关键步骤与质量门。
- 预计时间、成本等级和资料范围。
- 方案验证错误。
交互:
- 点击卡片或“查看流程”只切换预览。
- “采用此方案”调用 select API。
- “开始协作”再次校验并创建 run。
- 方案调整后显示新 revision;旧 revision 只读。
- 过期 revision 返回 409 后不静默覆盖。
验收:连续快速切换三张卡时,画布最终显示最后一次选择,不闪回旧图。
### FE-7:协作流程画布
技术:`@xyflow/react`。可以借鉴但不直接耦合:
- `frontend-web/src/components/ai-elements/canvas.tsx`
- `frontend-web/src/roundtable-planning/components/FlowGraphPanel.tsx`
节点显示:
- 节点名、角色名和分析角度。
- 状态文字、图标和颜色。
- 等待用户、返工、失败和 superseded 标记。
画布能力:
- 自动布局。
- 拖动节点只保存浏览器展示位置。
- 缩放、适配视图、方向切换、小地图。
- 活动边低强度流动动画。
- 点击节点打开覆盖在画布上的节点说明抽屉。
- 节点重跑、补充或纠偏一律通过左侧对话完成;抽屉只提供“在对话中对此节点提出意见”入口。
- 方案切换后清理不属于新方案的本地坐标。
验收:
- 30 个节点内流畅操作。
- 单个 node event 不导致整个 React Flow 重挂。
- `awaiting_input`、`reopened`、`superseded` 不与 `completed` 混淆。
### FE-8:节点说明抽屉与对话定位
点击画布节点打开 `NodeInspectorDrawer`。抽屉只展示计划合同:
1. 节点名称、角色、分析角度和当前状态标签。
2. 节点职责:负责解决什么问题。
3. 要根据什么:所需输入类型、上游节点类型、资料范围和时效要求。
4. 要产出什么:成果类型、结构要求和验收条件。
5. 可用工具、禁止事项、预算上限。
6. 上游与下游关系。
抽屉不展示:
- 节点实际生成内容。
- 工具调用返回值。
- EvidenceBundle 或其他成果物正文。
- attempt 执行时间线。
- 错误堆栈和调试信息。
- 报告正文。
交互:
- “在对话中对此节点提出意见”关闭抽屉、聚焦左侧 Composer,并绑定 `targetNodeId` 上下文。
- 若该节点对应正在并行运行的成员,同时绑定该成员的 `agentRunId` 并切换左侧选择器,使用户发送前能先看到该成员的真实对话与工具过程。
- 用户仍需在对话区输入“重新检索”“重新分析”等要求;抽屉不直接发起业务变更。
- 状态标签来自后端节点状态,但不加载节点结果接口。
- 关闭抽屉不清空 selected node;再次点击同一节点可恢复说明。
报告预览不使用常驻第三栏。最终报告、章节候选和版本先作为左侧 MessageList 中的普通消息/文件卡出现;点击文件卡时复用 `ArtifactFileDetail` 或现有 Markdown 能力打开大尺寸 Dialog,关闭后回到两栏工作台。
验收:
- 抽屉宽度不改变两栏布局,不挤压左侧对话区。
- 抽屉只读取节点合同和图结构,不请求节点执行结果。
- 所有原生成员消息、工具过程、错误和报告入口都能在左侧对话时间线找到。
### FE-9:全过程对话干预
`ReportComposer` 根据状态显示不同提示:
- 空闲:输入报告需求。
- 规划中:补充要求将在规划安全点应用。
- 运行中:协调者正在判断影响范围。
- 等待用户:优先回答等待问题。
- 完成后:可问答、重写、润色或重新研究。
发送流程:
1. 生成 idempotency key。
2. 插入 pending 用户消息;带 `targetNodeId`/`agentRunId` 时在相关成员消息流和共享上下文中引用同一条用户消息,不重复持久化。
3. 显示“正在识别修改范围”。
4. `command.classified` 后展示意图和影响节点。
5. 高成本或低置信度命令显示确认卡。
6. `command.accepted` 后显示排队或等待安全点。
7. 完成后关联新 node attempt 或 report version。
8. 失败时保留原消息和重试入口。
典型映射:
| 用户输入 | 预期操作 |
|---|---|
| “增加政策风险角度” | 新增角度节点和受影响下游 |
| “资料太旧,重新找” | 重新检索指定证据包 |
| “竞争格局分析不到位” | 复用证据,重新分析 |
| “重写第二章” | 只生成章节替换候选 |
| “语气更正式” | 新报告版本,不重新研究 |
| “为什么得出这个结论” | 只读问答,不修改报告 |
验收:
- 双击发送不创建重复命令。
- 选中“品牌竞争分析师”后发送补充要求,只影响该成员及依赖分析,其他并行成员仍保持消息流和运行状态。
- 运行中反馈不会让 run 或 node 误变 completed。
- “重写第二章”不会触发全量检索。
- “资料太旧”不会只做文字润色。
### FE-10:会话历史、报告版本与导出
- History Tab 显示标题、状态、更新时间、当前版本。
- 新建会话不删除旧会话。
- 会话切换时先关闭旧 SSE,再加载新快照。
- 报告修改先生成候选,确认后创建新版本。
- 版本恢复创建新的头版本,不删除历史。
- 下载复用现有 Markdown/Word 能力。
- 文件名来自报告标题,不暴露宿主机或沙箱路径。
验收:历史会话可完整恢复左侧消息流程、右侧节点状态和报告版本;不额外恢复节点结果面板。
### FE-11:测试、视觉回归和性能
单元测试:
- event normalizer/reducer。
- message adapter。
- plan revision 和选择状态。
- node status 和 available actions。
- command pending/idempotency。
组件测试:
- 空态、澄清、规划、候选、运行、等待、完成、失败、取消。
- 卡片选择、节点点击、只读说明 Drawer、确认弹窗和报告预览 Dialog。
- MessageList 通用业务卡插槽零回归。
- 单成员流式文本、TeamSay、工具调用与工具返回的原样重放;并行成员交错到达、切换标签、切回后不中断 delta。
- 非当前标签成员发起协助时显示待回复徽标,点击后使用原生协助卡回复到正确节点。
E2E:
1. 新建会话并输入新能源汽车报告要求。
2. 选择候选并开始。
3. 运行中增加风险角度。
4. 重新检索海外最新资料。
5. 完成后重写第二章。
6. 刷新、断网重连、切换会话。
7. 停止和重试失败节点。
性能门:
- 30 节点画布不卡顿。
- 长消息列表使用现有优化策略。
- SSE 高频 delta 合帧后再 setState。
- 画布和消息区使用独立 selector,避免互相触发整树重渲染。
- 节点抽屉只订阅节点合同和状态,不能因阶段产出更新而反复重渲染。
- 只渲染当前聚焦成员和共享消息的可视窗口;非当前成员的消息仍写入 store,但不因 token delta 重渲染当前 `MessageList`。
---
## 8. 后端接口依赖
前端开发前,后端必须冻结以下接口:
```text
POST /api/report-collaboration/sessions
GET /api/report-collaboration/sessions
GET /api/report-collaboration/sessions/{session_id}
PATCH /api/report-collaboration/sessions/{session_id}
DELETE /api/report-collaboration/sessions/{session_id}
POST /api/report-collaboration/sessions/{session_id}/messages
GET /api/report-collaboration/sessions/{session_id}/messages
POST /api/report-collaboration/sessions/{session_id}/plan-requests
GET /api/report-collaboration/sessions/{session_id}/plans
POST /api/report-collaboration/sessions/{session_id}/plans/{plan_id}/select
POST /api/report-collaboration/sessions/{session_id}/runs
GET /api/report-collaboration/runs/{run_id}
GET /api/report-collaboration/runs/{run_id}/events
GET /api/report-collaboration/runs/{run_id}/stream
POST /api/report-collaboration/runs/{run_id}/commands
POST /api/report-collaboration/runs/{run_id}/cancel
GET /api/report-collaboration/runs/{run_id}/nodes/{node_id}/contract
GET /api/report-collaboration/sessions/{session_id}/reports
POST /api/report-collaboration/sessions/{session_id}/report-rewrites
POST /api/report-collaboration/sessions/{session_id}/report-rewrites/{id}/apply
```
前后端共享枚举:
- session status。
- run status。
- node/node attempt status。
- command intent/status。
- event type/version。
- artifact type/schema version。
- report version/change type。
---
## 9. 前端开发顺序
页面与契约层已完成(代码在 `frontend-web/src/report-collaboration/`):
1. `RC-FE-001`:视觉截图与行为基线。
2. `RC-FE-002`:路由、菜单和左对话/右画布两栏空壳。
3. `RC-FE-003`:页面 token、弹窗、抽屉和响应式。
4. `RC-FE-004`:API 类型和 mock server。
5. `RC-FE-005`:SSE reducer 与快照恢复。
6. `RC-FE-006`:MessageList adapter 和通用卡片插槽。
7. `RC-FE-007`:需求澄清与候选方案卡。
8. `RC-FE-008`:流程画布和自定义节点。
9. `RC-FE-009`:只读节点说明抽屉与对话目标定位。
10. `RC-FE-010`:统一 Composer 和命令确认。
11. `RC-FE-011`:报告预览、版本和导出。
12. `RC-FE-012`:历史、重连和异常恢复。
13. `RC-FE-013`:组件/E2E/视觉/性能验收。
依赖规则:
- 契约已冻结为 `src/report-collaboration/api/types.ts`;后端 `RC-BE-001` 已对齐。
- 真实 SSE 联调:后端 `RC-BE-011` 已挂载 `GET /runs/{id}/stream`;默认无后台循环时流只会重放已入库事件。
- 报告版本操作已接后端 `RC-BE-015`(改写候选 / apply / restore)。
- 执行画布实时状态依赖打开 `worker_enabled`;质量角色内核已在 `RC-BE-013` 落地,真实成员见 `RC-BE-017`。
---
## 10. 前端完成定义
页面与 mock 联调路径已落地。真实后端可联调 `GET /runs/{id}/stream`、领取/恢复(`RC-BE-012`,默认不挂 worker)、质量角色(`RC-BE-013`)以及报告改写/恢复(`RC-BE-015`)。此前以 mock driver 覆盖交互,不以「前端未编码」计未完成。
前端只有同时满足以下条件才算完成:
1. 页面结构与 Coze 参考页面逐状态验收通过。
2. 消息区复用 DeerFlow `MessageList`,其他聊天页面无回归。
3. 候选卡、左侧对话流程、右侧流程图和报告来自同一 session/run/event 状态。
4. 点击候选只预览,明确确认后才执行。
5. 用户可以在规划、运行、完成后三个阶段继续对话。
6. 协助卡显示或提交不会导致前端误标完成。
7. 节点点击只打开说明抽屉,可查看职责、所需输入、预期输出、工具和验收条件,不展示执行结果。
8. 节点重开、返工和 superseded 状态表达正确。
9. SSE 重连、刷新和历史切换无重复消息和状态倒退。
10. 报告修改以候选和版本形式完成,不直接覆盖正式报告。
11. 页面始终只有对话与画布两个常驻区域,所有执行过程和产出入口都能在对话时间线中找到。
12. 响应式、键盘、对比度、加载反馈和错误恢复通过验收。
@@ -0,0 +1,485 @@
# 报告协作工作台 — 前端对接指南
> **适用版本:** RC-BE-000~018 已落地(2026-09-06)
> **配套文档:**
> - [前端实施计划](./agentscope-多智能体报告协作工作台-前端实施计划.md)
> - [后端实施计划](./agentscope-多智能体报告协作工作台-后端实施计划.md)
> - 模块 README:`frontend-web/src/report-collaboration/README.md`
本文说明**前端如何对接真实后端**:环境配置、API 契约、用户流程、状态机、错误处理与联调验收。前端 API 客户端与页面已实现,通常**无需再写一套 HTTP 层**。
---
## 1. 结论速览
| 问题 | 答案 |
|------|------|
| 前端还要写接口吗? | **不用**。`src/report-collaboration/api/` 已封装 REST + SSE,页面通过 `getReportCollaborationDriver()` 调用。 |
| 为什么调不通? | 最常见:`config.yaml` 里 `report_collaboration.enabled: false` → 全部 **503**;或 `worker_enabled: false` → run 不入队执行。 |
| Mock 和真后端怎么切? | **Mock 已移除**。前端永远请求真实后端(`deerflow.rc-mock` / `VITE_RC_MOCK` 开关已删除);联调需 `enabled: true`。 |
| 字段会和 MySQL 对不上吗? | 前端只认 JSON 契约(`api/types.ts`),不直连表。缺列表现为后端 500/SQL 错误,部署后需**重启 Gateway** 跑 `create_all` + 列同步。 |
| 从哪进页面? | `/page/workspace/report-collaboration`(新会话)或 `/page/workspace/report-collaboration/:sessionId`。侧边栏入口默认注释,可直接 URL 访问。 |
---
## 2. 架构:前端已有什么
```
ReportCollaborationPage
└─ useReportCollaborationSession(唯一数据入口)
├─ driver.getSnapshot() ← REST 冷启动
├─ driver.openRunStream() ← SSE 实时事件
├─ driver.sendMessage / createCommand / startRun …
└─ event-reducer ← 事件 → UI 状态
ReportConversationPanel
└─ MessageList(message-adapter 映射 CollaborationMessage → LangGraph Message)
```
### 2.1 目录结构
```text
frontend-web/src/report-collaboration/
api/
types.ts # 冻结契约(snake_case,与后端 Pydantic 一致)
client.ts # rcFetch:鉴权、幂等键、乐观锁、错误映射
sessions.ts # 会话 CRUD、消息
plans.ts # 方案请求 / 列表 / 选定
runs.ts # Run、SSE、命令、节点合同
reports.ts # 报告版本、改写、恢复
driver.ts # 真实后端统一门面(Mock 驱动已移除)
state/
event-normalizer.ts
event-reducer.ts
selectors.ts
message-adapter.ts
hooks/
useReportCollaborationSession.ts # 快照 → SSE → reducer → 动作
useReportCollaborationStream.ts # 断线重连、after_seq 续接
useReportCollaborationMessages.ts
components/ …
pages/ReportCollaborationPage.tsx
```
### 2.2 事实源原则
- **冷启动:** `GET /sessions/{id}` 返回 `SessionSnapshot`(session、messages、plans、run、nodes、agent_runs、commands、report_versions、last_seq)。
- **运行中:** `GET /runs/{id}/stream?after_seq=N` 订阅 durable SSE。
- **断线 / 序号缺口:** `GET /runs/{id}/events?after_seq=N` REST 补拉。
- **澄清 / 规划阶段(尚无 run):** 每 2.5s 轮询快照(后端事件主要在 run 流上)。
纯展示状态(预览方案、聚焦成员、面板宽度)**不**写入服务器,仅存前端。
---
## 3. 后端启用与部署
### 3.1 必改配置
文件:`offline-backend-20260512/backend/config.yaml`
```yaml
report_collaboration:
enabled: false # 联调必须改为 true
worker_enabled: false # 要看成员执行必须 true
planner_model: null # 建议填可用模型名
coordinator_model: null
research_model: null
writer_model: null
reviewer_model: null
# … token_budget、max_concurrent_runs_per_user 等见同文件
```
| 配置 | 现象 |
|------|------|
| `enabled: false` | 所有路由 **503**,`code: REPORT_COLLABORATION_DISABLED` |
| `enabled: true`,`worker_enabled: false` | REST/SSE 可用,run 入队但不自动执行(测 API 可用,无成员流式输出) |
| 两者 `true` + 模型配置完整 | 完整联调 |
### 3.2 MySQL / 表结构
生产环境 Alembic 自动升级默认关闭,启动时走 `create_all` + `_ensure_orm_columns_sync`。
- 迁移脚本(可选手动跑):`20260905_01`、`20260906_01`、`20260907_01`
- ORM:`packages/harness/deerflow/persistence/report_collaboration/model.py`(13 张表)
- **部署后务必重启 Gateway**,观察日志是否有 `Failed to auto-add column report_collaboration_*`
已有 RC-003 时代旧表会通过列同步补上 `template_snapshot_json`、`budget_snapshot_json`、`usage_json`、`budget_exhausted_reason` 等可空列,并创建 `rewrite_proposals`、`audits`。
### 3.3 前端环境变量
| 变量 | 说明 |
|------|------|
| `VITE_BACKEND_BASE_URL` | Gateway 地址,默认 `http://127.0.0.1:8001` |
请求经 `apiFetch`,自动携带登录 JWT(`credentials: "include"`)。**必须先登录 DeerFlow**。
---
## 4. API 基址与请求约定
### 4.1 Base URL
```text
{VITE_BACKEND_BASE_URL}/api/report-collaboration
```
代码常量:`REPORT_COLLABORATION_BASE()`(`api/client.ts`)。
### 4.2 请求头
| Header | 何时携带 | 说明 |
|--------|----------|------|
| `Authorization` | 全部 | 由 `apiFetch` 注入 |
| `X-Idempotency-Key` | 写操作 | 格式 `rc-{uuid}`;重复提交返回首次结果 |
| `X-Expected-Revision` | 选方案、开 run、改会话等 | 会话 `requirement_revision` 或方案 `revision` |
| `Accept: text/event-stream` | SSE | `openRunStream` |
### 4.3 错误响应格式
```json
{
"code": "REPORT_COLLABORATION_DISABLED",
"message": "报告协作工作台未启用",
"detail": { }
}
```
前端映射(`api/client.ts`):
| HTTP | 异常类 | 典型场景 |
|------|--------|----------|
| 409 | `ConflictError` | revision 过期、active run 冲突 |
| 422 | `ValidationError` | 参数/语义错误、缺幂等键 |
| 429 | `RateLimitError` | 预算耗尽、每用户并发 run 上限 |
| 5xx | `ServerError` | 可带同一幂等键重试 |
| 0 | `NetworkError` | fetch 失败 |
### 4.4 完整路由清单(与前端 client 对齐)
| 方法 | 路径 | 前端模块 |
|------|------|----------|
| POST | `/sessions` | `sessions.createSession` |
| GET | `/sessions` | `sessions.listSessions` |
| GET | `/sessions/{id}` | `sessions.getSessionSnapshot` |
| PATCH | `/sessions/{id}` | `sessions.updateSession` |
| DELETE | `/sessions/{id}` | `sessions.deleteSession` |
| GET | `/sessions/{id}/messages` | `sessions.listMessages` |
| POST | `/sessions/{id}/messages` | `sessions.sendMessage` |
| POST | `/sessions/{id}/plan-requests` | `plans.requestPlans` |
| GET | `/sessions/{id}/plans` | `plans.listPlans` |
| POST | `/sessions/{id}/plans/{planId}/select` | `plans.selectPlan` |
| POST | `/sessions/{id}/runs` | `runs.startRun` |
| GET | `/sessions/{id}/reports` | `reports.listReportVersions` |
| POST | `/sessions/{id}/report-rewrites` | `reports.createRewrite` |
| POST | `/sessions/{id}/report-rewrites/{id}/apply` | `reports.applyRewrite` |
| POST | `/sessions/{id}/report-versions/{id}/restore` | `reports.restoreReportVersion` |
| GET | `/runs/{id}` | `runs.getRun` |
| GET | `/runs/{id}/events` | `runs.listRunEvents` |
| GET | `/runs/{id}/stream` | `runs.openRunStream` |
| POST | `/runs/{id}/cancel` | `runs.cancelRun` |
| POST | `/runs/{id}/commands` | `runs.createCommand` |
| POST | `/runs/{id}/commands/{id}/confirm` | `runs.confirmCommand` |
| POST | `/runs/{id}/commands/{id}/cancel` | `runs.cancelCommand` |
| GET | `/runs/{id}/nodes/{nodeId}/contract` | `runs.getNodeContract` |
| GET | `/runs/{id}/artifacts` | (后端已暴露,前端按需接) |
| GET | `/runs/{id}/sources` | (后端已暴露,前端按需接) |
---
## 5. 用户流程与 API 时序
```mermaid
sequenceDiagram
participant U as 用户
participant FE as 前端 RC
participant API as Gateway
participant W as Worker
U->>FE: 输入需求
FE->>API: POST /sessions
FE->>API: POST /sessions/{id}/messages
API-->>FE: 澄清(快照 messages)
U->>FE: 回答澄清
FE->>API: POST /messages
FE->>API: POST /plan-requests
API-->>FE: 候选方案(快照 plans)
U->>FE: 采用方案
FE->>API: POST /plans/{id}/select
U->>FE: 开始协作
FE->>API: POST /runs
FE->>API: GET /runs/{id}/stream
W-->>API: 持久化事件
API-->>FE: SSE
U->>FE: 运行中干预
FE->>API: POST /commands → confirm
```
### 5.1 阶段 0:进入页面
| 路由 | 行为 |
|------|------|
| `/page/workspace/report-collaboration` | 空态;`POST /sessions` 后跳转带 `sessionId` |
| `/page/workspace/report-collaboration/:sessionId` | 加载快照;有 `location.state.rcInitialMessage` 时自动发首条消息 |
路由注册:`frontend-web/src/pages/WorkspaceRoutes.tsx`。
侧边栏入口已在 `workspace-nav-chat-list.tsx` 中放开(「报告协作」项),也可直接访问 URL。
### 5.2 阶段 1:需求澄清(无 run)
```http
POST /api/report-collaboration/sessions
POST /api/intent/init
POST /api/intent/stream
POST /api/report-collaboration/sessions/{sessionId}/intent-turns
```
- 报告页面固定调用内置 `report-collaboration-intent` 智能体;`/api/intent/stream` 原样透传 LangGraph `messages-tuple`,不是等待模型完成后包装响应。
- 正文 token、provider reasoning 和工具调用步骤实时写入当前 `MessageList` 气泡;终态后 `/intent-turns` 只负责持久化镜像与状态交接,不再调用模型识别意图。
- 旧 `/sessions/{sessionId}/messages` 在 `empty/clarifying` 阶段返回 `409 USE_STREAMING_INTENT`,防止退回阻塞式 `ainvoke` 路径。
- 会话状态:`empty` → `clarifying` → `planning` → `proposal_ready`。
- 澄清问题以 `CollaborationMessage` 进入时间线;业务卡通过 `MessageList` 的 `businessCardSlot` 渲染(`additional_kwargs.report_collaboration_card`)。
- 意图智能体输出 `INTENT_READY` 后,`POST /intent-turns` 自动创建并完成 `plan_request`;前端无需再展示“确认意图”或“生成候选方案”按钮。
### 5.3 阶段 2:候选方案
```http
# 正常路径:由最后一轮 POST /messages 自动触发规划
POST /api/report-collaboration/sessions/{sessionId}/plans/{planId}/select
```
- `POST /plan-requests` 仅保留给“重新生成”与兼容调用,不是首次规划的必经步骤。
- 规划师尚未判定 `ready` 时直接调用该兼容接口会返回 `422 REQUIREMENT_NOT_READY`,防止跳过意图确认。
- **预览方案**(`previewPlanId`):纯前端,不调 API。
- **采用方案**:`select` 写 `selected_plan_id`,**不**创建 run。
- 409:方案 revision 过期 → 前端 `refreshSnapshot`,提示用户重选。
- 右栏 `ReportFlowCanvas` 使用 `PlanNode` / `PlanEdge` 渲染 DAG。
### 5.4 阶段 3:开始执行与 SSE
```http
POST /api/report-collaboration/sessions/{sessionId}/runs
{ "plan_id": "plan-xxx" }
GET /api/report-collaboration/runs/{runId}/stream?after_seq=0
Accept: text/event-stream
```
SSE 每条 `data:` 为 JSON:
```typescript
interface CollaborationEvent {
eventId: string;
sessionId: string;
runId?: string | null;
seq: number;
type: CollaborationEventType;
timestamp: string;
data: unknown;
}
```
常用 `type`(完整列表见 `api/types.ts`):
| 类型 | 含义 |
|------|------|
| `message.created` / `message.delta` / `message.completed` | 对话镜像流式 |
| `tool_call.*` / `tool_result.*` | 工具调用与返回 |
| `team_message.*` | 成员 / 协调者广播 |
| `plan.proposed` / `plan.selected` | 方案生命周期 |
| `run.status.changed` | Run 状态 |
| `node.status.changed` / `node.progress` | 节点执行 |
| `command.confirmation.required` | 需用户确认的干预 |
| `report.version.created` | 报告版本落盘 |
| `heartbeat` | 保活 |
### 5.5 阶段 4:运行中干预
```http
POST /api/report-collaboration/runs/{runId}/commands
POST /api/report-collaboration/runs/{runId}/commands/{commandId}/confirm
POST /api/report-collaboration/runs/{runId}/commands/{commandId}/cancel
POST /api/report-collaboration/runs/{runId}/cancel
```
- Run 活跃时 `send()` 自动走 `createCommand`(而非 `sendMessage`)。
- 可从节点抽屉 / `AgentStageSelector` 传入 `target_node_id`、`agent_run_id`。
- `InterventionCard` 展示 `confirmation_required` 命令;确认后调 `confirmCommand`。
`CommandIntent` 枚举(后端分类,前端展示 reason/impact):`answer_question`、`update_requirements`、`research_again`、`rewrite_section`、`rerun_node`、`replan`、`cancel` 等。
### 5.6 阶段 5:报告版本与改写
```http
GET /api/report-collaboration/sessions/{sessionId}/reports
POST /api/report-collaboration/sessions/{sessionId}/report-rewrites
POST /api/report-collaboration/sessions/{sessionId}/report-rewrites/{rewriteId}/apply
POST /api/report-collaboration/sessions/{sessionId}/report-versions/{versionId}/restore
```
- `createRewrite` 只生成候选,不直接覆盖正式版本。
- `applyRewrite` / `restoreReportVersion` 产生新的 head 版本,历史保留。
- `ReportPreviewDialog` 展示 `ReportVersion.markdown`。
---
## 6. 前端状态机(接入方须知)
**不要**在页面里用零散 REST 字段拼 UI 状态。统一路径:
```text
SessionSnapshot → applySessionSnapshot()
CollaborationEvent[] → normalizeCollaborationEvent() → applyCollaborationEvents()
→ selectors(derivePagePhase、selectPlanForCanvas、…)
```
### 6.1 核心 Selector
| Selector | 用途 |
|----------|------|
| `derivePagePhase` | Composer 占位、方案卡、空态 |
| `selectPlanForCanvas` | 画布 DAG(含预览方案) |
| `selectAgentTabs` | 并行成员 Tab |
| `selectNodeStatusMap` | 节点颜色 / 状态 |
| `selectPendingConfirmationCommands` | 干预确认卡 |
| `selectHeadReportVersion` | 报告预览入口 |
| `selectStreamingAgentRunIds` | 流式成员指示 |
### 6.2 SSE 连接策略(`useReportCollaborationStream`)
- Run 非终态时连接;`completed` / `failed` / `cancelled` 后关流并 REST 最终补拉。
- 断线:指数退避重连(1s~30s),`after_seq` 取 reducer 内 `lastSeq`。
- `hasSeqGap`:暂停 live 应用,先 `listRunEvents` 回填。
### 6.3 乐观消息
用户发送时插入 `metadata.optimistic: true` 的 pending 消息;服务端镜像带相同 `idempotency_key` 时 reducer 原地替换。
---
## 7. 消息与 MessageList 复用
`useReportCollaborationMessages` 将 `CollaborationMessage[]` 转为 `@langchain/langgraph-sdk` 的 `Message[]`,并构造合成 `BaseStream` 供 `MessageList` 消费。
| 来源 | 渲染 |
|------|------|
| `human` / `ai` 文本 | 普通气泡 |
| `tool_calls` + `tool` | 现有工具卡 |
| `team_message` 事件 | 带 `name` 的成员发言 |
| 业务卡 | `businessCardSlot`(方案组、命令确认、报告可用) |
分组键:`core/messages/utils.ts` 中 `assistant:task-report-import` 同级扩展 `assistant:business-card`,判据 `additional_kwargs.report_collaboration_card`。
### 7.1 在其他页面嵌入 RC(最小集)
1. `useReportCollaborationSession(sessionId)`
2. `ThreadContext.Provider` + `MessageList` + `businessCardSlot`
3. 引入 `report-collaboration/styles/report-collaboration.css`
---
## 8. 单测
Mock 驱动(原 `api/mock.ts`)与 `deerflow.rc-mock` / `VITE_RC_MOCK` 开关已移除,前端只请求真实后端;本地演示请直接联调后端。
单测:
```bash
cd frontend-web
pnpm test:report-collaboration
```
---
## 9. 联调验收清单
### 9.1 准备
- [ ] `report_collaboration.enabled: true`
- [ ] `report_collaboration.worker_enabled: true`
- [ ] 五个 `*_model` 已配置且可用
- [ ] Gateway 已重启(MySQL 表/列就绪)
- [ ] 前端已登录(JWT 有效)
### 9.2 探活
```bash
curl -s -H "Authorization: Bearer <token>" \
http://127.0.0.1:8001/api/report-collaboration/sessions
```
期望:**200** + `{ "sessions": [...] }`,而非 503。
### 9.3 页面流程(浏览器 Network)
1. 打开 `/#/page/workspace/report-collaboration`
2. 输入需求 → `POST .../sessions` **200**
3. 跳转 → `GET .../sessions/{id}` **200**,响应含 `SessionSnapshot`
4. 首条消息 → `POST .../messages` **200**
5. 请求方案 → `POST .../plan-requests` **200**
6. 采用方案 → `POST .../plans/{id}/select` **200**
7. 开始协作 → `POST .../runs` **200**
8. `GET .../runs/{id}/stream` 持续收到 SSE(`message.delta`、`node.status.changed` 等)
9. 刷新页面 → 消息与 `last_seq` 续接正确
10. 运行中输入「重新检索」→ `POST .../commands` → 确认卡 → `confirm` **200**
### 9.4 常见失败
| 现象 | 原因 | 处理 |
|------|------|------|
| 全部 503 | `enabled: false` | 改配置并重启 |
| run 一直 queued | `worker_enabled: false` | 改为 true |
| 409 选方案 | revision 过期 | 刷新后重选(前端已自动 refresh) |
| 429 | 预算/并发上限 | 调大配置或取消其他 run |
| 500 + SQL | 表缺列 | 重启 Gateway,查列同步日志 |
---
## 10. 契约与类型维护
- **单一事实源:** `frontend-web/src/report-collaboration/api/types.ts`
- **后端镜像:** `offline-backend-20260512/backend/app/report_collaboration/contracts/`
- 修改字段须同步两份实施计划与本指南,并跑前后端相关测试。
`SessionSnapshot` 形状(摘要):
```typescript
interface SessionSnapshot {
session: ReportSession;
messages: CollaborationMessage[];
plans: ReportPlanCandidate[];
run: ReportRun | null;
nodes: CollaborationNodeState[];
agent_runs: AgentRun[];
commands: CollaborationCommand[];
report_versions: ReportVersion[];
last_seq: number;
}
```
`ReportRun` 可选字段(RC-BE-016):`usage`、`budget_exhausted_reason`。
---
## 11. 后续工作(非对接阻塞)
| 项 | 说明 |
|----|------|
| RC-BE-019 | 灰度发布与离线部署文档 |
| 侧边栏入口 | 已放开(`workspace-nav-chat-list.tsx` 的「报告协作」项) |
| iframe 嵌入 | RC 页尚未专门适配 `embed=1`,可参考现有深链模式扩展 |
| 真人盲评 | RC-BE-018 为确定性评测集,上线前仍需计划 §11.4 人工评审 |
---
## 12. 相关代码索引
| 用途 | 路径 |
|------|------|
| API 客户端 | `frontend-web/src/report-collaboration/api/` |
| 会话 Hook | `frontend-web/src/report-collaboration/hooks/useReportCollaborationSession.ts` |
| 页面 | `frontend-web/src/report-collaboration/pages/ReportCollaborationPage.tsx` |
| 路由 | `frontend-web/src/pages/WorkspaceRoutes.tsx` |
| 后端路由 | `offline-backend-20260512/backend/app/gateway/routers/report_collaboration.py` |
| 配置 | `offline-backend-20260512/backend/config.yaml` → `report_collaboration` |
| 持久化 | `offline-backend-20260512/backend/packages/harness/deerflow/persistence/report_collaboration/` |
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
# 日常使用复查(2026-09-14)
范围:ji 分支上继续检查知识库管理、助手知识库、我的项目、项目问答和官方入口。沿用本地隔离后端数据目录 `.runtime/ji-acceptance`,浏览器检查 464×642 与 1440×900 两种尺寸;未向生产库写入验收项目。
## 发现与修复
**首屏白屏的直接业务触发点也已修复:** `LlmWikiKnowledgeSelector` 在懒加载/未加载知识目录时,每次渲染创建新的空数组,推荐问题 effect 随之回写父页状态,形成无限更新。将目录空结果和默认助手库选择稳定化后,重新从登录进入新对话成功,欢迎引导、输入框及知识空间下拉均可操作(截图 06)。仅升级依赖并不能消除这个业务循环;上述修复与依赖兼容更新共同保留。
1. **首次进入:高影响,已修复依赖。** 本轮首次登录后出现整页空白,控制台为 ScrollArea `Maximum update depth exceeded`。安装版本 1.2.10 使用不稳定引用回调;升级并锁定 1.2.18,同步 package-lock,核对源码使用稳定 setState 引用。冷启动仍复现组合引用循环,进一步发现各基础组件带入 Slot 1.2.3/1.2.4;统一锁定 Slot 1.3.3,npm 与 pnpm 均配置覆盖间接依赖。依据 [Radix 发布记录](https://www.radix-ui.com/primitives/docs/overview/releases) 的 React 19 无限重渲染及 Slot 引用修复。
2. **新建项目:已修复。** 手机表单出现两个菜单按钮(截图 01)。由外层提供菜单时不再显示内部按钮;官方入口也去掉无效的内部侧栏按钮。
3. **项目历史:已修复。** 我的项目侧栏链接跳到旧项目空间(截图 02),导致返回目的地变化。现在保留我的项目路径,普通聊天与旧项目空间保持原路由。手机点历史后菜单自动收起。官方侧栏原本把项目聊天打开为普通聊天,现按项目归属进入项目工作区;`/official/workspace/projects/groups` 根路径回到普通问答项目列表。
4. **项目设置与失败恢复:已修复。** 默认智能体更新后,同步新对话选择器;项目对话权限/归属加载失败、普通问答项目列表失败均有重试入口。
5. **助手知识检索:已修复。** 连续检索或切换库时,以递增请求序号隔离过期成功/失败/结束回调,防止旧结果覆盖新库;新检索清除旧结果;空输入禁止提交。无结果原本只有小标签(截图 03),现在说明可调整关键词并提供浏览目录按钮。输入框补充可访问名称。
6. **窄屏输入栏:已修复。** 464px 截图中发送箭头被工具栏挤出右边缘(截图 07);工具区允许换行、发送区不收缩,截图 08 确认按钮完整可见。项目问答网络错误也增加“重新加载对话”,只重建读取状态,不自动重发消息。
## 复测记录
- 具名项目创建成功;新建项目对话,通过真实模型收到“项目问答回归通过”;刷新保留消息与项目归属。
- 修复工具栏后,在窄屏实际点击发送并收到“窄屏发送通过”;首屏知识空间菜单完成加载、选择助手库后显示已选择 1 个,未再出现循环白屏。
- 手机项目历史链接确认留在 `qa/projects/groups`;桌面官方 groups 根路径跳回正确列表,官方项目历史进入相同项目。
- 官方和常规项目切换时偶发网络 `Failed to fetch`,刷新/重新挂载恢复历史消息;没有将其描述为已排除的网络问题,新增恢复按钮未进行独立网络故障注入测试。
- 助手知识库列表、阅读、检索无结果、返回入口实际操作;空查询按钮禁用。检索竞态由代码检查修复,未使用浏览器网络故障注入。
- 后端 22 个相关文件重新运行:**273 passed**,涵盖知识库管理/导入/检索、Wiki、编码与向量、项目归属隔离、策略持久化及调用边界。
- 前端项目与策略测试:**33 passed**,新增项目历史保持入口、旧项目和普通聊天/创建向导回归。
- 生产构建通过。全仓类型检查仍有 **59 个既有错误**,与上一轮错误列表一致;不宣称全仓类型检查通过。
## 证据与边界
本轮截图与日志存放在 `frontend-web/.runtime/daily-usage-audit/`:`01-create-before.png`、`02-history-before.png`、`03-knowledge-search.png`、`04-official-desktop.png`、`05-official-project-after.png`(网络失败状态)、后续 after 截图,以及 tests/build/typecheck 日志。后端日志为 `.runtime/ji-acceptance/daily-regression.txt`。
上一轮真实文件入库、向量命中、方案生成与保存的验证详见 `ji-knowledge-projects-acceptance.md`。本轮不重复付费生成完整方案;没有进行生产全量语料质量评估、负载测试、断网故障注入或完整无障碍合规审计。已检查可见导航、表单名称、窄屏显示和主要失败恢复,不能据此承诺所有模块没有缺陷。代码未提交、推送或部署。
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
# ji 分支知识库与我的项目验收
日期:2026-09-14。基线:`ji` / `f62a512a`,已从 origin fast-forward 更新。
## 修复范围
1. 简洁模式进入我的项目保留功能导航,覆盖列表、策略工作台和问答项目;移动端有菜单展开入口。
2. 策略结果卡片的模型思考前置;检查意图、评判、方案、展开视图保持过程在正文前。
3. 普通问答改为真实项目分组:先填写项目名称创建项目,再在项目中创建多条问答。服务端持久归属与权限校验沿用 analysis-projects;不自动迁移或标记历史普通聊天。官方入口支持对应 groups 子路由。
4. 修复方案列表要求预先选中策略导致无法进入的问题;任务变化后已有方案仍可查看;请求序号避免旧请求失败覆盖成功结果。
5. 修复知识库管理目录缓存导致上游删除后仍显示的问题;保留检索端缓存。
6. 项目编辑保留知识库绑定,助手知识库补充普通用户空态。
## 自动化
- 后端 22 个相关测试文件:273 passed(知识库、Wiki、向量、编码器、项目归属、策略配置与持久化、边界等)。
- 前端策略与项目测试:31 passed。新增用例覆盖未选择策略、已有方案变更任务、未完成评判及全部策略失败。
- `tests/test_knowledge_live_embedding.py`:真实接口 1 passed;默认跳过,设置 `KNOWLEDGE_TEST_EMBEDDING_KEY` 后运行。默认服务 SiliconFlow、模型 BAAI/bge-m3;可用 `KNOWLEDGE_TEST_EMBEDDING_URL` / `KNOWLEDGE_TEST_EMBEDDING_MODEL` 更换。
- `pnpm build`:通过。
- `pnpm typecheck`:未完全通过,59 个错误位于此次未改动文件(nextra 缺失、Markdown 插件类型、旧 JSX 类型及旧问答页等);修改文件无类型错误。不能将生产构建通过等同于全仓类型检查通过。
## 真实接口与浏览器
测试使用 `.runtime/ji-acceptance` 独立数据目录,保留测试数据便于复查,未操作业务数据库已有项目。
- BAAI/bge-m3:中英文 3 条输入,均返回 1024 维有效向量。
- 实际检索服务:相关正文排名、指定库范围、草稿排除、概览查询通过。
- 两个项目 A/B:A 创建两条对话,B 列表为零;跨项目读取 A 的对话返回 404。
- 浏览器:简洁模式完整菜单可见;新建具名普通问答项目;项目内真实发送并收到回答;第二条对话独立;回列表仍是一张项目卡,刷新后保留。
- 方案整理:真实模型返回 1539 字符正文,含 agent_done / all_done,流正常结束。
- 方案入口:完成评判但尚未勾选策略的测试项目出现在方案列表。浏览器进入后勾选策略、生成 2755 字符正文、保存成功;服务端校验 synthesisStatus=done 且 solutionSavedAt 非空,刷新后正文与导出按钮恢复。
- 官方入口:`/official/workspace/projects/groups/new` 正常展示具名问答项目表单,官方侧栏保留。
- 助手知识库:创建、重命名、列表、拒绝 .py 上传通过;上传测试文本任务 completed;生成 Wiki 页面,向量检索命中 1 条,详情 HTTP 200。
## 限制
真实模型测试使用最小合成读书活动/设备资料,未对生产全量知识语料进行质量评估。API 密钥仅用于测试进程,不提交配置。仓库原有未跟踪 docx 与 packages1.zip 保持不变。未提交、推送代码,也未执行离线发布。
@@ -0,0 +1,304 @@
# OpenVibeCoding 内网可视化应用生成平台:分步开发方案
> 文档状态:待实施
>
> 目标环境:现有 Ubuntu 22.04 Docker 服务器;对外可用端口限定为 `8020-8030`。
>
> 本文基于 2026-08-31 的只读巡检编写。未在目标服务器上安装、停止或修改任何服务。
## 1. 目标与范围
将 OpenVibeCoding 改造成一个使用公司内网模型、在公司服务器 Docker 沙箱中生成并运行可视化应用的工作台。用户通过对话生成项目,查看并修改文件,在浏览器中预览运行结果。
第一期只服务以下项目类型:
- 数据大屏、数据看板、海报和展示型页面;
- React + Vite + TypeScript 前端;
- ECharts 图表、流程图;
- 可选的轻量 Python FastAPI 接口;
- 项目文件浏览、编辑、运行日志和实时预览。
第一期明确不做:
- 腾讯云 CloudBase、SCF、TCR、CodeBuddy、云端一键部署;
- 任意语言、任意 npm/PyPI 包的无限制安装;
- 用户自定义 Dockerfile、Docker Socket 挂载、宿主机命令执行;
- 直接将沙箱暴露为独立公网端口;
- 对不可信代码提供“绝对安全”的隔离承诺。
## 2. 已确认的服务器基线
目标服务器当前具备:
| 项目 | 巡检结果 | 判断 |
|---|---:|---|
| 操作系统 | Ubuntu 22.04.5 LTS | 支持 Docker 方案 |
| CPU | 32 vCPU | 足够第一期 |
| 内存 | 125 GiB;巡检时可用约 106 GiB | 足够第一期 |
| 根磁盘 | 2 TB;巡检时可用约 1.6 TB | 足够 Harbor、镜像与工作区 |
| Docker | 29.1.3,Docker Compose 2.40.3 | 已满足 |
| 负载 | 约 0.5 | 当前有余量 |
| `8020-8030` | 巡检时无监听、无 Docker 端口映射 | 可规划使用 |
该服务器已承载 DeerFlow、Coze、LiteLLM、数据库和其他容器;`80`、`8000`、`8005`、`8006`、`3306`、`5432` 等端口已经被使用。因此,本项目不能占用现有端口、网络、数据库或容器名称。
该服务器有公网 IP,且已有多项服务绑定在 `0.0.0.0`。本方案将它视作“公网可达的共享主机”处理;云安全组和宿主机防火墙必须额外核验,不能仅凭端口监听结果假设安全。
## 3. 总体架构
```mermaid
flowchart LR
U[用户浏览器] -->|:8020| G[App Builder Gateway]
U -->|:8022 /preview/<sandboxId>/| P[Preview Router]
G --> O[OpenVibe Web / Agent Server]
O --> M[现有内网模型网关]
O --> DB[(独立 PostgreSQL)]
O --> R[(独立 Redis)]
O --> SM[Local Sandbox Manager]
SM --> D[Docker Engine]
D --> S1[visual-ui Sandbox]
D --> S2[visual-fullstack Sandbox]
P --> S1
P --> S2
D --> H[Harbor :8023]
S1 --> N[内网 pnpm/npm 源或预置离线依赖]
S2 --> N
```
设计原则:
1. 保留 OpenVibe 的对话、任务、文件树、工具卡片和 OpenCode ACP 代码代理体验。
2. 模型请求仅由 OpenVibe 服务端发往既有内网模型网关;API Key 不进入沙箱。
3. 每个项目运行于独立 Docker 容器和独立工作区;沙箱只运行项目代码,不承担平台控制逻辑。
4. 浏览器预览只经过统一预览路由,不为每个项目映射新的公网端口。
5. 先用固定模板和固定依赖清单保证稳定,后续再按白名单增加依赖。
## 4. 端口规划
端口虽然可用,但应尽量少暴露。除 8020、8022 和按需开放的 8023 外,其余服务只加入 Docker 内部网络。
| 端口 | 服务 | 绑定范围 | 用途 |
|---:|---|---|---|
| 8020 | `appbuilder-gateway` | 公网访问面或 VPN 白名单 | 控制台页面、`/api`、SSE/WebSocket |
| 8021 | 预留 | 仅 `127.0.0.1` | 平台调试;第一期不对外开放 |
| 8022 | `preview-router` | 公网访问面或 VPN 白名单 | 统一预览入口:`/preview/<sandboxId>/` |
| 8023 | Harbor | 仅沙箱节点、构建节点和管理员网段 | 私有镜像仓库 HTTPS Registry |
| 8024 | 预留 | 不对外开放 | 后续 npm 私服或运维服务 |
| 8025-8030 | 预留 | 不对外开放 | 扩展、迁移或故障切换 |
### 4.1 预览路由规则
暂时没有可用泛域名时,使用路径型预览:
```text
http(s)://<服务器地址>:8022/preview/<sandboxId>/
```
项目模板的 Vite `base` 和 HMR 路径必须由启动脚本注入为该前缀,确保图片、JS/CSS 资源及热更新不会错误请求到根路径。后续若获得 `*.preview.company.local` 内网泛域名,可切换为子域名预览,用户体验更好。
## 5. 镜像、模板与离线依赖策略
### 5.1 标准镜像
第一期维护两种版本化镜像,不允许用户自行构建 Dockerfile:
| 镜像 | 用途 | 预置内容 |
|---|---|---|
| `appbuilder/visual-ui:<version>` | 大屏、海报、纯前端 | Node.js 20、pnpm、React、Vite、TypeScript、ECharts、流程图库、统一 UI 库、Tailwind、图标与中文字体 |
| `appbuilder/visual-fullstack:<version>` | 前端加接口 | 上述前端依赖 + Python 3.12、FastAPI、Uvicorn、Pydantic |
流程图库第一期统一选择一种(建议 React Flow),避免同时生成多种流程图语法和样式。地图、背景图、字体等资源也应作为受版本控制的本地资产打包,不能依赖 Google Fonts 或公网 CDN。
### 5.2 项目模板
每次创建项目时从镜像中的模板初始化到 `/workspace`:
```text
templates/
visual-screen/ # React + ECharts + React Flow + Mock 数据
visual-screen-api/ # visual-screen + FastAPI + /api 反向代理
poster-page/ # 海报、营销展示、静态动效
```
`visual-screen-api` 约定:前端只请求相对路径 `/api/*`;预览网关将其转发到同一沙箱的 FastAPI `8000` 端口。没有后端时保留 Mock 数据模块,生成的页面仍可运行。
### 5.3 依赖预置方式
不能仅把安装命令写进 Dockerfile 后在用户创建项目时再联网执行。正确做法是:
1. 在受控构建环境中锁定 `package.json`、`pnpm-lock.yaml`、`requirements.lock`。
2. 构建镜像时执行 `pnpm fetch`,在镜像保存只读 pnpm store;Python 包保存到 `/opt/wheelhouse`。
3. 沙箱初始化使用 `pnpm install --offline --frozen-lockfile` 和 `pip install --no-index --find-links=/opt/wheelhouse`。
4. 第一期开启“固定依赖白名单”:AI 只能使用镜像已安装的依赖;新依赖先由管理员审核、加入锁文件和下一版基础镜像。
5. 第二期部署 Verdaccio/Nexus 等内部制品源,作为受控补充而非允许访问公网 npm/PyPI。
## 6. OpenVibe 改造边界
### 6.1 保留
- 前端交互:对话、任务状态、文件浏览与修改、预览、日志;
- OpenCode ACP 代码代理;
- 项目与会话领域模型;
- 代码代理的流式事件协议。
### 6.2 替换或关闭
| OpenVibe 当前能力 | 第一期开源/内网实现 |
|---|---|
| CodeBuddy | 只启用 OpenCode,配置内网 OpenAI 兼容模型网关 |
| CloudBase、SCF 沙箱 | 新增 `LocalDockerSandboxManager` |
| TCR | Harbor |
| CloudBase 环境、用户环境池 | Docker 容器、工作区卷、沙箱记录 |
| CloudBase 消息与事件持久化 | 独立 PostgreSQL;Redis 用于临时队列与状态 |
| CloudBase 存储、函数、MCP、资源管理后台 | 第一期开关关闭或移除入口 |
| CloudBase 项目模板和系统提示词 | 替换为大屏/海报/FastAPI 模板与受控依赖提示词 |
重点改造点是将 OpenVibe 的 `scf-sandbox-manager` 和 CloudBase 生命周期调用替换为本地 Docker 生命周期。为降低前端和 OpenCode 工具改动范围,新管理器应适配现有的文件、命令、日志、健康检查与工作区信息契约,而不是改写所有 Agent 工具。
## 7. 沙箱安全基线
每个沙箱容器必须满足:
- 非 root 用户运行;禁止 `privileged`,禁止 Docker Socket,禁止宿主机目录挂载;
- `--cap-drop=ALL`、`no-new-privileges`、`pids-limit`;
- 首期默认限制:`1 vCPU`、`3 GB 内存`、`10 GB 工作区`、60 分钟空闲回收;
- 使用独立 Docker network;默认无公网出口,只允许访问预置依赖、必要的内网 DNS 和平台回调;
- 数据库、Redis、Harbor 管理接口、宿主机管理端口不在沙箱网络可访问范围;
- 运行命令、容器生命周期、文件变更和预览访问写入审计日志;
- 平台服务由受限服务账号调用 Docker API;用户代码永远不直接获得 Docker 权限。
第一期为“内部可信用户的容器隔离”。若后续允许大量非可信代码或文件上传,应迁移为 Kubernetes 节点,并评估 gVisor/Kata 等更强运行时隔离。
## 8. 分步实施计划
### 阶段 0:部署前隔离与基线确认
**工作项**
1. 为本项目建立独立目录、Docker Compose Project、卷和网络,命名统一为 `appbuilder-*`。
2. 确认云安全组、iptables/nftables 规则:仅允许管理员 SSH;8020、8022、8023 仅向 VPN 或指定办公出口开放。
3. 不复用当前服务器上已有的 MySQL、PostgreSQL、Redis、Nginx 配置;建立独立实例或独立命名空间。
4. 创建内部 CA 证书或确定可信 HTTPS 证书方案;Docker 构建/运行节点信任 Harbor 证书。
5. 轮换目标服务器 root 密码,改用 SSH 密钥和受限运维账号;关闭 root 密码远程登录。
**验收**
- `8020-8030` 无端口冲突;
- 新容器、网络和数据卷均不影响既有 DeerFlow 等服务;
- 业务数据库和沙箱端口无法从非授权公网地址访问。
### 阶段 1:内网基础设施与镜像供应链
**工作项**
1. 在独立 Compose 项目中部署 Harbor,主入口为 `8023`,镜像数据使用独立持久化目录。
2. 构建并推送 `visual-ui`、`visual-fullstack` 两种基础镜像;记录镜像版本、SBOM 和依赖锁文件。
3. 完成三个模板及离线依赖初始化脚本。
4. 先不启动漏洞扫描;严格断网环境下后续通过离线包维护漏洞库。
5. 预留内部 npm/PyPI 源接入方式;第一期仅使用预置依赖。
**验收**
- Docker daemon 能从 Harbor 拉取指定版本镜像;
- 在禁止公网访问的测试网络中,三个模板均能启动并构建;
- 一个 ECharts 页面、一个流程图页面和一个 FastAPI `/api/health` 均可运行。
### 阶段 2:OpenVibe 去 CloudBase 化与内网模型接入
**工作项**
1. Fork 固定版本的 OpenVibeCoding,建立 `local-platform` 改造分支,记录上游 commit 与许可证。
2. 只保留 OpenCode Agent;将 provider 指向现有内网模型网关,模型凭证只保存在服务端环境变量或密钥服务。
3. 将基础实体、任务、消息、流式事件的持久化迁移为独立 PostgreSQL;不再调用 CloudBase 集合。
4. 关闭 CloudBase 环境、函数、存储、数据库、资源仪表盘和相关 MCP 入口。
5. 将系统提示词和项目创建默认项改为“可视化页面 + 受控模板/依赖”。
**验收**
- 不设置任何腾讯云、CloudBase、CodeBuddy、TCR 环境变量时,平台可启动;
- 用户发起“生成 ECharts 大屏”后,OpenCode 能调用内网模型并生成项目文件;
- 服务端日志和沙箱环境中均没有模型 API Key。
### 阶段 3:本地沙箱管理器与预览路由
**工作项**
1. 实现 `LocalDockerSandboxManager`:创建、启动、停止、超时回收、查询状态和删除容器。
2. 每个沙箱分配工作区卷、随机内部容器地址、模板类型和资源限制;在数据库记录 `sandbox_id`、项目、用户、镜像版本、过期时间和状态。
3. 实现或适配沙箱内 runner:文件读写、受限命令执行、日志流、健康检查、前端端口和 FastAPI 端口发现。
4. 实现 `preview-router`:由平台根据 `sandboxId` 维护路由,将 `/preview/<sandboxId>/` 代理到对应内部容器;支持 WebSocket/HMR。
5. 增加容器异常退出、端口未就绪、构建失败、超时与手动重启的可见状态。
**验收**
- 两个用户创建的项目存在于不同容器和不同工作区;
- 修改 ECharts 配置文件后,预览地址显示修改结果;
- FastAPI 模板的 `/api/health` 可通过前端相对路径访问;
- 沙箱不能访问 Docker Socket、宿主机数据库和非白名单网络;
- 空闲超时后容器被回收,项目文件仍可恢复。
### 阶段 4:产品能力收口
**工作项**
1. 在文件面板支持安全的文件查看、编辑、保存、目录树刷新与下载;限制文件大小和可编辑扩展名。
2. 在对话中增加模板选择和能力提示:大屏、流程图、海报、可选 FastAPI。
3. 为 Agent 增加依赖白名单、图表主题、中文字体、Mock 数据、接口契约等明确提示词。
4. 增加“运行/停止/重启/删除沙箱”和日志面板;仅项目所有者或管理员有相应权限。
5. 增加项目快照、模板版本记录和基础审计日志。
**验收**
- 从一句自然语言需求到可预览项目的完整链路可完成;
- 用户可查看并手动修改文件,刷新后改动保留;
- 页面覆盖 ECharts、流程图、响应式大屏和可选 FastAPI 接口;
- 非拥有者不能读取、修改或预览另一用户的项目。
### 阶段 5:上线前安全与运行验收
**工作项**
1. 压测 6 个并发沙箱,并记录 CPU、内存、磁盘、容器启动时间、首屏预览时间和模型等待时间。
2. 验证镜像保留策略、工作区配额、容器回收、数据库备份和 Harbor 备份恢复。
3. 执行越权、路径穿越、命令注入、网络探测、资源耗尽和模型密钥泄露测试。
4. 建立日常运维操作:新增基础依赖、构建镜像、发布模板、回滚镜像、清理工作区和审计查询。
**验收**
- 并发运行时既有 DeerFlow 等服务不受明显影响;
- 任一沙箱异常退出不会影响其他项目或平台控制服务;
- 备份可恢复项目元数据、工作区和 Harbor 镜像;
- 仅开放计划中的入口端口,内部组件无不必要公网监听。
## 9. 首期资源与并发建议
由于该主机已有多项业务,首期不应按理论最大值分配:
| 组件 | 首期限制 |
|---|---|
| Harbor | 8 vCPU、16 GB 内存、500 GB 数据盘配额 |
| OpenVibe 控制服务 | 4 vCPU、8-16 GB 内存 |
| 单个 UI 沙箱 | 1 vCPU、3 GB 内存、10 GB 工作区 |
| 单个 Fullstack 沙箱 | 1.5 vCPU、4 GB 内存、12 GB 工作区 |
| 沙箱并发 | 先限制为 6;稳定后再逐步上调 |
当并发超过 10 个,或要面向更广泛用户开放时,应优先增加独立沙箱节点,而不是继续在本共享主机上加容器。
## 10. 实施顺序与交付物
建议按以下提交/交付顺序推进,每一步都可独立验收和回退:
1. `docs: confirm appbuilder network, ports and security baseline`
2. `infra: add Harbor and versioned visual sandbox images`
3. `infra: add offline templates and dependency locks`
4. `feat: replace OpenVibe CloudBase persistence and model provider`
5. `feat: add local Docker sandbox manager`
6. `feat: add sandbox runner and path-based preview router`
7. `feat: add visual-screen and FastAPI project workflows`
8. `test: add sandbox isolation, preview and recovery coverage`
9. `ops: add backup, cleanup, monitoring and rollout runbook`
达到阶段 3 即可交付“内网模型驱动、生成并预览大屏/海报页面”的 PoC;达到阶段 5 后再作为受控的内部多人平台发布。
@@ -0,0 +1,139 @@
# Iframe Chat Page Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add a standalone `/page/workspace/chats_iframe/*` chat page that reuses the existing thread system and history, while showing only `你好` and no input box before the first user message.
**Architecture:** Keep the existing workspace shell and chat runtime intact, then add a new route pair and a copied page component dedicated to the iframe path. The new page keeps the original chat behavior once a thread already has messages, but it owns its empty-state rendering and URL transition to `/page/workspace/chats_iframe/:thread_id`.
**Tech Stack:** React, TypeScript, React Router, Next navigation shim, existing LangGraph thread hooks
---
### Task 1: Add the iframe chat routes
**Files:**
- Modify: `frontend-web/src/pages/WorkspaceRoutes.tsx`
- [ ] **Step 1: Add `chats_iframe/new` and `chats_iframe/:thread_id` routes that render the new page inside the existing workspace layout and chat runtime**
```tsx
<Route
path="chats_iframe/new"
element={
<WorkspaceLayout {...layoutProps}>
<ChatRuntime>
<IframeChatPage />
</ChatRuntime>
</WorkspaceLayout>
}
/>
<Route
path="chats_iframe/:thread_id"
element={
<WorkspaceLayout {...layoutProps}>
<ChatRuntime>
<IframeChatPage />
</ChatRuntime>
</WorkspaceLayout>
}
/>
```
- [ ] **Step 2: Ensure the new route imports compile cleanly**
Run: `rg -n "IframeChatPage|chats_iframe" frontend-web/src/pages/WorkspaceRoutes.tsx`
Expected: `WorkspaceRoutes.tsx` contains one import for `IframeChatPage` and both `chats_iframe` route entries.
### Task 2: Add a standalone iframe chat page
**Files:**
- Create: `frontend-web/src/pages/IframeChatPage.tsx`
- Reference: `frontend-web/src/pages/ChatPage.tsx`
- [ ] **Step 1: Copy the current `ChatPage` implementation into `IframeChatPage` and preserve the existing chat runtime integration**
```tsx
export default function IframeChatPage() {
const routeBase = useRouteBase();
const router = useRouter();
const [showFollowups, setShowFollowups] = useState(false);
const [hasStartedConversation, setHasStartedConversation] = useState(false);
const { threadId, setThreadId, isNewThread, setIsNewThread, isMock } =
useThreadChat();
// keep the rest of the existing chat hooks and handlers aligned with ChatPage
}
```
- [ ] **Step 2: Change the thread creation URL replacement to stay on the iframe route family**
```tsx
onStart: (createdThreadId) => {
setThreadId(createdThreadId);
setIsNewThread(false);
history.replaceState(
null,
"",
`${window.location.pathname}${window.location.search}#${routeBase}/chats_iframe/${createdThreadId}`,
);
},
```
- [ ] **Step 3: Replace the default landing state with a simple `你好` view and do not render the input box while the iframe page is still a brand-new untouched chat**
```tsx
{isLandingState && mounted ? (
<div className="flex min-h-[240px] items-center justify-center">
<div className="text-2xl font-medium">你好</div>
</div>
) : null}
{!isLandingState &&
(mounted ? (
<div className="w-full -translate-y-4">
<InputBox
className="w-full"
isNewThread={false}
threadId={threadId}
autoFocus={false}
status={thread.error ? "error" : thread.isLoading ? "streaming" : "ready"}
context={settings.context}
disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" || isUploading}
onContextChange={(context) => setSettings("context", context)}
promptPrefix={promptPrefixProp}
onFollowupsVisibilityChange={setShowFollowups}
onSubmit={handleSubmit}
onStop={handleStop}
/>
</div>
) : (
<div aria-hidden="true" className="bg-background/5 h-32 w-full -translate-y-4 rounded-3xl border" />
))}
```
- [ ] **Step 4: Keep message rendering, thread title, export, token usage, todos, artifact triggers, and all post-first-message behavior identical to the original page**
Run: `rg -n "MessageList|ThreadTitle|ArtifactTrigger|TokenUsageIndicator|TodoList" frontend-web/src/pages/IframeChatPage.tsx`
Expected: The new page still renders the same core chat primitives used by `ChatPage`.
### Task 3: Verify the new page compiles
**Files:**
- Test: `frontend-web/src/pages/IframeChatPage.tsx`
- Test: `frontend-web/src/pages/WorkspaceRoutes.tsx`
- [ ] **Step 1: Run the frontend build**
Run: `cmd /c npm run build`
Expected: Build succeeds without TypeScript or bundling errors related to `IframeChatPage` or `chats_iframe`.
- [ ] **Step 2: Spot-check the changed routes in the built source**
Run: `rg -n "chats_iframe" frontend-web/src/pages`
Expected: Matches appear in `WorkspaceRoutes.tsx` and `IframeChatPage.tsx`.
- [ ] **Step 3: Commit after verification**
```bash
git add docs/superpowers/plans/2026-06-01-iframe-chat-page.md frontend-web/src/pages/WorkspaceRoutes.tsx frontend-web/src/pages/IframeChatPage.tsx
git commit -m "feat: add iframe chat page routes"
```
@@ -0,0 +1,105 @@
# 本地问答、资料库与技能并发验收
测试日期:2026-09-28 至 2026-09-29 凌晨。环境:Windows、约 8GB 物理内存、Python 3.12、Node 22、Gateway 单进程、SQLite、默认 MiniMax-M2.5。前端 Vite 5174,Gateway 8001。模型并发限流与 Redis 分布式门控未启用。
本次保留并验收了工作区原有的资料库索引、问答收尾、沙箱超时和流式恢复修改,另外修复了压测复现的技能刷新重复校验,以及真实地图问答暴露的内部待办提醒显示问题。测试结果不能等同于 Linux 多进程生产环境容量。
## 版本范围
开始测试时本地为 `3a07c476`,没有 `cognitive-situation-map`。随后拉取远程,发现 `origin/master` 已前进至 `3107f2cc`,包含该技能的初始化及 v2.6.0 精简运行时。保留本地修改后合入远程,合并提交为 `c9effe83`;最终绘图与多用户测试以合入后的代码为准。
旧本地版本里 `page-report-generation` 的地图仅支持中、美、日、台,因此其“不支持菲律宾”的反馈不能用于评价最新的 `cognitive-situation-map`。
## 真实问答
使用独立普通测试账户,阶梯间顺序运行,逐条检查预期测试关键词与结果、SSE `end`、持久化 `success`,结束后删除本轮生成的测试线程。1/3/5/10 路检查正文包含“测试”和数字 4;20 路增强为检查“测试正常”及明确的“2加2等于4”。这属于简单问答验收,不是复杂内容质量评测。
| 同时问答用户数 | 成功 | 首段答案中位耗时 | 流结束中位耗时 | 流结束最慢 |
|---|---:|---:|---:|---:|
| 1 | 1/1 | 5.792s | 6.439s | 6.439s |
| 3 | 3/3 | 2.214s | 3.245s | 3.287s |
| 5 | 5/5 | 2.885s | 3.702s | 4.373s |
| 10 | 10/10 | 2.920s | 4.796s | 5.416s |
| 20 | 20/20 | 4.364s | 10.622s | 11.135s |
累计 39/39 通过。20 用户整批耗时 11.829s,同期 health 12/12 成功、中位 13ms、最大 371ms。这里是一次阶梯短时突发,并未证明百用户持续长任务容量。
取消接口返回 204,58ms 后状态为 `interrupted`,测试线程删除返回 200。同期健康探测 20 次均成功,中位 9ms,最大 3.044s;说明仍存在数秒调度尖峰,不能仅凭平均值宣布无阻塞。
早期多个磁盘基准同时运行时,单路首段答案为 33.853s,日志显示同步 agent 构建 28.344s,health 也有 5s 超时。这批明确有本机资源争用,不纳入稳定容量结论。开发脚本启动的服务进程还曾消失,没有拿到退出或 reload 日志,原因未确认;期间的连接失败剔除。后续使用无热重载的固定进程复测。
## 资料库和知识库
- 资料库/知识库相关回归 186 项通过;资料库新存储 Memory/SQLite 专项另有 8 项通过,覆盖用户隔离、分页、原子换代、并发租约和旧任务围栏。
- 真实测试账户看到 2 个共享知识库;选中的库包含 668 份文档、168 个 Wiki 页面。首次 hybrid 查询 3.58s,返回 5 条。
- 排除合成磁盘负载后,空资料库、知识库目录和 hybrid 查询分别测试 1/4/8 并发,每档 8 次,总计 72/72 HTTP 200,零异常。
| 接口 | 8 并发中位耗时 | 8 并发最大耗时 |
|---|---:|---:|
| 资料库列表(空测试账户) | 165ms | 224ms |
| 知识库目录 | 517ms | 557ms |
| hybrid 检索(相同问题、5条结果) | 426ms | 441ms |
这组重复使用同账号和查询,包含热缓存效果;空账户列表不代表有大量文件的资料库。独立测试 SQLite 另生成了 101 个合成用户、10 万条资料元数据,480 次查询全部成功;其中单用户 5 万条资料关键词查询 P95 为 1.08s、首页 P95 为 130ms,但此轮同时有其他 IO 测试,只作为规模观察值。
资料库索引按 5 分钟过期刷新;进程异常退出时正在同步的租约最多等待 30 分钟恢复。大库关键词查询仍使用多字段包含匹配,不能据当前测试证明生产规模检索始终快速。
## 大技能与并发刷新
文件体积大和小文件数量多分别测试,使用隔离临时目录,不改真实技能内容。
| 场景 | 结果 |
|---|---|
| 真实技能副本,269 文件 / 2.75MiB,稳定缓存 64 并发 | 全成功,约 1.05s;早期混合负载观察值 |
| 同副本改 1 个资产,32 并发,修复前混合负载 | 27 成功、5 个 30s 锁等待超时,复现问题 |
| 独占配对:同副本改 1 个资产,32 并发,旧逻辑 | 32/32 成功,P95 13.700s,最大 14.842s |
| 独占配对:同场景,新逻辑 | 32/32 成功,P95 / 最大 3.963s,P95 降低约 71% |
| 128MiB 资产、34 文件,新逻辑 | 冷初始化 5.54s;变更后 32 并发 P95 0.584s,全成功 |
| 约 160 技能、5120 个小文件(修复前规模观察) | 冷加载执行者约 107s,31/32 等待者超时;热校验约 18s |
修复让同一进程内、相同权限配置的一批重叠请求共享一次刷新及最终校验。等待者仍检查当前缓存身份、权限哈希和能力标记;失败或技能下线时不返回旧视图。新增 8 项回归连同原有 62 项,共 70 项通过。
**剩余风险:** 数千个小文件的单次 Windows 元数据扫描仍昂贵,本次修复没有消除这项成本,也未证明跨进程刷新能合并。不能把 32/64 个技能调用线程等同于 32/64 个真实模型用户。
实际调用 `gongwen-assistant` 读取技能并输出短通知,10.672s 内正常结束,无工具卡住。但答案把要求的 10月8日改成10月15日:通信/技能读取通过,内容日期遵循失败,不能记为整体语义验收通过。
## 绘图与界面
普通问答已实际生成菲律宾地图底图及马尼拉、吕宋北部、巴拉望、棉兰老四个点位,点位弹窗可打开。使用明确标注的虚构数据,未进行时事真实性评估。初次模型额外要求确认消息内地图,回复确认后完成,属于可见的额外交互成本。
这次真实对话发现 `todo_completion_reminder` 被当作用户问题展示。修复后,后端待办提醒带 `hide_from_ui`,前端也按两个历史内部名字过滤聊天和问题导航;真实用户引用 `<system_reminder>` 的文本仍保留。后端 3 项、前端新及关联分组 12 项通过。
最新 `cognitive-situation-map v2.6.0` 已经通过真实问答完整调用:读取技能和菲律宾参考 JSON、写入场景、调用技能自带 `node render.mjs`、检查文件、`present_files` 交付,42.481s 完成,SSE 正常结束并保存 `success`。产物标题为“菲律宾冲突认知态势图(功能验收示意)”,包含 4 个事件、4 个标注、3 个行为体和 2 条连线,明确标注所有事件与等级均为测试数据。输出 `status=ok`、无恢复和警告。模型曾发起两次过宽的目录 glob,被技能访问隔离拒绝后自行改用指定技能目录完成,没有循环卡住。
同一最新技能的直接渲染为 624ms;8 个并发独立渲染进程全部成功,范围 650–949ms。围栏/截断/缺失字段/约 600KiB 场景输入的恢复、非空目录拒绝覆盖、脚本结束标签转义均完成专项检查。真实 Windows LocalSandbox 虚拟路径经 PowerShell 调用 Node 成功(含冷 shell 7.85s)。CSS、JS、菲律宾底图和旗帜资源均返回 200;2.93MB 底图一次请求耗时 208ms。8 个渲染进程不等于 8 个同时生成长内容的模型用户。
**最新 HTML 的视觉验收未通过:** 测试账户能在会话中看到生成文件卡片,文件接口返回 200,源码模式能显示 HTML、正确资源地址和页面结构,但 Codex 内嵌浏览器的预览面板空白;DOM 中 iframe 的 `src` 为 `blob:http://127.0.0.1:5174/...`,可访问树仍为 `about:blank`。普通地图组件的可见性不能替代这个 HTML 的验收,渲染器返回成功也不能证明最终视觉正确。已保留空白预览截图,未将此项计为通过。
进一步在内存中执行真实 `prepareGeneratedHtml`:11,269 字节输入变为 14,597 字节,原有 3 个脚本逐字保留、DOM id 与外链 URL 均不变,新增兼容脚本语法有效。暂未发现生成器或预处理破坏 HTML 的证据;故障停在预览加载/Blob 导航阶段,具体原因未确认,不将其归为已知浏览器限制,也不宣称已修复。
界面还复现了 TDesign 新手引导闲置时的 `reading 'element'` 异常:`current=-1` 时其 resize 监听仍读取不存在的步骤。简洁模式与智能体两处包装组件已改为只有有效步骤才挂载 Guide。浏览器复测了文件面板开关、侧栏切换、手动启动、下一步、跳过,未再出现新的同类异常;完成/跳过的持久化语义保持不变。
## 合并后回归
- 完整 harness:274/274 通过,53.07s;包含前述技能及 Todo 子集,不重复累加。
- 模型并发配置专项:10 项通过;种子技能资源:4 项通过。
- 前端流式恢复专项:9 组共 44 项通过;待办可见性及相关消息分组:12 项通过。
- 全量前端构建和类型检查最初并行运行时,系统空闲内存降到约 17MB,因此主动停止该轮类型检查,改为串行执行;该轮中断不作为代码失败。
- `pnpm build` 通过(10m25s,包含前期资源争用,有大 chunk 警告)。其后新增的两个 Guide 挂载条件已通过单独语法检查和真实浏览器回归;另补齐问题导航抽取后的类型导入,不改变生成代码行为。
- 最终 `pnpm typecheck` 仍未通过,共 73 项原有诊断;与测试前本地 `hang-typecheck.log` 的 75 项逐条比较,减少了消息分组测试的 2 项,没有新增诊断。本轮发现的 `QuestionItem` 类型导入遗漏已经修正,复跑后消失。剩余问题包括 `nextra` 依赖、旧 JSX 类型和既有组件/测试类型,未扩大范围处理,不能标记全量类型检查通过。
## 本地证据和复测入口
详细证据仅保留在 `.runtime/test-results/20260928-local-qa/`,不提交模型凭证、问答日志、测试数据库、构建 ZIP 或技能临时大目录:
- `qa-concurrency-results.json`:逐轮时间、结束事件、答案检查和清理结果。
- `qa-concurrency-20-results.json`、`harness-full.xml`:20 个独立用户问答和完整 harness 回归。
- `knowledge-stable-recheck.json`、`knowledge-library-report.md`:知识库与资料库稳定复测及限制。
- `skills-benchmark-paired.json`、`skills-findings.md`:同机旧/新刷新配对;“旧逻辑”在隔离进程禁用新合并函数回放,不改服务源码。
- `philippines-html.json`、`large-skill.json`:旧页面技能能力缺口与公文技能真实调用。
- `philippines-map-ui.png`:普通地图真实浏览器渲染。
- `cognitive-philippines.json`、`cognitive-skill-probe.json`:最新技能真实完整问答及渲染器专项。
- `cognitive-preview-ui.png`:最新 HTML 在本轮内嵌浏览器出现空白的实际截图。
- `frontend-build.log`、`frontend-typecheck-final.log`:全量构建与最终类型检查。
提交的回归入口包括 `packages/harness/tests/test_skill_view_refresh_coalescing.py`、`test_skill_view_waits.py`、`test_sandbox_command_liveness.py`、`test_run_completion_timeout.py`、`test_todo_reminder_visibility.py`,以及前端 `control-timeout`、`stream-terminal-recovery` 和 `todo-reminder-visibility` 测试。
@@ -0,0 +1,539 @@
# Thread 创建慢与回答结束后 History 等待:优化方案
日期:2026-10-22
配套文档:[完整排查手册](./线程创建与History等待慢-排查手册.md)
## 1. 优化目标与结论
目标:
- 降低 `POST /api/threads` 的 `checkpoint_create` 延迟;
- 降低 SSE 结束后 `/history` 的延迟;
- 避免慢 history 长时间占用全局 saver 锁并阻塞其他 thread;
- 处理 RunManager 内存 registry 持续增长;
- 保留对话 checkpoint 和历史记录,不通过直接删数据解决问题。
建议分四层实施:
| 优先级 | 动作 | 是否重启 | 风险 |
| --- | --- | --- | --- |
| P0 | 基于 EXPLAIN 在线补建 history 组合索引 | 否 | 低;增加少量写放大和磁盘占用 |
| P1 | History 明确主 namespace,缩短 alist 持锁范围并补计时 | 是 | 中;需要 history/subgraph 回归 |
| P1 | 修复 `RunManager.cleanup()` 未调用 | 是 | 低到中;需要重连/终态回归 |
| P2 | 让 PG saver 真正支持并发读写,或拆出独立 history reader | 是 | 中到高;需要并发与一致性测试 |
| P3 | 根据 dead tuples、I/O 和保留策略做维护/归档 | 视操作而定 | 中到高 |
最快的低风险止血方案是:先确认跨 namespace History 执行计划确实有 Sort,然后在线创建 `(thread_id, checkpoint_id DESC)` 索引。该索引只能缩短 SQL 和持锁时间,不能消除 saver 实例级串行。
## 2. P0:在线补建 History 组合索引
### 2.1 适用条件
同时满足以下条件时执行:
1. 线上 `/history` 当前需要跨 `checkpoint_ns` 返回最新 checkpoint;或者短期内不能发布代码来限定 namespace。
2. 慢 thread 的执行计划出现 per-thread Sort、扫描候选行较多或执行时间明显高于限定 `checkpoint_ns=''` 的版本。
3. 已确认目标表 schema;以下示例假设是 `public`。
如果每个 thread 只有极少 checkpoint,EXPLAIN 已是亚毫秒级且无明显扫描/Sort,建索引不会解决应用层 saver lock 排队,应直接转向 P1/P2。
### 2.2 建索引前检查
```sql
SELECT current_database(), current_schema(), current_schemas(true);
SELECT
schemaname,
tablename,
indexname,
indexdef
FROM pg_indexes
WHERE tablename = 'checkpoints'
ORDER BY indexname;
```
确认没有等价的 `(thread_id, checkpoint_id)` 索引。已有单列 `checkpoints_thread_id_idx(thread_id)` 不等价:它可以过滤 thread,但不能直接提供跨 namespace 的 `checkpoint_id` 顺序。
保存变更前基线:
```sql
EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
SELECT checkpoint_id, checkpoint_ns
FROM public.checkpoints
WHERE thread_id = '<THREAD_ID>'
ORDER BY checkpoint_id DESC
LIMIT 1;
```
### 2.3 在线创建
`CREATE INDEX CONCURRENTLY` 必须作为独立语句执行,不能放在显式事务块中。确认数据库客户端没有自动把整段脚本包在一个事务里。
```sql
SET lock_timeout = '5s';
SET statement_timeout = '0';
CREATE INDEX CONCURRENTLY IF NOT EXISTS
checkpoints_thread_checkpoint_id_desc_idx
ON public.checkpoints (thread_id, checkpoint_id DESC);
RESET lock_timeout;
RESET statement_timeout;
```
然后更新统计:
```sql
ANALYZE public.checkpoints;
```
不要把 `checkpoint` 或 `metadata` JSONB 加进 `INCLUDE`;它们较大,会显著扩大索引且不能解决此排序问题。
### 2.4 验证索引有效
```sql
SELECT
i.relname AS index_name,
x.indisvalid,
x.indisready,
pg_size_pretty(pg_relation_size(i.oid)) AS index_size,
pg_get_indexdef(i.oid) AS indexdef
FROM pg_class t
JOIN pg_index x ON x.indrelid = t.oid
JOIN pg_class i ON i.oid = x.indexrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE n.nspname = 'public'
AND t.relname = 'checkpoints'
AND i.relname = 'checkpoints_thread_checkpoint_id_desc_idx';
```
必须看到:
```text
indisvalid = true
indisready = true
```
重跑执行计划:
```sql
EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
SELECT checkpoint_id, checkpoint_ns
FROM public.checkpoints
WHERE thread_id = '<THREAD_ID>'
ORDER BY checkpoint_id DESC
LIMIT 1;
```
预期:
- 使用 `checkpoints_thread_checkpoint_id_desc_idx`;
- 不再出现额外 Sort;
- 扫描行数接近 1;
- buffer read 和实际执行时间明显下降。
### 2.5 上线观察
至少对比变更前后:
- `/history` p50/p95/p99;
- `POST /threads` 的 `checkpoint_create` p50/p95/p99;
- checkpoint INSERT/UPSERT 的平均与最大耗时;
- 新索引大小;
- `pg_stat_user_indexes.idx_scan`;
- checkpoint 写入吞吐与 WAL/磁盘增长。
索引使用统计:
```sql
SELECT
schemaname,
relname,
indexrelname,
idx_scan,
idx_tup_read,
idx_tup_fetch
FROM pg_stat_user_indexes
WHERE relname = 'checkpoints'
ORDER BY indexrelname;
```
### 2.6 回滚
如果索引导致不可接受的写放大、磁盘占用,或代码发布后已经不再需要跨 namespace 查询,可在线删除:
```sql
DROP INDEX CONCURRENTLY IF EXISTS
public.checkpoints_thread_checkpoint_id_desc_idx;
```
同样不要放在显式事务块内。
如果在线创建被中断,先查询 `indisvalid/indisready`。若留下 invalid 索引,低峰执行上面的 `DROP INDEX CONCURRENTLY` 后再重新创建,不要假设 `IF NOT EXISTS` 会修复 invalid 索引。
## 3. P1:让普通 History 明确查询主 namespace
### 3.1 为什么这是长期更优方案
普通聊天主图状态使用:
```text
checkpoint_ns = ''
```
`checkpoints` 现有主键:
```text
(thread_id, checkpoint_ns, checkpoint_id)
```
如果 History 的业务语义就是“普通聊天主图历史”,限定 `checkpoint_ns=''` 后,PostgreSQL 可以直接利用现有主键倒序取最新 checkpoint:
```sql
WHERE thread_id = $1
AND checkpoint_ns = ''
ORDER BY checkpoint_id DESC
LIMIT 1
```
这样不需要为同一访问模式长期维护额外索引,也避免误把 subgraph namespace 中较新的 checkpoint 当作主聊天最新状态。
### 3.2 建议代码改动
当前:
```python
config: dict[str, Any] = {"configurable": {"thread_id": thread_id}}
```
建议:
```python
config: dict[str, Any] = {
"configurable": {
"thread_id": thread_id,
"checkpoint_ns": "",
}
}
```
位置:
```text
offline-backend-20260512/backend/app/gateway/routers/threads.py:1886
```
### 3.3 发布前必须验证
- 普通 lead agent 首轮和多轮历史恢复;
- 自定义 agent 历史恢复;
- subagent/subgraph 事件不应错误覆盖主图历史;
- interrupt/HITL 恢复;
- checkpoint `before` 分页;
- 页面刷新、重新打开会话、断流重连;
- `fetchStateHistory: { limit: 1 }` 返回的 messages、title、thread_data 正确。
如果某些 API 消费者明确要求跨 namespace 历史,不要直接全局改变语义。可以为普通聊天与诊断/调试接口拆分不同路径。
### 3.4 与 P0 索引的关系
- 紧急止血可以先建 P0 索引,再发布 namespace 修复。
- namespace 修复稳定运行一段时间后,通过 `pg_stat_user_indexes` 确认 P0 索引已不再需要,再在线删除。
- 不要在代码上线同一时刻立刻删索引,保留可快速回退窗口。
## 4. P1:缩短 `/history` 持有 saver lock 的时间
### 4.1 当前问题
当前 route 在下面的 `async for` 内处理并序列化每个 checkpoint:
```python
async for checkpoint_tuple in checkpointer.alist(config, limit=body.limit):
# 读取 checkpoint
# 序列化 messages
# 构造 HistoryEntry
```
PostgreSQL saver 的 `alist()` 在 `_cursor()` context 内 fetchall 后逐条 yield。调用方在处理 yielded tuple 时,generator 尚未退出,因此 saver lock 可能覆盖业务层消息序列化时间。
### 4.2 低风险 quick win
先完整、快速消费 bounded 结果,让 generator 退出并释放 saver cursor/lock,再在锁外做响应序列化:
```python
checkpoint_tuples = [
item
async for item in checkpointer.alist(config, limit=body.limit)
]
for checkpoint_tuple in checkpoint_tuples:
# 原来的 HistoryEntry/messages 序列化逻辑
```
当前普通前端请求 `limit=1`,额外内存可以忽略。接口模型允许更大 limit 时,仍需保留现有上限并测试大 checkpoint payload。
该改动不会解除 saver 内部对 SQL/反序列化的串行,但能避免 route 的 Python 序列化继续占着 saver lock。
### 4.3 同时增加 History 分段计时
建议记录无内容的阶段指标:
```text
history_checkpoint_fetch_ms
history_serialize_ms
history_total_ms
thread_id(清洗后)
limit
checkpointer 类型
```
这样可以区分:
- saver lock + SQL + checkpoint load;
- Gateway 消息序列化;
- route 外的鉴权/代理等待。
不要在日志中记录消息正文、checkpoint JSON、数据库 URL 或 token。
## 5. P1:修复 RunManager 内存 registry 增长
### 5.1 当前问题
`RunManager.cleanup()` 已存在:
```text
packages/harness/deerflow/runtime/runs/manager.py:318-324
```
但 worker finally 当前只调:
```python
asyncio.create_task(bridge.cleanup(run_id, delay=60))
```
这只删除 stream bridge 中的流缓存,不删除 `RunManager._runs`。因此一个进程运行越久,`create_or_reject()` 在 manager lock 内扫描的对象越多。
### 5.2 建议改动
在 run 已完成、终态已持久化并发布 SSE end 后,调度 run registry 清理:
```python
asyncio.create_task(bridge.cleanup(run_id, delay=60))
asyncio.create_task(run_manager.cleanup(run_id, delay=300))
```
延迟值可以结合重连窗口调整,但不要无限保留。
### 5.3 必须验证
- 完成后 60 秒内 SSE join/reconnect 行为不变;
- 内存记录删除后,`GET run` 能从持久化 store fallback;
- 已完成 run 的 join 能返回干净终态,而不是 404;
- cancel/rollback 与正在运行的任务不会被提前删除;
- 管理员并发监控只展示真实 active run;
- 进程内 `_runs` 数量在稳定负载下有上限,不随总历史永久增长。
这项修复与数据库 `runs` 保留策略无关,不会删除持久化历史记录。
## 6. P2:解除单 saver 实例的全局串行
### 6.1 不能采用的“优化”
仅提高:
```text
DEER_FLOW_PG_POOL_MAX
```
不会解决问题,因为 saver 在 pool checkout 前先获取实例锁。连接池容量只有在多个可并发 saver 操作真正进入 checkout 时才有意义。
### 6.2 可评估的实现方向
按风险从低到高:
1. 为只读 History 建立独立 saver/reader 实例,与 graph 写入 saver 使用同一个连接池但不同实例锁。
2. 将 History 改为专用、只读、受支持的 PostgreSQL repository,明确复用 LangGraph schema 与序列化协议。
3. 升级到确认支持 pool 并发且兼容当前 schema/serializer 的 checkpointer 版本。
4. 维护受控 patch,使 pool 场景不再用一个实例锁包住所有连接,但必须保留单连接/pipeline 模式所需的互斥。
不要直接删除第三方 saver 的 lock。该 lock 还保护单连接、pipeline、cursor 和 setup 等行为,粗暴移除可能造成事务/cursor 并发错误。
### 6.3 并发回归要求
至少覆盖:
- 一个慢 history 与一个新 thread `aput` 并发;
- history 与 graph `aput_writes` 并发;
- 20 个不同 thread 同时读/写;
- 同一个 thread 的顺序和 checkpoint parent 关系;
- PostgreSQL 重启、断开连接、pool 替换坏连接;
- cancellation 不泄漏 cursor/connection/lock;
- setup migration 只安全执行一次或可幂等执行;
- 回答正文、最终 state 和历史 reopen 一致。
现有回归入口:
```text
offline-backend-20260512/backend/packages/harness/tests/test_thread_operation_timing.py
```
## 7. 前端结束态优化
### 7.1 当前行为
SDK 将结束后的 history refresh 放在 stream 的成功收尾内等待,因此 `/history` 延迟会直接延长 `thread.isLoading`。
30 秒 control/history timeout 只是防止永久挂死,不是性能优化。
### 7.2 可选方向
如果后端已经保证 SSE 最终 state 足够完整,可以评估:
- SSE `end` 到达后立即结束输入区 loading;
- `/history` 改为后台刷新;
- 刷新失败不丢弃已经流式到达的答案;
- 后台 history 成功后再校准 checkpoint id、title、thread_data 和 messages。
不要只把 `fetchStateHistory` 改成 `false`。当前 `onFinish(state, runMeta)` 依赖最终 state,直接关闭会改变回调语义,并可能影响标题、消息状态、listener 和断流恢复。
发布前至少验证:
- 最后一条 assistant message 不闪退、不重复;
- 首轮 thread id 和 URL 更新正确;
- interrupt/HITL 与 resume 正确;
- 页面刷新能从 checkpoint 恢复;
- SSE 丢失终态时仍能通过后台 history 校准;
- 用户不会在后端 run 尚未真正结束时误发下一轮。
因此前端解耦建议放在数据库索引、namespace 和 saver 持锁优化之后。
## 8. runs 表的针对性优化
### 8.1 先确认实际索引
当前 ORM 声明包括:
```text
runs_pkey(run_id)
ix_runs_thread_status(thread_id, status)
ix_runs_created_user_status(created_at, user_id, status)
ix_runs_user_created(user_id, created_at)
ix_runs_thread_created(thread_id, created_at)
ix_runs_created_assistant_user(created_at, assistant_id, user_id)
ix_runs_created_model_user(created_at, model_name, user_id)
```
生产库是否实际存在必须用 `pg_indexes` 验证。
### 8.2 不要为普通 INSERT/PK UPDATE 盲目加索引
普通 run 创建是 INSERT,结束是 `WHERE run_id = ?` 的 UPDATE。已有主键时,额外索引不会让这两个操作更快,反而增加每次 INSERT/UPDATE 的索引维护成本。
只有某个明确查询的 EXPLAIN 证明缺索引时才补建。例如:
- `WHERE thread_id=? ORDER BY created_at DESC LIMIT 100` 缺少 `(thread_id, created_at)`;
- pending 恢复查询成为已确认慢点时,才评估 partial index:
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_runs_pending_created
ON public.runs (created_at)
WHERE status = 'pending';
```
该 partial index不在普通 `/threads` 或 `/history` 路径上,不能作为本次问题的默认修复。
### 8.3 维护与膨胀
只有 `pg_stat_user_tables` 显示 runs/checkpoint 表死元组高、autovacuum 长期未运行时,才安排:
```sql
VACUUM (ANALYZE) public.runs;
VACUUM (ANALYZE) public.checkpoints;
VACUUM (ANALYZE) public.checkpoint_blobs;
VACUUM (ANALYZE) public.checkpoint_writes;
```
普通 `VACUUM (ANALYZE)` 与 `VACUUM FULL` 不同,但仍会产生 I/O,应低峰执行并监控。不要在线直接使用 `VACUUM FULL`。
autovacuum 参数应根据写入速率、表大小、死元组和数据库资源制定,不在没有现场指标时给所有表套固定值。
## 9. 数据保留和归档
归档不是本次 6 秒问题的第一优先级。确有长期容量压力时,另行设计:
- 明确保留期限与可恢复 SLA;
- 只归档真正终态且超过保留期的 thread;
- `checkpoints`、`checkpoint_blobs`、`checkpoint_writes` 必须按同一批 thread 完整处理;
- 停止相关 writer 或使用经过验证的一致性流程;
- 先 dry-run,导出候选 thread,备份并演练恢复;
- 同库 archive schema 不一定立即回收磁盘;
- 旧会话入口与正文恢复策略要一起设计。
不要只删除 `checkpoints` 主表而留下 blob/write,也不要只按全局时间无视仍活跃 thread。
## 10. 建议实施顺序
### 阶段 A:当天可做
1. 用配套排查文档采集一轮完整证据。
2. 确认 6 秒集中在 `checkpoint_create` 或 `/history`。
3. 对慢 thread 跑两条 EXPLAIN。
4. 如果跨 namespace 查询有 Sort/大量扫描,低峰在线创建 P0 索引。
5. `ANALYZE checkpoints`,重跑 EXPLAIN。
6. 对比变更前后 `/history` 与 `checkpoint_create`。
### 阶段 B:下一次应用发布
1. 确认普通 history 的 namespace 语义并限定 `checkpoint_ns=''`。
2. 先完整消费 `alist`,在 saver lock 释放后序列化响应。
3. 增加 history fetch/serialize 分段计时。
4. 调用 `RunManager.cleanup()`,限制内存 registry 增长。
5. 补单元、集成和并发回归。
### 阶段 C:压测后实施
1. 评估独立 history saver/reader 或兼容升级。
2. 验证多 checkpoint 操作真实并发。
3. 再根据新架构调整 pool 大小。
4. 基于真实容量与保留期制定归档策略。
## 11. 验收标准
不要只看一次“变快了”,至少记录一段稳定流量下的分位数。
| 指标 | 验收方式 |
| --- | --- |
| `/threads` 总耗时 | 浏览器/APM p50、p95、p99 |
| `checkpoint_create` | `Server-Timing`/日志 p50、p95、p99 |
| `/history` 总耗时 | Gateway/APM p50、p95、p99 |
| History SQL | `pg_stat_statements` mean/max,EXPLAIN 实际时间 |
| saver 排队 | 应用分段计时中 lock/fetch 与 serialize 分离后观察 |
| 正确性 | 首轮、多轮、刷新、重连、interrupt、subagent 历史一致 |
| 资源 | PG CPU、I/O、WAL、连接数、新索引大小 |
| 内存 registry | `_runs` 数量不再随累计历史永久增长 |
成功信号:
- History 计划使用目标组合索引,或限定 namespace 后使用现有主键;
- `/history` 不再出现秒级长尾;
- 同期 history 不再让新 thread 的 `checkpoint_create` 出现同等长尾;
- 回答正文结束到 UI 可再次输入之间的间隔显著下降;
- 对话刷新、历史恢复和重连行为无回归。
如果 History SQL 已稳定在毫秒级,但 `checkpoint_create` 仍有秒级长尾,应停止继续堆索引,转向 saver 实例锁和事件循环排队的 P1/P2 优化。
## 12. 变更与回滚清单
```text
[ ] 保存部署 commit、配置和指标基线
[ ] 保存目标 thread 的 EXPLAIN
[ ] 核对 schema 和现有等价索引
[ ] CREATE INDEX CONCURRENTLY(不在事务中)
[ ] 检查 indisvalid/indisready
[ ] ANALYZE checkpoints
[ ] 重跑 EXPLAIN
[ ] 观察 API、PG、WAL、磁盘指标
[ ] 准备 DROP INDEX CONCURRENTLY 回滚语句
[ ] 代码变更补 history/subgraph/reconnect 回归
[ ] 先发布代码并观察,再决定是否删除临时索引
```
@@ -0,0 +1,916 @@
# Thread 创建慢与回答结束后 History 等待:完整排查手册
日期:2026-10-22
适用范围:DeerFlow Gateway、LangGraph `useStream`、PostgreSQL 业务库与 PostgreSQL checkpointer。
## 1. 先说结论
当前代码证据表明:
1. `POST /api/threads` **不查询 `runs` 表**。它查询/写入 `threads_meta`,然后同步写入一个空 checkpoint。
2. 创建 run 时,持久化层主要执行 `INSERT INTO runs (...)`;run 结束时主要执行 `UPDATE runs ... WHERE run_id = ?`。`run_id` 是主键,`runs` 有 5 万行本身通常不足以造成 6 秒延迟。
3. 回答流结束后出现 `POST /api/threads/{thread_id}/history` 是前端 SDK 的正常行为。当前前端配置 `fetchStateHistory: { limit: 1 }`,SDK 会等待这个请求完成后才结束 `isLoading`,因此会出现“回答文字已经显示完,但页面仍在等待中”。
4. `/history` 实际查询 `checkpoints`、`checkpoint_blobs`、`checkpoint_writes`,不是查询 `runs`。
5. 当前 `/history` 只传 `thread_id`,核心查询是:
```sql
WHERE thread_id = $1
ORDER BY checkpoint_id DESC
LIMIT 1
```
`checkpoints` 主键为 `(thread_id, checkpoint_ns, checkpoint_id)`。当不限定 `checkpoint_ns` 时,主键不能直接提供跨 namespace 的 `checkpoint_id` 顺序,可能需要扫描该 thread 的候选行并做 top-N Sort。
6. 当前进程只创建一个全局 `AsyncPostgresSaver`。该 saver 在取得连接池连接之前先获取实例级 `asyncio.Lock`,所以 checkpoint 的 `aget/alist/aput/aput_writes` 在一个 Gateway 进程内实际是串行的。慢 `/history` 会延长持锁时间,并阻塞新 thread 的空 checkpoint 写入。
最符合当前现象的候选链路是:
```text
回答正文已经通过 SSE 到达浏览器
-> 后端完成 run 收尾并发送 SSE end
-> 前端 SDK 同步请求 /history
-> /history 查询或反序列化 checkpoint,期间占用 saver 实例锁
-> SDK 的 isLoading 仍为 true,页面继续显示等待
-> 同期创建新 thread 时,checkpoint_create 等待同一把 saver 锁
-> POST /threads 偶发耗时数秒
```
这只是代码层面的高概率根因。最终必须使用同一次线上复现的 `Server-Timing`、Gateway 日志和 PostgreSQL 活动快照闭环确认。
## 2. 两类 PostgreSQL 数据不要混淆
系统存在两类持久化访问。即使它们使用同一个 PostgreSQL DSN,也有不同的连接池和代码路径。
| 类型 | 主要表 | 主要用途 |
| --- | --- | --- |
| 应用 ORM 数据 | `threads_meta`、`runs` | 会话元数据、run 状态、统计字段 |
| LangGraph checkpointer | `checkpoints`、`checkpoint_blobs`、`checkpoint_writes`、`checkpoint_migrations` | 对话状态、消息、通道值、pending writes |
排查前先记录:
```text
部署 commit:
前端构建版本:
Gateway worker 数:
database.backend:
database PostgreSQL 主机/库名(脱敏):
checkpointer 实际后端:
checkpointer PostgreSQL 主机/库名(脱敏):
langgraph-checkpoint-postgres 版本:
```
注意:
- 仅确认 `database.backend=postgres` 不等于已经确认 `/history` 使用 PostgreSQL checkpointer。
- 当前运行时可能由统一 `database.postgres_url` 提供业务 ORM 与 checkpointer,也可能使用兼容配置中的独立 `checkpointer` 段。
- 若 legacy 配置为 `checkpointer.type=postgres` 但 `use_postgres=false`,checkpointer 会回退 SQLite。
- 当前 live run 与 SSE bridge 是进程内状态,正常部署要求 `GATEWAY_WORKERS=1`。不要用盲目增加 worker 的方式绕过该问题。
## 3. 浏览器看到的完整请求时间线
```mermaid
sequenceDiagram
participant UI as 浏览器 / useStream
participant API as Gateway
participant APPDB as 业务 PostgreSQL
participant CP as Checkpointer PostgreSQL
UI->>API: POST /api/threads
API->>APPDB: SELECT/INSERT threads_meta
API->>CP: UPSERT 初始 checkpoint
API-->>UI: thread_id
UI->>API: POST /api/threads/{id}/runs/stream
API->>APPDB: INSERT runs
API-->>UI: SSE 正文/工具事件
API->>CP: 持续写 checkpoint/blob/write
API->>APPDB: UPDATE runs 终态
API-->>UI: SSE end
UI->>API: POST /api/threads/{id}/history limit=1
API->>CP: 最新 checkpoint + blob/write
API-->>UI: history
Note over UI: history 完成后 isLoading 才结束
```
### 3.1 创建新会话
前端 SDK 在没有 `threadId` 时,会先 `await client.threads.create(...)`,成功后才发起 `runs.stream(...)`。因此 `POST /api/threads` 慢 6 秒,会直接表现为点击发送后 6 秒才开始回答流。
后端调用位置:
- `app/gateway/routers/threads.py:853-927`
- 前端使用点:`frontend-web/src/core/threads/hooks.ts:702-711`
- SDK 等待 thread create:安装包 `dist/react/stream.lgp.js:318-327`
### 3.2 回答结束后的 History
当前前端配置:
```ts
fetchStateHistory: { limit: 1 }
```
SDK 在 SSE 成功结束后执行:
```ts
const lastHead = (await history.mutate(threadId))?.at(0);
```
之后才调用 `onFinish` 并结束当前 stream loading 状态。当前项目的 `onFinish(state, runMeta)` 还显式接收最终 state,所以 SDK 也需要拿到 history state。
相关位置:
- `frontend-web/src/core/threads/hooks.ts:711`
- `frontend-web/src/core/threads/hooks.ts:976-1038`
- SDK `dist/react/stream.lgp.js:379-388`
- 页面最终暴露的 loading:`frontend-web/src/core/threads/hooks.ts:1920`
- 普通控制/history 请求超时保护:`frontend-web/src/core/api/api-client.ts:96-101`,当前为 30 秒
结论:最后看到 `/history` 并不表示模型还在生成;它可能只是 SDK 在做结束后的最终状态刷新。
## 4. 每个阶段实际执行什么 SQL
以下为当前代码和 `langgraph-checkpoint-postgres==3.1.2` 对应的等价 SQL。SQLAlchemy/psycopg 最终的占位符和列顺序可能略有差异,但访问表、过滤条件和索引需求一致。
### 4.1 `POST /api/threads`
调用链:
```text
threads.create_thread
-> ThreadMetaRepository.get
-> ThreadMetaRepository.create(仅新 thread)
-> AsyncPostgresSaver.aput(empty_checkpoint)
```
第一步,幂等查询:
```sql
SELECT ...
FROM threads_meta
WHERE thread_id = $1;
```
`threads_meta.thread_id` 应为主键。
新 thread 写元数据:
```sql
INSERT INTO threads_meta (...)
VALUES (...);
```
同步写入初始 checkpoint:
```sql
INSERT INTO checkpoints (
thread_id,
checkpoint_ns,
checkpoint_id,
parent_checkpoint_id,
checkpoint,
metadata
)
VALUES ($1, '', $2, NULL, $3, $4)
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id)
DO UPDATE SET
checkpoint = EXCLUDED.checkpoint,
metadata = EXCLUDED.metadata;
```
初始 checkpoint 的 `new_versions={}`,通常不会同时写 `checkpoint_blobs`。
该接口分阶段计时:
| `Server-Timing` 字段 | 实际内容 |
| --- | --- |
| `metadata_lookup` | `threads_meta` 按 `thread_id` 查询 |
| `metadata_create` | 新建 `threads_meta` 并提交事务 |
| `checkpoint_create` | 等待 saver 锁、取得连接、写 checkpoint、提交/同步 pipeline |
| `handler_total` | 进入 route handler 后的总时间 |
关键点:该接口的整条路径不读取或写入 `runs`。
### 4.2 `POST /api/threads/{thread_id}/runs/stream`
调用链:
```text
thread_runs.stream_run
-> services.start_run
-> RunManager.create_or_reject
-> RunRepository.put
-> 创建后台 run_agent task
```
`RunManager.create_or_reject` 先在 Python 进程内的全局 manager lock 下扫描 `_runs.values()`,检查同 thread、同模型以及同用户模型并发。该步骤不是 SQL。
然后持久化 run:
```sql
INSERT INTO runs (
run_id,
thread_id,
assistant_id,
user_id,
status,
model_name,
multitask_strategy,
metadata_json,
kwargs_json,
error,
follow_up_to_run_id,
created_at,
updated_at,
...
)
VALUES (...);
```
随后会查询或更新 `threads_meta`,再启动后台 agent。Gateway 在慢路径输出:
```text
[start-run-timing] thread=... total=...s enforce_access=...s run_create=...s thread_upsert=...s build_payload=...s
```
其中 `run_create` 包含:
- 进程内 `_runs` 扫描;
- `INSERT INTO runs`;
- 数据库 COMMIT。
### 4.3 graph 执行期间
LangGraph 会反复调用:
```sql
INSERT INTO checkpoint_blobs (...)
VALUES (...)
ON CONFLICT (thread_id, checkpoint_ns, channel, version)
DO NOTHING;
```
```sql
INSERT INTO checkpoints (...)
VALUES (...)
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id)
DO UPDATE SET checkpoint = EXCLUDED.checkpoint,
metadata = EXCLUDED.metadata;
```
```sql
INSERT INTO checkpoint_writes (...)
VALUES (...)
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
DO UPDATE SET channel = EXCLUDED.channel,
type = EXCLUDED.type,
blob = EXCLUDED.blob;
```
因此 checkpoint 数据量一般会明显大于 runs 数量:一个 run 可以产生多个 checkpoint、blob 和 write。
### 4.4 回答正文结束到 SSE `end`
graph 流结束后,后端仍会执行终态检查与收尾:
1. 第一次读取主 namespace 最新 checkpoint,用于确认 graph 已留下 terminal state:
```sql
SELECT ...
FROM checkpoints
WHERE thread_id = $1
AND checkpoint_ns = ''
ORDER BY checkpoint_id DESC
LIMIT 1;
```
2. 更新 run 状态:
```sql
UPDATE runs
SET status = $2,
updated_at = $3,
error = COALESCE($4, error)
WHERE run_id = $1;
```
3. 更新 run completion/token/message 统计,仍然是:
```sql
UPDATE runs
SET ...
WHERE run_id = $1;
```
4. 收尾阶段再次读取主 namespace 最新 checkpoint,用于同步标题和最终元数据。
5. 更新 `threads_meta` 状态/标题等信息。
6. 最后发布 SSE `end`。
两次 checkpoint 读取都会争用同一个 saver 实例锁。因此实际等待链可能是“正文已经生成 → terminal checkpoint 读取等锁 → completion 更新 → finalize checkpoint 读取再次等锁 → SSE end → 前端 `/history` 再次读 checkpoint”。
`runs` 的上述 UPDATE 按 `run_id` 主键定位。若该阶段慢,应该检查锁等待、连接池、事务提交和死元组,而不是仅凭总行数判断。
后端为终态收尾设置了 10 秒预算,相关日志包括:
```text
RUN_COMPLETION_TIMEOUT run_id=... phase=terminal_checkpoint
RUN_COMPLETION_TIMEOUT run_id=... phase=terminal_status
RUN_COMPLETION_TIMEOUT run_id=... phase=metadata_cleanup
```
### 4.5 `POST /api/threads/{thread_id}/history`
路由当前构造的 config 只有 `thread_id`:
```python
config = {"configurable": {"thread_id": thread_id}}
```
前端当前传 `limit=1`。saver 生成的核心 SQL 形态为:
```sql
SELECT
thread_id,
checkpoint,
checkpoint_ns,
checkpoint_id,
parent_checkpoint_id,
metadata,
(
SELECT array_agg(...)
FROM jsonb_each_text(checkpoint -> 'channel_versions')
JOIN checkpoint_blobs bl
ON bl.thread_id = checkpoints.thread_id
AND bl.checkpoint_ns = checkpoints.checkpoint_ns
AND bl.channel = jsonb_each_text.key
AND bl.version = jsonb_each_text.value
) AS channel_values,
(
SELECT array_agg(...)
FROM checkpoint_writes cw
WHERE cw.thread_id = checkpoints.thread_id
AND cw.checkpoint_ns = checkpoints.checkpoint_ns
AND cw.checkpoint_id = checkpoints.checkpoint_id
) AS pending_writes
FROM checkpoints
WHERE thread_id = $1
ORDER BY checkpoint_id DESC
LIMIT 1;
```
其中 blob/write 的相关子查询可以使用各自组合主键;最值得核对的是最外层 `checkpoints` 的跨 namespace 排序。
## 5. 为什么连接池最大 10 仍可能串行
当前 provider 创建:
```text
AsyncConnectionPool(min_size=1, max_size=10)
-> 一个 AsyncPostgresSaver(pool)
-> 挂到 app.state,供所有 thread/run/history 共用
```
`langgraph-checkpoint-postgres==3.1.2` 的 `_cursor()` 关键实现是:
```python
async with self.lock, get_connection(self.conn) as conn:
```
这意味着:
- saver 先拿实例锁,再去连接池 checkout;
- 同一个 saver 的所有 checkpoint 读写一次只能有一个进入 `_cursor()`;
- 把 `DEER_FLOW_PG_POOL_MAX` 从 10 调到更大,不能解除这个实例锁;
- 等待 saver 锁的 coroutine 尚未进入 PostgreSQL,因此 `pg_stat_activity` 可能只看到一个活动连接,看不到应用中其余等待者;
- `alist()` 在 cursor context 内 `fetchall()` 后逐项 `yield`,调用方处理 yielded tuple 时 generator 尚未退出,实例锁仍可能保持占用。
仓库已有 characterization test:
```text
packages/harness/tests/test_thread_operation_timing.py:204-247
```
它验证了 pool 场景下第二个 saver cursor 会等待第一个 cursor 释放。
## 6. `runs` 5 万行到底会不会慢
### 6.1 数据库中的 5 万条 runs
正常创建/完成路径主要是:
```sql
INSERT INTO runs (...);
UPDATE runs SET ... WHERE run_id = $1;
```
`run_id` 是主键,5 万行对 PostgreSQL 很小。只要:
- `runs_pkey` 存在且有效;
- 没有严重锁等待;
- 死元组和表/索引膨胀不严重;
- 数据库连接与存储 I/O 正常;
就不应仅因为 5 万行产生 6 秒延迟。
### 6.2 进程内 `_runs` 与数据库 `runs` 不是一回事
代码中存在一个独立问题:
- `RunManager.cleanup()` 能从 `_runs` 字典删除已结束记录;
- 当前 worker finally 只调用 `StreamBridge.cleanup()`;
- 全仓当前没有调用 `run_manager.cleanup(...)`;
- 因此同一个 Gateway 进程生命周期内完成的 run 会一直留在 `_runs`;
- 每次 `create_or_reject()` 会在 manager lock 内对 `_runs.values()` 做 1~3 次 O(N) 扫描。
数据库的 5 万条 runs 不会在启动时自动全部加载到 `_runs`。只有当当前进程自身长期运行并累计大量 run 时,这个问题才会放大。它是应该修复的增长性缺陷,但通常不是单独造成 6 秒的首要解释。
## 7. 一次完整的线上复现怎么采集
### 7.1 浏览器 Network
打开 DevTools → Network:
1. 勾选 `Preserve log`。
2. 过滤 `threads`。
3. 从创建新对话开始完整复现一次。
4. 记录以下请求:
| 阶段 | 请求 |
| --- | --- |
| 创建会话 | `POST /api/threads` |
| 问答流 | `POST /api/threads/{thread_id}/runs/stream` |
| 结束刷新 | `POST /api/threads/{thread_id}/history` |
记录:
```text
thread_id:
run_id:
请求开始时间:
HTTP 状态:
Waiting/TTFB:
Content Download:
响应大小:
请求结束时间:
```
另外记录:
- `runs/stream` 最后一个可见正文 chunk 的时间;
- SSE 真正结束时间;
- `/history` 开始和完成时间;
- 页面退出“等待中”的时间;
- `POST /api/threads` 响应头中的 `Server-Timing`。
导出 HAR 前删除 Authorization、Cookie、token 和业务正文。
### 7.2 `POST /threads` 的 `Server-Timing`
示例:
```http
Server-Timing: metadata_lookup;dur=18.20, metadata_create;dur=25.10, checkpoint_create;dur=5880.30, handler_total;dur=5930.10
```
判断:
| 结果 | 优先结论 |
| --- | --- |
| `checkpoint_create` 约等于总耗时 | saver 锁等待、checkpointer 连接获取或 checkpoint PG 写入 |
| `metadata_lookup` 慢 | 业务 PG 的 `threads_meta` 主键查询、连接池或锁 |
| `metadata_create` 慢 | 业务 PG 插入/提交、索引维护或锁 |
| 所有 phase 很快但 `handler_total` 慢 | phase 外逻辑或事件循环调度竞争 |
| `handler_total` 很快但浏览器 TTFB 慢 | 鉴权、中间件、反向代理、进入 handler 前排队 |
| 没有 `Server-Timing` | 线上版本不包含该诊断,或请求没有进入预期 route |
`checkpoint_create` 包含 saver lock 和 pool 等待,不只是 SQL 执行时间。
### 7.3 Gateway 日志
本地脚本部署:
```powershell
rg -n "GATEWAY_OPERATION_TIMING|start-run-timing|RUN_COMPLETION_TIMEOUT|completion metadata exceeded|Failed to finalize run|Checkpointer|pool timeout|OperationalError" .runtime/logs
```
容器部署:
```bash
docker logs --since 15m <gateway-container> 2>&1 \
| rg "GATEWAY_OPERATION_TIMING|start-run-timing|RUN_COMPLETION_TIMEOUT|completion metadata exceeded|Failed to finalize run|Checkpointer|pool timeout|OperationalError"
```
将同一个 `thread_id`、`run_id` 整理成时间线:
```text
T0 POST /threads 开始
T1 thread_create 分阶段日志
T2 run 开始
T3 最后正文事件
T4 run 标记 success/error
T5 SSE end
T6 /history 开始
T7 /history 完成
T8 UI 退出等待
```
## 8. PostgreSQL 只读排查 SQL
以下查询默认当前连接就是目标数据库。若应用使用非 `public` schema,先确认实际 schema,再修改后续 SQL。`<THREAD_ID>` 和 `<RUN_ID>` 必须替换成真实值。
### 8.1 确认 schema、版本和现有索引
```sql
SELECT current_database(), current_schema(), current_schemas(true);
SELECT max(v) AS checkpoint_schema_version
FROM checkpoint_migrations;
SELECT
schemaname,
tablename,
indexname,
indexdef
FROM pg_indexes
WHERE tablename IN (
'runs',
'threads_meta',
'checkpoints',
'checkpoint_blobs',
'checkpoint_writes'
)
ORDER BY tablename, indexname;
```
`langgraph-checkpoint-postgres 3.1.2` 正常 setup 应包含三张 checkpoint 表的组合主键以及:
```text
checkpoints_thread_id_idx
checkpoint_blobs_thread_id_idx
checkpoint_writes_thread_id_idx
```
不要因为模型代码声明了索引就假设生产库一定存在,最终以 `pg_indexes`/`pg_index` 为准。
确认索引是否 valid/ready:
```sql
SELECT
n.nspname AS schema_name,
t.relname AS table_name,
i.relname AS index_name,
x.indisvalid,
x.indisready,
pg_get_indexdef(i.oid) AS indexdef
FROM pg_class t
JOIN pg_namespace n ON n.oid = t.relnamespace
JOIN pg_index x ON x.indrelid = t.oid
JOIN pg_class i ON i.oid = x.indexrelid
WHERE t.relname IN (
'runs',
'threads_meta',
'checkpoints',
'checkpoint_blobs',
'checkpoint_writes'
)
ORDER BY t.relname, i.relname;
```
### 8.2 表规模、死元组和维护情况
```sql
SELECT
schemaname,
relname,
n_live_tup,
n_dead_tup,
round(
100.0 * n_dead_tup /
greatest(n_live_tup + n_dead_tup, 1),
2
) AS dead_pct,
last_vacuum,
last_autovacuum,
last_analyze,
last_autoanalyze
FROM pg_stat_user_tables
WHERE relname IN (
'runs',
'threads_meta',
'checkpoints',
'checkpoint_blobs',
'checkpoint_writes'
)
ORDER BY relname;
```
```sql
SELECT
schemaname,
relname,
pg_size_pretty(
pg_total_relation_size(
format('%I.%I', schemaname, relname)::regclass
)
) AS total_size
FROM pg_stat_user_tables
WHERE relname IN (
'runs',
'threads_meta',
'checkpoints',
'checkpoint_blobs',
'checkpoint_writes'
)
ORDER BY pg_total_relation_size(
format('%I.%I', schemaname, relname)::regclass
) DESC;
```
统计值是估算值,足以用于判断规模和维护异常;不必先执行昂贵的全表 `count(*)`。
### 8.3 故障 thread 的 checkpoint 分布
```sql
SELECT
checkpoint_ns,
count(*) AS checkpoint_rows,
min(checkpoint_id) AS oldest_checkpoint_id,
max(checkpoint_id) AS newest_checkpoint_id
FROM checkpoints
WHERE thread_id = '<THREAD_ID>'
GROUP BY checkpoint_ns
ORDER BY checkpoint_rows DESC;
```
如果单个 thread 有大量 checkpoint 或多个 namespace,当前 `/history` 的跨 namespace 排序更值得关注。
### 8.4 对比 History 与主 namespace 的执行计划
只对一个已知慢 thread 在低峰执行:
```sql
EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
SELECT checkpoint_id, checkpoint_ns
FROM checkpoints
WHERE thread_id = '<THREAD_ID>'
ORDER BY checkpoint_id DESC
LIMIT 1;
```
对比限定主 namespace:
```sql
EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
SELECT checkpoint_id, checkpoint_ns
FROM checkpoints
WHERE thread_id = '<THREAD_ID>'
AND checkpoint_ns = ''
ORDER BY checkpoint_id DESC
LIMIT 1;
```
重点看:
- 第一条是否出现 `Sort` / `top-N heapsort`;
- `Rows Removed by Filter`;
- 实际扫描行数;
- shared buffer read/hit;
- 第二条是否使用 `checkpoints_pkey` 的 backward index scan;
- 两条的实际耗时差异。
`EXPLAIN ANALYZE` 会真实执行 SELECT。这里的 SELECT 是只读的,但仍应对一个明确 thread 在低峰执行,不要直接对完整大型历史查询做无界分析。
### 8.5 验证 runs 的关键查询
按 run id:
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT run_id, status
FROM runs
WHERE run_id = '<RUN_ID>';
```
预期使用 `runs_pkey`。
按 thread 列表:
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT run_id, status, created_at
FROM runs
WHERE thread_id = '<THREAD_ID>'
ORDER BY created_at DESC
LIMIT 100;
```
预期使用 `(thread_id, created_at)` 组合索引,例如 ORM 当前声明的 `ix_runs_thread_created`。如果生产库没有该索引,先核对部署 migration/自动补列逻辑,再决定是否补建;不要建立重复索引。
### 8.6 卡顿正在发生时查看 PostgreSQL 活动
```sql
SELECT
pid,
application_name,
usename,
state,
wait_event_type,
wait_event,
xact_start,
query_start,
now() - query_start AS query_age,
pg_blocking_pids(pid) AS blocking_pids,
left(query, 500) AS query
FROM pg_stat_activity
WHERE datname = current_database()
AND pid <> pg_backend_pid()
AND (state <> 'idle' OR wait_event IS NOT NULL)
ORDER BY query_start;
```
阻塞关系:
```sql
SELECT
blocked.pid AS blocked_pid,
now() - blocked.query_start AS blocked_for,
blocked.wait_event_type,
blocked.wait_event,
left(blocked.query, 300) AS blocked_query,
blocker.pid AS blocker_pid,
blocker.state AS blocker_state,
now() - blocker.xact_start AS blocker_xact_age,
left(blocker.query, 300) AS blocker_query
FROM pg_stat_activity AS blocked
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid) ON true
JOIN pg_stat_activity AS blocker ON blocker.pid = b.pid
ORDER BY blocked.query_start;
```
注意:如果请求在 Python saver lock 上等待,它还没有 checkout PostgreSQL 连接,因此 PostgreSQL 里可能看不到对应 blocked session。
### 8.7 如果启用了 `pg_stat_statements`
先确认扩展:
```sql
SELECT extname, extversion
FROM pg_extension
WHERE extname = 'pg_stat_statements';
```
checkpoint 查询:
```sql
SELECT
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(max_exec_time::numeric, 2) AS max_ms,
rows,
shared_blks_hit,
shared_blks_read,
temp_blks_written,
left(query, 700) AS query
FROM pg_stat_statements
WHERE dbid = (
SELECT oid
FROM pg_database
WHERE datname = current_database()
)
AND query ILIKE '%checkpoints%'
ORDER BY max_exec_time DESC
LIMIT 30;
```
runs 查询:
```sql
SELECT
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(max_exec_time::numeric, 2) AS max_ms,
rows,
shared_blks_hit,
shared_blks_read,
temp_blks_written,
left(query, 700) AS query
FROM pg_stat_statements
WHERE dbid = (
SELECT oid
FROM pg_database
WHERE datname = current_database()
)
AND query ILIKE '%runs%'
ORDER BY max_exec_time DESC
LIMIT 30;
```
## 9. 证据如何判定
| 现场证据 | 结论/下一步 |
| --- | --- |
| `/threads` 的 `checkpoint_create` 接近 6 秒 | 优先排查 saver 锁排队或 checkpoint PG 写入 |
| `checkpoint_create` 很慢,但 `pg_stat_activity` 没有相应慢 SQL/锁 | 强烈支持请求仍在进程内 saver lock 上排队 |
| History EXPLAIN 出现大量候选扫描 + Sort | 为 `(thread_id, checkpoint_id DESC)` 建候选索引,或让接口限定 `checkpoint_ns=''` |
| History SQL 自身毫秒级,但接口仍数秒 | 重点查 saver lock wait、反序列化、消息序列化和事件循环阻塞 |
| 最后正文已到但 SSE 未结束,日志出现 `terminal_checkpoint` | run 收尾在 checkpoint 读取处等待 |
| 日志出现 `terminal_status` | `runs` 终态 UPDATE/COMMIT、业务 PG 连接或锁等待 |
| 日志出现 `metadata_cleanup` | journal、completion、标题或 thread 元数据收尾超时 |
| SSE 已结束,只有 `/history` pending | SDK 结束后 history 刷新卡住,不是模型还在生成 |
| `/history` 已 200,页面仍 loading | 再查前端构建版本、状态恢复和渲染逻辑 |
| `runs_pkey` 命中,dead tuples 低,无 DB wait | 5 万 runs 不是该故障的主要原因 |
| `runs` dead tuples 高、autovacuum 长期不工作 | 可能拖慢 UPDATE/COMMIT,但仍不能解释 `/history` 路径 |
| PG 出现 `wait_event_type='Lock'` 和 blocking pid | 已确认数据库锁等待,先处理 blocker |
| PG 出现明显 I/O wait 或大量 shared reads | 检查存储、缓存命中、膨胀及查询计划 |
| checkpoint migration 或必要索引缺失/invalid | 修复 schema/setup,再评估应用层锁 |
## 10. 不建议直接做的操作
- 不要因为有 5 万条 runs 就直接删除 runs。
- 不要在生产直接执行 `VACUUM FULL`,它会对表获取强锁。
- 不要先增加大量重复索引;每个索引都会增加 checkpoint 写放大。
- 不要只增大 `DEER_FLOW_PG_POOL_MAX`;单 saver 的实例锁仍会串行。
- 不要通过增加 Gateway worker 临时绕过;当前 run registry 与 SSE bridge 是进程内状态。
- 不要在未确认 history namespace 语义前直接把所有查询改成 `checkpoint_ns=''`。
- 不要把 checkpoint 归档作为本次 6 秒问题的第一步;归档涉及停写、备份、恢复演练,并不能消除 saver 实例锁。
## 11. 单次事故记录模板
```text
部署 commit:
前端构建版本:
Gateway worker:
database backend/host/db:
checkpointer backend/host/db:
发生时间:
thread_id:
run_id:
POST /threads:
- 浏览器总耗时:
- Server-Timing:
- HTTP 状态:
runs/stream:
- 开始时间:
- 最后正文时间:
- SSE end 时间:
- 是否收到 end:
history:
- 开始时间:
- TTFB:
- 完成/取消时间:
- HTTP 状态:
- 响应大小:
Gateway 日志:
- GATEWAY_OPERATION_TIMING:
- start-run-timing:
- RUN_COMPLETION_TIMEOUT:
- pool/DB 异常:
PostgreSQL:
- activity/wait_event:
- blocking_pids:
- checkpoint migration:
- 索引缺失/invalid:
- live/dead tuples:
- History EXPLAIN:
初步判定:
已经排除:
尚缺证据:
下一步:
```
## 12. 关键代码位置
| 位置 | 内容 |
| --- | --- |
| `offline-backend-20260512/backend/app/gateway/routers/threads.py:853-927` | 创建 thread、分阶段计时、同步写初始 checkpoint |
| `offline-backend-20260512/backend/app/gateway/routers/threads.py:1873-1944` | History config、alist 和消息序列化 |
| `offline-backend-20260512/backend/app/gateway/operation_timing.py:14-60` | `Server-Timing` 和 `GATEWAY_OPERATION_TIMING` |
| `offline-backend-20260512/backend/app/gateway/routers/thread_runs.py:98-133` | run 创建与 SSE 路由 |
| `offline-backend-20260512/backend/app/gateway/services.py:1374-1976` | `start_run` 和 `[start-run-timing]` |
| `offline-backend-20260512/backend/packages/harness/deerflow/persistence/run/sql.py:66-206` | runs INSERT/UPDATE |
| `offline-backend-20260512/backend/packages/harness/deerflow/persistence/run/model.py:14-56` | runs 主键和 ORM 索引声明 |
| `offline-backend-20260512/backend/packages/harness/deerflow/runtime/runs/manager.py:211-324` | `_runs` 扫描与未被调用的 cleanup |
| `offline-backend-20260512/backend/packages/harness/deerflow/runtime/runs/worker.py:479-501` | run 收尾后仅清理 stream bridge |
| `offline-backend-20260512/backend/packages/harness/deerflow/runtime/checkpointer/async_provider.py:93-123` | PG pool 与单 saver |
| `.venv/Lib/site-packages/langgraph/checkpoint/postgres/base.py:43-150` | checkpoint schema、索引和 SQL |
| `.venv/Lib/site-packages/langgraph/checkpoint/postgres/aio.py:119-179` | alist 查询、fetchall 与持锁 yield |
| `.venv/Lib/site-packages/langgraph/checkpoint/postgres/aio.py:363-403` | saver 实例锁先于 pool checkout |
| `frontend-web/src/core/threads/hooks.ts:702-711` | `fetchStateHistory: { limit: 1 }` |
| `frontend-web/src/core/threads/hooks.ts:976-1038` | onFinish 依赖最终 state |
| `frontend-web/src/core/api/api-client.ts:96-101` | 控制/history 请求 30 秒超时 |
## 13. 推荐排查顺序
按下面顺序执行,通常一次复现就能缩小范围:
1. 浏览器保存 `/threads`、`runs/stream`、`history` 时间线。
2. 查看 `/threads` 的 `Server-Timing`。
3. 用同一 `thread_id/run_id` 对齐 Gateway 日志。
4. 卡顿发生时立即保存 `pg_stat_activity` 和 blocker 快照。
5. 查询实际索引与表统计,不依赖代码声明猜测生产 schema。
6. 对慢 thread 比较两条 History EXPLAIN。
7. 只有证据显示查询计划问题时才加索引;只有 SQL 已很快而接口仍等待时,才优先改 saver/应用锁路径。
@@ -0,0 +1,358 @@
# 技能并发与流式修复:配置、前端包与验收说明
日期:2026-09-27(2026-09-28 补充高并发运行配置)。
本说明对应本次提交的修改,包含模型流式兼容与恢复、React #185 错误处理和已完成的最小技能示例,
以及可选的技能视图复用、版本缓存、模型计时日志队列和 Gateway 线程池扩容。
部署前通过 `git log -1` 核对代码提交;仅修改配置或替换旧包不能确认已部署本次修复。
## 1. 先确认需要更新什么
- **后台代码也要更新**:四个新开关需要新版后台读取。只换前端 dist 或只把字段写进旧版 config.yaml 不会实现后台优化。
- **前端**:使用本说明末尾的 ZIP,里面是完整 `dist/`,不是源码或 node_modules。
- **仓库运行配置已开启优化**:两份 config.yaml 的四个开关均已显式设为 `true`。但已有服务器的持久化/外挂配置不会被仓库自动覆盖,仍需手工同步。
- 开启线程池开关后可将上限调整为 100,但不提高模型服务商配额、不启用多 worker。
## 2. .env 需要修改哪些项
后台启动所使用的 `.env` 保持或修改为:
```dotenv
# Gateway 进程数,不是线程池大小;当前内存流/运行管理器必须单进程。
GATEWAY_WORKERS=1
# 默认就是 0;显式写 0 可防止误用不安全的多进程覆盖开关。
DEERFLOW_ALLOW_UNSAFE_MULTIWORKER=0
# Gateway asyncio 线程池上限;还必须打开下一节的 asyncio_thread_pool_enabled。
DEER_FLOW_ASYNCIO_THREAD_POOL_SIZE=100
```
适用于已更新的 `scripts/start_backend-online.sh` 和 `offline-backend-20260512/start_backend.sh`。
若通过自定义服务直接运行 Uvicorn,也应确认实际命令是单 worker;仅修改 .env 不会改变硬编码的启动命令。
启动环境中已导出的同名变量可能覆盖 .env,需一并核对。
前面三个技能/日志优化没有独立环境变量,它们配置在下一节的 `config.yaml`。
线程池上限变量现已真正接入;修改 .env 后必须重新启动后台,Docker 应通过现有启动脚本重新创建容器,
单纯 `docker restart` 不会更新容器创建时注入的环境变量。
其余模型地址、密钥、数据库连接等保留服务器原值,不用本机 .env 覆盖生产文件。
### 100 个线程与环境变量优先级
`GATEWAY_WORKERS=100` **不是**把工具线程池调成 100,而是启动 100 个进程,当前部署不要这样设置。
`DEER_FLOW_ASYNCIO_THREAD_POOL_SIZE=100` **已经实现**,兼容别名 `DEERFLOW_IO_THREADS=100`,
两者任选其一即可。开启线程池开关后,按以下顺序取第一个非空值:
1. `DEER_FLOW_ASYNCIO_THREAD_POOL_SIZE`(正式变量)
2. `DEERFLOW_IO_THREADS`(兼容别名)
3. `config.yaml` 的 `runtime_performance.asyncio_thread_pool_size`(默认 100)
有效范围为整数 **1..1024**。选中环境变量的值非法时启动失败并提示,不会静默退回默认小线程池。
开关关闭时不读取环境变量来改变线程池,保留 Python 原默认。已有正式变量时,修改别名不会覆盖它。
线程按需创建,100 是上限,不会预先常驻启动 100 个线程。
## 3. config.yaml 新增配置
在实际加载的 `config.yaml` **顶层**配置这一段,不能缩进到 `models`、`sandbox` 或 `skills` 内,
也不要重复定义两个 `runtime_performance`。下面是程序在字段缺失时的兼容性默认值;
当前仓库的两份可运行配置已使用后文的高并发开启值:
```yaml
runtime_performance:
# 一次工具调用内只获取一次已验证技能视图,默认 false。
skill_view_reuse_enabled: false
# 版本未变时复用技能视图,默认 false。
skill_view_cache_enabled: false
# 模型计时日志使用独立队列,不争抢耗时工具线程,默认 false。
model_timing_nonblocking_enabled: false
# 是否覆盖 Gateway asyncio 默认线程池,默认 false。
asyncio_thread_pool_enabled: false
asyncio_thread_pool_size: 100
```
如决定启用本次四项优化并将线程池上限设为 100,改为:
```yaml
runtime_performance:
skill_view_reuse_enabled: true
skill_view_cache_enabled: true
model_timing_nonblocking_enabled: true
asyncio_thread_pool_enabled: true
asyncio_thread_pool_size: 100
```
四个开关独立生效,可以单独开关。关闭/省略对应项时,对应的性能优化走原实现。
这四项不控制模型协议兼容修复或前端错误处理;全部关闭不等于回退所有代码。
为了让已有模型实例和所有后台进程配置一致,修改后重启后台;回退也是改回 `false` 后重启。
### 确认没有改错配置文件
- 已设置 `DEER_FLOW_CONFIG_PATH` 时,以它指向的文件为准;Docker 内该值必须是容器内可访问路径。
- 本仓库包含 `offline-backend-20260512/config.yaml` 和 `offline-backend-20260512/backend/config.yaml`;
两份已同步为高并发开启值,但服务器要修改的仍是启动时实际加载/挂载的那一份。
- 启动日志 `Loaded AppConfig from ...` 可确认路径,`RUNTIME_PERFORMANCE` 可确认实际开关值。
## 4. 开启后做了什么,没做什么
### 单次调用复用
同一次 `read_file`、`ls`、`glob`、`grep`、`bash` 等工具执行期间,技能检查、沙箱初始化、
路径替换和输出脱敏共用一份已验证视图;退出调用后清理作用域,下一次调用重新验证。
不会把一个问答最初的技能启停状态一直沿用到结束。
### 技能版本缓存
每次核对启停 JSON 内容、已知源/目标文件和目录的元数据及标记。
版本一致时不重新发现/解析全部技能、不复制文件、不持有全局刷新锁。
新增、编辑、删除、启停及支持文件变化触发重建,并保留跨进程锁合并并发刷新。
没有采用会延迟下线的 TTL 缓存;下一次工具调用能发现下线或无效配置并拒绝访问。
已经开始执行的工具不因此被强行中断。
缓存仅用于标准 `LocalSkillStorage`,自定义存储实现/子类保守回到原刷新路径。
同一 Gateway 进程内,仅在多个热命中调用真正重叠时合并为一次元数据校验;
该批调用结束后结果立即丢弃,新调用仍重新校验。启停文件哈希不同的调用不会加入旧校验,
校验异常会对该批调用统一 fail-closed,且不会阻止后续调用重试。
热路径仍有 O(文件数) 元数据校验,慢磁盘/网络挂载仍可能耗时;这不是“所有文件操作零开销”,
也没有把受锁保护的重建变成无锁写入。
### 模型计时日志
仅轻量计时/入队在回调中执行,日志 I/O 由独立线程消费,不占工具共享线程池或事件循环。
队列上限 4096 条;日志端长期阻塞时会丢弃诊断并在恢复后汇总告警,不无限积压或阻塞模型输出。
退出时最多等待 0.5 秒尽力刷新,异常退出可能丢失尾部日志。
这是 `ModelTimingCallback` 的优化,不会改变其他回调(如 RunJournal、可选追踪插件)、
子智能体调度池、数据库池或模型上游的连接/速率限制。不能据此保证 100 个会话同时生成。
### Gateway 工具线程池
开启 `asyncio_thread_pool_enabled` 后,在后台启动时、LangGraph 初始化之前设置当前
Gateway 事件循环的默认执行器。同步工具、该循环的 `asyncio.to_thread` 等可使用最多 100 个槽位。
关闭时完全不替换默认执行器;退出时由拥有该事件循环的服务运行器清理。
这不是 AnyIO 的同步 HTTP 路由线程池,也不改变子智能体专用池或独立事件循环的默认池。
线程池扩大只能减少可并行 I/O 的排队,不能让同一把技能锁同时被多人持有,也不会增加模型端的生成配额。
## 5. 日志检查
确认加载日志类似:
```text
RUNTIME_PERFORMANCE skill_view_reuse_enabled=True skill_view_cache_enabled=True model_timing_nonblocking_enabled=True asyncio_thread_pool_enabled=True asyncio_thread_pool_size=100
```
线程池最终是否生效,以另一条启动日志为准(进程 id 随实际启动变化):
```text
GATEWAY_ASYNCIO_EXECUTOR enabled=true max_workers=100 source=DEER_FLOW_ASYNCIO_THREAD_POOL_SIZE pid=12345
```
如果仍显示 `enabled=false max_workers=python_default`,说明线程池开关没打开或改错了配置文件,
不是已经调整到 100。改环境变量后若日志仍取旧值,检查是否重建了 Docker 容器及实际 env-file。
查看以下日志:
| 日志 | 用途 |
| --- | --- |
| `GATEWAY_ASYNCIO_EXECUTOR` | 实际线程池开关、最终上限、配置来源和进程 id;关闭时显示使用 Python 默认,不虚报 100 |
| `SKILL_VIEW_CACHE status=refreshed` | 发生重建;包含 `lock_wait_ms`、`refresh_ms`、`total_ms` 和条目数 |
| `SKILL_VIEW_CACHE status=joined` | 等待期间其他线程/进程已完成重建,本次直接复用 |
| `SKILL_VIEW_CACHE status=hit` | 缓存命中;正常命中为 DEBUG,超过 500ms 的慢命中为 INFO |
| `SKILL_VIEW_CACHE status=failed` | 刷新失败,旧能力不可继续使用,需要排查配置/磁盘 |
| `LLM_CONNECT_START/OK`、`LLM_REQUEST_DONE/FAILED` | 模型调用生命周期、首块和总耗时 |
| `LLM_CALL_RETRY/FAILED`、`OPENAI_TOOL_STREAM_SUMMARY` | 模型重试/兼容处理诊断 |
| `LLM_TIMING_LOG_DROPPED` | 日志队列曾满;检查日志磁盘/采集端速度 |
如需查看正常缓存命中,可短时设置顶层 `log_level: debug`;排查后恢复 `info`。
首块耗时不等于纯网络连接等待,仍包括上游排队、模型处理等阶段。单次 curl 成功也不能证明并发容量足够。
本次日志不记录技能正文、模型正文或 API 密钥。
## 6. 前端替换与回退
1. 先备份服务器当前前端目录和 `runtime-config.js`,并备份实际后台 .env/config.yaml。
2. 校验下载 ZIP 的 SHA-256 与本说明记录一致,再解压到一个新的发布目录。
3. ZIP 包含 `dist/`;Web 根目录应指向其内部,确保根下直接能找到 `index.html`,不要误放成 `dist/dist/`。
4. **保留/恢复服务器自己的 `runtime-config.js`**。核对生产后台地址、认证和嵌入参数;不要把构建机默认值当生产配置。
也不要覆盖生产 .env 的密钥与数据库配置。恢复 runtime-config 后其单文件哈希自然与原包不同。
5. 更新后台代码并按需设置四个开关,使用现有部署方式重启后台,再切换前端发布目录。
6. 刷新浏览器缓存后检查普通问答、智能体问答、技能示例、读取技能、生成文件以及离开后重新打开正在生成的会话。
7. 如需回退性能优化,后台关闭相应开关并重启,无需删除技能文件或技能缓存目录。
如需回退模型协议或前端修复,须恢复对应的已备份代码/前端发布目录,单独关闭性能开关不够。
正式 Linux AMD64 离线镜像/发版仍通过独立的 `knowledge-base-bj/deerflow-offline-deployment`
仓库流程执行;本次前端 ZIP 不是完整后台离线镜像。
## 7. 本地验证结果与限制
### 后台
- 提交前最终专项:技能/线程池/日志/启动配置及技能老回归 **166 项通过**;模型适配、错误分类、
诊断失败保护、SSE 响应头、会话计时与真实 transport **123 项通过**(两组不重叠,共 289 项)。
对应修改模块与测试 Ruff 通过,harness 未增加对 app 的反向依赖。后续没有执行生产模型并发压测。
- 本次技能复用/缓存/配置、日志回调与相关技能目录、大文件安全专项:**79 项通过**;
又补充 1 项开关关闭/重新开启的回退测试,通过缓存文件全部 13 项回归,合计 **80 项**。
- 模型工具参数流/推理流、错误恢复、SSE 传输和启动 worker 校验另 **76 项通过**;相关专项共 **156 项通过**。
- 后续新增线程池接入与配置专项 **45 项通过**(与前述配置测试有重叠,不相加充当独立总数):
覆盖默认关闭、两个环境变量优先级/别名、非法值拒启、启动顺序,以及实际 **24 / 100 个本地阻塞任务同时执行**、
退出后线程全部清理;新模块和相关测试 Ruff 检查通过。另一次联合技能/日志/启动配置回归 **88 项通过**。
该测试只验证本地线程池,不是 100 路模型压测。
- 线程池接入后再次尝试后台全量测试(首次失败即停止):**604 通过、2 跳过、1 失败**,
仍停在修改前已复现的 `test_llm_metrics.py::test_middleware_records_success_with_speed`,不是全量通过。
- 冷启动 8 线程并发只构建一次;真实第二进程复用持久化清单、不再发现技能。
- 下线/无效配置、源文件变更、同长保留 mtime 编辑、目标篡改、Windows junction 保护均有回归覆盖。
- 真实 LangChain 异步模型测试证明:默认工具线程池占满且日志处理器阻塞时,启用计时日志优化仍可开始、输出 token 并结束;未调用真实模型服务。
- 修改后尝试全量测试,设置失败 5 项停止:**871 通过、2 跳过、5 失败**,并非全量通过。
失败包括 `test_llm_metrics.py` 的 3 项记录时序断言、既有 Wiki `auto_sync` 配置与测试预期不一致、
`test_model_management.py` 的 thinking 参数预期不一致。首项在本轮修改前即已复现;
本轮没有修改指标中间件、模型工厂或 Wiki auto_sync 设置,不为过测试擅改这些业务配置。
- 本次针对 #185/MD 的追加回归:模型真实 SDK 回放、工具参数、思考字段、日志、配置、线程池、
错误中间件和传输联合 **145 项通过**。其中新增 SDK 回放 19 项,覆盖 8 种写文件形态,
确认 JSON 尚未闭合时部分 MD 已传出、最终工具名称和参数正确;没有连接线上模型。
### 合成性能对比
Windows 11 / Python 3.12.13,本机临时目录:150 个技能、450 个文件,各模式预热一次后串行 10 次。
旧刷新平均约 **3133ms**,缓存命中平均约 **806ms**(本次约 3.89 倍);
`load_skills` 从 10 次降为 0 次。临时数据已清理。
这不是生产 Linux 性能结论,也不是多人访问模型的承载压测。
### 前端与交付包
- 提交前最终前端专项 **60 项通过**(原 57 项,加同 reader 续接/新页面重播与迟到事件隔离 2 项、
最小技能示例 1 项);真实生产 React 浏览器错误边界测试再次通过。
- 最终全量类型检查仍有既有 **75 个诊断**,本次变更文件无新增诊断;记录在
`.runtime/frontend-final-typecheck-20260927.log`。不要把构建成功等同全量类型检查通过。
- 前端本次流式恢复、React #185 分类、技能示例、流式预览及相关权限等 **32 项专项通过**;
修正新增测试文件一处 `.ts` 导入导致的 TS5097 后,相关 16 项再次通过。
- 最新追加前端专项 **57 项通过**,含真实 SDK SSE → 文件参数 → MD 预览;旧 16ms 设置在连续流中
没有通知刷新,修复后在 JSON 尚未闭合时持续更新。真实 Chrome + 生产 React 中用循环 layoutEffect
触发 #185,验证静态友好兜底、无自动重挂、点击重新载入后恢复。
- 最新 `pnpm build` **通过**:Vite 13,853 个模块,8 分 49 秒;存在大于 500KB 的 chunk 提醒,不是构建失败。
构建日志 `.runtime/frontend-final-build-20260927.log`;本次修复重新打开会话的游标边界后已重新打包。
- 前一版临时 localhost 静态 HTTP 烟测 **通过**:入口 HTML 及引用的主 JS/CSS/runtime 等 5 个资源均 200,
响应字节 SHA-256 与磁盘一致,没有缺失资源;烟测服务已关闭。
- 最新 ZIP 中 **886 个文件**均逐文件比对大小和 SHA-256,与本次 dist 一致;入口/CSS 的 99 个本地资源引用全部存在。包内无 `.env`,
入口为 `dist/index.html`,包含 `dist/runtime-config.js`。
- 全量 `pnpm typecheck` **未通过**:复测还有 **75 个诊断、涉及 29 个本次未修改文件**,
包括现有 nextra / `@codemirror/state` 依赖、旧测试及 legacy QA 类型问题;
本次新增测试文件的 TS5097 已修正并复测,本次前端变更文件无类型诊断。
完整本地日志为 `.runtime/qa/frontend-delivery-typecheck-20260927.log`;
不能把生产构建通过表述成整个项目类型检查通过。
追加修复后本次产品变更文件无全量类型诊断,新增测试及依赖专项 TypeScript 检查为 0 诊断。
- 附加 legacy Chrome CSS 检查 **未通过**,报三个本轮未修改文件
`legacy-html-preview.test.ts`、`legacy-html-preview.ts`、`SolutionProjectLanding.tsx` 中的现代颜色函数字样;
没有报本次 dist CSS 缺失回退,也不能据此宣称完成旧浏览器端到端兼容验收。
交付 ZIP(仓库根目录):
```text
deerflow-frontend-dist-20260927-master-final.zip
```
- ZIP 大小:35,869,210 字节(约 34.2 MiB)。
- 此包替代 `deerflow-frontend-dist-20260927-191207-185-stream-fix.zip` 及更早版本;旧包保留,但不包含最终的游标作用域修复。
- 解压后文件总大小:66,347,693 字节。
- ZIP SHA-256:
```text
7E4C1525BDEB686161FFF5AED12D36087407BBF4F472B87E78CA04DADD1DF371
```
Linux 可用 `sha256sum deerflow-frontend-dist-20260927-master-final.zip`;
Windows 可用 `Get-FileHash -Algorithm SHA256 .\deerflow-frontend-dist-20260927-master-final.zip`。
未连接生产环境进行真实多人模型问答端到端验收,不能宣称所有线上卡顿已被实测消除。
## 8. 关于 20 人同时使用
当前不能承诺 20 人同时问答一定流畅。本次验证了本地代码路径和构建产物,并没有验证你的两台服务器、
上游模型地址/API key 配额、数据库/磁盘及实际技能耗时在 20 路负载下的容量。
部署新版后台、明确开启所需开关后,先在测试环境按 5 → 10 → 20 个独立会话逐级测试:
1. 纯聊天和包含技能读取/写文件的问答分开测试,保持提示长度和输出规模接近真实业务。
2. 每级记录成功/失败/超时数、首字和总耗时的分位数,以及技能 `lock_wait_ms/total_ms`。
3. 同步查看模型端 429/503、排队数量/首 token 延迟,以及应用 CPU、内存、磁盘和数据库等待。
4. 若上游只能并行处理少量请求,应用扩线程无法增加上游容量;应控制并发或扩容模型服务。
20 个在线用户、20 条运行中的问答和 20 个正在模型端生成的请求不是同一指标。
## 9. #185 与 MD 流式追加修复
用户已确认思考模式正常;本节针对仍出现的 #185 和 MD 预览卡住。
- 四个直接流入口统一使用 `STREAM_RENDER_BATCHING=true`,避免安装版本 SDK 的数字 16ms
尾部防抖不断推迟 UI 刷新;保留异步批处理,不改成每个片段同步强制渲染。
- #185 流错误不会再按模型异常直接显示原始错误串;同一轮最多一次自动恢复,重复失败暂停重连,
不主动取消后台任务,不循环重新发送问题。友好提示 30 秒去重。
- 真正渲染/commit 阶段的 #185 由页面错误边界接住,进入静态提示,只能手动重新载入;
不吞其他错误。控制台 `react_ui_render_error` 保留组件堆栈,帮助定位未知的线上循环组件。
- 恢复游标与当前页面的消息累积器绑定:同一页面断线续接不重复拼接工具参数,离开后重新打开或
切换会话则完整重播,不能复用全局旧游标跳过正文前缀;旧 reader 的迟到事件也不污染新页面。
- 后端兼容重复工具名称,避免 `write_filewrite_file` 使工具路由和预览识别失效;
`OPENAI_TOOL_STREAM_SUMMARY repeated_tool_names` 可确认是否命中。也修复了空 `error:{}` 被误判失败。
- 诊断日志写入失败不会覆盖真实模型异常、取消或成功结果。错误脱敏后仍在内存中识别上下文超限,
并识别 `invalid_api_key` 等结构化认证错误,防止本应修剪上下文或停止重试的请求反复排队。
- **实时预览和物理落盘不同**:模型还在生成参数时展示虚拟 MD 内容;参数完整、工具校验通过后,
`write_file` 才正式写沙箱文件。此次不把未完成的 JSON 直接写进最终文件。
本地已经复现并修复上述具体缺陷,但没有线上原始流/组件堆栈,不能保证它们解释全部生产故障。
## 10. `threads` 创建慢:数据库路由与阶段耗时
`POST /api/threads` 会先查/写应用数据库的 `threads_meta`,再调用检查点存储写入空 checkpoint;
它不需要请求模型,也不会在创建时遍历所有旧问答。
当前仓库部署模板是 `database.backend: mysql`,同时 `checkpointer.type: postgres`、
`checkpointer.use_postgres: false`。如果服务器保持这些值且没有 `DEER_FLOW_USE_PG_CHECKPOINTER`
覆盖,实际是 **MySQL 元数据 + SQLite 检查点**,清理 PostgreSQL 不会加速这条链路。
本地开发配置则是 SQLite。线上以实际加载的配置和环境覆盖为准,不凭数据库连接串是否存在判断。
新建/搜索接口新增 `GATEWAY_OPERATION_TIMING` 日志和 `Server-Timing` 响应头,
浏览器 Network 的响应头也能看到,不必先拿服务器日志:
- `metadata_lookup` / `metadata_create`:应用元数据查询/写入。
- `checkpoint_create`:检查点创建,包含 saver 锁/连接池等待和数据库写入,不能等同为纯 SQL 时间。
- `metadata_search`:会话列表的元数据查询。
- `handler_total`:进入处理函数后的耗时;**不含进入函数前的事件循环/鉴权/代理排队**。
模型图构建仍保持原来的任务上下文。新增 `AGENT_BUILD_TIMING`:超过 500ms 以 WARNING 记录,
正常为 DEBUG。已在本地复现同步慢工厂阻塞同事件循环的其他请求,但不能直接裸搬到线程:
延迟工具注册上下文需回传,MCP 初始化存在跨事件循环约束。此处目前是定位日志,不是已经消除阻塞。
本机安装的 SQLite saver 和 PostgreSQL saver 都存在实例级串行锁;后者使用连接池也不代表
同一个 saver 自动并行处理所有检查点。扩大 asyncio 线程池不解除此锁。
尚未取得线上分阶段耗时,因此不能承诺新建 10 秒已经根治,也不能承诺归档即可解决。
新增计时与真实 SQLite 锁测试、已有分析项目/浏览器内部创建入口联合 **43 项通过**,
其中计时专项 14 项;这是本地回归,不是线上延迟验收。
## 11. 30 天已结束会话的 PostgreSQL 归档 SQL
归档脚本单独交付,不进入本源码仓库,也不在启动时执行。使用 `pg_checkpoint_archive.sql` 搬移,
`pg_checkpoint_restore.sql` 按提交批次恢复;两者需与 `pg_checkpoint_common.sql` 放在同一目录。
应用数据库在 MySQL / PostgreSQL 的候选只读导出分别为
`mysql_checkpoint_candidates.sql` / `pg_checkpoint_candidates.sql`。
按用户确认,候选仅包括 30 天未更新、所有运行已结束的会话,排除正在运行、待处理和等待用户输入的会话。
PG 检查点没有应用会话终态字段,因此不能只按 `checkpoint.ts` 猜测,必须先从应用元数据导出候选 ID。
脚本仅在确认实际启用 PG、全部写入服务已停、备份可恢复及双读回退关闭后允许提交。
默认是预览/回滚;提交时三张原始表的全部 namespace 一起搬入新归档 schema,逐行校验后才删源行,
恢复时不覆盖同 ID 的新数据,归档副本保留。不删除沙箱文件。
**范围与风险**:这是 PG 检查点冷归档,不是完整应用归档。它不搬 MySQL `threads_meta/runs`,
因此旧会话列表入口可能仍在,但归档正文需要恢复后才能读取/续聊。归档到同一库的新表也不保证减少总磁盘占用。
SQL 的验证记录与具体执行命令见单独交付包的 README;部署前仍须在生产备份恢复的隔离副本演练。
不要跳过预检直接在生产提交。如果线上仍为 SQLite,这组 PG SQL 不适用。
独立包 `deerflow-db-archive-20260927.zip` 含 SQL、README 和复验测试,不含数据库数据、连接凭据或数据库二进制。
已在 PostgreSQL 16.15 + 安装的 LangGraph checkpoint 3.1.2 原始建表结构上通过 13 项真实执行和 14 项静态检查;
未执行真实 MySQL 候选导出,详见独立包 README。ZIP 共 9 个文件、20,983 字节,SHA-256:
```text
E90A189DA7D7032527EED7CEC9B51DE1A30FB6D48B4382CE06AF1C287B670F59
```
@@ -0,0 +1,73 @@
# 问答停在执行命令或读取技能:排查与修复
日期:2026-09-28。
本次检查针对普通问答和智能体问答:页面停在工具步骤,上游模型没有收到下一轮请求。
以下是代码审查和受控回归确认的触发路径;尚未收到具体生产对话 ID 和现场日志,不能据此认定某次现场故障只有一个根因。
## 已修复的等待路径
| 位置 | 原来的触发条件 | 当前行为 |
| --- | --- | --- |
| LocalSandbox 命令执行 | `subprocess.run` 超时仅终止外层 shell,后代仍持有输出管道;Windows 超时收尾继续无期限 `communicate` | 独立进程组、关闭交互输入、临时文件采集输出;超时清理进程树并限制回收等待 |
| 技能视图刷新 | 进程锁、跨进程文件锁和等待并发校验结果均没有统一等待上限 | 等待最多 30 秒后抛出明确工具错误;不删除正在执行的刷新,不使用未经校验的旧视图 |
| AIO 沙箱 | 上次命令未返回时,后续命令或文件操作无限等待同一把锁 | 锁等待 30 秒后失败;不抢占旧请求的锁,不自动重复执行命令 |
| 文件分段读取 | 超长单行先读完整行才裁剪;FIFO/设备文件可能一直等数据 | 达到当前行输出预算即返回;本地读取用非阻塞打开并检查普通文件,远端分段读取同步限制 |
| 前端结束恢复 | 后端已 success/error,但旧 SSE 仍开着,SDK `isLoading` 一直为真;整段 SSE 期间的 `sendInFlight` 又把同一轮结束快照丢掉 | 核对轮次及运行 ID 后清理重连标记、关闭本地 reader、应用结束快照;不因此取消后端或覆盖新一轮 |
| 前端恢复查询 | `/runs`、检查点或历史请求悬挂,占着 single-flight 恢复槽 | 普通 SDK 请求设置 30 秒超时;恢复失败仍保留后续检查机会,SSE 不受此总时长限制 |
| 后端结束收尾 | 图已返回,但检查点检查、状态写入、日志刷新或标题同步永远不返回,导致 `end` 发不出去 | 终态检查、终态状态写入分别有 10 秒预算;后续元数据收尾共享 10 秒预算,独立 finally 发出 `end` |
技能锁超时走原有工具错误处理链,模型可收到失败结果并决定后续操作;不会把“超时”伪装成成功。
元数据收尾超时只发生在图已经结束后,不给整个研究/子智能体执行增加统一短时限。
终态检查点超时会报告运行失败,不能直接当成模型成功。
## 配置和上线
本次需同时更新后端代码和前端构建产物,重启后端后生效。只刷新页面或调线程数不能替代修复。
本次未操作生产服务、未发布前端包;正式离线发版仍使用独立的 `deerflow-offline-deployment` 仓库。
本地命令保留原来的 600 秒默认执行时限,新版允许在实际加载的配置文件中调整:
```yaml
sandbox:
# 合并到已有 sandbox 段中,保留 use、mounts 等既有字段。
command_timeout_seconds: 600
```
该字段只控制 LocalSandbox 命令执行,必须为有限正数。未配置仍为 600 秒;不要把它误认为模型请求超时。
命令输出每个流最多读入 1 MiB 头尾内容,再经过既有工具输出裁剪。
运行中的命令约每 100ms 检查累计捕获输出,超过 16 MiB 请求终止;这是采样护栏,不是磁盘硬配额。
正常退出后的显式后台进程需要自行重定向输出和管理生命周期。
前端已有的无业务事件检查窗口仍为 90 秒;这是启动后台状态核对的时机,不是宣判任务失败的时限。
30 秒控制请求超时不影响合法的长时间 SSE 和工具执行。
## 仍需现场证据区分的情况
- 磁盘/NFS 本身阻塞的刷新执行者仍可能卡在操作系统 I/O;本次限制的是其他调用的等待,不宣称能终止任意内核 I/O。
- 自定义技能脚本自身请求外部服务不返回,仍会等到本地命令时限;建议技能内各 HTTP 请求也设置连接/读取超时。
- 整个图中的第三方异步工具、模型前中间件和检查点操作没有统一的“无事件即取消”规则,避免误杀合法研究任务。
- 检查点回滚是实际数据修改,保持原有完成/取消语义,不把仍在执行的回滚丢到后台后开放下一轮。
- 已提交给数据库的单条写入未必能被驱动撤销;取消和新轮次检查可阻止旧清理继续发起后续写入,不能保证撤回已经执行的 SQL。
再次出现时,记录对话 ID、运行 ID、最后一步和时间,并对照上游请求日志、运行状态及
`RUN_COMPLETION_TIMEOUT run_id=... phase=terminal_checkpoint|terminal_status|metadata_cleanup`。
技能锁超时会包含 `Timed out waiting for skill view ...`;沙箱命令超时会包含 `Command timed out`。
不要仅凭页面最后显示“读取技能”就断定仍在读文件,它也可能是结束消息没有传到浏览器。
## 回归入口
- 后端 `packages/harness/tests/test_skill_view_waits.py`:锁竞争和并发校验超时、失败后恢复。
- 后端 `packages/harness/tests/test_skill_view_cache.py`、`test_skill_view_tool_reuse.py`:既有启停与缓存安全性。
- 后端 `packages/harness/tests/test_sandbox_command_liveness.py`:真实父子进程、输出、非交互输入及特殊文件/长行。
- 后端 `packages/harness/tests/test_run_completion_timeout.py`:挂起的结束收尾、取消、新一轮隔离及正常长图执行。
- 前端 `src/core/api/control-timeout.test.ts`、`src/core/threads/stream-terminal-recovery.test.ts`:控制请求超时及真实 SDK reader 恢复。
- 前端既有 `stream-recovery`、`stream-display`、`stream-reasoning-replay`、`stream-cursor` 测试继续验证断流重连和消息显示。
## 本机验证结果
- 后端 `python -m pytest packages/harness/tests -q`:**263 passed**。旧同步日志断言补了显式测试配置,避免当前启用异步日志时与后台队列竞速;异步日志仍由独立测试覆盖,未改实际运行配置。
- 前端八个相关测试文件打包后用 Node test runner 执行:**31 passed**;新增测试类型修正后其中三个新增用例再次通过。
- 修改的后端代码和测试通过 Ruff;`git diff --check` 通过。
- 完整前端类型检查未通过:**75 个 TypeScript 错误**,均在本次未修改的文件,涉及 `nextra` 缺失、旧 JSX 类型、既有测试类型等。本次修改文件及新增测试无诊断。详细输出保留在 `frontend-web/.runtime/hang-typecheck.log`(本机文件,不作为发版资产)。
- 命令进程树测试在 Windows 使用真实子进程;Linux 进程组分支已审查,但本机未做 Linux 实跑,AIO 未连接实际容器。未用生产模型调用或真实业务技能执行验证。
+831
View File
@@ -0,0 +1,831 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>数据广场 DataFeed · 仿 Facebook 风格数据展示</title>
<style>
:root{
--fb-blue:#1877f2; --fb-blue-dark:#166fe5; --bg:#f0f2f5;
--card:#fff; --text:#1c1e21; --sub:#65676b; --weak:#8a8d91;
--divider:#e4e6eb; --hover:#f0f2f5; --hover2:#e4e6eb;
--green:#31a24c; --red:#e41e3f; --yellow:#f7b928;
--shadow:0 1px 2px rgba(0,0,0,.2);
}
*{box-sizing:border-box;margin:0;padding:0}
html{scrollbar-gutter:stable}
body{
background:var(--bg);color:var(--text);
font-family:"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",Helvetica,Arial,sans-serif;
font-size:15px;-webkit-font-smoothing:antialiased;
}
a{color:inherit;text-decoration:none}
button{font-family:inherit}
/* ============ 顶部导航(Facebook 蓝条) ============ */
.topbar{
position:fixed;top:0;left:0;right:0;height:56px;z-index:100;
background:var(--fb-blue);display:flex;align-items:center;justify-content:space-between;
padding:0 16px;gap:8px;
}
.tb-left{display:flex;align-items:center;gap:10px;flex:1;min-width:0}
.logo{
width:40px;height:40px;border-radius:50%;flex:none;
background:#fff;color:var(--fb-blue);font-size:22px;font-weight:800;
display:grid;place-items:center;cursor:pointer;
}
.search{position:relative}
.search svg{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--sub);pointer-events:none}
.search input{
width:250px;max-width:44vw;height:40px;border:none;border-radius:20px;outline:none;
background:rgba(255,255,255,.96);padding:0 14px 0 38px;font-size:15px;color:var(--text);
}
.search input::placeholder{color:var(--weak)}
.tb-center{display:flex;gap:4px;flex:none}
.tb-nav{
width:48px;height:48px;border-radius:10px;display:grid;place-items:center;
color:#dfe9fb;position:relative;cursor:pointer;
}
.tb-nav svg{width:26px;height:26px}
.tb-nav:hover,.tb-nav.active{background:rgba(255,255,255,.18);color:#fff}
.tb-right{display:flex;align-items:center;gap:8px;flex:1;justify-content:flex-end}
.icon-btn{
width:40px;height:40px;border-radius:50%;position:relative;flex:none;
background:rgba(255,255,255,.18);display:grid;place-items:center;color:#fff;cursor:pointer;
}
.icon-btn:hover{background:rgba(255,255,255,.28)}
.icon-btn svg{width:22px;height:22px}
.badge{
position:absolute;top:-3px;right:-3px;min-width:18px;height:18px;padding:0 4px;
border-radius:9px;background:var(--red);color:#fff;font-size:11px;font-weight:700;
display:grid;place-items:center;border:2px solid var(--fb-blue);
}
.me{
width:40px;height:40px;border-radius:50%;border:none;flex:none;cursor:pointer;
background:linear-gradient(135deg,#42a5f5,#0d47a1);color:#fff;font-weight:600;font-size:15px;
}
/* ============ 三栏布局 ============ */
.layout{
max-width:1284px;margin:0 auto;display:grid;gap:16px;
grid-template-columns:280px minmax(0,680px) 300px;
padding:72px 12px 40px;align-items:start;
}
.side{position:sticky;top:72px;max-height:calc(100vh - 88px);overflow-y:auto;padding:4px 2px}
.side::-webkit-scrollbar{width:8px}
.side::-webkit-scrollbar-thumb{background:#cfd2d6;border-radius:4px}
.side::-webkit-scrollbar-thumb:hover{background:#b6b9be}
/* ---- 左栏 ---- */
.profile-row{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;cursor:pointer}
.profile-row:hover{background:var(--hover)}
.profile-row b{font-size:15px}
.profile-row .sub{font-size:12.5px;color:var(--sub)}
.menu{margin-top:4px}
.mi{
display:flex;align-items:center;gap:12px;padding:7px 10px;border-radius:8px;
font-weight:600;font-size:15px;cursor:pointer;user-select:none;
}
.mi:hover{background:var(--hover)}
.mi .ic{width:36px;height:36px;border-radius:50%;display:grid;place-items:center;color:var(--fb-blue);flex:none}
.mi .ic svg{width:22px;height:22px}
.mi .cnt{
margin-left:auto;background:#d8dadf;color:var(--text);font-size:12px;font-weight:700;
border-radius:10px;padding:1px 8px;
}
.sq{width:36px;height:36px;border-radius:10px;display:grid;place-items:center;font-size:18px;flex:none}
.sq-blue{background:#e7f3ff}.sq-green{background:#e6f7ea}.sq-orange{background:#fff3d6}.sq-purple{background:#f0e9ff}
.hr{border:none;border-top:1px solid var(--divider);margin:10px 12px}
.side-title{font-weight:700;color:var(--weak);font-size:17px;padding:6px 12px 2px}
.side-foot{font-size:12px;color:var(--weak);padding:12px 12px 4px;line-height:1.7}
/* ---- 通用卡片 / 头像 ---- */
.card{background:var(--card);border-radius:8px;box-shadow:var(--shadow)}
.avatar{
width:40px;height:40px;border-radius:50%;display:grid;place-items:center;
color:#fff;font-weight:600;font-size:15px;flex:none;cursor:pointer;
}
.avatar.sm{width:32px;height:32px;font-size:13px}
.av-blue{background:linear-gradient(135deg,#1877f2,#0c56c0)}
.av-green{background:linear-gradient(135deg,#45bd62,#1a7a3a)}
.av-orange{background:linear-gradient(135deg,#f7a325,#d97b06)}
.av-purple{background:linear-gradient(135deg,#8b5cf6,#5b21b6)}
.av-teal{background:linear-gradient(135deg,#14b8a6,#0f766e)}
.sub{color:var(--sub)}
/* ---- 发布器 ---- */
.composer{padding:12px 16px 10px;margin-bottom:16px}
.composer-top{display:flex;gap:10px;align-items:center}
.composer-top input{
flex:1;height:42px;border-radius:21px;border:none;outline:none;
background:var(--hover);padding:0 16px;font-size:15px;color:var(--text);transition:box-shadow .15s,background .15s;
}
.composer-top input:focus{background:#fff;box-shadow:inset 0 0 0 2px var(--fb-blue)}
.composer-actions{display:flex;border-top:1px solid var(--divider);margin-top:10px;padding-top:6px}
.ca{
flex:1;display:flex;align-items:center;justify-content:center;gap:8px;
padding:9px 4px;border-radius:8px;font-weight:600;font-size:14.5px;color:var(--sub);
cursor:pointer;user-select:none;background:none;border:none;
}
.ca:hover{background:var(--hover)}
.ca svg{width:22px;height:22px}
.ca.c-blue{color:var(--fb-blue)}.ca.c-green{color:var(--green)}.ca.c-orange{color:#f0940a}
/* ---- 数据专题(Stories) ---- */
.stories{display:flex;gap:8px;overflow-x:auto;padding:12px;margin-bottom:16px;scrollbar-width:none}
.stories::-webkit-scrollbar{display:none}
.story{
flex:0 0 110px;height:190px;border-radius:14px;position:relative;overflow:hidden;
cursor:pointer;color:#fff;display:flex;flex-direction:column;justify-content:flex-end;
padding:10px;transition:transform .15s;
}
.story:hover{transform:scale(1.02)}
.story .big{position:absolute;top:44px;left:0;right:0;text-align:center;font-size:40px}
.story .av{position:absolute;top:8px;left:8px;width:30px;height:30px;border-radius:50%;border:2px solid rgba(255,255,255,.9)}
.story .nm{font-size:12.5px;font-weight:700;text-shadow:0 1px 3px rgba(0,0,0,.45);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.story.create{background:#fff;align-items:center;justify-content:flex-start;color:var(--text);padding-top:14px}
.story.create:hover{background:var(--hover)}
.story.create .plus{
width:44px;height:44px;border-radius:50%;background:var(--fb-blue);color:#fff;
display:grid;place-items:center;font-size:26px;font-weight:300;margin-bottom:8px;
}
.story.create span{font-size:13px;font-weight:600}
/* ---- 帖子(数据卡片) ---- */
.post{margin-bottom:16px}
.post-hd{display:flex;align-items:center;gap:10px;padding:12px 16px 0}
.post-hd .meta{min-width:0;flex:1}
.post-hd .meta b{font-size:15px;cursor:pointer}
.post-hd .meta b:hover{text-decoration:underline}
.post-hd .meta .sub{font-size:13px;display:flex;align-items:center;gap:4px}
.post-hd .more{color:var(--sub);cursor:pointer;padding:4px 8px;border-radius:50%;font-weight:700}
.post-hd .more:hover{background:var(--hover)}
.post-txt{padding:10px 16px 12px;line-height:1.55;font-size:15px}
.post-txt a{color:var(--fb-blue);font-weight:600}
.chart-wrap{padding:0 16px}
.chart-head{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;padding:0 16px 6px}
.chart-title{font-size:15px;font-weight:700}
.legend{display:flex;gap:14px;font-size:13px;color:var(--sub);align-items:center;flex-wrap:wrap}
.dot{width:10px;height:10px;border-radius:3px;display:inline-block;margin-right:5px;vertical-align:-1px}
.pills{display:flex;gap:6px}
.pill{
border:none;cursor:pointer;padding:4px 14px;border-radius:20px;
background:var(--hover);color:var(--sub);font-size:13px;font-weight:600;
}
.pill.active{background:#e7f3ff;color:var(--fb-blue)}
.summary{font-size:13px;color:var(--sub);padding:6px 16px 4px}
/* KPI 四宫格 */
.kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;padding:2px 16px 14px}
.kpi{background:#f7f8fa;border:1px solid var(--divider);border-radius:10px;padding:10px 12px}
.kpi .lab{font-size:12.5px;color:var(--sub);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.kpi .num{font-size:20px;font-weight:800;letter-spacing:-.3px;margin:3px 0 2px;white-space:nowrap}
.delta{font-size:12px;font-weight:700;display:inline-flex;align-items:center;gap:2px}
.up{color:var(--green)}.down{color:var(--red)}
.spark{width:100%;height:26px;display:block;margin-top:4px}
/* 柱状图 */
.bars{display:flex;align-items:flex-end;gap:14px;height:175px;padding:0 6px;margin-top:4px}
.bcol{flex:1;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:6px}
.bval{font-size:12px;font-weight:700;color:var(--sub)}
.bar{
width:100%;max-width:44px;border-radius:6px 6px 2px 2px;cursor:pointer;
background:linear-gradient(180deg,#4b95f5,#1877f2);transition:filter .15s;
}
.bar:hover{filter:brightness(1.12)}
.bar.top{background:linear-gradient(180deg,#1877f2,#0a4bb3)}
.bname{font-size:12px;color:var(--sub);white-space:nowrap}
/* 环形图 + 图例 */
.split{display:grid;grid-template-columns:210px 1fr;gap:8px;align-items:center;padding:2px 16px 14px}
.donut{width:180px;height:180px;margin:0 auto;display:block}
.lg-row{display:flex;align-items:center;gap:10px;padding:7px 0;font-size:14px;border-bottom:1px dashed #f0f2f5}
.lg-row:last-child{border-bottom:none}
.lg-row .nm{flex:1}
.lg-row .v{font-weight:700}
.lg-row .pc{color:var(--sub);font-size:13px;width:44px;text-align:right}
/* 表格 */
.tbl-wrap{overflow-x:auto}
.tbl{width:100%;border-collapse:collapse;font-size:14px;min-width:440px}
.tbl th{
text-align:left;font-size:13px;font-weight:600;color:var(--sub);
padding:8px 16px;border-bottom:1px solid var(--divider);white-space:nowrap;
}
.tbl td{padding:10px 16px;border-bottom:1px solid #f0f2f5;white-space:nowrap}
.tbl tr:last-child td{border-bottom:none}
.tbl tbody tr:hover{background:#f7f9fc}
.rank{width:22px;height:22px;border-radius:6px;display:grid;place-items:center;font-size:12px;font-weight:800;color:#fff}
.r1{background:#f7b928}.r2{background:#aeb3ba}.r3{background:#d08a4e}.rx{background:#e4e6eb;color:var(--sub)}
/* 互动条 */
.post-stats{display:flex;align-items:center;justify-content:space-between;padding:10px 16px 6px;color:var(--sub);font-size:14.5px}
.react{
width:20px;height:20px;border-radius:50%;background:#fff;box-shadow:0 0 0 1px var(--divider);
display:inline-grid;place-items:center;font-size:12px;margin-right:5px;vertical-align:-4px;
}
.actions{display:flex;border-top:1px solid var(--divider);padding:4px 6px}
.act{
flex:1;display:flex;align-items:center;justify-content:center;gap:8px;
padding:9px 4px;border-radius:8px;color:var(--sub);font-weight:600;font-size:14.5px;
cursor:pointer;user-select:none;background:none;border:none;
}
.act:hover{background:var(--hover)}
.act svg{width:20px;height:20px}
.act.liked{color:var(--fb-blue)}
/* 评论 */
.comments{padding:2px 16px 14px}
.cmt-more{color:var(--sub);font-size:14px;font-weight:600;padding:4px 0 8px;cursor:pointer}
.cmt-more:hover{text-decoration:underline}
.cmt{display:flex;gap:8px;margin-bottom:10px}
.cmt-bubble{background:var(--hover);border-radius:18px;padding:8px 13px;font-size:14px;line-height:1.45;max-width:100%}
.cmt-name{font-weight:700;font-size:13px;display:block;margin-bottom:1px}
.cmt-meta{font-size:12.5px;color:var(--sub);padding:3px 13px 0;display:flex;gap:8px}
.cmt-meta a{cursor:pointer}
.cmt-meta a:hover{text-decoration:underline;color:var(--text)}
.cmt-input{display:flex;gap:8px;align-items:center;margin-top:4px}
.cmt-input input{
flex:1;height:38px;border-radius:19px;border:none;outline:none;background:var(--hover);
padding:0 14px;font-size:14px;
}
.cmt-input input:focus{background:#fff;box-shadow:inset 0 0 0 2px var(--fb-blue)}
/* ---- 右栏 ---- */
.rc{padding:14px 12px;margin-bottom:16px}
.rc h4{font-size:16.5px;font-weight:700;color:var(--weak);margin:0 4px 8px;letter-spacing:.2px}
.rc-item{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;cursor:pointer}
.rc-item:hover{background:var(--hover)}
.rc-item .tt{font-size:14px;font-weight:600;line-height:1.3}
.rc-item .dd{font-size:12.5px;color:var(--sub)}
.rc-thumb{
width:96px;height:66px;border-radius:8px;flex:none;display:grid;place-items:center;
font-size:26px;color:#fff;
}
.rc-status{width:9px;height:9px;border-radius:50%;flex:none}
.on{background:var(--green)}.off{background:#bcc0c4}.pulse{background:var(--green);animation:pu 1.4s infinite}
@keyframes pu{0%{box-shadow:0 0 0 0 rgba(49,162,76,.5)}70%{box-shadow:0 0 0 7px rgba(49,162,76,0)}100%{box-shadow:0 0 0 0 rgba(49,162,76,0)}}
.rc-row{display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;cursor:pointer}
.rc-row:hover{background:var(--hover)}
.rc-row b{font-size:14.5px;font-weight:600}
.rc-row .sub{font-size:12.5px}
.rc-row .tail{margin-left:auto;font-size:12.5px;color:var(--sub);white-space:nowrap}
/* 空结果 / Toast */
.noresult{display:none;text-align:center;color:var(--sub);padding:40px 0;font-size:15px}
.toast{
position:fixed;left:50%;bottom:28px;transform:translateX(-50%) translateY(90px);
background:#1c1e21;color:#fff;padding:11px 22px;border-radius:10px;font-size:14px;
opacity:0;transition:all .25s;z-index:300;pointer-events:none;box-shadow:0 4px 14px rgba(0,0,0,.3);
}
.toast.show{transform:translateX(-50%);opacity:1}
/* ---- 响应式 ---- */
@media (max-width:1160px){
.layout{grid-template-columns:240px minmax(0,1fr)}
.side-r{display:none}
}
@media (max-width:920px){
.layout{grid-template-columns:minmax(0,1fr);padding-top:64px}
.side-l{display:none}
.tb-center{display:none}
}
@media (max-width:600px){
.kpis{grid-template-columns:repeat(2,1fr)}
.split{grid-template-columns:1fr}
.stories{padding:10px}
.composer-actions .ca span{display:none}
}
</style>
</head>
<body>
<!-- ================= 顶部导航 ================= -->
<header class="topbar">
<div class="tb-left">
<a class="logo" title="DataFeed 数据广场">数</a>
<div class="search">
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><line x1="16.5" y1="16.5" x2="21" y2="21"/></svg>
<input id="globalSearch" type="text" placeholder="搜索数据、指标、报表…" autocomplete="off">
</div>
</div>
<nav class="tb-center">
<a class="tb-nav active" title="首页"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3.1 3 10.2V21h6.2v-6h5.6v6H21V10.2z"/></svg></a>
<a class="tb-nav" title="实时看板"><svg viewBox="0 0 24 24" fill="currentColor"><rect x="2.3" y="5" width="19.4" height="14" rx="4" fill="none" stroke="currentColor" stroke-width="2"/><path d="M10 9.1v5.8L15.4 12z"/></svg></a>
<a class="tb-nav" title="数据集市"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 4h3l2.5 11a1.6 1.6 0 0 0 1.6 1.3h8.2a1.6 1.6 0 0 0 1.6-1.3L21 8H6.2"/><circle cx="10" cy="20" r="1.5" fill="currentColor"/><circle cx="17.2" cy="20" r="1.5" fill="currentColor"/></svg></a>
<a class="tb-nav" title="数据小组"><svg viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="8.6" r="3.3"/><path d="M3 19.2c.5-3.1 3-4.9 6-4.9s5.5 1.8 6 4.9z"/><circle cx="16.9" cy="7.8" r="2.5"/><path d="M15.6 13.7c2.7.2 4.8 1.9 5.3 4.5h-4.4a7 7 0 0 0-.9-4.5z"/></svg></a>
</nav>
<div class="tb-right">
<a class="icon-btn" title="功能菜单"><svg viewBox="0 0 24 24" fill="currentColor"><circle cx="6" cy="6" r="1.9"/><circle cx="12" cy="6" r="1.9"/><circle cx="18" cy="6" r="1.9"/><circle cx="6" cy="12" r="1.9"/><circle cx="12" cy="12" r="1.9"/><circle cx="18" cy="12" r="1.9"/><circle cx="6" cy="18" r="1.9"/><circle cx="12" cy="18" r="1.9"/><circle cx="18" cy="18" r="1.9"/></svg></a>
<a class="icon-btn" title="消息"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.7 3 2.5 6.8 2.5 11.4c0 2.6 1.4 5 3.6 6.6L5.2 22l4.2-2.1c.8.2 1.7.3 2.6.3 5.3 0 9.5-3.8 9.5-8.5S17.3 3 12 3z"/></svg><span class="badge">3</span></a>
<a class="icon-btn" title="通知"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3a5.8 5.8 0 0 0-5.8 5.8v3.6L4.6 15a1 1 0 0 0 .9 1.5h13a1 1 0 0 0 .9-1.5l-1.6-2.6V8.8A5.8 5.8 0 0 0 12 3z"/><path d="M9.8 19a2.3 2.3 0 0 0 4.4 0z"/></svg><span class="badge">5</span></a>
<button class="me" title="张分析 · 数据分析师">张</button>
</div>
</header>
<main class="layout">
<!-- ================= 左栏 ================= -->
<aside class="side side-l">
<div class="profile-row">
<div class="avatar av-blue">张</div>
<div><b>张分析</b><div class="sub">数据分析师 · 增长中心</div></div>
</div>
<nav class="menu">
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3.5" y="3.5" width="7.5" height="7.5" rx="2"/><rect x="13" y="3.5" width="7.5" height="7.5" rx="2"/><rect x="3.5" y="13" width="7.5" height="7.5" rx="2"/><rect x="13" y="13" width="7.5" height="7.5" rx="2"/></svg></span>数据概览</a>
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 13h3.2l2-5.2 3.5 9 2.2-7 1.5 3.2H21"/></svg></span>实时监控<span class="cnt">3</span></a>
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M6 2.5h8L19 8v13.5H6z"/><path d="M14 2.5V8h5M9 12.5h7M9 16h7"/></svg></span>报表中心</a>
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><ellipse cx="12" cy="5.5" rx="7.5" ry="3"/><path d="M4.5 5.5v13c0 1.7 3.4 3 7.5 3s7.5-1.3 7.5-3v-13"/><path d="M4.5 12c0 1.7 3.4 3 7.5 3s7.5-1.3 7.5-3"/></svg></span>数据源管理</a>
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.8l2.6 5.6 6.1.7-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.1l6.1-.7z"/></svg></span>我的收藏</a>
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4.5 6.5h15M9.5 6V4.2A1.2 1.2 0 0 1 10.7 3h2.6a1.2 1.2 0 0 1 1.2 1.2V6"/><path d="M7 6.5l.8 13a1.5 1.5 0 0 0 1.5 1.4h5.4a1.5 1.5 0 0 0 1.5-1.4l.8-13"/></svg></span>回收站</a>
</nav>
<hr class="hr">
<div class="side-title">快捷方式</div>
<nav class="menu">
<a class="mi"><span class="sq sq-blue">🛒</span>电商大促</a>
<a class="mi"><span class="sq sq-green">📈</span>用户增长</a>
<a class="mi"><span class="sq sq-orange">📣</span>营销投放</a>
<a class="mi"><span class="sq sq-purple">🎧</span>客服质量</a>
</nav>
<hr class="hr">
<div class="side-title">我的小组</div>
<nav class="menu">
<a class="mi"><span class="sq sq-blue">👥</span>增长数据组</a>
<a class="mi"><span class="sq sq-green">🧪</span>实验平台组</a>
</nav>
<div class="side-foot">隐私 · 条款 · 广告 · Cookie<br>DataFeed © 2026 · 仿 Facebook 风格演示页</div>
</aside>
<!-- ================= 中间信息流 ================= -->
<section class="feed">
<!-- 发布器(顶部搜索/筛选) -->
<div class="card composer">
<div class="composer-top">
<div class="avatar av-blue">张</div>
<input id="feedFilter" type="text" placeholder="筛选下方数据卡片,如:趋势 / 渠道 / 排行 / KPI…" autocomplete="off">
</div>
<div class="composer-actions">
<button class="ca c-blue" data-toast="演示页面:实时看板未接入"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2.3" y="5" width="19.4" height="14" rx="4"/><path d="M10 9.1v5.8L15.4 12z" fill="currentColor" stroke="none"/></svg><span>实时看板</span></button>
<button class="ca c-green" data-toast="演示页面:导入报表未接入"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="6.5" width="18" height="13.5" rx="3"/><circle cx="12" cy="13" r="3.6"/><path d="M8 6.5 9.3 4h5.4L16 6.5"/></svg><span>导入报表</span></button>
<button class="ca c-orange" data-toast="演示页面:智能分析未接入"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="8.5"/><circle cx="9" cy="10" r="1.1" fill="currentColor" stroke="none"/><circle cx="15" cy="10" r="1.1" fill="currentColor" stroke="none"/><path d="M8.5 14.5c1 1.2 2.1 1.8 3.5 1.8s2.5-.6 3.5-1.8"/></svg><span>智能分析</span></button>
</div>
</div>
<!-- 数据专题(Stories) -->
<div class="card stories" id="stories">
<div class="story create"><div class="plus">+</div><span>创建专题</span></div>
<div class="story" style="background:linear-gradient(165deg,#166fe5,#0a3d91)"><span class="av avatar av-orange">促</span><div class="big">🛒</div><div class="nm">双 11 作战室</div></div>
<div class="story" style="background:linear-gradient(165deg,#f7b928,#dd7d0a)"><span class="av avatar av-blue">渠</span><div class="big">📣</div><div class="nm">渠道复盘</div></div>
<div class="story" style="background:linear-gradient(165deg,#45bd62,#177a37)"><span class="av avatar av-green">像</span><div class="big">👥</div><div class="nm">用户画像</div></div>
<div class="story" style="background:linear-gradient(165deg,#fa383e,#a80f26)"><span class="av avatar av-teal">留</span><div class="big">📈</div><div class="nm">留存专题</div></div>
<div class="story" style="background:linear-gradient(165deg,#8b5cf6,#4c1d95)"><span class="av avatar av-purple">实</span><div class="big">🧪</div><div class="nm">A/B 实验</div></div>
</div>
<!-- 卡片 1:今日核心指标 KPI -->
<article class="card post" data-key="kpi 核心指标 概览 活跃用户 注册 订单 gmv dashboard">
<div class="post-hd">
<div class="avatar av-blue">数</div>
<div class="meta">
<b>数据中心</b>
<div class="sub">12 分钟前 · <svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm-1 5h2v6h-2zm0 8h2v2h-2z" opacity=".9"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm0 18.2c-4.5 0-8.2-3.7-8.2-8.2S7.5 3.8 12 3.8 20.2 7.5 20.2 12 16.5 20.2 12 20.2z"/></svg> 公开</div>
</div>
<span class="more">···</span>
</div>
<div class="post-txt">📊 <b>今日核心指标速览</b>(截至今日 16:00):活跃与 GMV 延续双位数增长,订单量小幅回落,详见 <a>#每日简报</a></div>
<div class="kpis">
<div class="kpi">
<div class="lab">今日活跃用户</div>
<div class="num">42.8 万</div>
<span class="delta up">▲ 12.5%</span>
<svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><polyline points="0,22 14,19 28,21 42,15 56,17 70,11 84,13 100,6" fill="none" stroke="#31a24c" stroke-width="2"/></svg>
</div>
<div class="kpi">
<div class="lab">新增注册</div>
<div class="num">8,642</div>
<span class="delta up">▲ 3.2%</span>
<svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><polyline points="0,20 14,21 28,16 42,17 56,14 70,15 84,9 100,7" fill="none" stroke="#31a24c" stroke-width="2"/></svg>
</div>
<div class="kpi">
<div class="lab">订单量</div>
<div class="num">15,237</div>
<span class="delta down">▼ 2.4%</span>
<svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><polyline points="0,8 14,12 28,10 42,15 56,14 70,18 84,17 100,21" fill="none" stroke="#e41e3f" stroke-width="2"/></svg>
</div>
<div class="kpi">
<div class="lab">GMV(成交总额)</div>
<div class="num">¥382.6 万</div>
<span class="delta up">▲ 8.1%</span>
<svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><polyline points="0,18 14,20 28,16 42,17 56,12 70,14 84,8 100,4" fill="none" stroke="#31a24c" stroke-width="2"/></svg>
</div>
</div>
<div class="post-stats">
<div><span class="react">👍</span><span class="like-num" data-count="1286">1,286</span></div>
<div><span class="cmt-num" data-count="86">86 条评论</span> · <span>42 次分享</span></div>
</div>
<div class="actions">
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
</div>
<div class="comments">
<div class="cmt-more">查看全部 <span class="cmt-total">86</span> 条评论</div>
<div class="cmt">
<div class="avatar av-orange sm">王</div>
<div>
<div class="cmt-bubble"><span class="cmt-name">运营小王</span>GMV 涨势不错,双 11 前继续冲 🚀</div>
<div class="cmt-meta"><a>赞</a><a>回复</a><span>42 分钟前</span></div>
</div>
</div>
<div class="cmt">
<div class="avatar av-blue sm">数</div>
<div>
<div class="cmt-bubble"><span class="cmt-name">数据中心</span>回复<span style="color:var(--fb-blue);font-weight:600">@运营小王</span>:建议同步关注订单量下滑,可能是支付成功率波动</div>
<div class="cmt-meta"><a>赞</a><a>回复</a><span>35 分钟前</span></div>
</div>
</div>
<div class="cmt-input">
<div class="avatar av-blue sm">张</div>
<input type="text" placeholder="撰写评论…(回车发送)">
</div>
</div>
</article>
<!-- 卡片 2:流量趋势折线图 -->
<article class="card post" data-key="趋势 流量 访问 折线 7天 30天 trend">
<div class="post-hd">
<div class="avatar av-green">增</div>
<div class="meta">
<b>增长分析组</b>
<div class="sub">1 小时前 · 内部可见</div>
</div>
<span class="more">···</span>
</div>
<div class="post-txt">📈 <b>平台访问量趋势</b>:今日访问创近期新高,较昨日同期 +22%,大促预热流量开始释放 <a>#流量监控</a></div>
<div class="chart-head">
<div class="legend">
<span><span class="dot" style="background:#1877f2"></span>今日</span>
<span><span class="dot" style="background:#b6bcc4"></span>昨日</span>
</div>
<div class="pills">
<button class="pill active" data-range="7">近 7 天</button>
<button class="pill" data-range="30">近 30 天</button>
</div>
</div>
<div class="chart-wrap">
<svg id="trendSvg" viewBox="0 0 640 264" style="width:100%;height:auto;display:block"></svg>
</div>
<div class="summary" id="trendSummary">单位:万次访问</div>
<div class="post-stats">
<div><span class="react">👍</span><span class="like-num" data-count="642">642</span></div>
<div><span>38 条评论</span> · <span>17 次分享</span></div>
</div>
<div class="actions">
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
</div>
</article>
<!-- 卡片 3:渠道转化率柱状图 -->
<article class="card post" data-key="渠道 转化率 柱状 对比 营销 channel bar">
<div class="post-hd">
<div class="avatar av-orange">营</div>
<div class="meta">
<b>营销实验室</b>
<div class="sub">3 小时前 · 公开</div>
</div>
<span class="more">···</span>
</div>
<div class="post-txt">🎯 <b>各渠道转化率对比</b>(本周 vs 上周):付费广告转化率升至 6.2% 领跑各渠道,邮件营销持续垫底,建议调整预算配比 <a>#渠道分析</a></div>
<div class="chart-head"><div class="chart-title">转化率(%)· 本周</div><div class="legend"><span>最深色为本周最优渠道</span></div></div>
<div class="chart-wrap" style="padding-bottom:14px">
<div class="bars">
<div class="bcol"><span class="bval">4.8</span><div class="bar" style="height:62%" title="自然搜索 4.8%"></div><span class="bname">自然搜索</span></div>
<div class="bcol"><span class="bval">6.2</span><div class="bar top" style="height:80%" title="付费广告 6.2%"></div><span class="bname">付费广告</span></div>
<div class="bcol"><span class="bval">3.9</span><div class="bar" style="height:50%" title="社交媒体 3.9%"></div><span class="bname">社交媒体</span></div>
<div class="bcol"><span class="bval">5.5</span><div class="bar" style="height:71%" title="直接访问 5.5%"></div><span class="bname">直接访问</span></div>
<div class="bcol"><span class="bval">2.1</span><div class="bar" style="height:27%" title="邮件营销 2.1%"></div><span class="bname">邮件营销</span></div>
<div class="bcol"><span class="bval">3.4</span><div class="bar" style="height:44%" title="联盟推广 3.4%"></div><span class="bname">联盟推广</span></div>
</div>
</div>
<div class="post-stats">
<div><span class="react">👍</span><span class="like-num" data-count="318">318</span></div>
<div><span>21 条评论</span> · <span>9 次分享</span></div>
</div>
<div class="actions">
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
</div>
</article>
<!-- 卡片 4:访问来源占比(环形图) -->
<article class="card post" data-key="来源 分布 占比 环形 donut 用户画像">
<div class="post-hd">
<div class="avatar av-teal">像</div>
<div class="meta">
<b>用户画像中心</b>
<div class="sub">5 小时前 · 公开</div>
</div>
<span class="more">···</span>
</div>
<div class="post-txt">🍩 <b>今日访问来源分布</b>:付费广告占比升至 31%(+4pt),自然流量份额被稀释,SEO 侧需要关注 <a>#来源分析</a></div>
<div class="chart-head"><div class="chart-title">访问来源占比 · 今日</div></div>
<div class="split">
<svg class="donut" viewBox="0 0 160 160">
<g transform="rotate(-90 80 80)">
<circle cx="80" cy="80" r="60" fill="none" stroke="#f0f2f5" stroke-width="26"/>
<circle cx="80" cy="80" r="60" fill="none" stroke="#1877f2" stroke-width="26" stroke-dasharray="155.3 377" stroke-dashoffset="0"/>
<circle cx="80" cy="80" r="60" fill="none" stroke="#45bd62" stroke-width="26" stroke-dasharray="113.9 377" stroke-dashoffset="-158.3"/>
<circle cx="80" cy="80" r="60" fill="none" stroke="#f7b928" stroke-width="26" stroke-dasharray="64.9 377" stroke-dashoffset="-275.2"/>
<circle cx="80" cy="80" r="60" fill="none" stroke="#fa383e" stroke-width="26" stroke-dasharray="30.9 377" stroke-dashoffset="-343.1"/>
</g>
<text x="80" y="76" text-anchor="middle" font-size="19" font-weight="700" fill="#1c1e21">128.4万</text>
<text x="80" y="96" text-anchor="middle" font-size="12" fill="#65676b">总访问量</text>
</svg>
<div>
<div class="lg-row"><span class="dot" style="background:#1877f2"></span><span class="nm">自然流量</span><span class="v">53.9 万</span><span class="pc">42%</span></div>
<div class="lg-row"><span class="dot" style="background:#45bd62"></span><span class="nm">付费广告</span><span class="v">39.8 万</span><span class="pc">31%</span></div>
<div class="lg-row"><span class="dot" style="background:#f7b928"></span><span class="nm">社交媒体</span><span class="v">23.1 万</span><span class="pc">18%</span></div>
<div class="lg-row"><span class="dot" style="background:#fa383e"></span><span class="nm">直接访问</span><span class="v">11.6 万</span><span class="pc">9%</span></div>
</div>
</div>
<div class="post-stats">
<div><span class="react">👍</span><span class="like-num" data-count="205">205</span></div>
<div><span>12 条评论</span> · <span>6 次分享</span></div>
</div>
<div class="actions">
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
</div>
</article>
<!-- 卡片 5:热销商品 TOP5 -->
<article class="card post" data-key="商品 排行 榜单 top 销量 销售额 电商 rank table">
<div class="post-hd">
<div class="avatar av-purple">电</div>
<div class="meta">
<b>电商运营组</b>
<div class="sub">8 小时前 · 公开</div>
</div>
<span class="more">···</span>
</div>
<div class="post-txt">🏆 <b>今日热销商品 TOP5</b>:降噪耳机 Pro 稳居榜首,便携榨汁机环比 +24.8% 增速最快 <a>#电商日报</a></div>
<div class="tbl-wrap" style="padding-bottom:8px">
<table class="tbl">
<thead><tr><th>#</th><th>商品</th><th>销量</th><th>销售额</th><th>环比</th></tr></thead>
<tbody>
<tr><td><span class="rank r1">1</span></td><td><b>无线降噪耳机 Pro</b></td><td>3,286 件</td><td>¥482.6 万</td><td class="up" style="color:var(--green);font-weight:700">▲ 18.2%</td></tr>
<tr><td><span class="rank r2">2</span></td><td><b>智能手表 S6</b></td><td>2,941 件</td><td>¥398.2 万</td><td style="color:var(--green);font-weight:700">▲ 9.6%</td></tr>
<tr><td><span class="rank r3">3</span></td><td><b>便携榨汁机</b></td><td>2,733 件</td><td>¥96.3 万</td><td style="color:var(--green);font-weight:700">▲ 24.8%</td></tr>
<tr><td><span class="rank rx">4</span></td><td><b>机械键盘 K87</b></td><td>2,158 件</td><td>¥172.9 万</td><td style="color:var(--red);font-weight:700">▼ 3.1%</td></tr>
<tr><td><span class="rank rx">5</span></td><td><b>桌面升降支架</b></td><td>1,986 件</td><td>¥119.5 万</td><td style="color:var(--green);font-weight:700">▲ 5.4%</td></tr>
</tbody>
</table>
</div>
<div class="post-stats">
<div><span class="react">❤️</span><span class="like-num" data-count="521">521</span></div>
<div><span>45 条评论</span> · <span>28 次分享</span></div>
</div>
<div class="actions">
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
</div>
</article>
<div class="noresult card" id="noResult" style="padding:40px 0">🔍 没有匹配的数据卡片,换个关键词试试(如:趋势 / 渠道 / 排行)</div>
</section>
<!-- ================= 右栏 ================= -->
<aside class="side side-r">
<div class="card rc">
<h4>推荐看板</h4>
<div class="rc-item">
<div class="rc-thumb" style="background:linear-gradient(140deg,#166fe5,#0a3d91)">🛒</div>
<div><div class="tt">双 11 作战室</div><div class="dd">datafeed.cn/board/d11</div></div>
</div>
<div class="rc-item">
<div class="rc-thumb" style="background:linear-gradient(140deg,#f7b928,#dd7d0a)">📣</div>
<div><div class="tt">渠道 ROI 分析</div><div class="dd">datafeed.cn/board/roi</div></div>
</div>
</div>
<div class="card rc">
<h4>数据更新计划</h4>
<div class="rc-row"><span class="rc-status on"></span><div><b>T+1 销售宽表</b><div class="sub">每日 02:00 · 已完成</div></div><span class="tail">2h 前</span></div>
<div class="rc-row"><span class="rc-status on"></span><div><b>用户标签计算</b><div class="sub">每日 03:30 · 已完成</div></div><span class="tail">40m 前</span></div>
<div class="rc-row"><span class="rc-status pulse"></span><div><b>实时埋点流</b><div class="sub">持续写入 · 运行中</div></div><span class="tail" style="color:var(--green);font-weight:700">正常</span></div>
<div class="rc-row"><span class="rc-status off"></span><div><b>周报快照</b><div class="sub">每周一 09:00 · 待执行</div></div><span class="tail">2d 后</span></div>
</div>
<div class="card rc">
<h4>值班分析师</h4>
<div class="rc-row"><div class="avatar sm av-green">李</div><div><b>李雷</b><div class="sub">主值班 · 增长数据</div></div></div>
<div class="rc-row"><div class="avatar sm av-blue">韩</div><div><b>韩梅梅</b><div class="sub">副值班 · 电商数据</div></div></div>
<div class="rc-row"><div class="avatar sm av-orange">陈</div><div><b>陈晨</b><div class="sub">渠道数据 · 离线</div></div></div>
</div>
<div class="card rc">
<h4>你的小组</h4>
<div class="rc-row"><div class="avatar sm av-blue">增</div><div><b>增长数据组</b><div class="sub">12 位成员 · 3 条新动态</div></div></div>
<div class="rc-row"><div class="avatar sm av-green">实</div><div><b>实验平台组</b><div class="sub">8 位成员 · 1 条新动态</div></div></div>
</div>
</aside>
</main>
<div class="toast" id="toast"></div>
<script>
/* ================= 折线图(平滑曲线,Catmull-Rom → 贝塞尔) ================= */
const SVGNS = 'http://www.w3.org/2000/svg';
const PAD = {l:44, r:628, t:16, b:222}; // 640 x 264 绘图区
function smoothPath(pts){
if(pts.length < 2) return '';
let d = `M ${pts[0][0].toFixed(1)} ${pts[0][1].toFixed(1)}`;
for(let i = 0; i < pts.length - 1; i++){
const p0 = pts[Math.max(0, i-1)], p1 = pts[i], p2 = pts[i+1], p3 = pts[Math.min(pts.length-1, i+2)];
const c1x = p1[0] + (p2[0]-p0[0])/6, c1y = p1[1] + (p2[1]-p0[1])/6;
const c2x = p2[0] - (p3[0]-p1[0])/6, c2y = p2[1] - (p3[1]-p1[1])/6;
d += ` C ${c1x.toFixed(1)} ${c1y.toFixed(1)}, ${c2x.toFixed(1)} ${c2y.toFixed(1)}, ${p2[0].toFixed(1)} ${p2[1].toFixed(1)}`;
}
return d;
}
function gen30(){ // 近 30 天(确定性伪随机,演示用)
const labels=[], today=[], yest=[];
for(let i = 29; i >= 0; i--){
const d = new Date(2026, 9, 25 - i);
labels.push(`${d.getMonth()+1}/${d.getDate()}`);
const v = 55 + 16*Math.sin(i/3.4) + 9*Math.cos(i/1.7) + (i%7===6 ? 9 : 0) - (i%7===0 ? 5 : 0);
today.push(Math.round(v*10)/10);
yest.push(Math.round((v - 6 + 4*Math.cos(i/2.2))*10)/10);
}
return {labels, today, yesterday:yest};
}
const DATASETS = {
'7': {labels:['10/19','10/20','10/21','10/22','10/23','10/24','10/25'],
today:[52.4,61.2,58.6,73.1,66.4,81.2,88.5],
yesterday:[48.9,55.3,60.2,64.5,59.1,70.6,72.3]},
'30': gen30()
};
function el(name, attrs){
const n = document.createElementNS(SVGNS, name);
for(const k in attrs) n.setAttribute(k, attrs[k]);
return n;
}
function buildTrend(range){
const ds = DATASETS[range];
const svg = document.getElementById('trendSvg');
svg.innerHTML = '';
const peak = Math.max(...ds.today, ...ds.yesterday);
const step = Math.max(10, Math.ceil(peak/4/5)*5);
const maxT = step*4;
const n = ds.today.length;
const X = i => PAD.l + (PAD.r-PAD.l)*i/(n-1);
const Y = v => PAD.b - (v/maxT)*(PAD.b-PAD.t);
// 渐变
const defs = el('defs');
const grad = el('linearGradient', {id:'gBlue', x1:0, y1:0, x2:0, y2:1});
grad.appendChild(el('stop', {offset:'0%', 'stop-color':'#1877f2', 'stop-opacity':.22}));
grad.appendChild(el('stop', {offset:'100%', 'stop-color':'#1877f2', 'stop-opacity':0}));
defs.appendChild(grad); svg.appendChild(defs);
// 网格 + Y 轴刻度
for(let i = 0; i <= 4; i++){
const v = step*i, y = Y(v);
svg.appendChild(el('line', {x1:PAD.l, x2:PAD.r, y1:y, y2:y, stroke:'#e4e6eb', 'stroke-dasharray': i? '3 5' : '0'}));
const t = el('text', {x:PAD.l-8, y:y+4, 'text-anchor':'end', 'font-size':11, fill:'#8a8d91'});
t.textContent = v; svg.appendChild(t);
}
const pt = arr => arr.map((v,i)=>[X(i), Y(v)]);
const pToday = pt(ds.today), pYest = pt(ds.yesterday);
// 面积(今日)
const area = smoothPath(pToday) + ` L ${pToday[n-1][0]} ${PAD.b} L ${pToday[0][0]} ${PAD.b} Z`;
svg.appendChild(el('path', {d:area, fill:'url(#gBlue)'}));
// 昨日(灰虚线)
svg.appendChild(el('path', {d:smoothPath(pYest), fill:'none', stroke:'#b6bcc4', 'stroke-width':2, 'stroke-dasharray':'5 6'}));
// 今日(蓝)
svg.appendChild(el('path', {d:smoothPath(pToday), fill:'none', stroke:'#1877f2', 'stroke-width':3, 'stroke-linecap':'round'}));
// 端点
svg.appendChild(el('circle', {cx:pToday[n-1][0], cy:pToday[n-1][1], r:4.5, fill:'#1877f2', stroke:'#fff', 'stroke-width':2}));
// X 轴标签 & 悬停提示
const labelStep = Math.max(1, Math.ceil(n/7));
for(let i = 0; i < n; i++){
if(n <= 8){
svg.appendChild(el('circle', {cx:X(i), cy:Y(ds.today[i]), r:2.6, fill:'#1877f2'}));
}
const hit = el('circle', {cx:X(i), cy:Y(ds.today[i]), r:11, fill:'transparent', style:'cursor:pointer'});
const ti = el('title'); ti.textContent = `${ds.labels[i]} · 今日 ${ds.today[i]} 万 / 昨日 ${ds.yesterday[i]} 万`;
hit.appendChild(ti); svg.appendChild(hit);
if(i % labelStep === 0 || i === n-1){
const t = el('text', {x:X(i), y:244, 'text-anchor':'middle', 'font-size':11, fill:'#8a8d91'});
t.textContent = ds.labels[i]; svg.appendChild(t);
}
}
const mx = Math.max(...ds.today), mn = Math.min(...ds.today);
const avg = (ds.today.reduce((a,b)=>a+b,0)/n).toFixed(1);
document.getElementById('trendSummary').textContent =
`单位:万次访问 · 峰值 ${mx} 万 · 谷值 ${mn} 万 · 均值 ${avg} 万`;
}
buildTrend('7');
document.querySelectorAll('.pill[data-range]').forEach(p => {
p.addEventListener('click', () => {
document.querySelectorAll('.pill[data-range]').forEach(x => x.classList.remove('active'));
p.classList.add('active');
buildTrend(p.dataset.range);
});
});
/* ================= 点赞 ================= */
document.querySelectorAll('.act-like').forEach(btn => {
btn.addEventListener('click', () => {
const post = btn.closest('.post');
const num = post.querySelector('.like-num');
const on = btn.classList.toggle('liked');
num.dataset.count = +num.dataset.count + (on ? 1 : -1);
const c = +num.dataset.count;
num.textContent = c >= 1000 ? (c/1000).toFixed(1).replace(/\.0$/,'') + 'k' : c.toLocaleString('zh-CN');
});
});
/* ================= 评论(回车发送) ================= */
const cmtInput = document.querySelector('.cmt-input input');
cmtInput.addEventListener('keydown', e => {
if(e.key !== 'Enter' || !e.target.value.trim()) return;
const post = e.target.closest('.post');
const wrap = e.target.closest('.comments');
const txt = e.target.value.trim();
e.target.value = '';
const div = document.createElement('div');
div.className = 'cmt';
div.innerHTML = `<div class="avatar av-blue sm">张</div>
<div><div class="cmt-bubble"><span class="cmt-name">张分析</span>${txt.replace(/</g,'&lt;')}</div>
<div class="cmt-meta"><a>赞</a><a>回复</a><span>刚刚</span></div></div>`;
wrap.insertBefore(div, e.target.closest('.cmt-input'));
const cn = post.querySelector('.cmt-num'), total = post.querySelector('.cmt-total');
cn.dataset.count = +cn.dataset.count + 1;
cn.textContent = cn.dataset.count + ' 条评论';
total.textContent = cn.dataset.count;
});
document.querySelectorAll('.act-comment').forEach(btn => {
btn.addEventListener('click', () => {
const input = btn.closest('.post').querySelector('.cmt-input input');
if(input){ input.focus(); } else { showToast('该卡片暂未开放评论(演示)'); }
});
});
/* ================= 分享 / 演示按钮 Toast ================= */
const toast = document.getElementById('toast');
let toastTimer;
function showToast(msg){
toast.textContent = msg;
toast.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove('show'), 1800);
}
document.querySelectorAll('.act-share').forEach(b => b.addEventListener('click', () => showToast('看板链接已复制(演示)')));
document.querySelectorAll('[data-toast]').forEach(b => b.addEventListener('click', () => showToast(b.dataset.toast)));
document.querySelectorAll('.story').forEach(s => s.addEventListener('click', () => showToast('演示页面:数据专题未接入')));
/* ================= 搜索 / 筛选(顶栏 + 发布器共用) ================= */
function filterPosts(q){
q = q.trim().toLowerCase();
let visible = 0;
document.querySelectorAll('.feed .post').forEach(p => {
const hit = !q || (p.dataset.key + ' ' + p.textContent).toLowerCase().includes(q);
p.style.display = hit ? '' : 'none';
if(hit) visible++;
});
document.getElementById('noResult').style.display = visible ? 'none' : 'block';
}
['globalSearch','feedFilter'].forEach(id => {
document.getElementById(id).addEventListener('input', e => {
filterPosts(e.target.value);
if(id === 'globalSearch'){ const f = document.getElementById('feedFilter'); if(f.value !== e.target.value) f.value = e.target.value; }
else { const g = document.getElementById('globalSearch'); if(g.value !== e.target.value) g.value = e.target.value; }
});
});
/* ================= 顶部导航高亮 ================= */
document.querySelectorAll('.tb-nav').forEach(n => {
n.addEventListener('click', () => {
document.querySelectorAll('.tb-nav').forEach(x => x.classList.remove('active'));
n.classList.add('active');
});
});
</script>
</body>
</html>
+59
View File
@@ -0,0 +1,59 @@
# 本地开发(pnpm dev)— 与原先 .env 保持一致
# 个人覆盖请新建 .env.development.local(已 gitignore,优先级更高)
# 任务看板数据源:true=真实接口(默认);改成 false 可让任务分析/三情分析两页走本地假数据。
VITE_USE_REAL_DATA=true
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(consumer 外网不可达时调试用)。
VITE_MOCK_COP_TASK_DETAIL=true
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:true 走本地样例假数据(真实接口未就绪时调试用);联调通过后置 false。
VITE_MOCK_SQ_REPORT=false
# 深链任务详情(cop-task-detail:任务名称/描述)数据源:true 走本地假数据(真实接口未就绪时调试用);联调通过后置 false。
VITE_MOCK_COP_TASK_DETAIL=true
# Gateway / DeerFlow API
VITE_BACKEND_BASE_URL=http://127.0.0.1:8001
VITE_LANGGRAPH_BASE_URL=http://127.0.0.1:8001/api
# 开发环境普通登录后进入 Vite 内隔离的官方风格页面;/page/* 仍访问当前定制版。
VITE_USE_OFFICIAL_DEERFLOW_ENTRY=false
# 轻应用「新建笔记」系列接口
VITE_NOTE_API_BASE_URL=http://47.88.25.99:8000
# CMZS后端接口
VITE_API_BASE_URL=https://ch1.b.uat.4.cn/zncm
# 佳来模型对话接口
VITE_AIPI_CHAT_URL=https://ch1.b.uat.4.cn/gpt
# 多轮检索接口
VITE_AIPI_GENERATE_CHAT_URL=https://ch1.b.uat.4.cn/jialai_b1_chat
VITE_AIPI_TASK_CHAT_URL=https://ch1.b.uat.4.cn/qq_b1_chat
VITE_AIPI_KNOWLEDGE_URL=https://chlib.b.uat.4.cn/knowlibrary
VITE_AIPI_B1COH_URL=https://ch1.b.uat.4.cn/web
VITE_AIPI_B2ACTOR_URL=https://ty.b.uat.4.cn
VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
VITE_AIPI_MOPECHAT_URL=https://ch1.b.uat.4.cn/likun_b1_mope
VITE_AIPI_BACKENP_URL=http://47.88.25.99:8000
# 工作室/空间后端接口(侧边栏“工作室”列表、空间详情等都走这里,不是 VITE_NOTE_API_BASE_URL)
# 工作室/空间前端地址(用于 auth/callback 等跳转)
# VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.uat.4.cn
VITE_AIPI_FRONTEND_URL=http://localhost:3000
VITE_AIPI_CONSUMER_URL=https://ch1.b.uat.4.cn/consumer
# A 系统跳转地址(人物/组织/事件等列表项打开链接)
VITE_AIPI_PRESENT_URL=https://present.a.uat.4.cn/present/domain
# B 系统知识库 iframe 根地址
VITE_AIPI_KNOWES_URL=https://ch1.b.uat.4.cn/knowes
# MaxKey 鉴权(getTokenByOnlineTicket)
VITE_AUTH_BASE_URL=https://auth.y.sit.4.cn
VITE_AIPI_PGLINKTO_URL=https://pg.b.uat.4.cn
VITE_AIPI_XKLINKTO_URL=https://kz.b.uat.4.cn
# 可选:Canvas 独立 LangGraph 地址(不设则回退到 VITE_LANGGRAPH_BASE_URL)
# VITE_CANVAS_LANGGRAPH_BASE_URL=
@@ -0,0 +1,31 @@
# 复制为 .env.development.local,仅本机生效,不提交 Git
# 直连本机 Gateway(需后端 CORS_ORIGINS 包含 http://127.0.0.1:5173 等)
VITE_BACKEND_BASE_URL=http://127.0.0.1:8001
VITE_LANGGRAPH_BASE_URL=http://127.0.0.1:8001/api
# 佳来模型对话接口
VITE_AIPI_CHAT_URL=https://ch1.b.uat.4.cn/gpt
# 多轮检索接口
VITE_AIPI_GENERATE_CHAT_URL=https://ch1.b.uat.4.cn/jialai_b1_chat
VITE_AIPI_TASK_CHAT_URL=https://ch1.b.uat.4.cn/qq_b1_chat
VITE_AIPI_KNOWLEDGE_URL=https://chlib.b.uat.4.cn/knowlibrary
VITE_AIPI_B1COH_URL=https://ch1.b.uat.4.cn/web
VITE_AIPI_B2ACTOR_URL=https://ty.b.uat.4.cn
VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
VITE_AIPI_MOPECHAT_URL=https://ch1.b.uat.4.cn/likun_b1_mope
# 工作室/空间后端接口(侧边栏“工作室”列表、空间详情等都走这里,不是 VITE_NOTE_API_BASE_URL)
VITE_AIPI_BACKENP_URL=https://knowledgetoolserver.b.uat.4.cn
# 工作室/空间前端地址(用于 auth/callback 等跳转)
VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.uat.4.cn
VITE_AIPI_CONSUMER_URL=https://ch1.b.uat.4.cn/consumer
# A 系统跳转地址(人物/组织/事件等列表项打开链接)
VITE_AIPI_PRESENT_URL=http://present.a.uat.4.cn/present/domain
# B 系统知识库 iframe 根地址
VITE_AIPI_KNOWES_URL=http://ch1.b.uat.4.cn/knowes
VITE_AUTH_BASE_URL=https://auth.y.sit.4.cn
VITE_AIPI_PGLINKTO_URL=https://pg.b.uat.4.cn
VITE_AIPI_XKLINKTO_URL=https://kz.b.uat.4.cn
# VITE_NOTE_API_BASE_URL=http://127.0.0.1:8000
+70 -5
View File
@@ -1,6 +1,71 @@
# 复制为 .env 后按需修改(Vite 仅暴露以 VITE_ 开头的变量)
# 直连本机 Gateway 时使用;若浏览器报 CORS,请在网关环境设置 CORS_ORIGINS,包含前端源站,例如:
# CORS_ORIGINS=http://127.0.0.1:5173,http://localhost:5173
# 环境变量说明(Vite 仅暴露以 VITE_ 开头的变量)
#
# ┌─────────────────┬──────────────────────────────────────────────────┐
# │ 命令 │ 生效文件 │
# ├─────────────────┼──────────────────────────────────────────────────┤
# │ pnpm dev │ .env.development + .env.development.local │
# │ pnpm build │ .env.production + .env.production.local │
# │ pnpm build:network │ .env.network + .env.network.local(内网地址) │
# │ scripts/start-* │ 脚本注入的环境变量会覆盖上述文件(见下方说明) │
# └─────────────────┴──────────────────────────────────────────────────┘
#
# 推荐:
# - 日常本地开发:改 .env.development(已提交,团队默认 UAT 地址)
# - 本机连 127.0.0.1:8001:复制 .env.development.local.example → .env.development.local
# - 内网打包部署:改 .env.network 后执行 pnpm build:network(或改 .env.production 后 pnpm build)
#
# 若浏览器直连后端报 CORS,请在 Gateway 配置 GATEWAY_CORS_ORIGINS,包含前端源站;无界嵌入时还要加宿主源站,例如:
# GATEWAY_CORS_ORIGINS=http://127.0.0.1:5174,http://localhost:5174,http://127.0.0.1:5183,http://localhost:5183
VITE_BACKEND_BASE_URL=http://127.0.0.1:8001
VITE_LANGGRAPH_BASE_URL=http://127.0.0.1:8001/api
# --- 开发环境(见 .env.development)---
# VITE_BACKEND_BASE_URL=https://ch1.b.uat.4.cn/deerflow
# VITE_LANGGRAPH_BASE_URL=https://ch1.b.uat.4.cn/deerflow/api
# VITE_NOTE_API_BASE_URL=http://47.88.25.99:8000
# VITE_AIPI_BACKENP_URL=https://knowledgetoolserver.b.uat.4.cn
# VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.uat.4.cn
# --- 生产打包(见 .env.production)---
# 部署前修改 .env.production 中的地址,再执行 pnpm build
# --- 任务看板(任务分析 / 三情分析)数据源开关 ---
# true=走真实接口;false 或未设=这两页使用本地假数据(演示用,无需后端)。
# .env.development / .env.production / .env.network / .env.sit 均默认 true(真实数据),
# 仅本机 .env 默认 false(假数据)。改后需重启 dev / 重新打包生效。
# VITE_USE_REAL_DATA=true
# --- 任务详情(登录深链 cop-task-detail)数据源开关 ---
# 默认真实接口(未设/false);改成 true 时该接口走本地假数据(consumer 外网不可达时调试用)。
# 与 VITE_USE_REAL_DATA 独立。改后需重启 dev / 重新打包生效。
# VITE_MOCK_COP_TASK_DETAIL=false
# VITE_POSITION_ROUNDTABLE_DEMO_MODE=false
# true=免登录直达岗位分析,完全使用前端 JSON,不请求任何后台接口。
# 仅限离线演示环境;生产环境请保持 false。
# VITE_POSITION_ROUNDTABLE_STANDALONE_MODE=false
# MaxKey 鉴权根地址(无界 onlineTicket 换 token)
# VITE_AUTH_BASE_URL=https://auth.y.sit.4.cn
# VITE_AIPI_CONSUMER_URL=https://ch1.b.uat.4.cn/consumer
# VITE_AIPI_B2ACTOR_URL=https://ty.b.uat.4.cn
# VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
# VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl
# VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
# 可选
# VITE_CANVAS_LANGGRAPH_BASE_URL=
# VITE_STATIC_WEBSITE_ONLY=
# 部署级紧凑导航:true 时固定收起工作台左侧栏,并隐藏换肤与全量/简洁模式切换。
# VITE_FORCE_COLLAPSED_SIDEBAR=false
# 简介模式左侧菜单类型:与菜单管理页「简介模式」的类型 A / B 对应。两套网页分别填 A 或 B。
# 不填或留空时按类型 A,继续使用原来的简介菜单数据。
# VITE_COMPACT_MENU_TYPE=A
# 问答页「极速」模式:true=在模式菜单显示并直连大模型;false 或未设=隐藏。
# 部署后优先改 dist/runtime-config.js 的 VITE_TURBO_MODE_VISIBLE,刷新即可。
# VITE_TURBO_MODE_VISIBLE=false
# VITE_GITHUB_OAUTH_TOKEN=
# --- 官方 DeerFlow 风格页面入口(仅 Vite,不引入 Next.js)---
# true 时,普通登录后进入同一 Vite 应用中隔离的 /official/*。
# 已指定 redirect 或 taskId/goPath 的登录仍保持原来的优先级。
# 仅 .env.development 默认 true;其余环境保持 false。
# VITE_USE_OFFICIAL_DEERFLOW_ENTRY=false
+60
View File
@@ -0,0 +1,60 @@
# 本地开发(pnpm dev)— 与原先 .env 保持一致
# 个人覆盖请新建 .env.development.local(已 gitignore,优先级更高)
# 任务看板数据源:true=真实接口(默认);改成 false 可让任务分析/三情分析两页走本地假数据。
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://10.19.200.5:2026
VITE_LANGGRAPH_BASE_URL=http://10.19.200.5:2026/api
# 内网环境保持当前定制版默认入口。
VITE_USE_OFFICIAL_DEERFLOW_ENTRY=false
# 轻应用「新建笔记」系列接口
VITE_NOTE_API_BASE_URL=http://47.88.25.99:8000
# CMZS后端接口
VITE_API_BASE_URL=https://ch1.b.uat.4.cn/zncm
# 佳来模型对话接口
VITE_AIPI_CHAT_URL=https://ch1.b.uat.4.cn/gpt
# 多轮检索接口
VITE_AIPI_GENERATE_CHAT_URL=https://ch1.b.uat.4.cn/jialai_b1_chat
VITE_AIPI_TASK_CHAT_URL=https://ch1.b.uat.4.cn/qq_b1_chat
VITE_AIPI_KNOWLEDGE_URL=https://chlib.b.uat.4.cn/knowlibrary
VITE_AIPI_B1COH_URL=https://ch1.b.uat.4.cn/web
VITE_AIPI_B2ACTOR_URL=https://ty.b.uat.4.cn
VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
VITE_AIPI_MOPECHAT_URL=https://ch1.b.uat.4.cn/likun_b1_mope
VITE_AIPI_BACKENP_URL=http://47.88.25.99:8000
# 工作室/空间后端接口(侧边栏“工作室”列表、空间详情等都走这里,不是 VITE_NOTE_API_BASE_URL)
# 工作室/空间前端地址(用于 auth/callback 等跳转)
# VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.uat.4.cn
VITE_NOTEBOOK_API_BASE_URL=http://47.88.25.99:8000
VITE_AIPI_FRONTEND_URL=http://47.88.25.99:3000
VITE_AIPI_CONSUMER_URL=http://10.19.200.5:8002/consumer
# A 系统跳转地址(人物/组织/事件等列表项打开链接)
VITE_AIPI_PRESENT_URL=http://present.a.uat.4.cn/present/domain
# B 系统知识库 iframe 根地址
VITE_AIPI_KNOWES_URL=http://ch1.b.uat.4.cn/knowes
# MaxKey 鉴权(getTokenByOnlineTicket)
VITE_AUTH_BASE_URL=https://auth.y.sit.4.cn
VITE_AIPI_PGLINKTO_URL=https://pg.b.uat.4.cn
VITE_AIPI_XKLINKTO_URL=https://kz.b.uat.4.cn
# 可选:Canvas 独立 LangGraph 地址(不设则回退到 VITE_LANGGRAPH_BASE_URL)
# VITE_CANVAS_LANGGRAPH_BASE_URL=
+53
View File
@@ -0,0 +1,53 @@
# 生产打包(pnpm build)— 部署前请改成实际内网/生产地址
# 打包后变量会写入 dist,运行时不可再改
# 任务看板数据源:true=真实接口(默认);改成 false 可让任务分析/三情分析两页走本地假数据。
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
# 线上保持当前定制版默认入口。
VITE_USE_OFFICIAL_DEERFLOW_ENTRY=false
# 轻应用「新建笔记」系列接口
VITE_NOTE_API_BASE_URL=https://your-intranet-host/note-api
# CMZS后端接口
VITE_API_BASE_URL=https://ch1.b.uat.4.cn/zncm
# 佳来模型对话接口
VITE_AIPI_CHAT_URL=https://ch1.b.uat.4.cn/gpt
# 多轮检索接口
VITE_AIPI_GENERATE_CHAT_URL=https://ch1.b.uat.4.cn/jialai_b1_chat
VITE_AIPI_TASK_CHAT_URL=https://ch1.b.uat.4.cn/qq_b1_chat
VITE_AIPI_KNOWLEDGE_URL=https://chlib.b.uat.4.cn/knowlibrary
VITE_AIPI_B1COH_URL=https://ch1.b.uat.4.cn/web
VITE_AIPI_B2ACTOR_URL=https://ty.b.uat.4.cn
VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
VITE_AIPI_MOPECHAT_URL=https://ch1.b.uat.4.cn/likun_b1_mope
# 工作室/空间后端接口(侧边栏“工作室”列表、空间详情等都走这里,不是 VITE_NOTE_API_BASE_URL)
VITE_AIPI_BACKENP_URL=https://knowledgetoolserver.b.uat.4.cn
# 我的空间前端
VITE_AIPI_FRONTEND_URL= https://knowledgetoolweb.b.uat.4.cn
VITE_AIPI_CONSUMER_URL=https://ch1.b.uat.4.cn/consumer
# A 系统跳转地址(人物/组织/事件等列表项打开链接)
VITE_AIPI_PRESENT_URL=https://present.a.uat.4.cn/present/domain
# B 系统知识库 iframe 根地址
VITE_AIPI_KNOWES_URL=https://ch1.b.uat.4.cn/knowes
# MaxKey 鉴权(getTokenByOnlineTicket)
VITE_AUTH_BASE_URL=https://auth.y.uat.4.cn
VITE_AIPI_PGLINKTO_URL=https://pg.b.uat.4.cn
VITE_AIPI_XKLINKTO_URL=https://kz.b.uat.4.cn
# 工作室/空间前端地址(用于 auth/callback 等跳转)
VITE_AIPI_FRONTEND_URL=https://knowledgetoolweb.b.uat.4.cn
# 可选:Canvas 独立 LangGraph 地址
# VITE_CANVAS_LANGGRAPH_BASE_URL=
@@ -0,0 +1,7 @@
# 复制为 .env.production.local,打包前临时覆盖生产地址(不提交 Git)
# VITE_BACKEND_BASE_URL=https://your-intranet-host/deerflow
# VITE_LANGGRAPH_BASE_URL=https://your-intranet-host/deerflow/api
# VITE_NOTE_API_BASE_URL=https://your-intranet-host/note-api
# VITE_AIPI_BACKENP_URL=https://your-notebook-backend-host
# VITE_AIPI_FRONTEND_URL=https://your-notebook-frontend-host
+59
View File
@@ -0,0 +1,59 @@
# SIT 环境打包(pnpm build:sit / npm run build:sit)— 接口地址为 UAT 的 sit 版本
# 打包后变量会写入 dist,运行时不可再改
# 任务看板数据源:true=真实接口(默认);改成 false 可让任务分析/三情分析两页走本地假数据。
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
# SIT 环境保持当前定制版默认入口。
VITE_USE_OFFICIAL_DEERFLOW_ENTRY=false
# 轻应用「新建笔记」系列接口
VITE_NOTE_API_BASE_URL=https://your-intranet-host/note-api
# CMZS后端接口
VITE_API_BASE_URL=https://ch1.b.sit.4.cn/zncm
# 佳来模型对话接口
VITE_AIPI_CHAT_URL=https://ch1.b.sit.4.cn/gpt
# 多轮检索接口
VITE_AIPI_GENERATE_CHAT_URL=https://ch1.b.sit.4.cn/jialai_b1_chat
VITE_AIPI_TASK_CHAT_URL=https://ch1.b.sit.4.cn/qq_b1_chat
VITE_AIPI_KNOWLEDGE_URL=https://chlib.b.sit.4.cn/knowlibrary
VITE_AIPI_B1COH_URL=https://ch1.b.sit.4.cn/web
VITE_AIPI_B2ACTOR_URL=https://ty.b.sit.4.cn
VITE_AIPI_B2ACTOR_XWT_PATH=/fromB/toXWT?isFrame=1
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL=https://ch1.b.sit.4.cn/knowes/api/iframeKnowledgeUrl
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN=red
VITE_AIPI_MOPECHAT_URL=https://ch1.b.sit.4.cn/likun_b1_mope
# 工作室/空间后端接口(侧边栏“工作室”列表、空间详情等都走这里,不是 VITE_NOTE_API_BASE_URL)
VITE_AIPI_BACKENP_URL=https://knowledgetoolserver.b.sit.4.cn
VITE_NOTEBOOK_API_BASE_URL=https://knowledgetoolserver.b.sit.4.cn
# 工作室侧边栏显示开关;仅控制入口显示,展开内容仍依赖 notebook 接口成功返回数据
VITE_STUDIO_ENABLED=true
# 工作室/笔记本前端地址(用于 auth/callback 等跳转)
VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.sit.4.cn
VITE_AIPI_CONSUMER_URL=https://ch1.b.sit.4.cn/consumer
# A 系统跳转地址(人物/组织/事件等列表项打开链接)
VITE_AIPI_PRESENT_URL=http://present.a.sit.4.cn/present/domain
# B 系统知识库 iframe 根地址
VITE_AIPI_KNOWES_URL=https://ch1.b.sit.4.cn/knowes
# MaxKey 鉴权(getTokenByOnlineTicket)
VITE_AUTH_BASE_URL=https://auth.y.sit.4.cn
VITE_AIPI_PGLINKTO_URL=https://pg.b.sit.4.cn
VITE_AIPI_XKLINKTO_URL=https://kz.b.sit.4.cn
# 工作室/空间前端地址(用于 auth/callback 等跳转)
VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.sit.4.cn
# 可选:Canvas 独立 LangGraph 地址
# VITE_CANVAS_LANGGRAPH_BASE_URL=
+46
View File
@@ -0,0 +1,46 @@
**Comparison target**
- Source visual truth (dark intelligent-agent list): `C:/Users/董宏凯/AppData/Local/Temp/codex-clipboard-75f6ce1c-cd70-4b8c-a80a-a3d100105c69.png`
- Additional source references: `C:/Users/董宏凯/AppData/Local/Temp/codex-clipboard-00567484-ba8a-4595-b386-52e1467ae9cf.png` (segmented switch), `C:/Users/董宏凯/AppData/Local/Temp/codex-clipboard-02808803-05ba-4f2c-be50-c72b484a9f06.png` (business-chain node card), `C:/Users/董宏凯/AppData/Local/Temp/codex-clipboard-adf38fec-7baf-4d01-9c73-bdbae94b774e.png` (business-chain selector)
- Implementation screenshots: `C:/Users/董宏凯/AppData/Local/Temp/position-roundtable-revised-light.png`, `C:/Users/董宏凯/AppData/Local/Temp/position-roundtable-revised-dark.png`
- Full-view comparison evidence: `C:/Users/董宏凯/AppData/Local/Temp/position-roundtable-revised-comparison.png`
- Viewport: 1280 × 720. Light route: `#/page/strategy/qa/position-roundtable`; dark embedded route: `#/page/strategy/qa/position-roundtable?embed=1&theme=dark`.
- State: local browser has no authenticated API session. The original intent API is invoked and reports `Authentication required`; business-chain and agent endpoints return no usable data.
**Findings**
- [P1] Populated agent and business-chain states cannot be compared yet.
Location: right agent list and non-planning-role chain diagram.
Evidence: reference images show populated cards and nodes; the implementation has `0 个` agents and no available business chain in the unauthenticated preview.
Impact: card density, selected-card indicator, chain node flow, and agent-detail transition cannot be truthfully verified against live data.
Fix: verify the route in an authenticated session with at least one public chain and tagged agents.
**Open Questions**
- The final business-chain stage arrangement is still pending product confirmation. The compact graph maps whatever stage configuration is returned, while intentionally omitting dependency-label text as requested.
**Implementation Checklist**
1. Left task panel is now display-only and retains its independent position-roundtable task adapter.
2. Business-chain selection uses the original roundtable card/radio/relationship-entry pattern.
3. Every position uses the original `useStep1Intent` interface and `Step1Panel` message list/input panel; only the position header changes.
4. The right switch now uses the exact `课题研究 / ai写作` segmented-control treatment (light gray track, white active state; dark blue glass equivalent).
5. The embedded layout widens the left panel to 360px and applies the deep-blue right-panel tokens used by the reference.
6. Other roles render a taller top-to-bottom card-node flow without dependency labels. The canvas supports mouse-drag panning, and each node retains only a name plus a single-line description.
**Follow-up Polish**
- [P3] If live content is unusually long, tune the compact flow node width or horizontal scrolling after seeing the production chain data.
**Comparison history**
- Iteration 1: task fields were editable and the right TDesign card tabs looked unlike the reference. Replaced the task form with display-only information and replaced the tabs with the existing `课题研究 / ai写作` segmented switch.
- Iteration 2: business-chain selection was a dropdown and the flow was vertical avatar chips. Replaced it with original-roundtable selection cards and compact business-chain configuration-style node cards with link lines but no dependency labels.
- Iteration 3: dark right-panel background differed from the supplied deep-blue reference. Applied the `#032650` / `#042b59` / `#2b8ffe` token family and captured the revised embedded dark state in the full-view comparison.
- Iteration 4: removed the custom disabled input from non-planning positions and reused the original roundtable input panel. Enlarged the left flow viewport, retained its connection lines, and removed node level/seat/status metadata.
- Iteration 5: converted the compact flow from left-to-right to top-to-bottom. Added mouse-drag panning and single-line description truncation; populated-chain visual QA remains blocked by the unauthenticated preview.
- Iteration 6: constrained the flow canvas to its card viewport, narrowed nodes from 190px to 158px, and realigned branch gaps plus connector anchors to prevent clipping and offset lines.
**Final result**
blocked
@@ -1,916 +0,0 @@
# AI 写作 — 后端开发文档
> **本文档目的**:帮助后端开发者快速理解 AI 写作子系统的代码结构、Graph 拓扑、数据流、持久化、容错策略和扩展点。
>
> **配套文档**:
> - 前端:`frontend-web/docs/ai-writing-frontend-dev.md`
> - 故障排查:`frontend-web/docs/ai-writing-说明.md`
> - 前端 API 字段索引:`frontend-web/docs/ai-writing-assistant-backend-api.md`
---
## 一、产品定位与技术架构
### 产品定位
**杂志社协作写作子系统**:由 4 个 AI Agent(**素材收集专家 / 作家 / 编辑 / 系统**)协作完成一篇文章,通过 4 个用户干预点参与决策。
### 技术栈
- **编排框架**:LangGraph(独立 StateGraph,不复用主 lead agent 的 middleware 链)
- **节点驱动**:异步 LLM 调用(`langchain_openai` 等),支持流式 token 推送到 SSE
- **状态持久化**:LangGraph checkpointer(SQLite 文件,跨重启可恢复)
- **业务数据**:MySQL `ai_writing_sessions` 表
- **协议**:SSE(Server-Sent Events)推进度 + REST 控制流
### 与主 Agent 的关系
**完全独立**。AI 写作 graph 不通过 `make_lead_agent` 也不走主 agent 的 18 层 middleware。它有自己的 StateGraph、自己的 checkpointer、自己的路由前缀(`/api/ai-writing/*`),跟主 agent 解耦。
---
## 二、目录结构
```
offline-backend-20260512/backend/
├── app/gateway/
│ ├── routers/
│ │ └── ai_writing.py # FastAPI 路由 + 模块级状态字典 + SSE 生成器(1000+ 行,核心)
│ ├── ai_writing_cleanup.py # 定期清理 + cron 调度(独立模块)
│ └── app.py # lifespan 启动/停止清理任务、检测多 worker、关闭 checkpointer
│
└── packages/harness/deerflow/
├── agents/ai_writing/
│ ├── __init__.py # 暴露 AI_WRITING_GRAPH + 工厂函数
│ ├── graph.py # ⭐ StateGraph 定义 + 4 个 pause 节点 + checkpointer 工厂(538 行)
│ ├── state.py # AIWritingState TypedDict(121 行)
│ │
│ ├── nodes/ # ── Graph 节点 ──
│ │ ├── _utils.py # LLM 工具:parse_json, ThinkTagParser, llm_json
│ │ ├── intent_parser.py # 节点 1:意图解析
│ │ ├── researcher.py # 节点 2:素材检索(支持流式 progress)
│ │ ├── writer_outline.py # 节点 3:大纲规划
│ │ ├── writer_draft.py # 节点 4:草稿生成(按章节流式)
│ │ └── editor.py # 节点 5:编辑审核(3 维度并行流式)
│ │
│ ├── prompts/ # ── Prompt 模板 ──
│ │ ├── __init__.py
│ │ ├── researcher_prompts.py
│ │ ├── writer_prompts.py
│ │ └── editor_prompts.py
│ │
│ └── search/ # ── 素材检索 provider ──
│ ├── base.py # SearchResult / SearchProvider 接口
│ ├── duckduckgo_search.py
│ ├── internet_search.py # 互联网检索(默认)
│ ├── intranet_stub.py # 内网检索占位(按部署接入)
│ └── demo_search.py # 离线 demo 数据
│
└── persistence/ai_writing_sessions/
├── __init__.py # AIWritingSessionRepository 工厂
├── model.py # ORM:AIWritingSessionRow
└── sql.py # CRUD 实现(含清理用的 list_older_than / delete_by_ids)
```
---
## 三、Graph 拓扑(最重要)
### StateGraph 节点 + 边
```
START
│
↓
┌─────────────────┐
│ intent_parser │ 解析用户意图(确定 article_type / target_audience)
└────────┬────────┘
↓
┌─────────────────┐
│ researcher │ ← (re_search 回到这里)
└────────┬────────┘
↓ (after_researcher: ⼟材 ready)
┌──────────────────────┐
│ pause_material │ ⚙️ PAUSE-1:素材确认
└─┬──────────┬─────────┘
│ confirm │ re_search
↓ └→ researcher
┌─────────────────┐
│ writer_outline │ ← (re_outline 回到这里)
└────────┬────────┘
↓
┌──────────────────────┐
│ pause_outline │ ⚙️ PAUSE-2:大纲确认
└─┬──────────┬─────────┘
│ confirm │ re_outline
↓ └→ writer_outline
┌─────────────────┐
│ writer_draft │ ← (素材补充后回到这里)
└─┬───────────────┘
↓ (after_writer_draft)
┌──────┴────────────────┐
↓ ↓
┌──────────────────┐ ┌────────────────────┐
│ pause_section_ │ │ pause_draft │ ⚙️ PAUSE-3:草稿确认
│ help(素材不足)│ │ │
└─┬─────────────┬──┘ └─┬────────┬───┬─────┘
│ supplement │ del/ │ │ │ to_editor
│↓ │ loose │ │ user_revise
research writer_ │ final ↓
draft │ ize writer_draft
│↓
done
│
(to_editor)│
↓
┌─────────────────┐
│ editor │ 3 维度并行流式审核
└────────┬────────┘
↓ (after_review)
┌──────────────────────┐
│ pause_review │ ⚙️ PAUSE-4:审核确认
└─┬──────────┬─────────┘
│ confirm │ revise
│↓ └→ writer_draft
done
```
### 节点定义位置一览
| 节点名 | 实现文件 | 类型 | 流式? |
|---|---|---|---|
| `intent_parser` | `nodes/intent_parser.py` | async function | 否 |
| `researcher` | `nodes/researcher.py` | async function | 是(research_progress) |
| `pause_material` | `graph.py` 顶部 | async, 调 `interrupt()` | — |
| `writer_outline` | `nodes/writer_outline.py` | async function | 是(outline_chunk) |
| `pause_outline` | `graph.py` 顶部 | async, 调 `interrupt()` | — |
| `writer_draft` | `nodes/writer_draft.py` | async function | 是(draft_chunk,按章节) |
| `pause_section_help` | `graph.py` 顶部 | async, 调 `interrupt()` | — |
| `pause_draft` | `graph.py` 顶部 | async, 调 `interrupt()` | — |
| `editor` | `nodes/editor.py` | async function | 是(review_chunk,3 路并行) |
| `pause_review` | `graph.py` 顶部 | async, 调 `interrupt()` | — |
### 条件路由函数(graph.py)
| 函数 | 在哪个节点之后 | 路由依据 |
|---|---|---|
| `after_researcher` | researcher | 是否找到素材 |
| `after_material_pause` | pause_material | `state["status"]` 是 researching 还是 writing_outline |
| `after_outline_pause` | pause_outline | 同上,writing_outline 还是 writing_draft |
| `after_writer_draft` | writer_draft | 是否有 blocked_sections |
| `after_section_help_pause` | pause_section_help | status |
| `after_draft_pause` | pause_draft | done / revising / reviewing |
| `after_review` | editor | review_result.verdict 是 pass 还是 reject + revision_count 上限 |
| `after_review_pause` | pause_review | done / writing_draft |
---
## 四、State 定义(state.py)
```python
class AIWritingState(TypedDict):
# —— 写作配置(启动时填充)——
user_intent: str
article_type: str
target_audience: str
word_count_target: int
keyword_count: int # 1-10,默认 6
writing_mode: str # "strict" | "loose"
# —— Agent 产出 ——
material_package: Optional[MaterialPackage] # 素材收集专家
current_outline: Optional[Outline] # 作家
drafts: Annotated[List[DraftArticle], operator.add] # 累计所有版本
current_draft: Optional[DraftArticle] # 最新草稿
review_result: Optional[ReviewResult] # 编辑
# —— 用户干预 ——
last_user_intervention: Optional[UserInterventionPayload]
blocked_sections: Optional[List[BlockedSection]] # 素材不足的章节
# —— 流程控制 ——
revision_count: int
max_revisions: int # 默认 3
status: WritingStatus
# —— SSE 推送队列 ——
progress_events: Annotated[List[dict], operator.add] # 累加,不覆盖
```
### State 字段的特殊语义
- **`Annotated[..., operator.add]`** — LangGraph 的累加 reducer,节点 return 时 `progress_events: [evt]` 会**追加**到现有列表,而不是替换
- **TypedDict** — 运行时是普通 dict,类型注解仅供 IDE 提示
- **节点输出** — 节点 return 的 dict 只需要包含**要更新的字段**,未指定的字段保持不变
---
## 五、路由层(app/gateway/routers/ai_writing.py)
### 14 个接口一览
| HTTP | 路径 | 用途 | 鉴权 |
|---|---|---|---|
| POST | `/api/ai-writing/start` | 启动写作,返回 session_id | 用户 |
| GET | `/api/ai-writing/{id}/stream` | SSE 进度流 | 用户 |
| POST | `/api/ai-writing/{id}/resume` | 提交用户干预 | 用户 |
| GET | `/api/ai-writing/{id}/state` | 查 graph 状态快照(调试用) | 用户 |
| GET | `/api/ai-writing/sessions` | 列出当前用户的历史会话 | 用户 |
| GET | `/api/ai-writing/sessions/{id}` | 获取单个历史会话 | 用户 |
| PATCH | `/api/ai-writing/sessions/{id}` | 重命名会话 | 用户 |
| DELETE | `/api/ai-writing/sessions/{id}` | 删除会话 | 用户 |
| PUT | `/api/ai-writing/sessions/{id}/transcript` | 保存对话时间线(**fire-and-forget**) | 用户 |
| GET | `/api/ai-writing/article-types` | 列出文章类型 | 用户 |
| POST | `/api/ai-writing/article-types` | 新增文章类型 | 用户(建议改成 admin) |
| PATCH | `/api/ai-writing/article-types/{id}` | 更新文章类型 | 用户 |
| DELETE | `/api/ai-writing/article-types/{id}` | 删除文章类型 | 用户 |
| POST | `/api/ai-writing/admin/cleanup` | **手动触发清理** | admin only |
### 模块级状态字典(关键设计 — 也是 worker 限制的根源)
```python
# 每个 session_id 对应一份内存状态。多 worker 部署时每个 worker 一份,互不共享。
_event_queues: dict[str, asyncio.Queue] # SSE 事件队列
_session_pending_pause: dict[str, tuple] # 挂起的 await_user 事件(供重连重投)
_session_model_names: dict[str, str] # 用户选的模型
_session_interventions: dict[str, list] # 累计干预历史
_session_repos: dict[str, repo] # DB 仓库引用
_session_user_ids: dict[str, str] # 用户 id
_session_article_types: dict[str, list] # 动态文章类型列表
_session_error_flags: dict[str, bool]
_inflight_graph_tasks: set[asyncio.Task] # in-flight task 注册表(lifespan drain 用)
_recovery_lock: asyncio.Lock # 跨 worker 会话恢复的并发锁
```
⚠️ **关键限制**:这些都是 per-process 内存。多 worker 部署下,worker B 看不到 worker A 的状态 → SSE 事件分发失败。详见 `frontend-web/docs/ai-writing-说明.md` 第五、六章。
### `_stream_graph_segment`(graph 推进函数)
`/start` 和 `/resume` 都调用这个函数(用 `_spawn_graph_task` 包装),负责:
1. 调 `graph.astream(input_or_command, config=config, stream_mode="updates")`
2. 把每个 chunk 解析成 SSE 事件 put 进 `_event_queues[session_id]`
3. 遇到 `__interrupt__` → 推 `await_user` 事件 → 返回(不关闭 queue)
4. 遇到 END → 推 `done` 事件 → 关闭 queue(put None 哨兵)
5. 任何异常 → 推 `error` 事件 → 关闭 queue
6. finally 段:更新 DB 最终状态、清理所有模块字典
### SSE 生成器 `_sse_generator`
`GET /stream` 的实现,从 `_event_queues[session_id]` 拿事件 → `_sse(event, data)` 序列化 → yield 给 fastapi `StreamingResponse`。
**关键逻辑**:
- 队列不存在时**等待 5 秒**,期间触发 `_recover_session`(跨 worker / 进程重启恢复)
- `_sse()` 三层兜底:`default=str` → 手写 notice 帧 → 永不抛 TypeError
- 收到 None 哨兵 → 关闭流
### `_recover_session`(跨 worker 恢复)
当 worker 内存里没有 session_id 但 sqlite checkpointer 有快照时:
1. 从 checkpointer 读出 state snapshot
2. 重建 `_event_queues[sid]` 队列
3. 从 snapshot 提取当前 interrupt 负载,put 进队列
4. 同时尽量恢复 `_session_repos`、`_session_user_ids` 等
返回三种状态:
- `"interrupted"` — 图停在干预点,已重建队列
- `"finished"` — 图已完成或中断在节点中间,推 done/error 事件后关闭
- `"unrecoverable"` — sqlite 也没有这个 thread_id → 真的丢了
### `_spawn_graph_task` / `wait_for_inflight_graph_tasks`(优雅关闭)
- `_spawn_graph_task(coro)` — 启 task 并自动登记到 `_inflight_graph_tasks`,完成时反登记
- `wait_for_inflight_graph_tasks(timeout)` — lifespan shutdown 等所有 task 跑到下一个 interrupt / END(默认 30s),超时则 cancel 强制结束
---
## 六、Graph 与持久化(graph.py)
### Lazy 单例 + 自动降级
```python
AI_WRITING_GRAPH = None # 模块级槽位(测试可 monkeypatch)
_async_checkpointer_singleton = None # checkpointer 单例
async def get_ai_writing_graph():
"""懒加载 graph。第一次调用时按 config.yaml 决定 checkpointer。"""
global AI_WRITING_GRAPH
if AI_WRITING_GRAPH is not None:
return AI_WRITING_GRAPH
checkpointer = await _get_async_checkpointer()
AI_WRITING_GRAPH = build_ai_writing_graph(checkpointer=checkpointer)
return AI_WRITING_GRAPH
```
### Checkpointer 优先级(_get_async_checkpointer)
```
1. config.yaml 的 checkpointer 段
├── type: sqlite → AsyncSqliteSaver(aiosqlite.connect(...))
├── type: postgres → AsyncPostgresSaver(AsyncConnectionPool(...))
└── type: memory → InMemorySaver
2. 任何初始化失败 → InMemorySaver(降级,打 warning)
3. 未配置 checkpointer 段 → InMemorySaver(降级,打 warning)
4. 未知 type(如 "mysql") → InMemorySaver(降级,打 warning)
```
**核心契约**:`_get_async_checkpointer()` **绝不抛异常**,永远返回一个可用的 saver。这是「写作流程能完整继续」契约的关键。
### Shutdown
`shutdown_ai_writing_graph()` 在 lifespan shutdown 时调用:
- 关闭 `aiosqlite.Connection` / `AsyncConnectionPool`
- 清空 `AI_WRITING_GRAPH` / `_async_checkpointer_singleton`
调用顺序(详见 `app/gateway/app.py` lifespan):
1. 停清理任务
2. `wait_for_inflight_graph_tasks(30s)`
3. `shutdown_ai_writing_graph()`
---
## 七、节点详解(nodes/)
### `nodes/_utils.py`(公共工具)
| 函数 / 类 | 用途 |
|---|---|
| `get_model(config, model_name)` | 从 config.configurable 拿 model_name 或回退默认 |
| `parse_json(text, fallback)` | 鲁棒 JSON 解析(支持代码块、不完整 JSON、转义错误) |
| `_extract_balanced(text)` | 找出第一对平衡的 `{...}` |
| `_repair_json(text)` | 修复常见的 JSON 错误(缺尾引号等) |
| `ThinkTagParser` | 流式解析 `<think>...</think>` 标签(思考 / 正文分流) |
| `llm_json(system, user, fallback, config)` | 调 LLM 并解析 JSON 输出 |
| `count_words(text)` | 中文 + 英文混合计字数 |
### `nodes/intent_parser.py` — 意图解析
- 调 LLM 把用户意图(`user_intent` 字符串)解析成结构化字段:`article_type`、`target_audience`、`word_count_target`
- 用户已经在 `AIWritingRequest` 里指定的字段会**覆盖** LLM 推断
- 输出:更新 state 的对应字段,推 `step_done` 事件
### `nodes/researcher.py` — 素材检索
- 根据 `user_intent` 用 LLM 生成 N 个关键词(N = `keyword_count`,默认 6)
- 用 `search/*` 的 provider 并行检索
- 流式推 `research_progress` 事件("正在搜索关键词 X 中...")
- 输出:`material_package = {keywords, materials, summary}`,推 `materials_ready`
### `nodes/writer_outline.py` — 大纲规划
- 输入:`user_intent` + `material_package`
- 调 LLM 流式生成大纲 JSON,期间推 `outline_chunk`(正文 + thinking 分流)
- 解析最终 JSON → `current_outline`,推 `outline_ready`
### `nodes/writer_draft.py` — 草稿生成(最复杂)
- 按大纲**逐章节**调 LLM 生成正文,每章节独立流式推 `draft_chunk`
- 检测 LLM 是否「拒答」(`_looks_like_refusal`),如果是则换提示重试
- **严格模式下**:如果章节关联的素材不足,把该章节加入 `blocked_sections`,触发 `pause_section_help`
- 完成所有章节后拼成 `current_draft.full_markdown`,推 `draft_ready`
### `nodes/editor.py` — 编辑审核(3 维度并行)
- 3 个维度(**fact / logic / language**)并行调 LLM
- 每个维度独立流式推 `review_chunk`,完成后推 `review_item_done`
- 三个都完成后聚合成 `review_result`,推 `review_ready`
- 评分加权(fact 40% + logic 30% + language 30%),超过 `pass_threshold`(默认 80)verdict = `pass`
---
## 八、持久化(persistence/ai_writing_sessions/)
### `model.py` — ORM
```python
class AIWritingSessionRow(Base):
__tablename__ = "ai_writing_sessions"
id: Mapped[str] # = session_id(uuid)
user_id: Mapped[str | None] # NULL = no-auth 模式
title: Mapped[str] # 从 user_intent 截取前 50 字
user_intent: Mapped[str | None]
status: Mapped[str] # in_progress / draft_ready / review_ready / done / error
draft_title: Mapped[str | None]
draft_markdown: Mapped[str | None]
completed_interventions: Mapped[str | None] # JSON 字符串
review_result: Mapped[str | None] # JSON 字符串
transcript: Mapped[str | None] # PortableLongText(MySQL→LONGTEXT,4GB)
created_at / updated_at: BeijingDateTime
```
### `sql.py` — Repository
| 方法 | 用途 |
|---|---|
| `create(id, title, user_intent, user_id)` | 启动写作时建一行 |
| `get(session_id, user_id)` | 取单个(带 user_id 权限校验) |
| `list(user_id, limit)` | 列出当前用户的会话 |
| `update(session_id, user_id, ...)` | 更新指定字段(其他保持不变) |
| `delete(session_id, user_id)` | 删除(带权限校验) |
| `list_older_than(cutoff, only_finished, limit)` | 清理用:列出过期 session_id |
| `delete_by_ids(session_ids)` | 清理用:批量删除 |
### Alembic 迁移
- `20260517_03_ai_writing_transcript.py` — 加 transcript 列(TEXT)
- `20260519_02_ai_writing_transcript_longtext.py` — MySQL 上把 transcript 改成 LONGTEXT(修 64KB 限制导致的 500)
---
## 九、定期清理(ai_writing_cleanup.py)
### 设计目标
- 删超过 `retention_days`(默认 7)的旧会话
- 联动清理:MySQL 业务行 + SQLite checkpointer 里的 thread 状态
- **绝对不删正在写的会话**(活跃保护)
### 关键函数
```python
async def run_cleanup_once(*, retention_days, only_finished=False, batch_size=500) -> dict
```
返回 `{deleted_db, deleted_checkpoints, skipped_active}`。
执行流程:
1. 调 `repo.list_older_than(cutoff, only_finished, batch_size)` 拿过期 id
2. 从 `_event_queues.keys()` 拿活跃 session_id 集合 → **过滤掉所有仍在跑的**
3. 对每个待删 id:调 `checkpointer.adelete_thread(id)` 删 checkpoint
4. 调 `repo.delete_by_ids(ids)` 批量删 MySQL
5. 循环直到本批 < batch_size
### Cron 调度
`cleanup_scheduler_loop()` 常驻后台任务:
- 用 `croniter` 解析 `ai_writing.cleanup.cron`(默认 `"0 3 * * *"`,每天凌晨 3 点)
- `asyncio.sleep` 到下次触发时间
- 多 worker 用文件锁(`runtime_home() / ".ai_writing_cleanup.lock"`)做 leader election
### Admin 手动触发
`POST /api/ai-writing/admin/cleanup`:
- 鉴权:`system_role == "admin"`
- 可选覆盖 `retention_days` / `only_finished` / `batch_size`
- 即使传 `retention_days: 0` 也不会秒杀活跃会话(活跃保护硬保证)
---
## 十、配置(config.yaml)
```yaml
# Checkpointer:graph 状态持久化
checkpointer:
type: sqlite # sqlite | postgres | memory
connection_string: .deer-flow/data/checkpoints.db
# AI 写作子系统
ai_writing:
# ── 清理调度 ─────────────────────────────────────────────
cleanup:
enabled: true
retention_days: 7
cron: "0 3 * * *" # 每天凌晨 3 点
delete_only_finished: false
batch_size: 500
# ── 素材收集专家(researcher)专用配置 ──────────────────
# 这两个模型名必须出现在顶层 models[] 段里;留空 / 不配则回退当前写作主模型。
# 拆出来是为了让「检索词生成 / 素材排序」这种结构化抽取任务可以走更轻量、
# 不带思考输出的小模型,省钱省时间,也避开写作主模型的思考干扰。
keyword_model: qwen3-4b-instruct # 检索词生成(EXTRACT_KEYWORDS_*)
rank_model: qwen3-4b-instruct # 素材排序筛选(RANK_MATERIALS_*)
# 素材总量上限:合并去重后保留多少条素材进入大纲 / 草稿阶段
# 取值范围 [1, 100],非法值或缺省回退 20。
# 每个检索词分到的检索条数 = ceil(max_materials / keyword_count),
# 所以这个数越大,每个关键词向 provider 拉的条数越多,整体耗时也越长。
max_materials: 20
# ── 素材检索 provider ───────────────────────────────────
# internet(默认,DuckDuckGo) / intranet(内网 ES) / tavily / demo
search_provider: internet
# internet 模式:DuckDuckGo 区域代码(cn-zh / us-en / wt-wt 等)
ddg_region: "cn-zh"
# intranet 模式:对接内网知识库 ES 检索接口
# 接口契约(POST):
# payload = {"query": "...", "knowledge_base_name": "<intranet_knowledge_base>", "ts": "yes"}
# response = [{"page_content": "...", "metadata": {m_title, content, recUuid, m_publish, source1}}]
# 实现见 packages/harness/deerflow/agents/ai_writing/search/intranet_stub.py
intranet_search_url: http://10.106.57.180:7863/knowledge_base/search_docs_es
intranet_knowledge_base: samples # 默认 samples,按部署的实际知识库名改
```
### 配置项与代码的对应关系
| 配置键 | 默认值 | 取值范围 / 说明 | 读取位置 |
|---|---|---|---|
| `ai_writing.keyword_model` | 空(回退写作主模型) | 必须是 `models[]` 段里已声明的模型名 | `nodes/researcher.py` → `llm_json(..., model_name=keyword_model)` |
| `ai_writing.rank_model` | 空(回退写作主模型) | 同上 | `nodes/researcher.py` → 排序分支 `llm_json(..., model_name=rank_model)` |
| `ai_writing.max_materials` | `20` | `[1, 100]`,非法值回退 20;`_resolve_max_materials` 钳制 | `nodes/researcher.py:_DEFAULT_MAX_MATERIALS` |
| `ai_writing.search_provider` | `"internet"` | `internet` / `intranet` / `tavily` / `demo` | `search/__init__.py:get_search_provider` |
| `ai_writing.ddg_region` | `"cn-zh"` | DuckDuckGo 区域代码,仅 `internet` 模式生效 | 同上 |
| `ai_writing.intranet_search_url` | `http://10.106.57.180:7863/knowledge_base/search_docs_es` | 仅 `intranet` 模式生效,POST JSON 接口 | `search/intranet_stub.py:_DEFAULT_ENDPOINT` |
| `ai_writing.intranet_knowledge_base` | `"samples"` | 仅 `intranet` 模式生效,知识库 ID/名称 | 同上 |
### 配置如何传到节点
```
config.yaml
└─ ai_writing: { ... }
│
▼ _ai_writing_config() 取出整个 dict
routers/ai_writing.py:_make_config()
│ 注入到 config.configurable.ai_writing_config
▼
nodes/researcher.py
cfg = config.get("configurable", {})
ai_writing_config = cfg.get("ai_writing_config", {})
keyword_model = ai_writing_config.get("keyword_model")
rank_model = ai_writing_config.get("rank_model")
max_materials = _resolve_max_materials(ai_writing_config.get("max_materials"))
provider = get_search_provider(ai_writing_config) # ← search_provider 等也从这里读
```
### 切换内网检索的最小步骤
1. `config.yaml` 改 `ai_writing.search_provider: intranet`
2. 填 `intranet_search_url` 和 `intranet_knowledge_base`(部署侧给)
3. 内网 ES 接口若返回结构异常 / 网络抖动,researcher 节点会收集 `provider.errors` + `provider.raw_responses`,作为非致命 `notice` 事件推前端时间线(折叠显示原始响应体),**不会中断写作流程**
4. 健康检查:可通过 `IntranetSearchProvider.health_check()` 单测,或直接发一笔 `/start` 看 `research_progress` 是否报错
### 备注
- `keyword_model` / `rank_model` 只影响素材收集专家的 LLM 调用,**不影响**大纲、草稿、编辑审核三个节点(它们各自走自己的主模型)。
- `max_materials` 是「合并去重后的总量上限」,不是每个关键词的检索条数;每个词的检索数会按 `ceil(max_materials / keyword_count)` 均分。`keyword_count` 由前端启动写作时传入(1~10,默认 6)。
- `intranet` 模式不带 fallback;如果内网 ES 全挂,researcher 拿到空结果会直接进入「未检索到素材,可重新搜索或在无素材的情况下继续写作」分支。如果想让内网失败时退回互联网检索,需要在 `get_search_provider` 里手动用 `_FallbackSearchProvider(IntranetSearchProvider(...), DuckDuckGoSearchProvider(...))` 包一层。
ai_writing:
keyword_model: deepseek-chat # 检索词生成专用模型,留空回退写作主模型
rank_model: deepseek-chat # 素材排序专用模型,留空回退写作主模型
max_materials: 50 # 合并去重后的素材总量上限,范围 [1, 100],默认 20
---
## 十一、SSE 事件协议(后端 → 前端契约)
后端通过 `_sse(event_type, data)` 推 `event: <type>\ndata: <json>\n\n` 格式。
### 推出事件的位置
| 事件 | 推出位置 |
|---|---|
| `connected` | `_sse_generator` 入口 |
| `step_start` / `step_done` | 节点内部主动 emit |
| `research_progress` | `researcher_node` 内的 `_emit` |
| `materials_ready` | `_stream_graph_segment` 检测到 `material_package` 字段 |
| `outline_chunk` | `writer_outline_node` 流式推(通过 `sse_queue`) |
| `outline_ready` | `_stream_graph_segment` 检测到 `current_outline` |
| `draft_chunk` | `writer_draft_node` 按章节流式推 |
| `draft_ready` | `_stream_graph_segment` 检测到 `current_draft` |
| `review_chunk` / `review_item_done` | `editor_node` 3 维度并行流式 |
| `review_ready` | `_stream_graph_segment` 检测到 `review_result` |
| `await_user` | `_stream_graph_segment` 捕获 `__interrupt__` |
| `resumed` | pause 节点 return 时塞进 `progress_events` |
| `notice` | 节点内手动推(非致命告警) |
| `done` | `_stream_graph_segment` 正常结束 |
| `error` | `_stream_graph_segment` except 分支 |
### 节点如何流式推 chunk
通过 `config.configurable.sse_queue`:
```python
async def writer_outline_node(state, config):
sse_queue = config.get("configurable", {}).get("sse_queue")
sse_session_id = config.get("configurable", {}).get("sse_session_id")
async for chunk in llm.astream(prompt):
if sse_queue:
await sse_queue.put(("outline_chunk", {
"session_id": sse_session_id,
"text": chunk.content,
"is_thinking": False,
}))
return {"current_outline": parsed, ...}
```
`sse_queue` 是路由层在 `_make_config` 里注入的 `_event_queues[session_id]`。
---
## 十二、扩展指南:常见开发任务
### 任务 1:新增一个 Graph 节点
**例**:在 `editor` 之后加一个「术语统一」节点。
1. **写节点**:在 `nodes/` 新建 `terminology.py`:
```python
async def terminology_node(state, config):
# ... 读 current_draft 改术语
return {
"current_draft": new_draft,
"progress_events": [{"type": "step_done", "agent_name": "术语统一", "message": "..."}],
}
```
2. **注册到 graph**:在 `graph.py` 的 `build_ai_writing_graph` 里:
```python
from .nodes.terminology import terminology_node
g.add_node("terminology", terminology_node)
# 改 editor 后的边
g.add_edge("editor", "terminology")
g.add_edge("terminology", "pause_review")
```
3. **State 加字段**(如果需要):`state.py` 加新字段到 `AIWritingState`
4. **前端事件支持**(如果要新事件类型):见前端文档「扩展指南」
5. **测试**:在 `tests/` 加单元测试,至少测节点能正常 return 和 graph 拓扑能编译
### 任务 2:新增一个用户干预点
1. **写 pause 节点**:在 `graph.py` 顶部加:
```python
async def pause_xxx(state):
user_input = interrupt({
"pause_point": "xxx_confirm",
"message": "...",
"context_field": state["..."],
})
action = user_input.get("action", "confirm")
if action == "confirm":
return {"status": "next_status", "progress_events": [{"type": "resumed", ...}]}
# ... 其他分支
```
2. **路由层 ResumeRequest 加字段**(如果干预需要新字段):
```python
class ResumeRequest(BaseModel):
# ...
new_field: Optional[str] = None
```
3. **`resume_writing` 路由把字段塞进 Command(resume=...)**:
```python
intervention = {
# ...
"newField": body.new_field,
}
```
4. **graph 拓扑加 pause 节点的边**:在 build_ai_writing_graph 里
5. **前端配合**:见前端文档
### 任务 3:新增一种素材检索 provider
1. 在 `agents/ai_writing/search/` 加新文件,实现 `SearchProvider` 接口(参考 `internet_search.py`):
```python
class MyProvider(SearchProvider):
async def search(self, keyword: str, limit: int) -> list[SearchResult]:
...
```
2. 配置 `config.yaml`:
```yaml
ai_writing:
search:
provider: my_pkg.search:MyProvider
# provider 特定的配置...
```
3. `researcher_node` 通过 `config.configurable.ai_writing_config.search.provider` 用 `resolve_class` 动态加载
### 任务 4:修改 LLM Prompt
所有 prompt 集中在 `agents/ai_writing/prompts/`:
- `researcher_prompts.py` — 检索专家
- `writer_prompts.py` — 大纲 + 草稿
- `editor_prompts.py` — 审核
改 prompt 后**强烈建议**:
1. 在 `tests/` 加针对该 prompt 输出的回归测试(用 LLM mock 或固定输入)
2. 跑现有测试确认拓扑兼容
### 任务 5:扩展持久化字段
例:给 `ai_writing_sessions` 加一个 `total_tokens` 列。
1. `model.py` 加列:
```python
total_tokens: Mapped[int | None] = mapped_column(Integer, nullable=True)
```
2. **必须**新建 alembic 迁移:
```bash
PYTHONPATH=. uv run alembic revision -m "add total_tokens column"
```
然后填 upgrade/downgrade 逻辑(参考 `20260519_02_ai_writing_transcript_longtext.py`)
3. `sql.py` 的 `update()` / `to_dict()` 加字段处理
4. `routers/ai_writing.py` 的 `SessionResponse` 加字段
5. 测试:在 `tests/test_ai_writing_session_repo.py` 加新字段的 round-trip 测试
---
## 十三、容错策略(关键设计原则)
### 「写作流程能完整继续」契约
后端承诺:**除非 Pydantic 校验失败(4xx),AI 写作的 4 个核心接口任何后端组件失败都不阻断当次写作的完整执行**。
### 落实位置
| 失败点 | 兜底位置 | 行为 |
|---|---|---|
| sqlite checkpointer 初始化失败 | `_get_async_checkpointer` | 自动降级 InMemorySaver |
| SSE JSON 序列化失败 | `_sse()` | 三层兜底(default=str → notice 帧) |
| DB `create()` session 行失败 | `start_writing` | try/except 吞掉,session_id 仍返回 |
| DB `update(draft)` 失败 | `_stream_graph_segment` | try/except 吞掉,graph 继续推 |
| DB `update(review)` 失败 | 同上 | 同上 |
| DB `update(transcript)` 失败 | `save_transcript` 路由 | 返回 `success=false`,不抛 5xx |
| 文章类型加载失败 | `start_writing` | 退回 `[]` |
| Graph 编译失败 | `start_writing` | 抛 503(极端情况,节点 import 错) |
| Graph 运行时节点抛错 | `_stream_graph_segment` | except 推 error 事件,session 结束 |
| Cleanup 误删活跃会话 | `run_cleanup_once` | 活跃保护硬过滤 |
### 容器优雅关闭
lifespan shutdown 顺序:
1. 停 cleanup scheduler
2. `wait_for_inflight_graph_tasks(30s)` — 等所有 in-flight 写作跑到下一个 checkpoint
3. 超时未结束的 task `cancel()` + 2s ack 等待
4. `shutdown_ai_writing_graph()` — 关闭 aiosqlite Connection / pg pool
---
## 十四、测试覆盖
| 测试文件 | 数量 | 覆盖范围 |
|---|---|---|
| `tests/test_ai_writing_session_repo.py` | 7 | Repo CRUD + 清理用的 list_older_than / delete_by_ids |
| `tests/test_ai_writing_session_recovery.py` | 8 | `_recover_session` / `_extract_interrupt` / `resume_writing` 跨 worker 恢复 |
| `tests/test_ai_writing_transcript_endpoint.py` | 5 | transcript 保存兜底 |
| `tests/test_ai_writing_cleanup.py` | 26 | 清理 + drain + checkpointer 降级 + SSE 序列化 + admin 接口 + 多 worker 检测 |
| `tests/test_portable_long_text.py` | 5 | LONGTEXT 列类型 + 迁移链 |
跑全部:
```bash
PYTHONPATH=. uv run pytest tests/test_ai_writing*.py tests/test_portable_long_text.py -v
```
期望 **51 个测试全过**。
---
## 十五、关键调试 / 排查命令
### 看 graph 当前状态
```python
# 进 python shell
from deerflow.agents.ai_writing.graph import get_ai_writing_graph
graph = await get_ai_writing_graph()
snap = await graph.aget_state({"configurable": {"thread_id": "<session_id>"}})
print(snap.values, snap.next, snap.tasks)
```
### 直接读 sqlite checkpointer
```bash
sqlite3 /app/.deer-flow/data/checkpoints.db
.tables # 看表(checkpoints / checkpoint_writes 等)
SELECT thread_id, checkpoint_ns, checkpoint_id FROM checkpoints
WHERE thread_id = '<session_id>' LIMIT 5;
```
### 查 MySQL 业务行
```sql
SELECT id, status, draft_title, updated_at,
JSON_LENGTH(transcript) AS transcript_size
FROM ai_writing_sessions
WHERE id = '<session_id>';
```
### 查内存中的活跃会话(调试时手动加)
```python
# 临时在路由加一个 admin 接口
@router.get("/admin/inflight")
async def admin_inflight():
return {
"event_queues": list(_event_queues.keys()),
"inflight_tasks": len(_inflight_graph_tasks),
"pending_pause": list(_session_pending_pause.keys()),
}
```
### 日志关键字
```bash
docker logs <gateway> 2>&1 | grep -E 'ai_writing|AsyncSqliteSaver|checkpointer|recovered'
```
期望看到(启动时):
- `ai_writing: 使用 AsyncSqliteSaver (xxx.db)` — 持久化生效
- `ai_writing_cleanup: 已启动 cron=...` — 清理调度起来
警告:
- `ai_writing: 持久化 checkpointer 不可用,退回 InMemorySaver` — sqlite 故障
- `⚠ 检测到 WEB_CONCURRENCY=N` — 多 worker 警告(详见 `ai-writing-说明.md`)
---
## 十六、性能与限制
### 单 session 资源占用
- 内存:~50KB(state + progress_events 累计)
- sqlite checkpoint:每次 state update 写一行(一篇完整文章约 20-50 行)
- LLM tokens:约 30K-100K(取决于素材量 + 字数 + 修订次数)
### 并发上限
- 单 worker 内:理论上百级 session 并发(IO bound),实际 LLM API rate limit 才是瓶颈
- 多 worker:**当前 in-memory dict 隔离,详见 ai-writing-说明.md 第六章**
### 长会话风险
- progress_events 累加无界 → 长会话 state 可能膨胀到几 MB
- transcript JSON 同理 → MySQL 行可能上 MB(但 LONGTEXT 列上限 4GB,影响读取性能)
### 优化方向
- progress_events 节流(聚合 chunk 事件)
- transcript 增量保存(diff 而非全量覆盖)
- 节点级 LLM 调用加 retry(tenacity)
---
## 十七、与主 Agent 的关系
| 维度 | 主 Agent | AI 写作 |
|---|---|---|
| Graph 入口 | `make_lead_agent` | `AI_WRITING_GRAPH` |
| Middleware | 18 层中间件 | 无(直接节点链) |
| State | `ThreadState` | `AIWritingState` |
| Checkpointer | `make_checkpointer()`(共享) | `_get_async_checkpointer()`(同一文件,不同 thread_id 命名空间) |
| 路由前缀 | `/api/langgraph/*` `/api/threads/*` | `/api/ai-writing/*` |
| 流式协议 | LangGraph stream_mode(messages-tuple/values) | 自定义 SSE 事件 |
| 用户干预 | 通过 `ask_clarification` 工具 | 通过 LangGraph `interrupt()` |
| 持久化业务表 | `threads_meta`、`runs` | `ai_writing_sessions` |
二者**完全独立**,仅在「共享同一个 sqlite checkpointer 文件」这一点上有间接关联(也可以拆开,性能层面没区别)。
---
## 十八、未来 RFC 方向
| 主题 | 描述 |
|---|---|
| 多 worker 部署支持 | 把 `_event_queues` 等搬 Redis Pub/Sub,参考 `ai-writing-说明.md` 方案 B |
| Graph 拓扑可配置 | 现在节点链路写死,未来按 article_type 走不同拓扑(如「研报」vs「散文」) |
| 节点级重试 | LLM 抽风时自动重试 N 次,参考 `tenacity` |
| 素材跨 session 复用 | 同一用户多次写作可能用同一批素材 → 缓存层 |
| 多模态素材 | 支持图片素材输入和图文混合输出 |
| 中文标点 / 排版规则注入 | 在节点 prompt 里强化中文出版规范 |
---
## 附录 A:相关文件速查
| 文件 | 行数 | 用途 |
|---|---|---|
| `routers/ai_writing.py` | 1006 | 路由 + 状态字典 + SSE + drain |
| `agents/ai_writing/graph.py` | 538 | StateGraph + checkpointer 工厂 |
| `agents/ai_writing/state.py` | 121 | AIWritingState 定义 |
| `agents/ai_writing/nodes/_utils.py` | 242 | LLM 工具 |
| `agents/ai_writing/nodes/intent_parser.py` | 131 | 节点:意图解析 |
| `agents/ai_writing/nodes/researcher.py` | 271 | 节点:素材检索 |
| `agents/ai_writing/nodes/writer_outline.py` | 147 | 节点:大纲规划 |
| `agents/ai_writing/nodes/writer_draft.py` | 318 | 节点:草稿生成 |
| `agents/ai_writing/nodes/editor.py` | 180 | 节点:编辑审核 |
| `app/gateway/ai_writing_cleanup.py` | ~280 | 清理 + 调度 |
| `persistence/ai_writing_sessions/sql.py` | ~200 | Repository |
| `persistence/ai_writing_sessions/model.py` | ~35 | ORM |
---
## 附录 B:常见踩坑
| 现象 | 根因 | 解决 |
|---|---|---|
| `/start` 报 500 | graph 编译失败(多半是 import 错) | 看启动日志 stack trace |
| `/resume` 报 404 | session_id 不存在或 checkpointer 没快照 | 看 `ai_writing recover` 日志 |
| transcript 500 | DB 列容量 / 网络抖 | ✅ 已修,前端 fire-and-forget |
| SSE 卡住不动 | 多 worker SSE 隔离 / 反代超时 | 见 `ai-writing-说明.md` |
| `draft_chunk` 丢失内容 | `ThinkTagParser` 在 `<think>` 标签边界处理 | 看 `_utils.py:ThinkTagParser.feed` 单测 |
| graph 卡在某节点不退出 | LLM API 卡住 / 无限重试 | 看节点日志,加 timeout |
| cleanup 没跑 | cron 表达式配错 / 文件锁被其他 worker 持有 | 看 `ai_writing_cleanup` 日志 |
| 草稿在前端看不到但 MySQL 有 | 多 worker 导致 SSE 事件丢失 | 同上 |
| 配 mysql 做 checkpointer 报错 | LangGraph 不支持 MySQL checkpointer | 用 sqlite 或 postgres |
---
如需补充内容,请直接编辑本文件,并在 git commit message 里注明改动原因。
@@ -1,726 +0,0 @@
# AI 写作助手后端接口与 Prompt 协议文档
## 1. 文档目标
本文档用于指导 AI 写作助手第二阶段升级中的后端开发、接口设计、提示词设计和联调约束。
本轮后端目标不是重做 DeerFlow 的整体架构,而是在保留现有 Python + LangGraph + 线程体系的基础上,新增一套稳定的“选区改写型能力”,服务前端的 Tiptap 写作编辑器。
---
## 2. 本轮后端职责
后端负责:
- 接收当前线程信息
- 接收用户选区文本
- 接收改写动作
- 选取必要上下文
- 调用模型生成候选改写结果
- 返回纯净候选文本
后端本轮不负责:
- 直接编辑 Tiptap JSON
- 直接操作前端编辑器选区
- 直接替换前端文档内容
- 做复杂富文本 patch
- 做 tracked changes
---
## 3. 设计原则
### 3.1 纯文本协议优先
首版只让后端处理:
- 选区文本
- 前后文文本
- 动作类型
- 风格参数
不让后端直接理解完整富文本 JSON。
### 3.2 前端负责应用,后端负责生成
- 前端负责选区获取
- 前端负责候选结果展示
- 前端负责替换 / 插入
- 后端只负责“给出候选文本”
### 3.3 结果必须可直接落文档
后端输出必须尽量是可直接放回编辑器的正文,不应带解释性前缀,例如:
- “当然可以,以下是润色版本:”
- “我帮你改写如下:”
- “下面是优化后的内容:”
这类内容必须禁止。
---
## 4. 推荐接口设计
## 4.1 主接口
推荐新增统一接口:
```text
POST /api/writing/rewrite
```
由 `action` 决定具体重写类型。
## 4.2 为什么推荐统一接口
因为前端交互是一套统一浮层和统一预览面板,拆成多个接口会导致:
- 前端判断分支增多
- 埋点与异常处理分散
- 后续新增动作不方便扩展
统一接口更适合本轮需求。
---
## 5. 请求体定义
建议请求体如下:
```json
{
"threadId": "string",
"documentId": "string",
"selection": {
"from": 120,
"to": 260,
"text": "待改写文本"
},
"action": "polish",
"tone": "professional",
"surroundingContext": {
"before": "选区前文",
"after": "选区后文"
}
}
```
---
## 6. 字段说明
### 6.1 `threadId`
用途:
- 关联当前 DeerFlow 线程
- 必要时取线程上下文或会话元数据
### 6.2 `documentId`
用途:
- 标识当前右侧文档
- 首版可选
- 如果当前系统还没有独立文档 ID,可先允许为空
### 6.3 `selection.from` / `selection.to`
用途:
- 帮助前后端联调排查
- 首版后端通常不需要真正使用偏移量
- 建议保留,便于日志定位
### 6.4 `selection.text`
用途:
- 这是本轮最核心输入
- 后端实际重写的主文本
### 6.5 `action`
允许值:
- `polish`
- `expand`
- `shorten`
- `tone`
### 6.6 `tone`
仅当 `action = tone` 时使用。
建议允许值:
- `professional`
- `casual`
- `readable`
- `academic`
- `expressive`
### 6.7 `surroundingContext.before`
用途:
- 提供选区前文
- 帮助模型理解语气、主语、叙事连续性
建议:
- 控制长度
- 不要塞太多无关上下文
### 6.8 `surroundingContext.after`
用途:
- 提供选区后文
- 帮助模型在扩写、改语气时与后续内容衔接
---
## 7. 返回体定义
建议返回体如下:
```json
{
"output": "AI 改写后的候选文本",
"originalSelection": {
"from": 120,
"to": 260,
"text": "待改写文本"
},
"metadata": {
"action": "polish",
"tone": null,
"model": "your-model-name"
}
}
```
---
## 8. 返回字段要求
## 8.1 `output`
必须:
- 只包含候选正文
- 尽量不夹带解释语
- 能直接被前端替换或插入
## 8.2 `originalSelection`
作用:
- 前端可以做校验
- 联调时方便确认是针对哪段文本返回的
## 8.3 `metadata`
作用:
- 便于埋点
- 便于日志记录
- 便于问题追踪
---
## 9. 错误响应规范
建议统一错误结构:
```json
{
"error": {
"code": "WRITING_REWRITE_FAILED",
"message": "rewrite failed"
}
}
```
建议错误码:
- `WRITING_REWRITE_FAILED`
- `WRITING_INVALID_ACTION`
- `WRITING_INVALID_TONE`
- `WRITING_EMPTY_SELECTION`
- `WRITING_MODEL_UNAVAILABLE`
- `WRITING_CONTEXT_TOO_LARGE`
---
## 10. 动作语义定义
## 10.1 `polish`
目标:
- 保持原意
- 改善表达
- 提升通顺度、自然度和可读性
不应:
- 引入新事实
- 改写成完全不同内容
## 10.2 `expand`
目标:
- 保持主旨
- 扩充细节
- 增强画面感、解释性或完整度
不应:
- 无限制发散
- 添加明显脱离主题的新内容
## 10.3 `shorten`
目标:
- 压缩篇幅
- 保留关键信息
- 减少重复表达
不应:
- 丢失关键论点
- 压缩到语义残缺
## 10.4 `tone`
目标:
- 不改变原意
- 调整语言风格
不应:
- 改写事实
- 改写逻辑结构到完全不同
---
## 11. Prompt 设计原则
## 11.1 通用系统约束
所有改写类 prompt 都应包含以下约束:
- 直接输出最终可用正文
- 不输出标题,除非原文本身就是标题改写
- 不输出解释
- 不输出分析过程
- 不输出“以下是结果”之类前缀
- 保持与上下文语气一致
## 11.2 上下文使用原则
前后文只用于理解,不要求模型重写前后文。
明确告诉模型:
- 只改写选中文本
- 前后文仅用于参考衔接
## 11.3 长度控制原则
- `polish`:长度与原文接近
- `expand`:长度可明显增加,但不要失控
- `shorten`:长度明显缩短,但要保留关键信息
- `tone`:长度尽量与原文接近
---
## 12. Prompt 模板建议
## 12.1 润色模板
```text
你是一名中文写作编辑助手。
请在不改变原意的前提下,对“选中文本”进行润色,使表达更自然、更流畅、更清晰。
要求:
1. 保留原文事实和核心意思。
2. 不要添加原文没有的新事实。
3. 不要输出解释,不要输出前缀,不要输出分析过程。
4. 直接输出润色后的正文。
前文参考:
{before}
选中文本:
{selection}
后文参考:
{after}
```
## 12.2 扩写模板
```text
你是一名中文写作编辑助手。
请在不偏离主题的前提下,对“选中文本”进行扩写,增加必要细节、画面感或补充说明,使内容更充实。
要求:
1. 保持原文主旨不变。
2. 增加内容时要自然,不要跑题。
3. 不要输出解释,不要输出前缀,不要输出分析过程。
4. 直接输出扩写后的正文。
前文参考:
{before}
选中文本:
{selection}
后文参考:
{after}
```
## 12.3 缩写模板
```text
你是一名中文写作编辑助手。
请在保留关键信息和原意的前提下,对“选中文本”进行缩写,使其更精炼。
要求:
1. 不要丢掉核心信息。
2. 去掉重复、冗余和拖沓表达。
3. 不要输出解释,不要输出前缀,不要输出分析过程。
4. 直接输出缩写后的正文。
前文参考:
{before}
选中文本:
{selection}
后文参考:
{after}
```
## 12.4 改语气模板
```text
你是一名中文写作编辑助手。
请在不改变原意和事实的前提下,把“选中文本”改写成更{tone_label}的表达方式。
要求:
1. 保持原文信息不变。
2. 只调整表达风格,不改变事实和逻辑。
3. 不要输出解释,不要输出前缀,不要输出分析过程。
4. 直接输出改写后的正文。
前文参考:
{before}
选中文本:
{selection}
后文参考:
{after}
```
---
## 13. Tone 映射建议
建议前端传标准值,后端映射中文标签:
- `professional` -> 专业、正式
- `casual` -> 口语化、轻松自然
- `readable` -> 更易读、更清晰
- `academic` -> 学术、严谨
- `expressive` -> 更有文采、更有表现力
---
## 14. 上下文截取策略
## 14.1 推荐策略
前端传:
- 选区前固定长度文本
- 选区后固定长度文本
例如:
- 前文 200 到 500 字
- 后文 200 到 500 字
### 原因
- 足够帮助模型理解文气和衔接
- 不会让请求太重
## 14.2 不建议
- 把整篇长文全量塞进去
- 把整个线程消息都塞进改写接口
如果后端确实要参考线程上下文,也建议只取最近和写作相关的少量消息摘要。
---
## 15. LangGraph 接入建议
## 15.1 推荐接入方式
在现有 LangGraph / gateway 架构中新增一个写作改写专用入口。
建议二选一:
### 方案 A
新增专用 router:
- `POST /api/writing/rewrite`
内部调用现有模型层 / agent 层。
### 方案 B
新增专用 graph node 或 tool:
- `rewrite_selection`
再由 router 调用该能力。
## 15.2 更推荐方案
推荐:
- 对外暴露统一 router
- 内部走已有模型封装或 LangGraph 节点
这样前端接口更稳定,后续后端内部重构不会影响前端。
---
## 16. 后端模块拆解
## 16.1 模块 A:接口层
负责:
- 请求校验
- 错误响应
- 参数标准化
需要完成:
- 统一 rewrite API
- action / tone 校验
- 空选区校验
## 16.2 模块 B:上下文拼装层
负责:
- 拼装 before / selection / after
- 必要时提取线程相关信息
需要完成:
- 上下文长度控制
- 清洗空白和异常字符
## 16.3 模块 C:Prompt 层
负责:
- 选择模板
- 填充 action 和 tone
需要完成:
- 4 类动作模板
- tone 映射
## 16.4 模块 D:模型调用层
负责:
- 走现有模型配置体系
- 执行大模型请求
需要完成:
- 统一调用入口
- 模型不可用错误处理
## 16.5 模块 E:结果清洗层
负责:
- 去掉解释性前缀
- 去掉多余包裹
- 标准化返回
需要完成:
- 输出清洗
- metadata 填充
---
## 17. 返回结果清洗建议
即使 prompt 已经约束,模型仍可能输出:
- “以下是润色后的内容:”
- “当然,这里是改写结果:”
- “优化如下:”
建议后端加一层轻量清洗:
- 去掉常见说明性前缀
- 去掉包裹性 markdown 代码块
- 去掉多余首尾空白
注意:
- 清洗必须保守
- 不要误删正文
---
## 18. 日志与观测建议
建议记录:
- `threadId`
- `documentId`
- `action`
- `tone`
- `selection_length`
- `before_length`
- `after_length`
- `model_name`
- `latency_ms`
- `success / fail`
不要直接把整段用户正文原文打到普通日志里,避免敏感信息风险。
---
## 19. 后端测试清单
## 19.1 单元测试
- action 校验
- tone 校验
- 空选区校验
- prompt 选择逻辑
- 输出清洗逻辑
## 19.2 集成测试
- `polish`
- `expand`
- `shorten`
- `tone-professional`
- `tone-casual`
- `tone-readable`
- `tone-academic`
- `tone-expressive`
## 19.3 边界测试
- 选区过短
- 选区过长
- 前后文为空
- 多段文本带换行
- 模型超时
- 模型不可用
---
## 20. 联调约束
## 20.1 前后端必须统一
- `action` 枚举值
- `tone` 枚举值
- 错误码
- 返回体字段名
## 20.2 联调重点
- 多段落文本中换行保留是否正确
- AI 返回内容是否适合直接落文档
- 超时和失败时前端是否能优雅重试
## 20.3 联调建议顺序
1. 先 mock 返回固定文本
2. 再接真实模型
3. 先验证单段落
4. 再验证多段落
5. 最后验证大段文本
---
## 21. 优先级建议
### P0
- 统一 rewrite API
- 4 类动作支持
- 输出纯净正文
- 错误结构标准化
### P1
- 输出清洗增强
- 埋点与日志
- 上下文截断策略优化
### P2
- 更细粒度风格控制
- 结果质量二次校验
---
## 22. 完成定义
后端满足以下条件即可视为本轮完成:
- 前端能通过统一接口发起改写
- 4 类动作均可稳定返回候选文本
- 返回文本基本可直接用于替换或插入
- 多段落文本能稳定处理
- 错误结构规范统一
---
## 23. 结论
本轮后端最重要的,不是做复杂文档结构编辑,而是把“选区改写”做成稳定、可预测、可直接接入前端编辑器的能力。
最稳妥的路线是:
- 统一接口
- 统一动作枚举
- 统一 prompt 模板
- 统一错误结构
- 统一输出约束
只要这层做稳,前端的 Tiptap 写作编辑器就能很顺畅地完成豆包式“选中即改、预览后应用”的核心体验。
@@ -1,703 +0,0 @@
# AI 写作助手前端开发任务清单
## 1. 文档目标
本文档用于把《AI 写作助手右侧编辑器升级需求文档》进一步拆成前端可直接执行的任务清单。
目标是让前端团队按模块并行推进,最终完成:
- 保留左侧聊天区
- 右侧升级为 `Tiptap` 写作编辑器
- 支持选区浮层
- 支持润色 / 扩写 / 缩写 / 改语气
- 支持替换 / 插入
- 支持标题 / 列表 / 引用 / 代码块工具条
- UI 参考豆包 + Novel + open-canvas
---
## 2. 本轮前端改造范围
### 2.1 保留不动
- 左侧聊天主链路
- 现有线程消息流
- 现有模型选择器
- 现有输入框的 `writing_mode` 总入口
### 2.2 重点改造
- 右侧 Artifact 面板承载方式
- 新增独立写作工作区
- 富文本编辑器内核
- 选区浮层
- AI 改写结果预览
- 文档级工具条
---
## 3. 推荐目录结构
建议新增独立模块目录:
```text
frontend-web/src/open-canvas-writing/
routes/
WritingRoutes.tsx
pages/
WritingWorkspacePage.tsx
components/
WritingShell.tsx
WritingHeader.tsx
WritingToolbar.tsx
WritingEditorPane.tsx
WritingBubbleMenu.tsx
WritingAiMenu.tsx
WritingRewritePreview.tsx
WritingStatusBar.tsx
WritingEmptyState.tsx
editor/
TiptapEditor.tsx
TiptapExtensions.ts
commands.ts
selection.ts
context/
WritingEditorContext.tsx
hooks/
useWritingEditor.ts
useWritingSelection.ts
useWritingRewrite.ts
useWritingToolbar.ts
api/
rewrite.ts
documents.ts
types/
document.ts
rewrite.ts
utils/
apply-rewrite.ts
markdown.ts
editor-style.ts
```
---
## 4. 现有代码落点
## 4.1 需要接入的现有文件
- `frontend-web/src/pages/PageRoutes.tsx`
- 增加新写作路由入口
- `frontend-web/src/components/workspace/chats/chat-box.tsx`
- 当前双栏布局参考来源
- 后续决定是否复用布局容器,或在新页面中重建双栏
- `frontend-web/src/components/workspace/input-box.tsx`
- 保留 `writing_mode`
- 后续可在切换写作模式时跳转到新写作页面
- `frontend-web/src/components/workspace/artifacts/context.tsx`
- 仅保留给旧 Artifact 逻辑
- 不要继续承载写作编辑器状态
## 4.2 不建议继续沿用的方式
- 不要把编辑器主状态存成 `string[] artifacts`
- 不要把右侧主体验继续建在 `artifact-file-detail.tsx` 上
- 不要让 AI 改写结果先回聊天,再由用户手动复制
---
## 5. 任务分阶段拆解
## 阶段 A:路由与页面壳
### 目标
先把新的写作工作区页面立起来,让后续编辑器与交互都有落点。
### 任务
- 新增 `WritingRoutes.tsx`
- 新增 `WritingWorkspacePage.tsx`
- 在 `PageRoutes.tsx` 中挂入 `page/writing/*`
- 确认新页面进入方式
- 确定是:
- 通过左侧聊天上下文进入
- 通过 `writing_mode` 入口进入
- 或二者都支持
### 交付物
- 新写作页面能被路由访问
- 页面有基础左右布局和空态
### 验收
- 打开 `page/writing` 能进入工作区
- 页面不报错
---
## 阶段 B:编辑器底座
### 目标
把右侧正式替换成富文本编辑器。
### 任务
- 安装 Tiptap 依赖
- 建立 `TiptapEditor.tsx`
- 建立 `TiptapExtensions.ts`
- 配置节点:
- paragraph
- heading
- bulletList
- orderedList
- listItem
- blockquote
- codeBlock
- hardBreak
- 配置 marks:
- bold
- italic
- underline
- strike
- code
- 建立编辑器初始化逻辑
- 建立编辑器销毁逻辑
- 定义最小文档状态
### 交付物
- 可编辑正文区域
- 初始文档可加载
- 内容可读可写
### 验收
- 可以直接输入正文
- 可以换行、加标题、切换列表
- 不出现内容错位和明显闪烁
---
## 阶段 C:主工具栏
### 目标
右侧具备正式写作工具栏。
### 任务
- 新增 `WritingToolbar.tsx`
- 新增 `useWritingToolbar.ts`
- 实现按钮:
- 正文
- H1
- H2
- H3
- 有序列表
- 无序列表
- 引用
- 代码块
- 加粗
- 斜体
- 下划线
- 删除线
- 处理 active 状态
- 处理不可用状态
- 处理光标块状态联动
### 交付物
- 主工具栏可用
### 验收
- 工具条按钮能正确反映当前块状态
- 操作后编辑器内容正确变化
---
## 阶段 D:选区状态与浮层
### 目标
实现豆包式选区浮层基础能力。
### 任务
- 新增 `useWritingSelection.ts`
- 新增 `selection.ts`
- 新增 `WritingBubbleMenu.tsx`
- 基于 Tiptap 监听 selection 变化
- 过滤掉空选区
- 处理多段连续选区
- 浮层按钮:
- AI 改写
- 加粗
- 斜体
- 标题
- 复制
- 处理滚动定位
- 处理窗口尺寸变化
### 交付物
- 选中内容后出现浮层
### 验收
- 单段可触发
- 多段可触发
- 浮层位置稳定
---
## 阶段 E:AI 改写菜单
### 目标
把选区浮层接到 AI 改写工作流。
### 任务
- 新增 `WritingAiMenu.tsx`
- 新增 `useWritingRewrite.ts`
- 新增 `api/rewrite.ts`
- 实现一级动作:
- 润色
- 扩写
- 缩写
- 改语气
- 实现改语气二级菜单:
- 更专业
- 更口语化
- 更易读
- 更学术
- 更有文采
- 封装请求入参
- 增加 loading 态
- 增加 error 态
- 增加 retry 入口
### 交付物
- AI 改写菜单和请求链路
### 验收
- 4 个动作都能发请求
- 改语气的二级菜单可正常展开
- 请求失败时有反馈
---
## 阶段 F:候选结果预览
### 目标
把 AI 结果变成“可预览、可决策、可回退”的候选内容。
### 任务
- 新增 `WritingRewritePreview.tsx`
- 新增 `apply-rewrite.ts`
- 显示原文与候选内容
- 提供按钮:
- 替换
- 插入
- 重试
- 取消
- 用 transaction 应用结果
- 处理应用成功后的焦点与滚动
### 交付物
- 改写结果预览卡片或面板
### 验收
- 替换准确
- 插入准确
- 取消后文档保持原样
---
## 阶段 G:文档状态与容器体验
### 目标
补齐正式产品的壳层体验。
### 任务
- 新增 `WritingShell.tsx`
- 新增 `WritingHeader.tsx`
- 新增 `WritingStatusBar.tsx`
- 新增 `WritingEmptyState.tsx`
- 补充文档标题区域
- 补充文档状态提示
- 补充空态和加载态
### 交付物
- 页面完整壳层
### 验收
- 页面不是裸编辑器
- 有完整的文档工作区感
---
## 阶段 H:视觉打磨
### 目标
让整体观感接近成熟产品。
### 任务
- 调整右侧阅读宽度
- 调整字体大小和行高
- 调整段距和标题层级
- 调整工具栏阴影、边框、圆角
- 调整浮层动效
- 调整 AI 预览卡片质感
- 优化深浅色模式兼容
### 交付物
- 完整视觉优化
### 验收
- 明显优于当前版本
- 有豆包 / Novel 风格的编辑器质感
---
## 6. 组件级开发清单
## 6.1 `WritingWorkspacePage.tsx`
职责:
- 页面级容器
- 获取线程 / 文档上下文
- 组织左右布局
必须完成:
- 页面初始化
- 与左侧聊天协同
- 右侧编辑区挂载
## 6.2 `WritingShell.tsx`
职责:
- 写作工作区总壳层
- 布局标题区、工具栏、正文区、状态区
必须完成:
- 自适应布局
- 桌面端优先
- 窄屏降级
## 6.3 `TiptapEditor.tsx`
职责:
- 包装 Tiptap EditorContent
- 负责 editor 实例初始化
必须完成:
- `onUpdate`
- `onSelectionUpdate`
- 内容同步
## 6.4 `WritingToolbar.tsx`
职责:
- 顶部主工具栏
必须完成:
- 所有基础格式化命令
- 当前状态高亮
## 6.5 `WritingBubbleMenu.tsx`
职责:
- 选区浮层
必须完成:
- 跟随选区
- 基础快捷操作
- AI 改写入口
## 6.6 `WritingAiMenu.tsx`
职责:
- AI 改写动作菜单
必须完成:
- 一级菜单
- 改语气二级菜单
- 动作触发
## 6.7 `WritingRewritePreview.tsx`
职责:
- 展示候选内容
必须完成:
- 替换
- 插入
- 重试
- 取消
---
## 7. Hook 级开发清单
## 7.1 `useWritingEditor.ts`
负责:
- editor 生命周期
- 初始内容装载
- 内容变更同步
## 7.2 `useWritingSelection.ts`
负责:
- 当前选区抽取
- 选区文本缓存
- 多段落纯文本拼接
## 7.3 `useWritingRewrite.ts`
负责:
- 改写请求
- loading / success / error
- 结果缓存
- 重试
## 7.4 `useWritingToolbar.ts`
负责:
- toolbar active 状态
- editor command 映射
---
## 8. API 对接清单
前端需向后端约定以下接口能力:
- `POST /api/writing/rewrite`
前端请求内容至少包括:
- `threadId`
- `documentId`
- `selection.from`
- `selection.to`
- `selection.text`
- `action`
- `tone`
- `surroundingContext.before`
- `surroundingContext.after`
前端需处理的返回字段:
- `output`
- `originalSelection`
- `metadata`
---
## 9. 状态管理建议
建议新增独立 Context:
- `WritingEditorContext.tsx`
建议持有:
- 当前文档内容
- 当前 editor 实例
- 当前选区
- 当前改写请求状态
- 当前候选结果
- 当前 UI 面板状态
不建议继续复用旧 Artifact Context 的原因:
- 旧 Context 关注文件列表和文件路径
- 新编辑器关注选区、结构、候选结果、应用动作
- 关注点完全不同
---
## 10. 前端联调检查点
## 10.1 与后端联调前
- 先用 mock 数据打通浮层和预览
- 先验证替换 / 插入逻辑
## 10.2 与后端联调时
- 检查多段落选区拼接结果
- 检查 AI 返回内容是否带说明性前缀
- 检查替换后位置是否准确
## 10.3 联调后
- 验证大段文本性能
- 验证撤销 / 重做
- 验证快速连续触发是否会状态错乱
---
## 11. 前端测试清单
## 11.1 功能测试
- 输入正文
- 插入标题
- 切换列表
- 插入引用
- 插入代码块
- 加粗 / 斜体 / 下划线 / 删除线
- 选区浮层显示
- 选区浮层隐藏
- AI 改写菜单打开
- 改语气二级菜单打开
- 改写结果替换
- 改写结果插入
- 改写结果取消
## 11.2 场景测试
- 单段短文本润色
- 多段文本润色
- 多段文本扩写
- 多段文本缩写
- 多段文本改语气
- 连续两次改写同一段
- 快速切换线程后重新进入
## 11.3 回归测试
- 左侧聊天是否正常
- 模型切换是否正常
- `writing_mode` 是否正常
- 原有 artifact 模块是否仍可使用
---
## 12. 任务优先级
### P0
- 路由与页面壳
- Tiptap 接入
- 主工具栏
- 选区浮层
- 改写菜单
- 替换 / 插入
### P1
- 页面头部与状态
- 优雅 loading / error / retry
- 多段落稳定性
- UI 打磨
### P2
- 空态优化
- 动效优化
- 快捷键支持
---
## 13. 建议分工
### 前端 1 号
负责:
- 路由与页面壳
- Tiptap 接入
- 主工具栏
### 前端 2 号
负责:
- 选区状态
- BubbleMenu
- AI 菜单
### 前端 3 号
负责:
- 候选结果预览
- 替换 / 插入
- 状态栏与页面体验
### 联调负责人
负责:
- 前后端请求协议
- 错误态规范
- 多段落测试和回归
---
## 14. 前端完成定义
满足以下条件可视为前端完成:
- 右侧能作为正式编辑器独立使用
- 选区后可直接发起 AI 改写
- 改写后可替换或插入
- 视觉上明显优于当前版本
- 左侧聊天和现有系统不被破坏
---
## 15. 下一步建议
前端团队可以按以下顺序开工:
1. 先起页面和路由
2. 再接 Tiptap 与主工具栏
3. 再做选区浮层
4. 再接 AI 菜单和结果预览
5. 最后做视觉打磨
这个顺序风险最小,也最容易在中途验收。
@@ -1,457 +0,0 @@
# AI 写作助手源码与实现映射表
## 1. 文档目标
本文档用于把以下几类信息对应起来:
- 豆包 AI 写作助手里要借鉴的交互
- Novel / open-canvas / Tiptap 中可参考的实现思路
- DeerFlow 当前项目里已经存在的落点
- 本次新建模块应该落到哪里
这份文档不是源码复制文档,而是开发时的“对照表”和“导航图”。
---
## 2. 使用方式
开发时建议按以下顺序看:
1. 先看“目标能力”
2. 再看“参考来源”
3. 再看“DeerFlow 当前落点”
4. 最后看“本次目标文件”
这样可以避免出现两种常见问题:
- 直接照搬外部项目结构,结果和你们现有架构冲突
- 只看自己项目,不知道成熟产品交互应该怎么落
---
## 3. 总体映射
| 目标能力 | 产品参考 | 外部参考实现 | DeerFlow 当前落点 | 本次目标文件 |
| --- | --- | --- | --- | --- |
| 写作工作区路由 | open-canvas 独立页面 | open-canvas 路由组织思路 | `frontend-web/src/pages/PageRoutes.tsx` | `frontend-web/src/open-canvas-writing/routes/WritingRoutes.tsx` |
| 左右双栏工作区 | 豆包写作页 / open-canvas | open-canvas 页面壳思路 | `frontend-web/src/components/workspace/chats/chat-box.tsx` | `frontend-web/src/open-canvas-writing/pages/WritingWorkspacePage.tsx`、`WritingShell.tsx` |
| 富文本正文编辑 | Novel | Tiptap 官方编辑器模式 | 当前无正式富文本正文编辑器 | `frontend-web/src/open-canvas-writing/editor/TiptapEditor.tsx` |
| 文档工具栏 | 豆包 / Novel | Tiptap Toolbar 组合思路 | 当前右侧无正式工具栏 | `frontend-web/src/open-canvas-writing/components/WritingToolbar.tsx` |
| 选区浮层 | 豆包 | Tiptap BubbleMenu | 当前右侧无选区浮层 | `frontend-web/src/open-canvas-writing/components/WritingBubbleMenu.tsx` |
| AI 改写菜单 | 豆包 | 自定义菜单 + BubbleMenu 挂接 | 当前无 | `frontend-web/src/open-canvas-writing/components/WritingAiMenu.tsx` |
| 候选结果预览 | 豆包 / open-canvas | open-canvas 候选应用思路 | 当前无 | `frontend-web/src/open-canvas-writing/components/WritingRewritePreview.tsx` |
| 替换 / 插入 | 豆包 | Tiptap transaction 应用 | 当前无 | `frontend-web/src/open-canvas-writing/utils/apply-rewrite.ts` |
| 写作模式总入口 | 当前 DeerFlow | 现有 `writing_mode` 开关 | `frontend-web/src/components/workspace/input-box.tsx` | 保留现有入口并接新页面 |
| 线程与模型协同 | 当前 DeerFlow | 现有线程 / 模型体系 | 现有 `core/threads`、`core/models` | 继续复用,新增 `api/rewrite.ts` |
---
## 4. 豆包功能到 DeerFlow 的映射
## 4.1 滑词 / 选区浮层
### 豆包里的体验
- 选中文本后出现轻量浮层
- 浮层里有:
- AI 改写
- 文本样式
- 复制
### DeerFlow 当前状态
- 右侧还没有正式的选区级工具层
### 本次实现方式
- 使用 Tiptap 的 `BubbleMenu`
- 再叠加自定义菜单逻辑
### 本次落点
- `frontend-web/src/open-canvas-writing/components/WritingBubbleMenu.tsx`
- `frontend-web/src/open-canvas-writing/hooks/useWritingSelection.ts`
- `frontend-web/src/open-canvas-writing/editor/selection.ts`
---
## 4.2 多段落改写
### 豆包里的体验
- 不是只改单句
- 能对连续几段一起润色、扩写、缩写、改语气
### DeerFlow 当前状态
- 现有右侧编辑区没有正式的多段落选区改写模型
### 本次实现方式
- 前端提取连续选区纯文本
- 前端附带前后文
- 后端返回候选纯文本
- 前端决定替换或插入
### 本次落点
- `frontend-web/src/open-canvas-writing/hooks/useWritingSelection.ts`
- `frontend-web/src/open-canvas-writing/hooks/useWritingRewrite.ts`
- `frontend-web/src/open-canvas-writing/api/rewrite.ts`
---
## 4.3 替换 / 插入
### 豆包里的体验
- 改写结果不是直接覆盖原文
- 用户可选择:
- 替换
- 插入
### DeerFlow 当前状态
- 当前没有候选文本应用层
### 本次实现方式
- 建立候选结果预览区
- 基于 Tiptap transaction 应用文本
### 本次落点
- `frontend-web/src/open-canvas-writing/components/WritingRewritePreview.tsx`
- `frontend-web/src/open-canvas-writing/utils/apply-rewrite.ts`
---
## 4.4 标题 / 列表 / 引用 / 代码块工具条
### 豆包里的体验
- 右侧本身就是正式文档编辑器
- 可以快速切换文档结构
### DeerFlow 当前状态
- 当前右侧偏预览,不是正式写作编辑器
### 本次实现方式
- 使用 Tiptap 节点和命令
- 在主工具栏中集中承载
### 本次落点
- `frontend-web/src/open-canvas-writing/components/WritingToolbar.tsx`
- `frontend-web/src/open-canvas-writing/hooks/useWritingToolbar.ts`
- `frontend-web/src/open-canvas-writing/editor/commands.ts`
- `frontend-web/src/open-canvas-writing/editor/TiptapExtensions.ts`
---
## 5. Novel 参考映射
## 5.1 最值得借鉴的不是“代码整搬”,而是这三件事
- 编辑器主容器的产品感
- 工具栏和空态的组织方式
- 正文阅读宽度、排版、留白
## 5.2 对应到 DeerFlow 的实现位置
- 页面壳:`WritingShell.tsx`
- 顶部文档区:`WritingHeader.tsx`
- 编辑容器:`TiptapEditor.tsx`
- 工具栏:`WritingToolbar.tsx`
- 空态:`WritingEmptyState.tsx`
## 5.3 不建议直接照搬的部分
- Next.js 页面结构
- 依赖其服务端 AI 调用方式
- 与 Vercel AI SDK 深绑定的部分
---
## 6. open-canvas 参考映射
## 6.1 主要借鉴对象
open-canvas 这次最值得借鉴的不是页面外观,而是:
- AI 工作流组织方式
- 改写结果应用节奏
- 编辑器和聊天协作的模式
## 6.2 借鉴重点
### 借鉴 1:独立工作区思想
不要把写作体验塞进一个零散的弹窗或文件详情页,要有独立工作区。
对应 DeerFlow:
- `frontend-web/src/open-canvas-writing/pages/WritingWorkspacePage.tsx`
### 借鉴 2:画布状态独立维护
不要让写作状态完全依附聊天消息渲染结果,要独立维护文档和候选状态。
对应 DeerFlow:
- `frontend-web/src/open-canvas-writing/context/WritingEditorContext.tsx`
### 借鉴 3:AI 输出先预览,再应用
对应 DeerFlow:
- `frontend-web/src/open-canvas-writing/components/WritingRewritePreview.tsx`
---
## 7. Tiptap 参考映射
## 7.1 Tiptap 在本项目中的职责
- 作为右侧正式富文本编辑器内核
- 提供结构节点与 marks
- 提供 BubbleMenu 能力
- 提供 transaction 应用能力
## 7.2 建议直接参考的实现点
- `EditorContent` 的封装模式
- `BubbleMenu` 的接入方式
- heading / list / blockquote / codeBlock 扩展配置
- `editor.chain().focus()` 命令调用模式
- selection 变化监听
## 7.3 DeerFlow 本次落点
- `frontend-web/src/open-canvas-writing/editor/TiptapEditor.tsx`
- `frontend-web/src/open-canvas-writing/editor/TiptapExtensions.ts`
- `frontend-web/src/open-canvas-writing/editor/commands.ts`
- `frontend-web/src/open-canvas-writing/components/WritingBubbleMenu.tsx`
---
## 8. DeerFlow 现有文件到新模块的映射
## 8.1 `frontend-web/src/pages/PageRoutes.tsx`
### 当前职责
- 汇总页面路由
### 本次作用
- 挂入新的写作助手路由
### 后续动作
- 引入 `WritingRoutes`
- 增加 `page/writing/*`
---
## 8.2 `frontend-web/src/components/workspace/chats/chat-box.tsx`
### 当前职责
- 左聊天 + 右 Artifact 双栏布局
### 本次作用
- 提供双栏工作区组织思路
- 可复用布局比例和 panel 交互经验
### 不建议直接复用的部分
- 不要继续让右侧核心能力挂在 ArtifactFileDetail 上
### 本次目标替代
- `WritingWorkspacePage.tsx`
- `WritingShell.tsx`
---
## 8.3 `frontend-web/src/components/workspace/artifacts/context.tsx`
### 当前职责
- 管理文件型 artifact 列表、选中项和开关状态
### 本次作用
- 仅作为旧 Artifact 模块保留
### 本次目标替代
- `WritingEditorContext.tsx`
### 原因
- 写作编辑器需要的不是文件路径状态
- 而是文档状态、选区状态、候选结果状态、工具层状态
---
## 8.4 `frontend-web/src/components/workspace/input-box.tsx`
### 当前职责
- 聊天输入区
- 已有 `writing_mode` 入口
### 本次作用
- 保留为用户进入写作模式的现有入口
### 本次改造建议
- 写作模式打开时,跳转或唤起新的写作工作区
- 不再只停留在“生成 Markdown 文件”这个层面
---
## 9. 新模块间的依赖关系
## 9.1 页面层
- `WritingRoutes.tsx`
- `WritingWorkspacePage.tsx`
- `WritingShell.tsx`
职责:
- 页面路由
- 双栏或工作区布局
- 上下文装配
## 9.2 编辑器层
- `TiptapEditor.tsx`
- `TiptapExtensions.ts`
- `commands.ts`
- `selection.ts`
职责:
- 编辑器内核
- 节点和 marks
- 基础命令
- 选区抽取
## 9.3 交互层
- `WritingToolbar.tsx`
- `WritingBubbleMenu.tsx`
- `WritingAiMenu.tsx`
- `WritingRewritePreview.tsx`
职责:
- 工具栏
- 浮层
- AI 菜单
- 候选内容应用
## 9.4 状态层
- `WritingEditorContext.tsx`
- `useWritingEditor.ts`
- `useWritingSelection.ts`
- `useWritingRewrite.ts`
- `useWritingToolbar.ts`
职责:
- 主状态
- 选区状态
- 改写状态
- 工具栏状态
## 9.5 API 层
- `api/rewrite.ts`
- `api/documents.ts`
职责:
- 对接后端写作改写接口
- 对接文档加载与保存接口
---
## 10. 能力到文件的精确映射
| 能力 | 新文件 | 说明 |
| --- | --- | --- |
| 新写作页面 | `frontend-web/src/open-canvas-writing/pages/WritingWorkspacePage.tsx` | 承载整个新模式 |
| 写作路由 | `frontend-web/src/open-canvas-writing/routes/WritingRoutes.tsx` | 统一路由入口 |
| 页面外壳 | `frontend-web/src/open-canvas-writing/components/WritingShell.tsx` | 页面布局与容器 |
| 文档头部 | `frontend-web/src/open-canvas-writing/components/WritingHeader.tsx` | 标题、状态 |
| 主工具栏 | `frontend-web/src/open-canvas-writing/components/WritingToolbar.tsx` | 文档结构与格式工具 |
| 正文编辑器 | `frontend-web/src/open-canvas-writing/editor/TiptapEditor.tsx` | Tiptap 核心封装 |
| 扩展配置 | `frontend-web/src/open-canvas-writing/editor/TiptapExtensions.ts` | 节点和 marks |
| 选区浮层 | `frontend-web/src/open-canvas-writing/components/WritingBubbleMenu.tsx` | 选区出现的悬浮条 |
| AI 菜单 | `frontend-web/src/open-canvas-writing/components/WritingAiMenu.tsx` | 润色、扩写等动作 |
| 改写预览 | `frontend-web/src/open-canvas-writing/components/WritingRewritePreview.tsx` | 候选内容展示与应用 |
| 替换 / 插入 | `frontend-web/src/open-canvas-writing/utils/apply-rewrite.ts` | 应用候选结果 |
| 编辑器状态 | `frontend-web/src/open-canvas-writing/context/WritingEditorContext.tsx` | 独立上下文 |
| 改写请求 | `frontend-web/src/open-canvas-writing/api/rewrite.ts` | 调后端接口 |
---
## 11. 开发时的参考顺序
建议开发顺序如下:
1. 先看 `PageRoutes.tsx`,确定路由接法
2. 再看 `chat-box.tsx`,理解当前左右布局
3. 然后起 `WritingWorkspacePage.tsx` 和 `WritingShell.tsx`
4. 再接 `TiptapEditor.tsx`
5. 再做 `WritingToolbar.tsx`
6. 再做 `WritingBubbleMenu.tsx`
7. 再做 `WritingAiMenu.tsx`
8. 最后做 `WritingRewritePreview.tsx`
这样可以让每一层都有稳定承载,不会出现“先做了 AI 菜单,但页面还没落点”的混乱情况。
---
## 12. 明确哪些是“参考”,哪些是“目标”
### 12.1 参考
- 豆包:交互体验参考
- Novel:页面和编辑器质感参考
- open-canvas:AI 工作流参考
- Tiptap:编辑器技术实现参考
### 12.2 目标
目标不是复刻任何一个外部项目,而是:
- 在 DeerFlow 现有架构中
- 用 React + Vite + 现有线程体系
- 做出一个更成熟的 AI 写作编辑器模式
---
## 13. 结论
这份映射表的核心作用,是避免团队在开发时迷路。
真正推荐的姿势是:
- 用豆包定义目标体验
- 用 Novel 定义页面质感
- 用 open-canvas 定义 AI 工作流
- 用 Tiptap 作为编辑器内核
- 用 DeerFlow 现有路由、线程、模型体系做宿主
这样推进,既不会脱离你们现有工程,也能尽量快地把右侧编辑区拉到更接近成熟产品的水平。
File diff suppressed because it is too large. Load diff
@@ -1,645 +0,0 @@
# AI 写作后端新路线设计草案
## 1. 目标
为“弱模型多 Agent 写作工作流”建设一条独立后端路线,满足以下要求:
- 不影响现有同事正在开发的功能
- 不强耦合现有 DeerFlow 通用对话主链路
- 可独立部署、独立调试、独立回滚
- 支持多阶段写作编排、人工介入、失败重试、流式事件输出
---
## 2. 推荐建设方式
优先建议:
- 在 `offline-backend-20260512` 下新建独立应用或独立模块
建议目录:
```text
offline-backend-20260512/
apps/
ai_writing_orchestrator/
api/
application/
domain/
infrastructure/
prompts/
tests/
```
如果当前后端没有 `apps/` 结构,也可以采用:
```text
offline-backend-20260512/
ai-writing-orchestrator/
api/
application/
domain/
infrastructure/
prompts/
tests/
```
重点不是目录名字,而是一定要把“多 Agent 写作编排”与现有通用聊天能力隔离开。
---
## 3. 技术路线建议
推荐组合:
- 编排框架:`LangGraph`
- 模型调用:接你们内网模型网关
- 检索层:接内网知识库 / 文档库 / 搜索服务
- 状态存储:先用数据库或 Redis + DB,后续再演进
- 事件输出:SSE 或流式 HTTP
推荐原因:
- `LangGraph` 适合状态机和多节点回退
- 对弱模型最关键的是“强流程控制”,不是“自由 Agent 对话”
- 后续加人工确认节点和 checkpoint 会更自然
---
## 4. 分层设计
建议按四层拆分。
## 4.1 API 层
职责:
- 接收前端请求
- 鉴权
- 参数校验
- 返回 workflow 信息
- 提供事件流出口
建议文件:
```text
api/
routes/
workflows.py
workflow_events.py
schemas/
workflow_request.py
workflow_response.py
```
## 4.2 Application 层
职责:
- 组织用例
- 调度 workflow service
- 管理人工确认动作
- 处理重试和终止逻辑
建议文件:
```text
application/
services/
workflow_service.py
workflow_event_service.py
human_action_service.py
use_cases/
create_workflow.py
start_workflow.py
confirm_outline.py
rewrite_section.py
approve_final.py
```
## 4.3 Domain 层
职责:
- 定义工作流状态机
- 定义 Agent 输入输出协议
- 定义 artifact 与评分模型
建议文件:
```text
domain/
models/
workflow.py
workflow_stage.py
workflow_event.py
artifact.py
review_result.py
agents/
researcher.py
outliner.py
writer.py
editor.py
supervisor.py
graphs/
writing_graph.py
policies/
retry_policy.py
quality_policy.py
```
## 4.4 Infrastructure 层
职责:
- 访问模型网关
- 访问检索服务
- 访问数据库
- 发送事件
- 缓存与日志
建议文件:
```text
infrastructure/
llm/
model_client.py
retrieval/
intranet_search_client.py
knowledge_base_client.py
persistence/
workflow_repository.py
artifact_repository.py
streaming/
sse_publisher.py
logging/
workflow_logger.py
```
---
## 5. 工作流最小闭环
第一版建议只做如下状态机:
1. `collect_materials`
2. `generate_outline`
3. `await_outline_confirmation`
4. `write_draft`
5. `review_draft`
6. `rewrite_if_needed`
7. `complete`
终止规则:
- 编辑评分达标则完成
- 否则进入重写
- 最多重写 2 次
- 超过次数则标记 `human_intervention_required`
---
## 6. Agent 模块设计
## 6.1 Researcher
输入:
- 主题
- 用户要求
- 检索范围
- 可用资料源
输出:
- `material_cards`
- `facts`
- `quotes`
- `examples`
- `risks`
- `source_refs`
程序职责:
- 先做检索
- 再把检索结果裁剪后送给模型
- 输出必须结构化
## 6.2 Outliner
输入:
- 用户要求
- 研究结果
输出:
- `title_candidates`
- `outline_sections`
- `key_points_per_section`
约束:
- 提纲优先,不写正文
## 6.3 Writer
输入:
- 已确认提纲
- 素材卡片
- 风格要求
输出:
- `draft_sections`
- `section_source_refs`
- `full_draft_markdown`
建议:
- 按章节分段生成,不要一次长文直出
## 6.4 Editor
输入:
- 初稿
- 提纲
- 素材
- 用户要求
输出:
- `issues`
- `severity`
- `score`
- `rewrite_instructions`
- `decision`
规则:
- 先查事实,再查结构,再查文风
## 6.5 Supervisor
输入:
- 各阶段结果
- 重试计数
- 评分结果
输出:
- 下一跳节点
- 是否需要人工确认
- 是否结束
---
## 7. Prompt 组织建议
建议为每个 Agent 分开管理 prompt,不要写成一个超级 prompt。
建议目录:
```text
prompts/
researcher/
system.txt
output_schema.json
outliner/
system.txt
output_schema.json
writer/
system.txt
output_schema.json
editor/
system.txt
output_schema.json
supervisor/
system.txt
```
原则:
- 每个 Agent 一套职责
- 每个 Agent 一套输出 schema
- Prompt 版本可管理
- 后续支持 A/B 调参
---
## 8. 弱模型适配策略
## 8.1 先检索后生成
不要让模型自己“想资料”,程序先检索、裁剪、去重后再喂给模型。
## 8.2 短上下文任务化
每个节点只给弱模型一小段明确任务:
- 研究归纳
- 提纲整理
- 单章节写作
- 单章节审稿
## 8.3 结构化输出
优先 JSON 或 Pydantic schema,不要放任自然语言自由返回。
## 8.4 章节级重写
不要整篇回炉。编辑指出第 2 节有问题,就只重写第 2 节。
## 8.5 程序接管质量门槛
例如:
- 资料引用数不足,不进入下一步
- 提纲章节数过少,直接重生
- 编辑评分低于阈值,自动重写
---
## 9. 数据模型建议
## 9.1 Workflow
建议字段:
- `id`
- `status`
- `current_stage`
- `user_id`
- `thread_id`
- `input_payload`
- `current_artifact_id`
- `retry_count`
- `created_at`
- `updated_at`
## 9.2 Workflow Artifact
建议字段:
- `id`
- `workflow_id`
- `artifact_type`
- `stage`
- `version`
- `title`
- `content`
- `metadata`
## 9.3 Workflow Event
建议字段:
- `id`
- `workflow_id`
- `event_type`
- `stage`
- `agent_name`
- `payload`
- `created_at`
## 9.4 Human Action
建议字段:
- `workflow_id`
- `action_type`
- `payload`
- `operator`
- `created_at`
---
## 10. API 草案
## 10.1 创建任务
`POST /api/ai-writing/workflows`
请求:
```json
{
"topic": "主题",
"articleType": "行业分析",
"audience": "管理层",
"tone": "专业克制",
"targetLength": 3000,
"constraints": ["避免口语化"],
"referenceScope": ["内网知识库", "项目复盘文档"]
}
```
返回:
```json
{
"workflowId": "wf_xxx",
"status": "idle"
}
```
## 10.2 启动任务
`POST /api/ai-writing/workflows/{id}/start`
## 10.3 查询任务
`GET /api/ai-writing/workflows/{id}`
## 10.4 订阅事件
`GET /api/ai-writing/workflows/{id}/events`
返回事件流示例:
```json
{
"type": "stage_changed",
"stage": "generating_outline",
"message": "正在生成提纲"
}
```
## 10.5 确认提纲
`POST /api/ai-writing/workflows/{id}/confirm-outline`
## 10.6 指定章节重写
`POST /api/ai-writing/workflows/{id}/rewrite-section`
## 10.7 确认终稿
`POST /api/ai-writing/workflows/{id}/approve-final`
---
## 11. LangGraph 实现建议
## 11.1 推荐 graph 节点
- `load_input`
- `retrieve_materials`
- `normalize_materials`
- `generate_outline`
- `wait_for_outline_confirmation`
- `write_sections`
- `merge_sections`
- `review_draft`
- `rewrite_sections`
- `publish_final_artifact`
## 11.2 推荐 state
建议 state 字段:
- `workflow_id`
- `input_payload`
- `materials`
- `outline`
- `outline_confirmed`
- `draft_sections`
- `merged_draft`
- `review_result`
- `rewrite_targets`
- `final_article`
- `retry_count`
- `events`
## 11.3 条件边
建议条件边逻辑:
- 提纲未确认 -> 等待用户
- 编辑通过 -> 完成
- 编辑不通过且可重试 -> 重写
- 编辑不通过且超限 -> 人工介入
---
## 12. 可观测性要求
第一版就建议带上以下能力:
- 每个 workflow 的事件日志
- 每个 Agent 的输入输出摘要
- 每次重试原因
- 每个阶段耗时
- 每次模型调用 token 与错误日志
后续排问题会非常依赖这些数据。
---
## 13. 测试建议
## 13.1 单元测试
覆盖:
- stage 流转
- retry policy
- quality policy
- 事件构造
## 13.2 集成测试
覆盖:
- 创建任务到完成的主链路
- 提纲确认链路
- 审稿失败后重写链路
- 人工介入链路
## 13.3 Prompt 回归集
建议建立 10-20 个固定写作样例,做回归:
- 短文
- 长文
- 事实密集型文章
- 宣传型文章
- 分析型文章
---
## 14. 开发顺序建议
## Step 1:先做 domain 与 API 契约
先定:
- stage 枚举
- event 枚举
- artifact 结构
- human action payload
## Step 2:先做 fake orchestrator
先不接真实模型,只模拟事件流,把前后端联调跑通。
## Step 3:接 Researcher + Outliner
优先把“研究 + 提纲”做出来,因为这是弱模型提升最大的环节。
## Step 4:接 Writer + Editor
再接初稿和审稿重写。
## Step 5:接可观测性和缓存
最后再补生产化能力。
---
## 15. 风险控制建议
### 风险 1:直接复用现有线程流,导致协议污染
建议:
- workflow 用独立 route 和独立 event schema
### 风险 2:写作结果与右侧 artifact 模型不兼容
建议:
- 后端统一输出标准 markdown artifact
### 风险 3:弱模型频繁输出不合法 JSON
建议:
- 每个节点加 schema repair
- 加轻量重试
- 尽量减少复杂嵌套输出
### 风险 4:研究资料太多导致上下文爆炸
建议:
- 检索后先裁剪、摘要、分桶
---
## 16. 最终建议
后端第一版最重要的是把“状态机、事件流、人工确认、章节重写”这四件事做对,而不是一开始就追求很多花哨 Agent。
建议 MVP 只保留:
1. Researcher
2. Outliner
3. Writer
4. Editor
5. Supervisor
当这条链路稳定后,再继续扩展 fact-checker、style editor、compliance reviewer。
@@ -1,806 +0,0 @@
# AI 写作执行方案
## 1. 总体原则
本项目的最终落地原则:
1. 前端继续基于当前 `open-canvas` 页面开发,不复制第二套页面
2. 后端单独开 `ai-writing-orchestrator` 新路线,不侵入现有主链路
3. 编排框架采用 `LangGraph`
4. 写作工作流采用 `Researcher -> Outliner -> Writer -> Editor -> Supervisor`
5. Agent 间输出统一采用 `JSON Schema / Pydantic`
6. 前后端通过 `SSE` 传递工作流事件
7. 第一版只做最小闭环,不做过多花哨扩展
一句话说明:
用独立的新后端路线承载多 Agent 写作工作流,前端继续复用 `open-canvas`,实现上采用 `LangGraph + A/B/C Agent + SSE` 的最小闭环。
---
## 2. 项目边界
## 2.1 前端边界
继续使用当前页面:
- [CanvasResizableLayout.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/layout/CanvasResizableLayout.tsx)
- [CanvasChatPanel.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/chat/CanvasChatPanel.tsx)
- [CanvasArtifactPanel.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/artifact/CanvasArtifactPanel.tsx)
前端做的事情:
- 左侧增加“写作工作流模式”
- 展示多 Agent 执行进度与中间产物
- 提供提纲确认和指定章节重写
- 将初稿、终稿同步到右侧 artifact
前端不做的事情:
- 不重写右侧编辑器
- 不重写现有普通 chat 流程
- 不把 workflow 状态散落在多个旧 context 里
## 2.2 后端边界
后端采用独立新路线:
推荐目录:
```text
offline-backend-20260512/
apps/
ai_writing_orchestrator/
api/
application/
domain/
infrastructure/
prompts/
tests/
```
后端做的事情:
- 实现写作 workflow 状态机
- 实现 A/B/C Agent 与 Supervisor
- 接内网模型与内网检索
- 输出标准事件流和文章 artifact
后端不做的事情:
- 不直接改现有 DeerFlow 主流程
- 不把工作流逻辑塞到现有通用 thread 协议里
## 2.3 资料搜集边界
第一版处于互联网开发阶段,因此研究员的资料搜集先走互联网检索,不接内网检索服务。
第一版要求:
- 研究员可以调用互联网搜索能力收集公开资料
- 研究结果必须保留来源 URL、标题、摘要、抓取时间
- 检索层必须抽象成统一接口,不能把互联网搜索逻辑写死在 Agent prompt 或 graph 节点里
第二版预留:
- 后续替换或并行接入内网搜索接口
- 后续接入内部知识库、文档库、FAQ、项目复盘库
- 前端和工作流层不因检索源变化而改协议
统一设计要求:
- `Researcher` 只依赖“检索接口”,不依赖具体是互联网还是内网
- `writing_graph` 只读取标准化后的素材结果
- API、事件流、artifact 结构不区分互联网资料和内网资料
推荐检索抽象:
```text
infrastructure/
retrieval/
base.py
internet_search_client.py
intranet_search_client.py
retriever_router.py
```
建议接口:
```python
class RetrievalProvider(Protocol):
def search(self, query: str, top_k: int) -> list[RetrievedDocument]: ...
class RetrievedDocument(BaseModel):
title: str
url: str | None
source_type: str
snippet: str
published_at: str | None = None
fetched_at: str
reliability: str | None = None
```
第一版路由策略:
- 默认 `internet`
- 配置项预留 `intranet`、`hybrid`
例如:
```yaml
retrieval:
provider: internet
top_k: 8
timeout_seconds: 15
```
这样第一版先跑公网资料,后续切换内网时,只替换 `retriever_router` 和对应 provider,不改 workflow 主逻辑。
---
## 3. 第一版产品目标
用户在 `open-canvas` 中选择“写作工作流模式”后,可以完成以下流程:
1. 输入主题、体裁、读者、风格、篇幅
2. 研究员搜集资料并输出素材卡片
3. 提纲 Agent 生成提纲
4. 用户确认提纲
5. Writer 生成初稿
6. Editor 给出问题清单与评分
7. 不达标则重写一次或两次
8. 终稿写入右侧 artifact
第一版成功标准:
- 不是“生成得像最强模型一样好”
- 而是“明显优于单轮直出,并且流程可控、可回退、可人工介入”
## 3.1 第一版研究员目标
第一版 `Researcher` 的核心职责,不是“写文章”,而是“给 Writer 准备可信、可引用、可筛选的素材”。
第一版输入:
- 用户主题
- 用户写作要求
- 检索源配置,第一版默认 `internet`
第一版输出至少包含:
- `material_cards`
- `facts`
- `quotes`
- `examples`
- `risks`
- `source_refs`
每条素材最少要带:
- 来源标题
- 来源 URL
- 摘要
- 可信度标签
- 被引用的原始片段或整理后的事实点
第一版 Researcher 的程序流程建议:
1. 根据主题自动生成 3-5 个检索 query
2. 调用互联网检索接口拿回候选文档
3. 做去重、裁剪、初筛
4. 让模型将结果整理成结构化素材卡片
5. 将结构化结果返回给 Outliner 和 Writer
第一版先不做:
- 深度网页 crawling
- 多轮自动追问式深研究
- 内网知识库接入
- 复杂引用格式生成
---
## 4. 最终工作流
## 4.1 Agent 角色
### `Researcher`
职责:
- 从配置的检索源检索信息
- 产出结构化素材卡片
- 标注来源、可信度、风险点
第一版说明:
- 默认走互联网公开资料检索
- 必须预留后续切换到内网检索源的接口
- 检索实现放在 `infrastructure/retrieval/`,不要写死在 prompt 中
第一版检索源字段建议:
- `source_type = "internet"`
- 后续预留 `source_type = "intranet" | "hybrid"`
输出:
- `material_cards`
- `facts`
- `quotes`
- `examples`
- `risks`
- `source_refs`
### `Outliner`
职责:
- 根据用户要求和研究结果生成提纲
输出:
- `title_candidates`
- `outline_sections`
- `key_points_per_section`
### `Writer`
职责:
- 基于提纲和素材写初稿
- 按章节写,不一次生成整篇长文
输出:
- `draft_sections`
- `section_source_refs`
- `full_draft_markdown`
### `Editor`
职责:
- 检查事实、结构、文风
- 给出评分与重写建议
输出:
- `issues`
- `severity`
- `score`
- `rewrite_instructions`
- `decision`
### `Supervisor`
职责:
- 负责流程调度
- 负责通过 / 重写 / 人工介入判断
## 4.2 状态机
第一版统一采用:
- `idle`
- `collecting_materials`
- `generating_outline`
- `await_outline_confirmation`
- `writing_draft`
- `reviewing_draft`
- `rewriting_draft`
- `completed`
- `failed`
- `human_intervention_required`
## 4.3 流程闭环
最小闭环固定为:
1. `Research`
2. `Outline`
3. `HumanConfirmOutline`
4. `Draft`
5. `Review`
6. `RewriteIfNeeded`
7. `Complete`
重试规则:
- 最多重写 2 次
- 达标则完成
- 超限则进入人工介入
## 4.4 LangGraph 推荐节点
第一版推荐节点:
- `load_input`
- `build_search_queries`
- `retrieve_materials`
- `normalize_materials`
- `generate_outline`
- `wait_for_outline_confirmation`
- `write_sections`
- `merge_sections`
- `review_draft`
- `rewrite_sections`
- `publish_final_artifact`
其中和资料搜集直接相关的节点说明:
### `build_search_queries`
职责:
- 根据用户主题和目标文章类型,生成 3-5 个检索 query
### `retrieve_materials`
职责:
- 调用检索 provider 获取候选文档
- 第一版默认走 `internet_search_client`
- 后续可切到 `intranet_search_client`
### `normalize_materials`
职责:
- 做去重
- 做摘要裁剪
- 做来源字段统一
- 输出标准 `RetrievedDocument[]`
---
## 5. 前端最终做法
## 5.1 目录建议
在现有 `open-canvas` 下新增:
```text
frontend-web/src/open-canvas/
workflow/
api/
writing-workflow.ts
components/
WritingWorkflowEntryForm.tsx
WritingWorkflowTimeline.tsx
WritingWorkflowEventList.tsx
WritingWorkflowArtifactDrawer.tsx
WritingWorkflowConfirmCard.tsx
WritingWorkflowHeader.tsx
CanvasWorkflowPanel.tsx
contexts/
WritingWorkflowContext.tsx
hooks/
useWritingWorkflow.ts
useWritingWorkflowEvents.ts
types/
workflow.ts
```
## 5.2 左侧改造策略
`CanvasChatPanel` 只承担模式切换与容器职责:
- `chat` 模式:沿用现有普通聊天
- `writing_pipeline` 模式:渲染 `CanvasWorkflowPanel`
新面板负责:
- 写作任务表单
- 进度时间线
- 事件列表
- 中间产物抽屉
- 提纲确认卡片
## 5.3 右侧衔接策略
继续复用现有 `CanvasArtifactPanel`。
同步规则:
- 提纲:可选同步到右侧预览
- 初稿:同步到右侧
- 重写稿:覆盖当前草稿
- 终稿:作为最终 artifact
## 5.4 前端状态设计
新增:
- `workflowMode`
- `workflowRunId`
- `workflowStage`
- `workflowStatus`
- `workflowEvents`
- `workflowArtifacts`
- `workflowPendingAction`
注意:
- workflow 状态放进新的 `WritingWorkflowContext`
- 不塞进现有 `CanvasGraphContext`
## 5.5 前端显示的资料信息
第一版左侧至少要能展示研究员产出的资料摘要:
- 来源标题
- 来源域名或 URL
- 资料摘要
- 可信度标签
- 是否被提纲或正文引用
建议在 `WritingWorkflowArtifactDrawer.tsx` 中增加“素材卡片”视图。
注意:
- 第一版显示公开互联网来源即可
- 后续接内网时,这个展示层不变,只是来源字段从 URL 变成内网文档标识或内部链接
---
## 6. 后端最终做法
## 6.1 分层
推荐分层:
```text
api/
application/
domain/
infrastructure/
prompts/
tests/
```
## 6.2 核心模块
建议核心文件:
```text
domain/
models/
workflow.py
workflow_stage.py
workflow_event.py
artifact.py
review_result.py
agents/
researcher.py
outliner.py
writer.py
editor.py
supervisor.py
graphs/
writing_graph.py
policies/
retry_policy.py
quality_policy.py
```
## 6.3 检索层实现要求
第一版检索层必须独立成基础设施模块,不允许:
- 在 Agent prompt 中直接拼接“去网上找资料”
- 在 graph 节点中散落请求第三方搜索的代码
- 把互联网检索和内网检索混在一个无抽象的函数里
建议结构:
```text
infrastructure/
retrieval/
base.py
internet_search_client.py
intranet_search_client.py
retriever_router.py
material_normalizer.py
```
建议职责:
- `internet_search_client.py`
- 第一版实际使用
- 对接互联网搜索 API 或爬取网关
- `intranet_search_client.py`
- 第一版只保留接口和空实现或 mock
- 后续接企业内部接口
- `retriever_router.py`
- 根据配置选择 provider
- `material_normalizer.py`
- 统一清洗和标准化结果
## 6.4 Prompt 管理
统一独立存放:
```text
prompts/
researcher/
system.txt
output_schema.json
outliner/
system.txt
output_schema.json
writer/
system.txt
output_schema.json
editor/
system.txt
output_schema.json
supervisor/
system.txt
```
## 6.5 输出约束
每个 Agent 都必须:
- 优先输出 JSON / Pydantic schema
- 失败时允许轻量 repair 和一次重试
- 避免自由散文式输出
## 6.6 Researcher 的实现细则
Researcher 推荐由两部分组成:
1. 程序化检索
2. 模型化整理
推荐伪流程:
```python
def run_research(topic: str, article_type: str, provider: RetrievalProvider):
queries = build_queries(topic, article_type)
raw_docs = []
for query in queries:
raw_docs.extend(provider.search(query=query, top_k=5))
docs = normalize_materials(raw_docs)
docs = dedupe_materials(docs)
docs = rank_materials(docs)
return llm_extract_material_cards(docs)
```
第一版建议:
- 先把 query 生成逻辑做简单
- `top_k` 先控制在 5-10
- 先做轻量去重和摘要裁剪
- 不做很重的网页全文抓取
---
## 7. 前后端协议
## 7.1 API
第一版统一提供:
- `POST /api/ai-writing/workflows`
- `POST /api/ai-writing/workflows/{id}/start`
- `GET /api/ai-writing/workflows/{id}`
- `GET /api/ai-writing/workflows/{id}/events`
- `POST /api/ai-writing/workflows/{id}/confirm-outline`
- `POST /api/ai-writing/workflows/{id}/rewrite-section`
- `POST /api/ai-writing/workflows/{id}/approve-final`
## 7.2 SSE 事件
统一事件类型:
- `workflow_started`
- `stage_changed`
- `agent_started`
- `agent_output_chunk`
- `artifact_generated`
- `human_confirmation_required`
- `retry_scheduled`
- `workflow_completed`
- `workflow_failed`
第一版前端不需要消费复杂嵌套事件,只要先把这 9 类打通。
## 7.3 配置项补充
建议增加以下配置项:
```yaml
retrieval:
provider: internet
top_k: 8
timeout_seconds: 15
enable_content_fetch: false
workflow:
max_revisions: 2
models:
researcher: your-default-model
outliner: your-default-model
writer: your-default-model
editor: your-default-model
```
说明:
- 第一版 `provider=internet`
- 第二版可切成 `intranet` 或 `hybrid`
---
## 8. 必须做 / 延后做 / 不建议现在做
## 8.1 必须做
### 架构
- 独立后端路线 `ai-writing-orchestrator`
- 前端独立 `workflow/` 目录
- LangGraph 状态机
- `Researcher / Outliner / Writer / Editor / Supervisor`
- 独立检索抽象层,第一版先落互联网 provider
### 协议
- 标准 workflow 状态枚举
- 标准 SSE 事件枚举
- 标准 artifact 结构
- JSON / Pydantic 输出约束
### 功能
- 启动写作任务
- 研究阶段
- 提纲阶段
- 提纲确认
- 初稿生成
- 审稿与最多 2 次重写
- 终稿同步到右侧
- 素材卡片展示
- 来源 URL、标题、摘要、可信度落库或挂在 artifact metadata
### UI
- 模式切换
- 时间线
- 事件列表
- 提纲确认卡片
- 右侧终稿显示
- 左侧素材卡片视图
## 8.2 延后做
- 章节级精准重写
- 初稿多版本树
- FactChecker
- StyleEditor
- ComplianceReviewer
- 自动评分看板
- 素材引用可视化高亮
- 更复杂的人机协作节点
- 内网知识库正式接入
- 混合检索 `hybrid`
- 网页全文抓取与深摘要
## 8.3 不建议现在做
- 直接接入现有 DeerFlow 主 agent 包
- 同时试 MetaGPT、CrewAI、AutoGen 多套底座
- 一开始就做 5 个以上 Agent
- 一开始就做很复杂的文章版本管理
- 一开始就把评分阈值和 prompt 写死得非常细
## 9. 最终开发顺序
## Step 1:先定契约
先一起拍板:
- stage 枚举
- event 枚举
- artifact 结构
- confirm / rewrite 的 payload
- retrieval provider 接口
- RetrievedDocument 结构
## Step 2:先做 fake workflow
后端先不接真实模型,只吐 mock SSE 事件,前端把左侧工作台跑通。
## Step 3:先接互联网版 Researcher + Outliner
优先打磨“研究 + 提纲”,这是弱模型提升最大的部分。
这一阶段要求:
- `Researcher` 先走互联网检索
- `retriever_router` 可配置
- `intranet_search_client` 先留接口空壳
## Step 4:接 Writer + Editor
再补初稿与审稿重写闭环。
## Step 5:接右侧 artifact
把初稿和终稿稳定写入右侧。
## Step 6:补生产化
- 缓存
- 日志
- 错误回放
- 配置化 prompt
## 10. 推荐任务拆分
## 前端
- `CanvasChatPanel` 模式切换
- `workflow/` 目录与类型
- 时间线 / 事件列表 / 确认卡片
- SSE 订阅 hook
- 右侧 artifact 映射
- 素材卡片列表展示
- 来源字段展示规范
## 后端
- workflow API
- LangGraph graph
- 5 个 Agent 模块
- Prompt 目录
- SSE 输出
- 仓储与日志
- `RetrievalProvider` 抽象
- `internet_search_client`
- `intranet_search_client` 预留接口
- `material_normalizer`
## Prompt / 算法
- Researcher prompt
- Outliner prompt
- Writer prompt
- Editor prompt
- JSON schema
- 失败样本回归
## 联调
- mock SSE
- 真模型接入
- artifact 同步校验
- 提纲确认链路验证
- 互联网资料来源字段联调
- 素材卡片到提纲引用链路联调
---
## 11. 开发过程中的约束
开发过程中统一采用下面这套口径:
- 产品形态:当前 `open-canvas` 页面上的“写作工作流模式”
- 技术底座:`LangGraph`
- 核心模式:`Researcher -> Outliner -> Writer -> Editor -> Supervisor`
- 后端方式:独立 `ai-writing-orchestrator`
- 检索方式:第一版 `internet`,接口预留 `intranet`
- 通信方式:`SSE`
- 输出方式:`JSON Schema / Pydantic`
- 第一版目标:先做最小闭环,不追求角色数量和复杂度
给开发团队的统一口径:
“我们在 `open-canvas` 上开发写作工作流模式,后端单开 `ai-writing-orchestrator`,第一版先用互联网资料检索,保留内网检索接入口,用 LangGraph 编排 Researcher、Outliner、Writer、Editor、Supervisor,把研究、提纲、初稿、审稿重写这条最小闭环做稳。”
@@ -1,538 +0,0 @@
# AI 写作 — 前端开发文档
> **本文档目的**:帮助前端开发者快速理解 AI 写作子系统的代码结构、数据流、状态机和扩展点。
>
> **配套文档**:
> - `ai-writing-说明.md` — 故障排查与运维向解决方案
> - `ai-writing-assistant-backend-api.md` — 后端 API 详细字段定义
> - `ai-writing-assistant-source-map.md` — 旧版前端结构索引(已合并到本文档)
---
## 一、产品定位
AI 写作是 DeerFlow 的「**杂志社协作写作**」子产品,由 LangGraph 后端驱动 4 个 AI Agent(**素材收集专家 / 作家 / 编辑 / 系统**)协作完成一篇文章。用户通过 **4 个干预点**(素材确认、大纲确认、草稿确认、审核确认)参与决策,UI 实时呈现进度。
### UI 入口
- 路由:`/canvas/ai-writing`(在 `WorkspaceRoutes.tsx` 注册)
- 入口页:`src/open-canvas/pages/AIWritingPage.tsx`
- 双栏布局:左 AI 写作面板(聊天 + 干预),右草稿预览
---
## 二、目录结构
```
frontend-web/src/open-canvas/
├── pages/
│ └── AIWritingPage.tsx # 入口页(双栏 Resizable 布局)
│
├── api/ # ── 后端 API 适配层 ──
│ ├── ai-writing.ts # /start /resume + SSE 订阅(核心)
│ ├── ai-writing-sessions.ts # 历史会话 CRUD + transcript 保存
│ └── ai-writing-article-types.ts # 文章类型 CRUD
│
├── hooks/ # ── 状态管理 ──
│ ├── useAIWriting.ts # 写作主状态机(最重要)
│ ├── useAIWritingSessions.ts # 历史会话列表 hook
│ └── useArticleTypes.ts # 文章类型选项 hook
│
├── components/ai-writing/ # ── UI 组件 ──
│ ├── AIWritingPanel.tsx # 左侧主面板(聊天 + 干预编排)
│ ├── AIWritingDraftPanel.tsx # 右侧草稿预览面板
│ ├── AIWritingPageHeader.tsx # 顶部标题/历史下拉
│ ├── AIWritingForm.tsx # 写作请求表单(首次启动用)
│ │
│ ├── AIWritingTimeline.tsx # 时间线主容器
│ ├── TimelineStep.tsx # 单条进度事件
│ ├── CompletedInterventionCard.tsx # 已完成的干预记录
│ │
│ ├── InterventionCard.tsx # 4 个干预点 + 求助点的卡片(核心)
│ ├── MaterialsCard.tsx # 素材确认
│ ├── MaterialItem.tsx # 单个素材项
│ ├── MaterialsToolbar.tsx # 素材筛选/搜索工具栏
│ ├── OutlineCard.tsx # 大纲确认(含编辑)
│ ├── OutlineSection.tsx # 大纲单章节
│ ├── ReviewCard.tsx # 审核确认
│ ├── IssueList.tsx # 审核意见列表
│ ├── ScoreBar.tsx # 评分进度条
│ │
│ ├── OutlineStreamingView.tsx # 大纲流式打字机
│ ├── DraftStreamingView.tsx # 草稿流式打字机
│ ├── ReviewStreamingView.tsx # 审核流式打字机
│ ├── WritingSkeletonCard.tsx # 加载骨架屏
│ ├── RevisionSummaryCard.tsx # 修改前后对比摘要
│ │
│ ├── AIWritingHistoryDropdown.tsx # 历史会话下拉
│ └── AIWritingHistoryView.tsx # 历史会话只读回显
│
└── types/
└── ai-writing.ts # 全部类型定义(重要参考)
```
---
## 三、数据流总览
```
┌─────────────────────────────────────────────────────────────────┐
│ AIWritingPanel │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ useAIWriting() 主状态 hook │ │
│ │ ┌────────────────────────────────────────────────────┐ │ │
│ │ │ startWriting() ─── POST /api/ai-writing/start │ │ │
│ │ │ ↓ 返回 session_id │ │ │
│ │ │ │ │ │
│ │ │ subscribeToProgress(sessionId) │ │ │
│ │ │ ─── GET /api/ai-writing/{id}/stream (SSE) │ │ │
│ │ │ ─── 持续推 ProgressEvent 给 handleEvent │ │ │
│ │ │ ─── handleEvent reducer → setState │ │ │
│ │ │ │ │ │
│ │ │ submitIntervention() │ │ │
│ │ │ ─── POST /api/ai-writing/{id}/resume │ │ │
│ │ │ ─── graph 续推 → 新事件继续走 SSE │ │ │
│ │ │ │ │ │
│ │ │ saveAIWritingTranscript()(fire-and-forget) │ │ │
│ │ │ ─── PUT /api/ai-writing/sessions/{id}/transcript │ │
│ │ └────────────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ 渲染: │
│ ├ AIWritingForm(idle 状态) │
│ ├ AIWritingTimeline(运行中) │
│ │ ├ TimelineStep × N(progressEvents) │
│ │ └ CompletedInterventionCard × N(已完成的干预) │
│ ├ {Outline,Draft,Review}StreamingView(流式打字机) │
│ ├ InterventionCard(当前 currentPause 存在时弹出) │
│ └ WritingSkeletonCard(运行中无 pause 时的骨架屏) │
└─────────────────────────────────────────────────────────────────┘
```
---
## 四、状态机(useAIWriting.ts)
### 状态字段(完整定义见 `types/ai-writing.ts`)
```typescript
interface AIWritingState {
// —— 核心标识 ——
sessionId: string | null; // 后端返回的会话 id
status: WritingStatus; // 当前阶段(13 种状态之一)
isPaused: boolean; // 是否在干预点等待用户
error: string | null;
// —— 配置 ——
request: AIWritingRequest | null; // 用户提交的写作请求
// —— 累计数据 ——
progressEvents: ProgressEvent[]; // SSE 事件全量历史(供时间线渲染)
materials: AIMaterial[]; // 素材列表(素材就绪后填充)
outline: AIOutline | null; // 大纲(大纲就绪后填充)
currentDraftMarkdown: string; // 草稿正文(草稿就绪后填充)
currentDraftTitle: string;
reviewResult: ReviewResult | null;
revisionCount: number;
completedInterventions: CompletedIntervention[]; // 已完成的干预历史
// —— 干预 ——
currentPause: ProgressEvent | null; // 当前挂起的 await_user 事件
// —— 流式视图状态 ——
streamingDraftTitle: string;
streamingDraftSections: StreamingDraftSection[];
outlineStreamingText: string;
outlineThinkingText: string;
researchProgress: string;
streamingReviewItems: StreamingReviewItem[];
revisionSummary: RevisionSummary | null;
pendingRevisionContext: { /* ... */ } | null;
}
```
### 状态转移图(写作状态机)
```
┌──────┐
│ idle │ ←─────────────────────────────────────┐
└──┬───┘ │
│ startWriting() │
↓ │
┌─────────────────┐ │
│ researching │ │
└──┬──────────────┘ │
↓ materials_ready │
┌─────────────────────────────┐ │
│ awaiting_material_confirm │ ← await_user │
└──┬──────────────────────────┘ │
↓ submit(confirm) │
┌─────────────────┐ │
│ writing_outline │ ← (re_search 路径) │
└──┬──────────────┘ │
↓ outline_ready │
┌─────────────────────────────┐ │
│ awaiting_outline_confirm │ │
└──┬──────────────────────────┘ │
↓ submit(confirm) │
┌─────────────────┐ │
│ writing_draft │ ← (re_outline 路径) │
└──┬──────────────┘ │
│ │
┌───────┴────────┐ │
↓ ↓ │
awaiting_section_ awaiting_draft_confirm │
help (素材不足) └─┬───┬───┬──────────────┐ │
│ (supplement) │ │ │ to_editor │ │
│ ↑回到 research │ │ ↓ │ │
│ │ │ reviewing │ │
│ │ │ └─┬──────┐ │ │
│ │ │ ↓ ↓ │ │
│ │ │ awaiting_review_confirm │
│ │ │ └─┬────────┐ │
│ │ │ ↓ submit ↓ │
│ │ │ revising done ───────────────┘
│ │ │ │
│ │ │ └─→ writing_draft (循环修订)
│ │ │
│ │ │ user_revise
│ │ └─→ revising
│ │
│ │ finalize
│ └─→ done
│
└──→ (delete/loose) writing_draft 继续
```
### handleEvent reducer(核心)
`useAIWriting.ts` 里的 `handleEvent` 是个**纯 reducer**,根据 SSE 事件类型更新状态:
| 事件类型 | 主要影响的状态字段 |
|---|---|
| `connected` | 仅记录到 progressEvents |
| `step_start` | 切到对应 `status`(如「编辑」→ reviewing) |
| `step_done` | 仅记录 |
| `research_progress` | `researchProgress`(实时检索进度文案) |
| `materials_ready` | `materials`、清空 researchProgress |
| `outline_chunk` | `outlineStreamingText` / `outlineThinkingText`(打字机) |
| `outline_ready` | `outline`、清空流式文本 |
| `draft_chunk` | `streamingDraftSections`(按章节拼接打字机) |
| `draft_ready` | `currentDraftMarkdown` / `currentDraftTitle` |
| `review_chunk` | `streamingReviewItems[i].streamingText`(逐条打字机) |
| `review_item_done` | `streamingReviewItems[i]` 标记 isDone + 结构化结果 |
| `review_ready` | `reviewResult` |
| `await_user` | `currentPause = event`,`isPaused = true`,**弹出 InterventionCard** |
| `resumed` | `currentPause = null` |
| `notice` | 仅记录(非致命告警) |
| `done` | `status = 'done'` |
| `error` | `status = 'error'`,`error = event.message` |
---
## 五、API 层(api/)
### 1. `api/ai-writing.ts` — 核心写作 API
```typescript
// 启动写作 → 返回 session_id
export async function startWritingSession(req: AIWritingRequest): Promise<string>
// 订阅 SSE 进度流 → 返回取消订阅函数
export function subscribeToProgress(
sessionId: string,
onEvent: (event: ProgressEvent) => void,
): () => void
// 提交用户干预 → 让 graph 续推
export async function resumeWriting(
sessionId: string,
payload: UserInterventionPayload,
): Promise<void>
```
**关键实现细节**:
- **snake_case ↔ camelCase 转换**:后端返回 snake_case,前端类型是 camelCase。所有 normalize 函数(`normalizeMaterial`、`normalizeOutlineSection`...)集中在这一层做转换
- **SSE 事件白名单**:`SSE_EVENT_TYPES` 数组列出所有合法事件名,未知事件会被静默忽略
- **取消订阅**:`subscribeToProgress` 返回的函数会调用 `AbortController.abort()` 关闭 fetch stream
- **重连机制**:当前**没有内置重连** — 如果 SSE 断开(网络抖动、反代超时),需要用户主动重启写作或刷新页面
- 后端 `_recover_session` 能让 SSE 重连时从 checkpointer 恢复事件,但前端没主动重连逻辑
### 2. `api/ai-writing-sessions.ts` — 历史会话
```typescript
// CRUD
listAIWritingSessions() : Promise<AIWritingSessionSummary[]>
getAIWritingSession(id) : Promise<AIWritingSessionSummary>
renameAIWritingSession(id, title) : Promise<AIWritingSessionSummary>
deleteAIWritingSession(id) : Promise<void>
// 时间线持久化(fire-and-forget,永不抛错)
saveAIWritingTranscript(id, transcript) : Promise<boolean>
```
**关键设计**:`saveAIWritingTranscript` 内部用 try/catch 吞掉所有异常(网络错误、HTTP 500 等),只 `console.warn` 不影响主流程。这是**「锦上添花」契约**的前端侧。
### 3. `api/ai-writing-article-types.ts` — 文章类型管理
| 函数 | 用途 |
|---|---|
| `listArticleTypes()` | 表单下拉框选项 |
| `createArticleType()` | 管理员新增 |
| `updateArticleType()` | 管理员编辑 |
| `deleteArticleType()` | 管理员删除 |
---
## 六、组件树详解
### 顶层:`AIWritingPanel`(457 行,最大)
负责:
1. 调用 `useAIWriting()` 拿主状态
2. 调用 `useAIWritingSessions()` 拿历史列表
3. 协调表单 / 时间线 / 干预卡 / 流式视图 / 草稿同步
4. **自动滚底逻辑**:检测用户是否手动上划,决定是否跟随最新内容
5. **草稿同步到右侧画布**:监听 `currentDraftMarkdown` 变化,调 `setArtifact` 更新右侧
6. **历史会话回显**:当 `historySession` 非空时,渲染 `AIWritingHistoryView` 而不是实时面板
### 干预卡:`InterventionCard`(663 行,第二大)
按 `pausePoint` 渲染**不同的卡片**:
| pausePoint | 卡片 | 用户能做的 |
|---|---|---|
| `material_confirm` | `MaterialsCard` | 勾选保留素材 / 加关键词重新搜 |
| `outline_confirm` | `OutlineCard` | 直接编辑大纲 / 给反馈让重写 |
| `draft_confirm` | 草稿确认卡 | 定稿 / 给修订意见 / 提交编辑审核 |
| `review_confirm` | `ReviewCard` | 勾选采纳的意见 / 强制通过 |
| `section_help` | 求助卡 | 逐章选择:补充检索 / 删除 / 按通用知识续写 |
### 时间线:`AIWritingTimeline`
迭代 `progressEvents`,每个 `step_start` / `step_done` / `notice` 渲染成一条 `TimelineStep`。`CompletedInterventionCard` 穿插显示已完成的干预记录。
### 流式视图:`{Outline,Draft,Review}StreamingView`
- **OutlineStreamingView**:打字机渲染 `outlineStreamingText`,支持 `<think>...</think>` 折叠显示
- **DraftStreamingView**:按章节流式拼接 `streamingDraftSections`,每章节独立打字机
- **ReviewStreamingView**:3 条审核(事实 / 逻辑 / 语言)并行打字机,完成后切到结构化评分
### 历史回显:`AIWritingHistoryView`
只读模式,从 `AIWritingSessionSummary` 重建 UI。**当 `transcript` 字段有值时**,从里面拿到完整 `progressEvents`,UI 表现跟实时一模一样。`transcript` 没有时退回到只显示最终草稿。
---
## 七、SSE 事件协议(前后端契约)
后端通过 SSE 推 `event: <type>\ndata: <json>\n\n` 格式,前端用浏览器原生 `fetch + ReadableStream` 解析(不用 `EventSource`,因为 EventSource 不能自定义 header)。
### 解析流程
```
ReadableStream → TextDecoder
→ 按 "\n\n" 分帧
→ 每帧匹配 /^event: (.+)\ndata: (.+)$/
→ JSON.parse(data)
→ normalize(parsed)(snake → camel)
→ onEvent(normalized)
```
### 事件载荷字段(不完全列表)
| 字段 | 出现在哪些事件 | 用途 |
|---|---|---|
| `type` | 全部 | 事件类别 |
| `sessionId` | 全部 | 标识 |
| `message` | 大多数 | 显示给用户的文案 |
| `agentName` | step_* | 「素材收集专家」/「作家」/「编辑」/「系统」 |
| `materials` | materials_ready | 素材数组 |
| `outline` | outline_ready | 大纲对象 |
| `draftMarkdown` / `draftTitle` | draft_ready | 草稿内容 |
| `reviewResult` | review_ready | 完整审核结果 |
| `pausePoint` | await_user | 哪个干预点 |
| `pauseContext` | await_user | 干预所需的上下文(如待确认的素材列表) |
| `blockedSections` | await_user (section_help) | 素材不足的章节列表 |
| `title` / `detail` / `raw` | notice / error | 非致命告警的标题、详情、原始错误 |
---
## 八、扩展指南:常见开发任务
### 新增一个干预点
1. **前端类型扩展**:
- 在 `types/ai-writing.ts` 的 `ProgressEvent.pausePoint` 联合类型里加新 case
- 在 `WritingStatus` 加对应的 `awaiting_xxx`
- 在 `CompletedIntervention.pausePoint` 加 case
2. **写 InterventionCard 分支**:在 `InterventionCard.tsx` 里加新 `pausePoint` 分支,做 UI + 提交逻辑
3. **后端配合**(详见后端开发文档):
- `graph.py` 加 `pause_xxx_confirm` 节点
- graph 拓扑加这个节点的边
4. **完成干预后的清理**:在 `useAIWriting.ts` 的 `submitIntervention` 函数里,**确保把这次干预 push 到 `completedInterventions`**,让历史能看到
### 新增一个 SSE 事件类型
1. `types/ai-writing.ts`:
- `ProgressEventType` 联合类型加新值
- `ProgressEvent` 接口加新字段(如果有载荷)
2. `api/ai-writing.ts`:
- `SSE_EVENT_TYPES` 数组加新值(不加会被忽略)
- `normalizeEvent` 函数里加字段转换(如果是 snake_case 需要 normalize)
3. `useAIWriting.ts` 的 `handleEvent`:加新 case 处理状态更新
4. 组件层:根据需要在时间线 / 干预卡 / 流式视图里渲染
### 修改一个流式打字机的行为
每个 streaming view 内部都是独立的:
- 状态在 `useAIWriting.ts` 的 `streaming*` 系列字段
- 渲染在 `*StreamingView.tsx`
- 流式 chunk 处理在 `handleEvent` 的 `outline_chunk` / `draft_chunk` / `review_chunk` 分支
### 新增草稿到右侧画布的逻辑
`AIWritingPanel.tsx` 里 `useEffect` 监听 `state.currentDraftMarkdown` → 调 `setArtifact` 更新右侧 `CanvasGraphContext`。如果需要新的 artifact 类型,看 `contexts/CanvasGraphContext.tsx` 的 artifact 接口。
---
## 九、容错与边界处理
### 已落实的容错(不会阻断写作)
- ✅ `saveAIWritingTranscript` 失败仅 `console.warn`
- ✅ 历史会话列表加载失败仅 `console.warn`
- ✅ 重命名/删除会话失败静默吞掉
- ✅ 后端 SSE 推 `notice` / `error` 事件时,前端只渲染不中断
- ✅ JSON parse 失败时 SSE 帧被静默丢弃(不影响后续帧)
### 已知边界(可能影响 UI 体验)
- ⚠️ **SSE 断线无自动重连** — 网络抖动 / 反代超时后用户需要手动刷新
- ⚠️ **多 worker 部署下 SSE 事件丢失**(详见 `ai-writing-说明.md`)—— 前端只能感知到「卡住」,没有重连恢复机制
- ⚠️ `outline_chunk` / `draft_chunk` / `review_chunk` 的 `text` / `is_thinking` 字段是 snake_case,前端类型是 `text` / `isThinking` 但 normalize 时是**保留 snake_case 直接读**(参考 `useAIWriting.ts` 的 `(event as unknown as { text: string }).text`),这是历史包袱,未来 normalize 函数应统一处理
---
## 十、调试技巧
### 看 SSE 原始事件
浏览器 DevTools → Network → 找 `/api/ai-writing/<id>/stream` 请求 → Response(注意是 EventStream 格式,不能直接展开 JSON)。
### 查当前 hook 状态
在浏览器 console 里:
```js
// 需要安装 React DevTools,在 Components tab 找到 AIWritingPanel
// 或在 useAIWriting 里临时加:
useEffect(() => { (window as any).__aiwriting = state; }, [state]);
// 然后在 console 里 __aiwriting 看
```
### 模拟事件
开发期可以注释掉 `subscribeToProgress`,手动调 `handleEvent({...})` 测试 reducer 行为。
### 看后端 transcript
```
GET /api/ai-writing/sessions/<id>
```
返回里 `transcript` 字段就是前端组装过的完整时间线 JSON。
---
## 十一、性能注意点
### 大数组渲染
- `progressEvents` 在长写作里可能上千条 → `AIWritingTimeline` 应该考虑虚拟滚动(当前未实现,会议室会议讨论过)
- `streamingDraftSections` 章节多时也是潜在瓶颈
### transcript PUT 频率
- 当前每次 `progressEvents` 变化都会触发保存(实际上是 useEffect 监听)
- 大量 chunk 事件会导致**每秒 N 次 PUT**,后端 MySQL 写压力大
- **优化建议**:在 `useAIWriting.ts` 给 saveAIWritingTranscript 加 debounce(1-2 秒),或者只在 `await_user` / `done` / `error` 关键节点保存
### 浏览器内存
- progressEvents 不主动清理 → 长会话可能占用几十 MB
- 完成一篇文章后建议 `reset()` 清空状态
---
## 十二、相关后端接口(速查)
| 接口 | 用途 | 前端调用方 |
|---|---|---|
| `POST /api/ai-writing/start` | 启动写作 | `startWritingSession` |
| `GET /api/ai-writing/{id}/stream` | SSE 进度流 | `subscribeToProgress` |
| `POST /api/ai-writing/{id}/resume` | 提交干预 | `resumeWriting` |
| `GET /api/ai-writing/{id}/state` | 查 graph 状态快照(调试用) | 暂未调用 |
| `GET /api/ai-writing/sessions` | 历史列表 | `listAIWritingSessions` |
| `GET /api/ai-writing/sessions/{id}` | 历史详情 | `getAIWritingSession` |
| `PATCH /api/ai-writing/sessions/{id}` | 重命名 | `renameAIWritingSession` |
| `DELETE /api/ai-writing/sessions/{id}` | 删除会话 | `deleteAIWritingSession` |
| `PUT /api/ai-writing/sessions/{id}/transcript` | 保存时间线(fire-and-forget) | `saveAIWritingTranscript` |
| `GET /api/ai-writing/article-types` | 文章类型下拉 | `listArticleTypes` |
| `POST /api/ai-writing/admin/cleanup` | admin 手动清理 | 暂未在 UI 暴露 |
---
## 十三、未来优化方向
| 项目 | 说明 | 工作量 |
|---|---|---|
| transcript PUT 防抖 | 减少 MySQL 写压力 | 1 小时 |
| SSE 自动重连 | 网络抖动 / 反代超时后能恢复 | 0.5 天 |
| 时间线虚拟滚动 | 处理超长 progressEvents | 0.5 天 |
| 干预卡组件解耦 | 663 行的 InterventionCard 拆成 5 个独立卡片 | 1 天 |
| AbortController 串行化 | 避免重启写作时旧 SSE 还没断 | 0.5 天 |
| 后端字段统一 camelCase | 消除 snake_case ↔ camelCase 转换层 | 需后端配合 |
---
## 附录 A:所有类型一览
完整定义在 `types/ai-writing.ts`,主要类型:
```typescript
// 业务实体
AIMaterial // 单个素材
AIOutline // 大纲
OutlineSection // 大纲单章节
ReviewIssue // 审核问题
ReviewResult // 完整审核结果
BlockedSection // 素材不足的章节
SectionDecision // 章节求助决策
// 流程
WritingStatus // 13 种状态
ProgressEventType // 17 种事件类型
ProgressEvent // SSE 事件载荷
UserInterventionPayload // 干预提交体
AIWritingRequest // 启动写作的请求
CompletedIntervention // 已完成的干预记录
// 流式视图
StreamingDraftSection
StreamingReviewItem
RevisionSummary
// Hook 状态
AIWritingState // useAIWriting 的完整状态
```
---
## 附录 B:常见踩坑
| 现象 | 原因 | 解决 |
|---|---|---|
| 前端类型 camelCase 但拿到 undefined | 后端 snake_case 没 normalize | 在 `api/ai-writing.ts` 的 normalize 函数里加字段 |
| 进度卡住不动 | SSE 断了或落到错的 worker | 刷新页面,看 `ai-writing-说明.md` 多 worker 部分 |
| 历史会话回显时间线缺失 | transcript 保存失败 | DB 列容量 / 后端日志查 `save_transcript` |
| 修改大纲后没生效 | 用户 PATCH editedOutline 但没勾选 confirm | InterventionCard 大纲分支检查 action 字段 |
| 草稿渲染换行错乱 | LLM 输出包含奇怪 markdown | `DraftStreamingView` 里 markdown parser 设置 |
---
如需补充内容,请直接编辑本文件,并在 git commit message 里注明改动原因。
@@ -1,472 +0,0 @@
# AI 写作前端改造清单
## 1. 目标
在不新增第二套页面的前提下,基于现有 `open-canvas` 页面,把左侧从“单轮聊天输入框”升级为“多 Agent 写作工作台”,右侧继续沿用当前 `artifact` 编辑与流式预览能力。
当前核心文件:
- [CanvasResizableLayout.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/layout/CanvasResizableLayout.tsx)
- [CanvasChatPanel.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/chat/CanvasChatPanel.tsx)
- [CanvasArtifactPanel.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/artifact/CanvasArtifactPanel.tsx)
- [CanvasGraphContext.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/contexts/CanvasGraphContext.tsx)
- [CanvasStreamContext.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/contexts/CanvasStreamContext.tsx)
- [useCanvasThreadStream.ts](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/hooks/useCanvasThreadStream.ts)
- [runs.ts](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/api/runs.ts)
---
## 2. 改造原则
- 不改右侧主编辑器交互心智
- 不复制新页面
- 不破坏现有普通 chat 模式
- 新增“写作工作流模式”时尽量以增量状态字段和新组件完成
- 所有 workflow 能力都应允许逐步灰度
---
## 3. 推荐前端结构
建议在 `frontend-web/src/open-canvas` 下新增以下目录:
```text
frontend-web/src/open-canvas/
workflow/
api/
writing-workflow.ts
components/
WritingWorkflowEntryForm.tsx
WritingWorkflowTimeline.tsx
WritingWorkflowEventList.tsx
WritingWorkflowArtifactDrawer.tsx
WritingWorkflowConfirmCard.tsx
WritingWorkflowHeader.tsx
contexts/
WritingWorkflowContext.tsx
hooks/
useWritingWorkflow.ts
useWritingWorkflowEvents.ts
types/
workflow.ts
utils/
workflow-event.ts
```
说明:
- `open-canvas` 原有聊天、artifact、editor 目录不重构
- 以 `workflow/` 作为新能力边界,减少对既有文件的侵入
---
## 4. 状态设计
## 4.1 新增的核心状态
建议新增:
- `workflowMode: "chat" | "writing_pipeline"`
- `workflowRunId: string | null`
- `workflowStage`
- `workflowStatus: "idle" | "running" | "waiting_user" | "completed" | "failed"`
- `workflowEvents: WritingWorkflowEvent[]`
- `workflowArtifacts: WritingWorkflowArtifact[]`
- `workflowPendingAction: WritingPendingAction | null`
## 4.2 推荐类型定义
建议在 `workflow/types/workflow.ts` 中先定义:
```ts
export type WritingWorkflowStage =
| "idle"
| "collecting_materials"
| "generating_outline"
| "await_outline_confirmation"
| "writing_draft"
| "reviewing_draft"
| "rewriting_draft"
| "completed"
| "failed";
export type WritingWorkflowEventType =
| "workflow_started"
| "stage_changed"
| "agent_started"
| "agent_output_chunk"
| "artifact_generated"
| "human_confirmation_required"
| "retry_scheduled"
| "workflow_completed"
| "workflow_failed";
```
第一版把类型先收紧,后续再扩展。
---
## 5. 组件拆分建议
## 5.1 左侧主面板改造
当前 `CanvasChatPanel` 建议只承担“模式路由”和布局容器职责,不继续无限堆逻辑。
建议改造为:
- `chat` 模式继续渲染现有消息列表 + 输入框
- `writing_pipeline` 模式渲染新的工作流视图
建议拆分出:
- `CanvasChatConversation.tsx`
- `CanvasChatInputBox.tsx`
- `CanvasWorkflowPanel.tsx`
这样后续不会把 `CanvasChatPanel.tsx` 变成一个过大的组件。
## 5.2 新增组件职责
### `WritingWorkflowEntryForm.tsx`
负责采集:
- 主题
- 文章类型
- 目标读者
- 语气风格
- 目标篇幅
- 是否需要引用资料
- 禁写项
- 补充说明
### `WritingWorkflowTimeline.tsx`
负责显示阶段:
- 研究中
- 提纲生成中
- 等待确认提纲
- 正在写初稿
- 正在审稿
- 正在重写
- 已完成
### `WritingWorkflowEventList.tsx`
负责显示细粒度事件:
- 哪个 Agent 开始执行
- 当前在处理哪一步
- 当前产生了什么中间结果
- 是否重试
### `WritingWorkflowArtifactDrawer.tsx`
负责展示中间产物:
- 素材卡片
- 提纲
- 初稿
- 编辑意见
- 重写稿
### `WritingWorkflowConfirmCard.tsx`
负责展示用户确认点:
- 确认提纲
- 驳回提纲并附带修改意见
- 继续写稿
- 指定重写章节
---
## 6. Context 与 Hook 改造建议
## 6.1 `CanvasGraphContext`
当前它只维护:
- `messages`
- `artifact`
- `streamingArtifact`
- `isStreaming`
建议不要把 workflow 状态直接塞进现有 `CanvasGraphContext`,否则会让语义过重。
推荐做法:
- 保留 `CanvasGraphContext` 继续服务右侧 artifact 和通用流式状态
- 新增 `WritingWorkflowContext`
## 6.2 `WritingWorkflowContext`
建议承载:
- 当前 workflow 运行状态
- 中间产物列表
- 待确认操作
- workflow 事件缓存
- 启动 / 取消 / 确认 / 重写等 action
## 6.3 `useCanvasThreadStream`
当前这个 hook 已经负责:
- 创建 thread
- 提交消息
- 接收 thread stream
- 将 `update_artifact` 同步到右侧
建议不要把“多 Agent workflow 状态机”也硬塞进去。
推荐方案:
- 保留 `useCanvasThreadStream` 给普通 chat 或兼容旧能力使用
- 新增 `useWritingWorkflow`
- 新增 `useWritingWorkflowEvents`
分工如下:
- `useCanvasThreadStream`:普通对话流
- `useWritingWorkflow`:创建 workflow、提交表单、触发确认动作
- `useWritingWorkflowEvents`:订阅 workflow 事件流
---
## 7. API 接入建议
## 7.1 前端 API 文件
新增:
- `workflow/api/writing-workflow.ts`
建议暴露方法:
- `createWorkflow(payload)`
- `startWorkflow(id)`
- `getWorkflow(id)`
- `subscribeWorkflowEvents(id, handlers)`
- `confirmOutline(id, payload)`
- `rewriteSection(id, payload)`
- `approveFinal(id)`
## 7.2 事件流形式
优先级建议:
1. `SSE`
2. 流式 HTTP chunk
3. 轮询兜底
理由:
- 事件驱动比整段消息流更适合 workflow UI
- 可以更方便映射到时间线和事件列表
---
## 8. 与右侧 Artifact 的衔接
## 8.1 现有优势
当前 `CanvasArtifactPanel` 已具备:
- 流式展示内容
- 最终 artifact 渲染
- 右侧编辑体验成熟
这意味着多 Agent 工作流不需要再做第二套文章渲染,只要把最终阶段结果推成 artifact 即可。
## 8.2 建议接法
工作流各阶段结果按两类处理:
- 中间产物:进入左侧 `workflowArtifacts`
- 可阅读正文:同步一份到右侧 `artifact`
推荐映射:
- 提纲:可选同步到右侧,供用户预览
- 初稿:同步到右侧
- 重写稿:覆盖或新增版本到右侧
- 终稿:作为最终右侧主版本
## 8.3 版本策略
建议右侧版本保留:
- `outline`
- `draft_v1`
- `draft_v2`
- `final`
如果现有 artifact 数据结构不方便承载完整版本树,第一版可先保留在 workflowArtifacts 中,右侧只展示当前激活版本。
---
## 9. 页面交互流程
## 9.1 用户首次进入
- 默认仍是现有 chat 模式
- 在左侧增加一个显眼切换入口:`普通对话` / `写作工作流`
## 9.2 启动写作工作流
- 用户填写写作任务表单
- 点击“开始生成”
- 左侧切换到时间线 + 事件流视图
- 右侧进入 loading 或素材 / 提纲预览态
## 9.3 等待提纲确认
- 时间线停在 `await_outline_confirmation`
- 左侧出现确认卡片
- 用户可执行:
- 通过提纲
- 要求调整提纲
- 追加要求
## 9.4 生成初稿与审稿
- 左侧显示 Agent 事件
- 右侧展示初稿内容
- 审稿意见在左侧展示,同时高亮需要重写的章节
## 9.5 完成
- 左侧显示“终稿已完成”
- 右侧进入可继续局部 AI 编辑状态
---
## 10. 分步开发清单
## Step 1:类型与假数据
目标:
- 先把 workflow 的类型、mock 数据、组件骨架搭好
任务:
- 新建 `workflow/types/workflow.ts`
- 新建 `workflow/components/*`
- 用本地 mock 事件驱动时间线和事件流
验收:
- 不接后端也能在页面中演示完整流程
## Step 2:模式切换
目标:
- 在 `CanvasChatPanel` 中接入 `chat / writing_pipeline` 双模式
任务:
- 拆出 `CanvasWorkflowPanel`
- 增加模式切换 UI
- 保证旧 chat 不回归
验收:
- 现有功能不受影响
- 新模式可进入表单页
## Step 3:接入 workflow API
目标:
- 从 mock 切到真实 API
任务:
- 接 `create/start/get/events`
- 实现基础错误态和重试态
验收:
- 前后端可联调跑一条主链路
## Step 4:接入确认节点
目标:
- 支持提纲确认和指定章节重写
任务:
- 做确认卡片
- 做动作回传
验收:
- 用户能在流程中介入
## Step 5:打通右侧版本
目标:
- 让 workflow 产物稳定进入右侧编辑器
任务:
- 约定 artifact 映射
- 接入版本切换或当前版本覆盖
验收:
- 终稿稳定显示在右侧
---
## 11. 建议修改点位
优先涉及文件:
- [CanvasChatPanel.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/chat/CanvasChatPanel.tsx)
- [CanvasGraphContext.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/contexts/CanvasGraphContext.tsx)
- [useCanvasThreadStream.ts](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/hooks/useCanvasThreadStream.ts)
- [CanvasArtifactPanel.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/artifact/CanvasArtifactPanel.tsx)
建议新增,不建议重写原有:
- `open-canvas/workflow/api/writing-workflow.ts`
- `open-canvas/workflow/contexts/WritingWorkflowContext.tsx`
- `open-canvas/workflow/hooks/useWritingWorkflow.ts`
- `open-canvas/workflow/hooks/useWritingWorkflowEvents.ts`
- `open-canvas/workflow/components/*`
---
## 12. 联调约定
前后端需要尽早统一:
- workflow id 命名
- stage 枚举
- event type 枚举
- artifact type 枚举
- user action payload
- 错误码与可恢复动作
建议先由前端与后端共同确认一份 `workflow.ts` 契约文档,再开工。
---
## 13. 最终建议
前端最重要的不是“把 Agent 结果展示出来”,而是把“工作流过程可视化并允许人工介入”做清楚。
第一版建议先保证三件事:
1. 左侧能看见阶段进展
2. 用户能确认提纲
3. 右侧能稳定收到初稿和终稿
只要这三件事稳定,后续再继续加章节重写、评分展示、素材卡片增强,风险会小很多。
@@ -1,718 +0,0 @@
# AI 写作弱模型多 Agent 编排需求文档
## 1. 背景与目标
当前 `open-canvas` 页面右侧的成品展示与编辑体验已经比较成熟,但左侧模型直接生成文章的质量还不稳定。对于内网部署的弱性能大模型,单轮直出通常会出现以下问题:
- 结构松散,长文容易跑题
- 素材不足,内容空泛
- 事实依据弱,容易幻觉
- 润色能力有限,语言风格不统一
- 一次生成失败后缺少可控的纠偏机制
因此本次需求的核心目标不是继续优化“单个模型一次写完”,而是在内网用代码编排一个“小型杂志社工作流”,让弱模型通过多角色分工协作,产出明显优于单模型直出的文章质量。
建议的角色分工:
- `Agent A 研究员`:负责搜集内网素材、归纳事实、提取观点
- `Agent B 作家`:基于选题、素材和结构写初稿
- `Agent C 严苛编辑`:负责挑错、质检、润色、打回重写
- `Supervisor / Orchestrator`:负责流程调度、状态记录、重试与终止判断
---
## 2. 本次建设边界
### 2.1 前端边界
前端继续使用现有 `open-canvas` 页面,不新开第二套编辑器页面。
当前相关入口:
- [CanvasResizableLayout.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/layout/CanvasResizableLayout.tsx)
- [CanvasChatPanel.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/chat/CanvasChatPanel.tsx)
- [CanvasArtifactPanel.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/components/artifact/CanvasArtifactPanel.tsx)
- [CanvasStreamContext.tsx](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/contexts/CanvasStreamContext.tsx)
- [runs.ts](/F:/react/deeflow-code/deerflow-server-master/frontend-web/src/open-canvas/api/runs.ts)
前端本期只做以下增强:
- 在左侧聊天区增加“写作工作流模式”
- 让用户能看到多 Agent 阶段进度,而不是只看到最终回答
- 支持结构化输入:主题、体裁、目标读者、篇幅、语气、参考资料、禁写项
- 支持查看中间产物:提纲、素材卡片、初稿、编辑意见、终稿
- 支持人工介入:确认提纲、确认初稿、接受编辑建议、手动重跑某一步
### 2.2 后端边界
后端必须单开新路线,不影响其他同事当前功能开发。
建议原则:
- 不直接改现有 DeerFlow 主流程
- 不把多 Agent 逻辑硬塞进当前通用对话链路
- 以独立服务或独立模块形式建设
- 通过清晰 API 与当前前端页面对接
推荐落地位置:
- 基于仓库中的 `offline-backend-20260512` 单独开一条 `ai-writing-orchestrator` 路线
- 或在后端新建独立目录,例如 `offline-backend-20260512/apps/ai_writing_orchestrator`
---
## 3. 为什么多 Agent 对弱模型更合适
弱模型最怕“一个 prompt 做完所有事”,因为这要求模型同时完成:
- 选题理解
- 信息检索
- 信息筛选
- 结构规划
- 长文写作
- 自我校验
- 风格润色
把这些任务拆开后,每个 Agent 只处理一个更短、更清晰、更容易被弱模型完成的子任务,通常会带来以下收益:
- 降低单次上下文复杂度
- 降低一次性长输出失败率
- 把“写得不好”变成“某一步做得不好”,便于重试
- 可以在关键节点插入规则校验与人工确认
- 可以用程序补足模型短板,而不是完全依赖模型智力
这套方案的本质不是“让模型变聪明”,而是“让系统更会组织模型工作”。
---
## 4. 可借鉴的开源项目
以下项目适合借鉴,但不建议整套照搬。建议以“借鉴状态机、角色协作、阶段拆分、重试与审稿机制”为主。
### 4.1 第一优先级:LangGraph
推荐原因:
- 天然适合把写作流程建模成状态图
- 支持多步骤、条件分支、重试、人工介入
- 便于把“研究 -> 提纲 -> 初稿 -> 评审 -> 重写”固化成可控流程
- 对“弱模型 + 强流程控制”很友好
可借鉴点:
- `StateGraph` 的状态驱动编排
- 每一步单独定义输入、输出、失败处理
- 可视化地表达“通过 / 打回 / 重试 / 终止”
参考:
- [langchain-ai/langgraph](https://github.com/langchain-ai/langgraph)
- [langgraph supervisor pattern](https://github.com/langchain-ai/langgraph-supervisor-py)
### 4.2 第二优先级:STORM
推荐原因:
- 它本身就是“研究 + 提纲 + 成文 + 打磨”的长文系统
- 对“先研究后写作”的思路非常契合
- 很适合借鉴其“问题驱动研究”和“分阶段生成”的思想
根据其 GitHub README,STORM 将长文生成拆成两个大阶段:先研究并产出提纲,再基于提纲与资料写长文;其引擎进一步拆成知识整理、提纲生成、正文生成、文章润色四个模块。
这和我们的目标高度一致,尤其适合借鉴:
- 提纲先行
- 素材引用先行
- 分模块写作
- 后置润色
参考:
- [stanford-oval/storm](https://github.com/stanford-oval/storm)
### 4.3 第三优先级:Deep Research Agent
推荐原因:
- 明确支持本地模型与云模型混用
- 已经包含研究、写作、质量校验、缓存、重试等能力
- 很适合借鉴“研究阶段如何约束弱模型”
根据其 README,这个项目采用四个专职 Agent,并且带有可信度评分、质量验证、重试逻辑、缓存和 checkpoint。
特别适合借鉴:
- 素材缓存
- 分阶段质量评分
- 节点失败重试
- 研究结果结构化存储
参考:
- [tarun7r/deep-research-agent](https://github.com/tarun7r/deep-research-agent)
### 4.4 可选借鉴:CrewAI
推荐原因:
- 角色扮演表达自然
- 写“研究员 / 作家 / 编辑”这种协作关系很直观
- Flow + Crew 的组织方式适合做 demo 和快速验证
不建议作为首选底座的原因:
- 更偏“Agent 角色编排体验”
- 若要做企业内网稳定落地,状态管理和流程可控性通常不如 LangGraph 路线清晰
适合借鉴:
- 角色定义写法
- Task 模板
- 多角色协作 prompt 结构
参考:
- [crewAIInc/crewAI](https://github.com/crewAIInc/crewAI)
### 4.5 不建议新项目优先采用:AutoGen
原因:
- 截至最近公开信息,`microsoft/autogen` 已进入 maintenance mode
- 官方建议新项目优先采用 `Microsoft Agent Framework`
如果要借鉴,只建议借鉴早期多 Agent 对话模式,不建议作为本项目主框架。
参考:
- [microsoft/autogen](https://github.com/microsoft/autogen)
- [microsoft/agent-framework](https://github.com/microsoft/agent-framework)
### 4.6 结论
综合本项目需求,建议技术选型优先级如下:
1. `LangGraph` 作为主编排框架
2. `STORM` 借鉴研究-提纲-成文-润色的模块划分
3. `Deep Research Agent` 借鉴缓存、评分、重试、可观测性
4. `CrewAI` 借鉴角色 prompt 设计与任务模板
---
## 5. 目标产品形态
用户在当前 `open-canvas` 页面中,不再只是“向模型提问写文章”,而是启动一个可视化的写作流水线。
理想交互流程:
1. 用户输入主题、用途、风格、读者、篇幅要求
2. 系统先进入“研究阶段”
3. 系统给出资料卡片与候选提纲
4. 用户确认提纲或调整
5. 系统生成初稿
6. 严苛编辑给出问题清单
7. 系统自动重写问题段落
8. 系统输出终稿到右侧编辑区
9. 用户可继续局部改写、扩写、精简
核心体验目标:
- 左侧像“编辑部工作台”
- 右侧像“成文编辑器”
- 用户知道系统现在进行到哪一步
- 用户可以在关键节点接管,而不是只能等待最终结果
---
## 6. 多 Agent 流程设计
## 6.1 建议的最小可用流程 MVP
第一版不要一上来做很复杂,建议先做 4 步闭环:
1. `Research`
- 输入:主题、用户要求、内网资料源
- 输出:素材卡片列表、可引用事实列表、风险点列表
2. `Outline`
- 输入:用户要求 + 素材卡片
- 输出:结构化提纲
3. `Draft`
- 输入:提纲 + 素材卡片
- 输出:初稿
4. `ReviewAndRewrite`
- 输入:初稿 + 用户要求 + 素材卡片
- 输出:问题清单、改写稿、终稿
MVP 终止条件:
- 编辑评分达标则结束
- 不达标最多重写 2 次
- 超过次数则返回“需要人工介入”
## 6.2 第二阶段增强流程
在 MVP 跑通后,再增加:
- `Planner`:根据文章类型动态规划流程
- `SectionWriter`:按章节分别写作,避免长文崩坏
- `FactChecker`:逐段核对素材来源
- `StyleEditor`:统一语气、标题风格、句式节奏
- `ComplianceReviewer`:内网场景下做敏感词、保密、术语规范检查
## 6.3 建议的状态机
建议将流程状态固定为:
- `idle`
- `collecting_materials`
- `generating_outline`
- `await_outline_confirmation`
- `writing_draft`
- `reviewing_draft`
- `rewriting_draft`
- `completed`
- `failed`
- `human_intervention_required`
这样前端和后端都可以围绕统一状态通信。
---
## 7. Agent 角色定义建议
## 7.1 Agent A 研究员
职责:
- 搜集内网知识库、文档库、FAQ、历史稿件中的相关信息
- 输出结构化素材,而不是长篇自然语言
- 对每条素材标注来源、可信度、适用角度
输出格式建议:
- `facts[]`
- `quotes[]`
- `examples[]`
- `risks[]`
- `source_refs[]`
约束建议:
- 禁止直接生成整篇文章
- 不做风格化表达
- 每条结论必须可回溯到来源
## 7.2 Agent B 作家
职责:
- 严格基于提纲和素材写稿
- 按章节写,而不是一次写完整篇
- 对每段附带素材引用 ID,便于后续审核
约束建议:
- 无素材不发挥
- 每段只服务一个小节目标
- 段落长度控制
- 输出结构化草稿数据,而不仅是纯文本
## 7.3 Agent C 严苛编辑
职责:
- 检查逻辑跳跃、素材不足、事实不稳、表述空泛、风格不统一
- 输出明确的“问题清单”和“改写指令”
- 必要时打回指定章节,而不是整篇推翻
输出格式建议:
- `issues[]`
- `severity`
- `rewrite_instructions[]`
- `accept/reject`
编辑原则建议:
- 优先挑事实问题,再挑结构问题,最后才是文风问题
- 问题描述必须可执行,不能只说“写得不够好”
## 7.4 Supervisor
职责:
- 负责流程启动、状态流转、失败重试、记录日志
- 判断是否需要回到上一步
- 控制最大重试次数
- 对外提供统一 API 与流式事件
---
## 8. 前端需求
## 8.1 保持当前页面结构不变
继续沿用当前左右布局:
- 左侧:聊天 + 流程进度 + 中间产物
- 右侧:最终文章编辑与局部 AI 改写
不建议再复制一套新页面,以免造成维护分叉。
## 8.2 左侧新增 UI 模块
建议在 `CanvasChatPanel` 基础上新增:
- 写作任务表单
- 工作流阶段时间线
- Agent 执行日志面板
- 中间产物抽屉
- 人工确认卡片
建议新增的前端概念:
- `workflowMode`: `chat | writing_pipeline`
- `workflowStage`
- `workflowRunId`
- `workflowEvents[]`
- `workflowArtifacts[]`
## 8.3 需要展示的中间产物
至少支持展示:
- 素材卡片
- 提纲
- 初稿
- 编辑问题单
- 重写结果
- 最终定稿
这些内容建议不仅显示在消息区,也保存到右侧可选版本中,便于回看。
## 8.4 人工介入节点
至少提供两个确认点:
- 提纲确认
- 初稿确认或编辑后重跑
后续可扩展:
- 指定重写某个章节
- 锁定某段不允许再改
- 替换某条素材后重新生成
---
## 9. 后端需求
## 9.1 架构原则
后端新路线必须满足:
- 与现有通用对话链路解耦
- 与现有 Agent 运行时解耦
- 独立维护 Prompt、状态机、数据结构
- 可以单独部署、单独回滚、单独压测
## 9.2 推荐模块划分
建议后端拆分为以下模块:
- `workflow_orchestrator`
- `agent_registry`
- `material_retriever`
- `outline_generator`
- `draft_writer`
- `editor_reviewer`
- `rewrite_engine`
- `workflow_store`
- `stream_event_adapter`
## 9.3 API 建议
建议最小 API:
- `POST /api/ai-writing/workflows`
- 创建写作任务
- `POST /api/ai-writing/workflows/{id}/start`
- 启动流程
- `GET /api/ai-writing/workflows/{id}`
- 查询当前状态
- `GET /api/ai-writing/workflows/{id}/events`
- 获取事件流或轮询事件
- `POST /api/ai-writing/workflows/{id}/confirm-outline`
- 用户确认提纲
- `POST /api/ai-writing/workflows/{id}/rewrite-section`
- 指定章节重写
- `POST /api/ai-writing/workflows/{id}/approve-final`
- 确认终稿
## 9.4 流式事件建议
为了与当前 `CanvasStreamContext` 风格兼容,建议后端输出结构化事件流,例如:
- `workflow_started`
- `stage_changed`
- `agent_started`
- `agent_output_chunk`
- `artifact_generated`
- `human_confirmation_required`
- `retry_scheduled`
- `workflow_completed`
- `workflow_failed`
前端只要订阅事件,就能把左侧工作台做出来。
---
## 10. 弱模型优化策略
这是本项目成功的关键,不能只靠“多 Agent”这四个字。
## 10.1 强约束输出格式
每个 Agent 尽量输出 JSON 或结构化对象,不要自由发挥。
原因:
- 便于程序消费
- 便于后续 Agent 接续
- 便于失败重试
- 便于质量评估
## 10.2 长文拆成章节生成
不要让弱模型一次生成整篇长文,建议:
- 先出提纲
- 再按章节逐段写
- 最后统一润色
## 10.3 把检索和写作分离
研究员只负责找资料,作家只负责组织表达。不要让写作 Agent 同时去“边搜边编”。
## 10.4 程序兜底而不是模型兜底
程序需要承担:
- 去重
- 引用格式化
- 章节拼接
- 长度控制
- 评分阈值判断
- 重试路由
## 10.5 小步快跑、失败可回退
每步都要能独立失败、独立重试、独立回放。
## 10.6 引入可量化评分
编辑 Agent 输出不能只是一段文字,建议给出评分维度:
- 相关性
- 事实性
- 结构完整度
- 语言流畅度
- 风格一致性
系统据此决定是否进入下一步。
---
## 11. 分阶段实施计划
## Phase 1:需求冻结与技术验证
目标:
- 确认文章类型范围
- 确认内网资料来源
- 选定主框架
- 跑通最小多 Agent demo
交付物:
- 技术选型说明
- 角色与状态机设计
- 1 个主题的端到端 demo
验收标准:
- 弱模型可完成“研究 -> 提纲 -> 初稿 -> 编辑 -> 重写”闭环
## Phase 2:后端新路线搭建
目标:
- 建立独立 orchestrator
- 建立 workflow state store
- 建立事件流输出
- 建立可配置 prompt 模板
交付物:
- 独立服务目录
- 基础 API
- 状态机运行骨架
验收标准:
- 不依赖现有主流程改造即可独立跑通
## Phase 3:前端接入当前页面
目标:
- 在 `CanvasChatPanel` 接入工作流模式
- 增加阶段展示与人工确认
- 中间产物可视化
交付物:
- 左侧工作流时间线
- 中间产物展示面板
- 流程控制按钮
验收标准:
- 用户可以在当前页面完成一次全流程写作
## Phase 4:质量优化
目标:
- 强化素材检索质量
- 提高提纲质量
- 引入章节级重写
- 引入评分与回退机制
交付物:
- 质量评估规则
- 重试策略
- Prompt 调优包
验收标准:
- 弱模型效果明显优于单轮直出
## Phase 5:生产化
目标:
- 加缓存
- 加日志
- 加监控
- 加失败告警
- 加审计记录
交付物:
- 可观测性方案
- 运行日志与回放
- 配置中心或 prompt 管理机制
验收标准:
- 可长期维护并可定位问题
---
## 12. 团队协作与隔离方案
为了不影响其他同事,建议采用以下协作原则:
- 新后端目录独立开发
- 新接口使用独立路由前缀
- 前端只在 `open-canvas` 内增量开发
- 不修改现有公共线程协议,必要时增加新事件类型
- Prompt、Agent 配置、评分规则独立存放
推荐分工:
- 前端 1 人:负责左侧工作流 UI 与右侧版本接入
- 后端 1-2 人:负责 orchestrator、Agent 执行、事件流
- 算法/Prompt 1 人:负责角色 prompt、评分规则、失败样本调优
---
## 13. 风险与规避
### 风险 1:Agent 太多,成本和耗时暴涨
规避:
- MVP 只保留 3 个业务 Agent + 1 个 Supervisor
- 长文按章节写,失败只重写局部
### 风险 2:弱模型在自由对话场景中失控
规避:
- 全流程结构化
- 每步只做一件事
- 强约束输入输出格式
### 风险 3:内网检索质量不足,导致垃圾进垃圾出
规避:
- 先把资料源治理好
- 对素材做来源、可信度、去重处理
### 风险 4:前后端协议频繁变化影响联调
规避:
- 先定义事件模型和 artifact 模型
- 先 mock 数据,再并行开发
### 风险 5:影响现有功能稳定性
规避:
- 新路线、新接口、新状态机
- 不侵入现有主链路
---
## 14. 推荐结论
本项目推荐的总体策略:
1. 前端继续基于当前 `open-canvas` 页面开发,不复制新页面
2. 后端单独开 `ai-writing-orchestrator` 新路线,避免影响现有同事
3. 主框架优先采用 `LangGraph`
4. 流程设计借鉴 `STORM`
5. 质量控制借鉴 `Deep Research Agent`
6. 角色设计与任务模板可参考 `CrewAI`
7. 第一版只做 4 步 MVP:研究、提纲、初稿、编辑重写
一句话总结:
不是继续“调一个更强的 prompt”,而是把弱模型放进一个可控的编辑部流水线,让系统帮它把复杂写作拆开完成。
---
## 15. 参考链接
- [LangGraph](https://github.com/langchain-ai/langgraph)
- [LangGraph Supervisor](https://github.com/langchain-ai/langgraph-supervisor-py)
- [STORM](https://github.com/stanford-oval/storm)
- [Deep Research Agent](https://github.com/tarun7r/deep-research-agent)
- [CrewAI](https://github.com/crewAIInc/crewAI)
- [Microsoft Agent Framework](https://github.com/microsoft/agent-framework)
- [AutoGen](https://github.com/microsoft/autogen)
-501
View File
@@ -1,501 +0,0 @@
# AI 写作 — 迁移到 LangGraph Server 的分步实现方案
> **文档目的**:彻底解决 AI 写作在多 worker 部署下"SSE 时断时续 / resume 偶发 404"的根因,参照主聊天(`/workspace/chats/new`)的实现,把 AI 写作的 graph 注册成 LangGraph Server 上的一个 assistant,让 Server 接管线程、checkpoint、SSE、interrupt/resume 的全部协议。
>
> **配套文档**:[ai-writing-说明.md](./ai-writing-说明.md) 里描述了为什么会出问题、当前已落地的兜底方案,以及方案 B/C/F 三条"绕过"路径。本文档是其中"长期方案"的具体实现路线 —— 不是绕过多 worker,而是从架构层面让它**天然不受 worker 数影响**。
>
> **更新日期**:2026-05-20
---
## 一、为什么走这条路
主聊天和 AI 写作功能形态几乎一致(多步流式、可中断/恢复、有持久化),但**主聊天完全不受多 worker 影响**。差别在于:
| 维度 | 主聊天(现状) | AI 写作(现状) | AI 写作(迁移后) |
|---|---|---|---|
| 前端流接入 | `useStream` (SDK) | `fetch` + 自写 `EventSource` | `useStream` (SDK) |
| 后端运行时 | **LangGraph Server**(独立进程,端口 2024 / 经 nginx 走 `/api/langgraph`) | 嵌在 FastAPI Gateway 路由里直接跑 | **LangGraph Server**(同主聊天) |
| 线程状态 | Server 自带持久化 checkpointer | 自管 sqlite + 一堆模块级 dict | Server 自带持久化 checkpointer |
| SSE 通道 | Server ↔ SDK 协议层 | 自写 `asyncio.Queue` per session_id | Server ↔ SDK 协议层 |
| 多 worker | 任何 worker 都能查 Server | per-worker 内存 dict 隔离 | 任何 worker 都能查 Server |
| Interrupt/Resume | Server 协议(`Command(resume=...)`)| 自写 `_session_pending_pause` + `/resume` 路由 | Server 协议 |
**核心收益**:迁完后 `_event_queues`、`_session_pending_pause`、`_session_repos`、`_session_user_ids`、`_session_interventions`、`_session_article_types`、`_session_error_flags`、`_session_pending_pause`、`_inflight_graph_tasks`、`_recover_session()`、自管 sqlite checkpointer 这一整套"per-process 内存状态"全部可以删掉 —— 不是"绕过"问题,是**让问题消失**。
**代价**:节点要改造(流式 chunk 改走 LangGraph 原生 `StreamWriter`/state update)、前端干预卡的交互要重写、业务表写入路径要从"路由里写"挪到"节点里写"。约 **6 人日**核心改造 + 50% buffer,建议按 **9 人日**排期。
---
## 二、现状盘点:要删 / 要留 / 要改
### 2.1 要删的(迁完即可移除)
| 位置 | 内容 | 备注 |
|---|---|---|
| `app/gateway/routers/ai_writing.py` | `POST /start`、`GET /{id}/stream`、`POST /{id}/resume`、`GET /{id}/state` | 由 LangGraph Server 的 `runs.stream / threads.create / runs.wait` 替代 |
| 同上 | `_event_queues`、`_session_pending_pause`、`_session_model_names`、`_session_repos`、`_session_user_ids`、`_session_interventions`、`_session_error_flags`、`_session_article_types` 这 8 个模块级 dict | 状态全部交给 LangGraph Server |
| 同上 | `_recover_session()`、`_inflight_graph_tasks`、`_spawn_graph_task()`、`wait_for_inflight_graph_tasks()` | 跨 worker 恢复 / drain 都由 Server 内建机制处理 |
| 同上 | `_make_config()` 里注入 `sse_queue` / `sse_session_id` 的逻辑 | 流式输出改走 LangGraph 原生通道 |
| `packages/harness/deerflow/agents/ai_writing/graph.py` | `_get_async_checkpointer()`、`get_ai_writing_checkpointer()`、`shutdown_ai_writing_graph()`、`AI_WRITING_GRAPH` 单例、`_async_checkpointer_singleton` | checkpoint 由 langgraph.json 的全局 checkpointer 接管 |
| `app/gateway/ai_writing_cleanup.py` | "联动清理 sqlite checkpointer thread" 那一段 | 改成调 `langgraph_sdk` 的 `threads.delete()` |
| `offline-backend-20260512/config.yaml` | `checkpointer:` 段里 AI 写作专用的 sqlite 路径(如果跟主 checkpointer 不同) | 共用主配置 |
### 2.2 要保留的
| 位置 | 内容 | 理由 |
|---|---|---|
| `packages/harness/deerflow/persistence/ai_writing_sessions/` | MySQL 业务表(标题、最终 draft、completed_interventions、transcript、article_type、status…) | 列表页 / 历史回显 / 全文搜索都依赖业务表,**不能让 LangGraph checkpoint 取代它** —— checkpoint 是流程状态,业务表是产品形态 |
| `GET/PATCH/DELETE /api/ai-writing/sessions[/{id}]` | 列表 / 重命名 / 删除 | 只查业务表,不碰 graph |
| `PUT /api/ai-writing/sessions/{id}/transcript` | 时间线持久化 | 维持锦上添花的回显方案 |
| `GET/POST/PATCH/DELETE /api/ai-writing/article-types[/{id}]` | 文章类型 CRUD | 纯业务路由,跟 graph 无关 |
| `POST /api/ai-writing/admin/cleanup` | admin 清理入口 | 路由保留,内部实现改 |
| 4 个 interrupt 暂停点 + 5 个节点 + 全部 state 字段 | 业务逻辑零改动 | `pause_material_confirm` / `pause_outline_confirm` / `pause_section_help` / `pause_draft_confirm` / `pause_review_confirm` 用的就是 LangGraph 原生 `interrupt()`,直接吃迁移红利 |
### 2.3 要改的
| 位置 | 改造点 |
|---|---|
| `graph.py` | 删自管 checkpointer,导出 `make_ai_writing_graph(config) → CompiledStateGraph`,由 Server 注入 checkpointer |
| `langgraph.json` | `graphs` 里增加 `"ai_writing": "deerflow.agents.ai_writing.graph:make_ai_writing_graph"` |
| 各 node(`researcher.py` / `writer_outline.py` / `writer_draft.py` / `editor.py`) | 流式输出从 `sse_queue.put_nowait(...)` 改成 LangGraph 原生 `get_stream_writer()` 推 custom 事件 |
| 各 node | DB 写入(草稿、审核结果、status)从「路由里调 repo」改成「节点里通过 `RunnableConfig` 拿 `thread_id` 调 repo」 |
| 各 node | "创建 session 行"从 `/start` 路由里挪到 `intent_parser_node`(或前端 `onCreated` 回调里调一个轻量级 upsert API) |
| `langgraph_auth.py` | 给 `ai_writing` assistant 加授权规则(保证只能访问自己的 thread) |
| 前端 `frontend-web/src/open-canvas/` | 完全弃用现有 `api/ai-writing.ts` 的 `fetch + EventSource`,新写 `useAIWritingStream` hook(基于 `@langchain/langgraph-sdk/react` 的 `useStream`) |
| 前端 4 个干预卡 | 提交回调从 `POST /resume` 改为 `thread.submit(new Command({ resume: payload }))` |
| 前端"启动写作"按钮 | 从 `POST /start` + 拿 session_id + 建 EventSource 改成 `thread.submit({...args})` 触发 `onCreated` 回调 |
| `tests/test_ai_writing_session_recovery.py` | 整体删除 —— 跨 worker 恢复由 LangGraph Server 接管,不再是 AI 写作自己的事 |
| 新增 `tests/test_ai_writing_assistant.py` | 通过 LangGraph SDK in-process 跑一遍 graph,覆盖 interrupt / resume / custom stream / state 持久化 |
---
## 三、分步实施
### 阶段 0:可行性预演(0.5 d)
**目标**:在不动现有代码的前提下,验证"把 ai_writing graph 注册到 LangGraph Server 并通过 SDK 跑通"这条路完全可行。
1. 临时在 `langgraph.json` 的 `graphs` 里加一条 `"ai_writing_probe": "deerflow.agents.ai_writing.graph:build_ai_writing_graph"`(直接复用现有 `build_ai_writing_graph`,不传 checkpointer 让 Server 注入)。
2. 起 `make dev`,确认 LangGraph Server 把 `ai_writing_probe` 列入 assistant 列表。
3. 用 Python SDK 客户端(`langgraph_sdk.get_client()`):
```python
from langgraph_sdk import get_client
client = get_client(url="http://localhost:8001/api/langgraph")
thread = await client.threads.create()
async for chunk in client.runs.stream(
thread["thread_id"], "ai_writing_probe",
input={"user_intent": "测试", "article_type": "analysis", ...},
stream_mode=["values", "messages-tuple", "custom"],
): print(chunk)
# 跑到 pause_material_confirm 应该收到 interrupt 事件
await client.runs.stream(thread["thread_id"], "ai_writing_probe",
command={"resume": {"action": "confirm", "approvedMaterialIds": [...]}})
```
4. 验证:interrupt 能正确暂停、`Command(resume=...)` 能续跑、state 能持久化到 Server checkpoint。
5. 跑通后**回滚 langgraph.json** —— 这一步只是"摸路"。
**通过条件**:4 个 pause 点全部能用 SDK 跑通 interrupt + resume。如果某个 pause 点的 payload 结构跟 SDK 协议不兼容(例如用了非 JSON 可序列化的对象),阶段 0 就要解决,否则会在阶段 2 翻车。
---
### 阶段 1:graph 注册为 assistant(0.5 d)
**改动文件**:`packages/harness/deerflow/agents/ai_writing/graph.py`、`offline-backend-20260512/backend/langgraph.json`
1. `graph.py` 顶部新增:
```python
from langchain_core.runnables import RunnableConfig
def make_ai_writing_graph(config: RunnableConfig | None = None):
"""LangGraph Server 入口:不接收 checkpointer,由 Server 注入。"""
g = StateGraph(AIWritingState)
# ... 跟现在 build_ai_writing_graph 完全一样的节点 / 边定义 ...
return g.compile() # 注意:不传 checkpointer
```
2. 旧的 `build_ai_writing_graph(checkpointer=None)`、`get_ai_writing_graph()`、`_get_async_checkpointer()`、`get_ai_writing_checkpointer()`、`shutdown_ai_writing_graph()` 全部**先标 `@deprecated` 暂留** —— 阶段 7 再删,避免阶段 2/3 出错时无法快速回退。
3. `langgraph.json`:
```json
{
"graphs": {
"lead_agent": "deerflow.agents:make_lead_agent",
"canvas_agent": "deerflow.agents.canvas_agent:make_canvas_agent",
"ai_writing": "deerflow.agents.ai_writing.graph:make_ai_writing_graph"
}
}
```
4. `checkpointer.path` 已经指向 `make_checkpointer`(看 `langgraph.json:15-17`),AI 写作直接共享主 checkpointer 即可,**不要**重新搞一套。
**通过条件**:启动 LangGraph Server 后 `GET /api/langgraph/assistants` 能列出 `ai_writing`,state schema 字段齐全。
---
### 阶段 2:节点改造 —— 流式输出走原生通道(1.5 d)
**核心问题**:现在的 `writer_draft_node` / `writer_outline_node` / `researcher_node` 通过 `config["configurable"]["sse_queue"]` 把 LLM token chunk 推给前端。LangGraph Server 不会再注入 `sse_queue`,必须改用原生流通道。
**选型**:用 `langgraph.config.get_stream_writer()` 推 `custom` 事件(保留现有"非聊天消息、自定义协议"的形态)。
> 不选 `messages-tuple` 模式的原因:草稿生成不是聊天消息流,而是大段 markdown;硬塞成 `AIMessage` 会让前端渲染逻辑变得很别扭。custom 通道改动最小、契合度最高。
**改造模板**(每个节点都按这个模板改):
```python
# 旧:
from .nodes._utils import push_sse_event
async def writer_draft_node(state, config):
sse_queue = config["configurable"].get("sse_queue")
sse_queue.put_nowait({"event": "progress", "data": {...}})
async for chunk in llm.astream(...):
sse_queue.put_nowait({"event": "draft_chunk", "data": {"text": chunk}})
# 新:
from langgraph.config import get_stream_writer
async def writer_draft_node(state, config):
writer = get_stream_writer() # 注意:必须在 async 函数体内调,不能模块级缓存
writer({"type": "progress", "agent": "writer", "message": "开始写作"})
async for chunk in llm.astream(...):
writer({"type": "draft_chunk", "text": chunk})
```
**业务表写入改造**:现在 `writer_draft_node` 收尾时通过 `config["configurable"]["sse_session_id"]` + `_session_repos[sid]` 调 `repo.save_draft()`。新方案:
```python
async def writer_draft_node(state, config):
thread_id = config["configurable"]["thread_id"] # LangGraph Server 注入
# 从 thread metadata / state 里拿到 user_id(在阶段 4 写入)
user_id = state.get("_user_id") or config["configurable"].get("user_id")
repo = get_ai_writing_session_store() # 进程内全局,无 per-session 字典
try:
await repo.save_draft(thread_id, user_id, state["current_draft"])
except Exception:
logger.exception("save_draft failed (non-fatal)")
```
**注意事项**:
- `get_stream_writer()` 在子图 / 工具函数里会拿到当前 graph 的 writer,**不要**在模块 import 时缓存。
- 节点要兼容"测试场景下没有 LangGraph runtime":包一层 `try: writer = get_stream_writer() except ...`,单测里 writer 是 no-op。
- progress_events 字段保留写入 state(现在节点都已经 return `{"progress_events": [...]}`),这样 history / 回放仍然能在 state 里看到完整轨迹;custom stream 只是为了**实时推送**。
**通过条件**:手动跑一次 `make dev`,用 SDK 客户端从前一阶段验证脚本流式拿到 `draft_chunk` 事件。
---
### 阶段 3:前端接入 LangGraph SDK(1 d)
**核心改动**:`frontend-web/src/open-canvas/api/ai-writing.ts` 整文件作废,改写 `frontend-web/src/open-canvas/hooks/useAIWritingStream.ts`。
**新 hook 骨架**(参考 `frontend-web/src/core/threads/hooks.ts:207` 现有主聊天写法):
```ts
import { useStream } from "@langchain/langgraph-sdk/react";
import { Command } from "@langchain/langgraph-sdk";
import { getAPIClient } from "@/core/api/api-client";
interface AIWritingValues {
user_intent: string;
article_type: string;
status: string;
material_package?: MaterialPackage;
current_outline?: Outline;
current_draft?: DraftArticle;
review_result?: ReviewResult;
progress_events: any[];
}
export function useAIWritingStream(sessionId: string | "new") {
const stream = useStream<AIWritingValues, { CustomEventType: AIWritingCustomEvent }>({
client: getAPIClient(),
assistantId: "ai_writing",
threadId: sessionId === "new" ? undefined : sessionId,
reconnectOnMount: true,
onCreated(meta) {
// 后端会用同一个 thread_id 做 ai_writing_sessions.id;通知 UI 写入 URL
navigateTo(`/workspace/ai-writing/${meta.thread_id}`);
},
onCustomEvent(event) {
// 节点 push 来的 draft_chunk / progress / notice
pushUIEvent(event);
},
});
return stream;
}
```
**4 个干预卡的提交逻辑**(旧 → 新):
```ts
// 旧(自写 fetch):
await fetch(`/api/ai-writing/${sessionId}/resume`, {
method: "POST",
body: JSON.stringify({ action: "confirm", approvedMaterialIds: [...] }),
});
// 新(SDK 原生 Command):
stream.submit(undefined, {
command: { resume: { action: "confirm", approvedMaterialIds: [...] } },
});
```
**启动写作**:
```ts
// 旧:POST /start → 返回 session_id → 建 EventSource
// 新:
stream.submit({
user_intent, article_type, target_audience, word_count_target, keyword_count, writing_mode,
}, {
config: { configurable: { model_name } },
metadata: { feature: "ai_writing", article_type }, // 走业务表筛选
});
```
**列表页 / 历史回显**:仍然走 `GET /api/ai-writing/sessions` 业务 API,**无改动**。点进某条历史记录时:
- 拿到 `sessionId` (== LangGraph `thread_id`)
- `useAIWritingStream(sessionId)` 自动调 `client.threads.getState()` 拉最新 state,渲染最后一次草稿 / 干预点 / interrupt 等待
- 已结束的会话 (`status == "done"`) 直接读业务表的 `draft_markdown` 字段,**不挂 SDK stream**(省 Server 资源)
**通过条件**:手动跑完一个完整流程(启动 → 4 次干预 → 拿到草稿),过程中刷新页面 / 切 worker,进度都不丢。
---
### 阶段 4:业务表写入解耦(0.5 d)
**问题**:现在 `/start` 路由先 INSERT 一行 `ai_writing_sessions(id=session_id, ...)`,再启动 graph。迁移后前端用 `stream.submit(...)` 直接触发 LangGraph 建 thread + 跑 graph,业务表行没人建 → 列表页查不到。
**两个方案二选一**:
**方案 4A(推荐)**:节点里建业务表行
- `intent_parser_node` 开头:`await repo.upsert_session(thread_id, user_id, user_intent, article_type, status="researching")`
- 优点:单一数据源(节点),不依赖前端做"双写"。
- 缺点:用户从前端点"启动" → 看到列表里出现这条 → 之间有 200~500ms 延迟(intent_parser 跑完才入库),需要前端 onCreated 后乐观插入一条临时行。
**方案 4B**:前端 onCreated 时调一个轻量 upsert API
- 新增 `POST /api/ai-writing/sessions/{thread_id}/init`:只插业务表行,不碰 graph。
- 前端 `onCreated(meta)` 回调里立刻 fire-and-forget 调它。
- 优点:列表瞬间出现新行。
- 缺点:前端要多调一次 API,且失败要兜底;多了一条"双方都能建行"的路径。
**推荐 4A** —— 单一数据源比 UI 响应更重要,200ms 延迟用 loading skeleton 即可。
**用户身份传递**:节点要拿到 `user_id` 写入业务表。两条路:
- LangGraph Server 已有 `langgraph_auth.py` 注入 auth context,在节点里 `config["configurable"].get("langgraph_auth_user")` 取(具体字段名以现有实现为准)。
- 或者前端 `submit()` 时 metadata 里带上 `user_id`,节点从 `config["configurable"]["metadata"]` 拿。
**通过条件**:从启动到列表显示新行,延迟 < 1s;多用户场景下不会出现"A 用户的 thread 落到 B 的业务表行"。
---
### 阶段 5:transcript 持久化(0.2 d)
**当前**:前端 `PUT /api/ai-writing/sessions/{id}/transcript` 全量覆盖 `ai_writing_sessions.transcript` 列。
**改造选择**:
- **维持现状**(推荐):transcript 是前端组装的时间线 blob,让前端继续 fire-and-forget PUT 即可,跟迁移正交。
- 或者完全弃用 transcript 列,直接从 `client.threads.getHistory()` + `getState()` 还原 —— 工作量大且需要重写回显逻辑,**不推荐第一版做**。
**通过条件**:原 PUT 接口照常工作;新建会话也能落库。
---
### 阶段 6:admin 清理改造(0.3 d)
**改动文件**:`app/gateway/ai_writing_cleanup.py`
```python
# 旧:
saver = get_ai_writing_checkpointer()
await saver.adelete_thread(sid) # 自管 sqlite
# 新:
from langgraph_sdk import get_client
lg_client = get_client(url=internal_langgraph_url())
await lg_client.threads.delete(sid)
```
**活跃保护**:旧逻辑是看 `sid in _event_queues`。新逻辑:
```python
state = await lg_client.threads.get_state(sid)
is_active = (
state.get("next") # graph 还有未执行的节点
or state.get("tasks") # 当前有 pending task
or state.get("metadata", {}).get("interrupted") # 卡在 interrupt 上
)
if is_active:
skipped_active += 1
continue
```
**通过条件**:admin cleanup 接口照常返回 `deleted_db / deleted_checkpoints / skipped_active`,且能正确跳过仍在 interrupt 等待用户的会话。
---
### 阶段 7:删冗余代码(0.3 d)
按 §2.1 列表逐项删除。建议**单独开一个 PR**,跟阶段 1~6 解耦:
- 前 6 个 PR 全部上线、灰度验证至少 1 周
- 确认旧代码路径再无流量后,再走清理 PR
- 这样万一灰度阶段需要回滚,旧路径还在
**通过条件**:`make test` 全绿,`grep -r "_event_queues\|_session_pending_pause\|_recover_session" app/ packages/` 零命中。
---
### 阶段 8:测试 + 灰度(1 d)
**新增测试**:
- `tests/test_ai_writing_assistant.py` —— 用 `langgraph_sdk` 客户端打 LangGraph Server,覆盖:
- 完整流程:start → 4 个 interrupt → resume → done
- state 持久化:跑到 pause_outline 后重建客户端,能 `getState` 看到 outline
- custom stream:能收到 `draft_chunk` 等事件
- 错误兜底:节点抛错时 status 落 error、业务表 status 同步
- 保留 `tests/test_portable_long_text.py` / `tests/test_ai_writing_transcript_endpoint.py` / `tests/test_ai_writing_session_repo.py` —— 这几个跟业务表强相关,不受迁移影响。
**删除测试**:
- `tests/test_ai_writing_session_recovery.py` —— 跨 worker 恢复改由 LangGraph Server 提供,不再是 AI 写作自己的能力。
- `tests/test_ai_writing_cleanup.py` 里关于"drain + checkpointer 降级 + SSE 序列化"的几个用例 —— 这些机制已删,对应用例失效。
**灰度策略**:
- **前端开关**:`VITE_AI_WRITING_BACKEND` = `legacy | langgraph`,默认 `legacy`
- `legacy` → 走老的 `fetch + EventSource + /resume`
- `langgraph` → 走新 `useAIWritingStream`
- **后端**:旧路由(`/start /stream /resume /state`)保留两个发版周期,逐步下线
- **数据兼容**:业务表 schema 完全不变,两条路径都用同一张表
- **回滚成本**:改回 `VITE_AI_WRITING_BACKEND=legacy` 重新部署即可,无 DB migration
**通过条件**:
- 灰度环境跑 100+ 写作流程,对比新旧两条路径的成功率、SSE 中断率、resume 成功率
- 新路径在 worker=4 部署下 SSE 中断率 = 0(旧路径基线约 5~15%)
---
## 四、关键设计决策与权衡
### 4.1 为什么不让 LangGraph checkpoint 替代业务表?
LangGraph checkpoint 存的是"图执行状态",业务表存的是"产品形态"。两者职责不同:
- **会话列表筛选/排序**:业务表 `WHERE user_id = ? AND status = ? ORDER BY updated_at` —— LangGraph checkpoint 没法这样查(它是 `(thread_id, checkpoint_ns)` 主键)
- **全文搜索 draft**:业务表 `LIKE '%关键词%'` —— checkpoint 是序列化 blob
- **transcript 自定义 UI 协议**:前端组装的时间线 JSON,跟 graph state 不一一对应
**结论**:两者**并存**,`thread_id` 作为外键。这是主聊天的做法(`threads_meta` + LangGraph checkpoint),AI 写作迁完后也是同样的形态。
### 4.2 为什么 graph 节点里直接调 repo,不发到外面消费?
考虑过"节点只 emit custom event,路由层订阅事件后写业务表" —— 但这又把状态分散回路由层了。
直接在节点里调 `await repo.save_draft(...)`:
- 节点拿得到 `thread_id`(== session_id == business id),主键一致
- `repo` 是单例(DB 连接池),不依赖 per-session 字典
- 写入失败包 try/except 即可(草稿落 state 比落 DB 更关键,DB 失败不阻断流程)
### 4.3 为什么用 custom stream 而不是 messages-tuple?
writer_draft 输出是大段 markdown,强行包成 `AIMessage` 后:
- 前端要把它从消息列表里拎出来当草稿渲染(混杂)
- 大纲 / 审核结果是结构化 JSON,更不像聊天消息
- progress_events / notice / draft_chunk / outline_chunk 几种事件类型,全塞 message 通道得发明 metadata convention
custom stream 是为这种"非聊天但需要流式 push"场景设计的,匹配度更高。
### 4.4 在 Server 进程里跑 graph,资源够用吗?
LangGraph Server 是独立 Python 进程,跟 Gateway 共享同一台机器但不共享内存。新增一个 assistant 的常驻开销 ~10 MB(graph 编译后的 schema 缓存),每个并发会话峰值 ~50 MB(LLM client + state)。
实测建议:在阶段 0 之后跑一次 10 个并发的压测,观察 Server RSS 增量。若一台机器 4 GB 内存,理论支撑 60~80 并发 AI 写作,足够 50 人规模团队使用。
---
## 五、风险清单
| # | 风险 | 缓解 |
|---|---|---|
| R1 | LangGraph Server 升级版本时 `interrupt()` / `Command(resume=...)` 协议有 breaking change | 在 `pyproject.toml` 里 pin `langgraph` minor 版本;升级前先在阶段 0 那个 probe 跑一遍冒烟 |
| R2 | 前端 `useStream` 的 `reconnectOnMount` 行为跟自写 EventSource 不完全一致,刷新页面后某些情况下不会自动续接 SSE | 阶段 3 手动测刷新场景;如不达预期,配合 `client.threads.getState()` 拉一次 state 兜底 |
| R3 | 节点里 `get_stream_writer()` 在单测里没有 LangGraph runtime → 抛错 | 节点 wrap `try: writer = get_stream_writer() except: writer = lambda x: None` |
| R4 | 多用户场景下 `langgraph_auth.py` 没对 ai_writing assistant 做隔离,可能跨用户拿到别人的 thread state | 阶段 4 一并配置 auth;新增专项测试 |
| R5 | `client.threads.delete()` 是异步删,admin 清理脚本调完后立即查 state 还能短暂查到 → `skipped_active` 误判 | 删之前先 lock thread 或调用 `client.runs.cancel()` 强制收敛 |
| R6 | LangGraph Server 自带 checkpoint 仍然是 sqlite(`langgraph.json` 里配的),在容器重启时跟 AI 写作原有的 `.deer-flow/data/checkpoints.db` 是同一个文件 → schema 共用 | 阶段 1 之前先确认主 checkpointer 配置路径,避免双开 sqlite 文件锁竞争 |
| R7 | 现有用户在迁移窗口期发起的会话,灰度切到新路径后无法续跑(state 在旧 sqlite,新路径查不到) | 迁移前 1 小时禁止新会话;或写一个一次性脚本把旧 checkpointer 的 thread 复制到主 checkpointer |
---
## 六、工时与里程碑
| 阶段 | 工时 | 可独立交付 |
|---|---|---|
| 阶段 0:可行性预演 | 0.5 d | ✅ |
| 阶段 1:graph 注册 | 0.5 d | ❌(后端只生效,前端没接) |
| 阶段 2:节点改造 | 1.5 d | ❌ |
| 阶段 3:前端接入 | 1 d | ✅(带开关上灰度) |
| 阶段 4:业务表写入解耦 | 0.5 d | ❌(跟阶段 3 合并发) |
| 阶段 5:transcript | 0.2 d | ✅ |
| 阶段 6:admin 清理改造 | 0.3 d | ✅ |
| 阶段 7:删冗余 | 0.3 d | ✅(独立 PR,灰度后再发) |
| 阶段 8:测试 + 灰度 | 1 d | ✅ |
| **核心工时** | **5.8 d** | |
| **+ 50% buffer** | **8.7 d ≈ 9 d** | |
**建议排期**:
- 第 1 周:阶段 0 + 1 + 2(后端完整、本地能跑通)
- 第 2 周:阶段 3 + 4 + 5 + 6(前端 + 业务集成)
- 第 3 周:阶段 8(测试 + 灰度)
- 灰度 1~2 周后:阶段 7(删冗余)
---
## 七、回滚预案
每个阶段都设计为可独立回滚:
| 场景 | 回滚动作 |
|---|---|
| 阶段 3 上线后发现 SSE 不稳 | 前端开关 `VITE_AI_WRITING_BACKEND=legacy`,重新部署,0 dataloss |
| 阶段 7 删冗余代码后发现新路径有问题 | 从 git revert 删除 commit,恢复旧路由代码;业务表/checkpoint 不受影响 |
| 阶段 1 注册 assistant 后 LangGraph Server 起不来 | 从 `langgraph.json` 移除 `ai_writing` 那一行,重启 Server,回到迁移前状态 |
**数据兼容承诺**:
- 业务表 schema 完全不变
- `thread_id` (== `ai_writing_sessions.id`) 含义保持一致
- transcript 列含义不变
**最坏回滚**:把 `VITE_AI_WRITING_BACKEND` 改回 `legacy`、`langgraph.json` 删 `ai_writing` 那行,回到迁移前的"方案 C/F/B 路径"。已经走完的会话留在新 checkpoint 里成"孤儿",但业务表里的草稿和审核结果**完整无损**。
---
## 八、迁移成功后能享受的"免费红利"
1. **完整 history API**:`client.threads.getHistory(thread_id)` 拿到每一步 checkpoint,做"回到某一步重试"非常便宜
2. **time travel**:用户能从任意 checkpoint 分叉重写
3. **跟主聊天共享基础设施**:升级 LangGraph 版本时一并升级,不用维护两套 SSE / checkpoint 协议
4. **天然支持水平扩容**:哪天上 K8s 多副本部署,AI 写作跟主聊天一样开箱即用
5. **天然支持 IM 渠道接入**:`app/channels/` 那套 Feishu / Slack 实现是 `langgraph-sdk` 的,迁完后 AI 写作也能在 IM 里用,零额外代码
---
## 九、相关文件索引(迁移前后参照)
### 现状(迁前)
- `app/gateway/routers/ai_writing.py:148-176` —— 8 个模块级 dict + drain task
- `packages/harness/deerflow/agents/ai_writing/graph.py:370-538` —— 自管 checkpointer
- `frontend-web/src/open-canvas/api/ai-writing.ts` —— 自写 fetch + EventSource
### 参照(主聊天迁后形态)
- `frontend-web/src/core/threads/hooks.ts:207` —— `useStream` 用法
- `frontend-web/src/core/api/api-client.ts` —— LangGraph SDK Client 初始化
- `offline-backend-20260512/backend/langgraph.json` —— assistant 注册位置
- `offline-backend-20260512/backend/packages/harness/deerflow/agents/lead_agent/` —— graph 工厂参考写法
- `offline-backend-20260512/backend/packages/harness/deerflow/runtime/checkpointer/async_provider.py` —— 共享 checkpointer 入口
### 目标(迁后)
- 新增:`packages/harness/deerflow/agents/ai_writing/graph.py:make_ai_writing_graph`
- 新增:`frontend-web/src/open-canvas/hooks/useAIWritingStream.ts`
- 删除:`app/gateway/routers/ai_writing.py` 中的 `/start /stream /resume /state` 路由 + 8 个 dict
- 删除:`frontend-web/src/open-canvas/api/ai-writing.ts` 中的 `startWriting / streamSession / resume` 全部 fetch 调用
- 简化:`app/gateway/ai_writing_cleanup.py`(改用 SDK client 删 thread)
---
## 十、决策摘要(给 PM / 维护者)
> **TL;DR**
> 1. 主聊天不受多 worker 影响,是因为它把状态托管给了独立的 LangGraph Server 进程,前端直接通过 SDK 跟 Server 通信。AI 写作要做同样的事。
> 2. 改造范围:后端 graph 注册 + 节点流通道改造 + 前端 hook 换 SDK + 业务表写入解耦。**核心约 6 人日,含 buffer 9 人日**。
> 3. 业务表、节点逻辑、4 个干预点、UI 形态全部保留,**用户感知层面零变化**。
> 4. 改造完一次性获得"刷新不丢进度、多 worker 不裂、跟主聊天共享基础设施、IM 渠道免费支持"等长期红利。
> 5. 建议跟"方案 C"并行:先按 [ai-writing-说明.md](./ai-writing-说明.md) 上方案 C 应急止血,本方案作为长期改造按周排期。两者不冲突,方案 C 上线即受益,本方案完工后可下线方案 C 的双进程配置。
@@ -0,0 +1,253 @@
# AI 写作「四阶段内置智能体化」改造方案
> 目标:把 AI 写作现有的 **素材收集专家 / 写作大纲 / 作家写作 / 编辑审核** 四个功能,
> 从「硬编码的 LangGraph 节点 + 硬编码提示词」改造为由**内置功能型智能体**驱动——
> 每个阶段对应一个可配置的内置 agent(独立人设 SOUL、可配模型、可挂技能/工具)。
本文给出现状梳理、目标设计、以及**分步可独立交付的实现计划**。
---
## 0. 一句话结论
不推倒重来。**保留现有图的编排骨架、4 个用户干预点、流式与状态机,只把每个阶段节点的「大脑」从「硬编码 prompt 直调 LLM」替换为「加载对应内置 agent 的 SOUL+配置、在子线程上跑该 agent、按结构化契约解析其输出」。** 这样前端几乎不动,复杂逻辑(严格模式、素材不足求助、逐章流式、技能检索步骤)全部保留。
---
## 1. 现状梳理(精确到文件)
AI 写作是一条 LangGraph 图:`packages/harness/deerflow/agents/ai_writing/graph.py`
```
intent_parser → researcher → (pause 素材确认) → writer_outline → (pause 大纲确认)
→ writer_draft → (pause 草稿确认 / 素材不足求助) → editor → (pause 编辑打回) → done
```
四个待改造阶段(均为**硬编码节点**,直接调 LLM、不走 agent 运行时):
| 阶段(用户语言) | 节点文件 | 提示词 | 产出(`state.py`) |
|---|---|---|---|
| 素材收集专家 | `nodes/researcher.py` | `prompts/researcher_prompts.py` | `material_package`(keywords + materials) |
| 写作大纲 | `nodes/writer_outline.py` | `prompts/writer_prompts.py` | `current_outline`(Outline JSON) |
| 作家写作 | `nodes/writer_draft.py` | `prompts/writer_prompts.py` | `current_draft`(Markdown,逐章流式) |
| 编辑审核 | `nodes/editor.py` | `prompts/editor_prompts.py` | `review_result`(评分 + 问题列表 JSON) |
关键事实:
- **LLM 调用方式**:节点通过 `nodes/_utils.py` 的 `get_model()` + `llm_json()` **直接调 LLM**,提示词写死在 `prompts/*.py`。**没有**走 agent 人设 / 技能 / 工具体系。
- **模型**:全程单一 `state.model_name`(用户在写作表单里选的主模型),各阶段无法分别配。
- **干预点 / 流式 / 严格模式 / 素材不足求助**:都在 `graph.py` 的 pause 节点和 `writer_draft` 里,逻辑较重,需原样保留。
- **前端**:`frontend-web/src/open-canvas/contexts/AIWritingContext.tsx` 是状态机(`researching/writing_outline/writing_draft/reviewing/...`),时间线 `AIWritingTimeline.tsx` 按 `progress_events`(已带 `agent_name` 字段)渲染。
---
## 2. 可复用的现成机制(不用造轮子)
代码库里**已经有**一套成熟的「内置功能型智能体」范式——圆桌的 `roundtable-intent / roundtable-recommender / roundtable-coordinator`:
1. **资源即代码**:`app/gateway/routers/_roundtable_seed_assets/<agent-id>/`
- `config.yaml`(`id` / `name` / `description`,可扩展 `model` / `skills` / `tool_groups`)
- `SOUL.md`(人设 + 职责 + 工作流 + **结构化输出契约**)
2. **种子器**:`app/gateway/routers/_roundtable_seed.py::ensure_roundtable_functional_agents`
- 启动时 + 相关路由入口自愈:目录不存在才从资源字节级落盘到 `.deer-flow/agents/<id>/` + DB(**已存在则永不覆盖**,尊重本地编辑)。
3. **运行**:在**独立 thread** 上跑该内置 agent(见 `app/gateway/routers/intent.py`,`INTENT_AGENT_ID = "roundtable-intent"`),通过 lead agent 运行时把 SOUL.md 作系统提示,流式经 LangGraph `custom`/`messages` 通道透传。
4. **结构化输出约定**:SOUL 规定模型末尾输出固定 **marker + ```json```**(如 `[INTENT_READY]\n```json{...}```),后端用正则解析(`intent.py::_INTENT_READY_PATTERN`)。
> 我们要做的,本质就是**照搬这套范式,给 AI 写作做 4 个功能型 agent**,并让对应的图节点改成「跑这个 agent + 解析其结构化输出」。
另有 agents 通用体系可复用:`agents` 表、`/api/agents` CRUD、智能体管理页(配模型/技能/工具)——4 个写作 agent 落盘后天然出现在这里,可被 admin 编辑。
---
## 3. 目标设计
### 3.1 四个内置写作智能体(建议 id / 职责)
| Agent id | 名称 | 取代节点 | 结构化输出 marker | 产出 schema |
|---|---|---|---|---|
| `ai-writing-researcher` | 素材收集专家 | `researcher` | `[MATERIALS_READY]` | `MaterialPackage` |
| `ai-writing-outliner` | 大纲规划师 | `writer_outline` | `[OUTLINE_READY]` | `Outline` |
| `ai-writing-writer` | 作家 | `writer_draft` | `[SECTION_READY]`(逐章) | 章节 Markdown |
| `ai-writing-editor` | 编辑 | `editor` | `[REVIEW_READY]` | `ReviewResult` |
每个 agent 自带:
- `config.yaml`:`id / name / description` +(扩展)`model`(该阶段专用模型,可空=回退用户主模型)、`skills`(如 researcher 挂检索技能)、`tool_groups`。
- `SOUL.md`:由现有 `prompts/*.py` 内容迁移改写,**追加结构化输出契约**(严格 marker + JSON 格式 + 反例,仿 `roundtable-intent` SOUL 的「硬规则」写法,压制弱模型乱输出)。
### 3.2 节点改造方式(核心)
每个阶段节点保留**输入/输出契约不变**(仍读写 `state` 的同一批字段),内部从:
```
# 旧:硬编码 prompt 直调
model = get_model(config, state["model_name"])
result = llm_json(model, SYSTEM_PROMPT, USER_PROMPT.format(...))
```
改为:
```
# 新:跑对应内置 agent,按 marker 解析
result = await run_writing_agent(
agent_id="ai-writing-outliner",
state=state, config=config,
user_payload=<本阶段输入>, # 意图/素材/大纲/草稿等拼成的一段输入
marker="[OUTLINE_READY]", # 结构化输出契约
)
```
新增统一助手 `nodes/_agent_runner.py::run_writing_agent(...)`:在子 thread 上跑指定内置 agent(复用 `intent.py` 的 run/stream 机制)、把流式 chunk 透传到 `custom` 通道(前端时间线不回归)、用复用的 `_utils.parse_json` 多级容错解析 marker 后的 JSON。
### 3.3 为什么选这个方案(A)而非全多智能体重写(B)
- **方案 A(推荐)**:保留图骨架,逐节点替换大脑。前端基本不动;干预点/流式/严格模式/素材求助原样保留;可**按阶段灰度 + feature flag 回退**,风险可控。
- **方案 B(不推荐)**:仿圆桌重做成多 agent 编排,需重写编排、状态、流式、4 个干预点对接,工作量数倍、回归面巨大,收益(更"纯"的多 agent)对本场景并不必要。
---
## 4. 配置与可管理性
- **落盘**:仿 roundtable 新增 `_ai_writing_seed_assets/` + 一个 `ensure_ai_writing_functional_agents()` 种子器,在 Gateway 启动与 ai_writing 会话入口自愈。
- **管理界面**:4 个 agent 落盘后即出现在智能体管理页,admin 可编辑 **SOUL(人设)/ 模型 / 挂载技能**。可选:在「文章类型配置页」旁加一个「写作智能体配置」入口,或给这 4 个打一个 `tag` 便于筛选。
- **模型优先级**:节点跑 agent 时 `该 agent config.model > 用户写作表单选的主模型 model_name`(保留现有"用户选模型"语义,新增 per-阶段覆盖能力)。
- **技能**:researcher 现有的技能检索能力(`search/skill_search.py`)改为 `ai-writing-researcher` 的**挂载技能**,admin 可增减;检索步骤事件(`SkillStep`)形态保留给前端展示。
---
## 5. 分步实现计划(每步可独立交付 / 验收)
### Phase 0 · 契约冻结
- 定 4 个 agent 的 `id / name`、每个的 **marker + JSON schema**(与 `state.py` 的 `MaterialPackage/Outline/DraftArticle/ReviewResult` 严格对齐)。
- **验收**:本文 §3.1 / §6 的契约评审通过、字段与现有 TypedDict 一一对应。
### Phase 1 · 内置 agent 种子化(后端,纯新增,不接管流程)
- 新建 `app/gateway/routers/_ai_writing_seed_assets/<4 个 agent>/{config.yaml, SOUL.md}`;SOUL 由现有 `prompts/*.py` 迁移改写 + 追加结构化输出契约。
- 仿 `_roundtable_seed.py` 写 `ensure_ai_writing_functional_agents()`,挂到启动 lifespan + ai_writing 入口。
- **验收**:启动后 4 个 agent 出现在 `.deer-flow/agents/`、DB、`/api/agents`,能在智能体管理页查看/编辑;**此阶段不改图,写作流程行为不变**。
### Phase 2 · 节点接入「跑内置 agent」(后端,逐阶段灰度)
- 新增 `nodes/_agent_runner.py::run_writing_agent(...)`(子线程跑 agent + 流式透传 + marker 解析)。
- 加 feature flag:`config.yaml → ai_writing.use_builtin_agents.{editor,outliner,researcher,writer}`(默认 false=走旧节点)。
- **接入顺序(由易到难)**:
1. **editor**(最简单:小 JSON、无检索、无逐章流式)→ flag 打开端到端验证。
2. **outliner**(输出 Outline JSON)。
3. **researcher**(保留技能检索步骤事件、素材确认暂停)。
4. **writer**(最难:保留**逐章流式** + **严格模式素材不足求助** `blocked_sections`;建议**仍由节点控制"逐章循环"**,每章调一次 `ai-writing-writer`,`section_help` 暂停逻辑不动)。
- 每接一个,旧 prompt 与旧逻辑**保留**,节点按 flag 二选一。
- **验收**:每个阶段 flag 打开后端到端走通,产出结构与旧版一致,干预点 / 流式 / 严格模式 / 求助暂停均不回归。
### Phase 3 · 每阶段 agent 配置化
- per-agent 模型覆盖生效(`agent.config.model > model_name`)。
- researcher 的检索能力改为挂载技能,admin 可增减。
- 智能体管理页可编辑这 4 个的 SOUL / 模型 / 技能;config 热加载,新会话即生效、不重启前端。
- **验收**:admin 改某阶段 agent 的模型 / SOUL / 技能后,新会话立即按新配置运行。
### Phase 4 · 前端适配(小改)
- 时间线 / 状态文案:阶段名读对应 agent 的 `name`(`progress_events.agent_name` 已存在,基本沿用,去掉写死文案)。
- 可选:写作表单 / 设置加「查看·配置写作智能体」入口,跳智能体管理页。
- **验收**:前端展示各阶段对应的智能体名;配置入口可达。
### Phase 5 · 清理收口
- 四阶段稳定后,默认打开全部 flag、移除旧 prompt 直调路径与 flag(prompts 历史留在 git)。
- 更新 `offline-backend-20260512/backend/CLAUDE.md` 架构描述。
- **验收**:回归测试通过、冗余删除、文档同步。
---
## 6. 结构化输出契约(与现有 state 对齐)
各 agent SOUL 末尾必须输出 `marker + ```json``` 块,schema 直接对齐 `state.py`:
- `ai-writing-researcher` → `[MATERIALS_READY]`:`{ "keywords": string[], "materials": Material[] }`(`Material` 见 `state.py`,含 `id/title/content/source/relevance_score/source_type/...`)。
- `ai-writing-outliner` → `[OUTLINE_READY]`:`Outline = { "title": string, "sections": OutlineSection[] }`(`OutlineSection = { section_title, key_points: KeyPoint[], material_ids }`)。
- `ai-writing-writer` → 逐章 `[SECTION_READY]`:`{ "section_title": string, "markdown": string, "needs_more_material"?: { "reason": string } }`(`needs_more_material` 触发严格模式求助 `blocked_sections`)。
- `ai-writing-editor` → `[REVIEW_READY]`:`ReviewResult = { "verdict": "pass"|"reject", "fact_score", "logic_score", "language_score", "overall_score", "pass_threshold", "revision_notes": ReviewIssue[] }`。
解析复用 `nodes/_utils.py::parse_json`(多级容错),marker 正则仿 `intent.py::_INTENT_READY_PATTERN`。
---
## 7. 风险与注意
1. **弱模型结构化输出不稳**:SOUL 写严格格式 + 反例 + 「输出 marker 后立刻闭嘴」硬规则(仿 `roundtable-intent` SOUL §0);解析层复用 `parse_json` 多级降级。
2. **writer 的逐章流式 + 严格模式求助最复杂**:建议**循环控制权留在节点**(每章调一次 agent),不要让 agent 一次吐全文,否则 `blocked_sections` / `section_help` / 逐章流式都要重做。
3. **researcher 技能检索步骤事件**(`SkillStep`)前端有专门卡片:迁移时保留这些 `progress_events` 形态。
4. **种子器 never-overwrite**:迭代 SOUL 后**老部署不会自动更新**(与圆桌同一问题)。运维更新办法:删 `.deer-flow/agents/<id>/` 重新种子,或后续给种子器加「内置功能 agent 按版本/hash 覆盖」开关。
5. **子线程隔离**:跑写作 agent 的子 thread 与主 ai_writing thread 状态隔离,注意 checkpointer 与清理(沿用 ai_writing 既有的会话清理)。
6. **离线内网**:researcher 的检索一律走技能(不联网),与现有「离线部署禁 web_search、走 skill」策略一致。
---
## 8. 涉及文件清单(落地时对照)
**后端(主要改动)**
- 新增 `app/gateway/routers/_ai_writing_seed_assets/{ai-writing-researcher,ai-writing-outliner,ai-writing-writer,ai-writing-editor}/{config.yaml,SOUL.md}`
- 新增 `app/gateway/routers/_ai_writing_seed.py`(种子器,仿 `_roundtable_seed.py`)
- 新增 `packages/harness/deerflow/agents/ai_writing/nodes/_agent_runner.py`(`run_writing_agent`)
- 改 `nodes/{researcher,writer_outline,writer_draft,editor}.py`(按 flag 二选一)
- 改 `config.yaml`(新增 `ai_writing.use_builtin_agents.*` 开关;可选 per-agent 默认模型)
- 保留 `prompts/*.py`(回退用,Phase 5 删)
**前端(小改)**
- 改 `src/open-canvas/components/ai-writing/AIWritingTimeline.tsx`(阶段名读 agent name)
- 可选:写作表单/设置加「配置写作智能体」入口(跳 `/page/...` 智能体管理页)
**文档**
- 本文件
- Phase 5 收口时更新 `offline-backend-20260512/backend/CLAUDE.md`
---
## 9. 实施记录(2026-06-11,Phase 1-4 已落地)
### 已交付
- **Phase 1**:`_ai_writing_seed_assets/{ai-writing-researcher,ai-writing-outliner,ai-writing-writer,ai-writing-editor}/{config.yaml,SOUL.md}` + `_ai_writing_seed.py::ensure_ai_writing_functional_agents()`,挂启动 lifespan(`_sync_legacy_agents` 之前)+ `ai_writing.list_sessions / list_article_types` 入口自愈。
- **Phase 2**:`nodes/_agent_runner.py`(`stream_writing_agent` / `run_writing_agent` / `parse_marker_json` / `resolve_agent_model_name` / `use_builtin_agent`);四节点按 `config.yaml → ai_writing.use_builtin_agents.{researcher,outliner,writer,editor}` 二选一(默认全 false,config 按 mtime 热加载,改完即对新会话生效)。agent 目录缺失时节点**静默回退旧 prompt 路径**,写作流程永不因 agent 被删而中断。
- **Phase 3(部分)**:per-agent 模型覆盖已生效(优先级 `agent config.model > 节点显式回退模型(keyword_model/rank_model)> 表单主模型 model_name`);SOUL/模型在智能体管理页可编辑、按 mtime 热加载。researcher「检索能力改挂载技能」未做(仍走节点内 SkillPicker 编排)。
- **Phase 4**:时间线 agent 名由后端 `progress_events.agent_name` 动态下发(flag 开启时读 agent config 的 `name`);`TimelineStep.tsx` 补「大纲规划师」配色(未命中名字回退灰色,admin 改名不报错)。
- **测试**:`tests/test_ai_writing_seed.py`(资源完整性 / 契约 marker / never-overwrite)+ `tests/test_ai_writing_agent_runner.py`(marker 多级解析 / 模型优先级 / flag / 流式端到端 / SOUL 缺失降级),共 31 例。
### 与 §6 契约的修订(以实现为准)
为保住「逐章流式打字机」「review_chunk/review_item_done 分维度卡片」「素材确认/求助暂停」等前端形态,编排控制权全部留在节点,agent 只承担**单次结构化产出**:
| Agent | 实际契约 |
|---|---|
| `ai-writing-researcher` | 两个子任务:`[KEYWORDS_READY]` + `{"keywords": []}`;`[MATERIALS_RANKED]` + `{"ranked_ids": [], "summary": ""}`。素材本体来自节点的检索编排(agent 不联网),`MaterialPackage` 仍由节点组装 |
| `ai-writing-outliner` | `[OUTLINE_READY]` + 完整 `Outline` JSON(新规划 / 修改模式共用,payload 开头标明任务模式) |
| `ai-writing-writer` | **无 JSON marker**:每章直接输出 Markdown 正文(保流式);严格模式素材不足只输出一行 `[[SECTION_BLOCKED]] 原因`(沿用原哨兵) |
| `ai-writing-editor` | 每个维度一次调用:`[REVIEW_READY]` + `{"score": int, "issues": []}`;综合分/verdict/pass_threshold 仍由节点按 config 计算(不信任 LLM 自判通过) |
另一处架构修订:**不在子 thread 上经 lead agent 运行时跑**(§3.2 原设想复用 `intent.py` 机制,但其 loopback 在 app 层,harness 图节点不可 import;且单轮结构化调用无需 thread/checkpointer/中间件成本)。`run_writing_agent` 直接「SOUL 作 system prompt + 单条输入」调模型,规避了 §7.5 的子线程隔离/清理风险。researcher 挂技能(Phase 3 剩余项)如需完整工具体系再评估接入运行时。
### 已知存量测试失败(与本次无关)
`test_ai_writing_graph.py`(mock 已删除的 `intent_parser.llm_json`)、`test_ai_writing_word_count.py`(mock 已删除的 `writer_draft.get_model`)、`test_ai_writing_draft_headings.py`(断言三级结构升级前的 `####→###` 行为)、`test_ai_writing_outline_revise.py`(断言旧 prompt 文案),改造前即失败,待另行清理。
## 10. Phase 3 收尾:检索类型两项化 + 配置技能驱动检索(2026-06-13 已实施)
本节落地了 §9 遗留的「researcher 检索改挂载技能」,并按新需求重新设计了检索类型与 PAUSE-1 交互。
### 10.1 检索类型(material_source)收敛为两项
- 写作表单「素材来源」改名「检索类型」,只剩 `general`(通用检索,默认)/ `notebook`(我的空间);旧值 `knowledge_base` / `skill` 由 researcher 节点按 `general` 兼容(老会话 resume 不受影响)。
- 前端:`AIWritingForm.tsx`(选项/标签)、`WritingFormContext.tsx`(默认值/类型/applyProposal 旧值映射)、`types/ai-writing.ts`、`message-list.tsx`(审批卡标签兼容旧值)。
### 10.2 通用检索 = 素材收集专家配置的技能编排
- `ai-writing-researcher` agent 的 `config.yaml → skills` 是权威配置(智能体管理页可增删/替换);种子默认 `[knowledge-base-search]`。
- 内置技能 **knowledge-base-search(知识库检索)**:把原 web/intranet 关键词并发检索包装成技能。researcher 对它特殊处理——不拼 description,直接对 Step1 生成的检索词做原生并发检索(行为与旧 knowledge_base 模式一致)。其它配置技能按 `意图 + description` 拼定向 query 检索。按配置顺序执行、累积达 `max_materials` 早停(`stop_early`)。
- 技能配置为空/全部失效 → 内存兜底回退知识库检索(`researcher._load_configured_skills`),检索永不瘫痪。
- 种子:`_ai_writing_seed_assets/skills/knowledge-base-search/SKILL.md` → `skills/public/`(never-overwrite);旧部署的 researcher `config.yaml` 缺 `skills` 键时就地补默认(显式 `skills: []` 不动)。`_ai_writing_seed.py::ensure_ai_writing_functional_agents()` 一并处理。
### 10.3 PAUSE-1 输入框 → 匹配技能检索并**追加**
- 用户在素材确认卡输入自然语言(如「检索 A 的数据」)→ `re_search + user_query`:配置技能 >1 个时 `SkillPicker(candidates=配置技能)` 让模型按输入匹配排序(流式打字机保留),单技能直接用;用用户原话(非知识库技能附 description)检索。
- **追加语义**:保留原素材列表与顺序,新素材按 URL 去重后追加在末尾(ID 续号),跳过 LLM 重排与 max_materials 截断(仅 100 条硬上限),summary 显示「追加检索到 X 条新素材,当前共 Y 条」。原 20 条 + 新 20 条 = 40 条。
- 「技能检索」独立按钮已删除(通用检索本来就走技能编排);后端继续兼容旧 `enable_skill_search` action(按 user_query 追加处理)。无输入的「重新搜索」仍为覆盖式重检。
- 前端:`InterventionCard.tsx`(按钮/文案,hasQuery 时按钮文案「检索并追加素材」)、`MaterialsToolbar.tsx`(提示语)、`useAIWritingStream.ts`(素材卡回到 researching 一律置 skillSearchPending,让 SkillStepsCard 占位即时挂载)。
### 10.4 测试
- `tests/test_ai_writing_material_source.py` 重写(9 例):缺省/旧值→通用检索、自定义技能 description query、user_query 追加+URL 去重+多技能 picker 匹配(candidates 断言)、无输入重检覆盖、空配置回退。
- `tests/test_ai_writing_seed.py` 扩展(+5 例):技能资产存在、researcher 种子含默认 skills、技能种子 never-overwrite、缺 skills 键就地补丁、显式 `[]` 不动。
@@ -0,0 +1,507 @@
# AI 写作「对话驱动写作台」实现方案(可落地版)
> 需求:**复制**现有 AI 写作代码,新增一个独立页面(**原页面/原路由零改动**)。在新页面里
> **大改交互流程**——去掉「素材收集 / 大纲规划 / 作家写作 / 编辑审核」四个阶段干预卡里的**输入框**,
> 只**保留原来的确认按钮**;在页面**底部新增一个统一的多行智能输入框**,具备**强意图理解**能力:
> 重新搜索、新增检索词、添加检索素材、重新规划大纲、按要求改大纲、提修改意见、审核意见、
> 素材不足继续搜集、对写作内容提问……**覆盖现有全部交互甚至更多**。
>
> 交互节奏不变:**一步一确认**——进行到某个专家阶段时,交互就针对该专家(阶段作用域);
> 用户可以**点原来的确认按钮**,也可以**在底部输入框里发「继续下一步」的意图**推进。
> 意图**拿不准时**主动向用户**发起协助/澄清**,绝不盲目触发高代价动作(定稿 / 重搜等)。
本文是**实现指引**,落地时按第 9 节路线图分阶段推进。文中所有文件路径、符号名均对齐当前代码。
---
## 1. 现状梳理(改造地基)
现有 AI 写作是一套**独立 LangGraph 子系统**(不是 lead_agent),前后端都已成型、可复用。
### 1.1 后端 `ai_writing` graph
- 图工厂:`offline-backend-20260512/backend/packages/harness/deerflow/agents/ai_writing/graph.py`
(`make_ai_writing_graph`,registered as `assistant_id="ai_writing"`)
- 状态:`.../ai_writing/state.py`(`AIWritingState`)
- 四个「阶段大脑」节点:
| 阶段 | 节点 | 文件 |
|------|------|------|
| 素材收集 | `researcher` | `nodes/researcher.py` |
| 大纲规划 | `writer_outline` | `nodes/writer_outline.py` |
| 作家写作 | `writer_draft` | `nodes/writer_draft.py` |
| 编辑审核 | `editor` | `nodes/editor.py` |
- **五个暂停点**(`interrupt()`,`Command(resume=payload)` 续跑)——这是对话改造的核心可复用资产:
| pause_point | 语义 | 现有 action |
|-------------|------|-------------|
| `material_confirm` | 素材确认 | `confirm` / `re_search` / `enable_skill_search` |
| `outline_confirm` | 大纲确认 | `confirm` / `re_outline` |
| `draft_confirm` | 草稿确认 | `to_editor` / `finalize` / `user_revise` |
| `review_confirm` | 编辑打回确认 | `accept_review` / `force_finalize` |
| `section_help` | 素材不足求助 | `section_help`(+`sectionDecisions`) |
- resume 载荷(`UserInterventionPayload`,`types/ai-writing.ts`)字段:`action`、`approvedMaterialIds`、
`userQuery`(自然语言补充检索)、`editedOutline`、`outlineFeedback`、`userRevisionNotes`、
`overrideVerdict`、`selectedIssueIndices`、`sectionDecisions`。
**协议已同时支持「自然语言 + 结构化 action」**——这是对话层能复用的关键。
> 结论:**状态机 / 流式 / 暂停·续跑协议 / 持久化都可复用**,无需重写引擎。改造本质是
> 「把分散在干预卡里的输入框,换成一个底部智能输入框 + 意图路由层」,再把意图翻译回**现有
> `action + payload`**;仅少量新意图(对内容提问、素材不足自动回退重搜、追加审核意见)需新增能力。
### 1.2 前端 `open-canvas` 子系统
- 主页面:`frontend-web/src/open-canvas/pages/AIWritingPage.tsx`
- 路由注册:`open-canvas/routes/OpenCanvasRoutes.tsx`(`/page/canvas/ai-writing/*`)、
`pages/WorkspaceRoutes.tsx`(`/page/workspace/ai-writing/*`)、`pages/NotebookAIWritingPage.tsx`
- 状态机 + 流式:`contexts/AIWritingContext.tsx`(`useReducer` + LangGraph `useStream`,`assistantId:'ai_writing'`)
- 事件翻译 / reducer:`hooks/useAIWritingStream.ts`
- 类型:`types/ai-writing.ts`
- **左栏面板**:`components/ai-writing/AIWritingPanel.tsx`(时间线 + 干预卡 + 状态栏;idle 时挂启动表单)
- **要改造的输入 UI**(本次重点):
- 干预卡 `components/ai-writing/InterventionCard.tsx`:内含
`MaterialConfirmCard`(素材:有 `MaterialsToolbar` 输入框)、
`OutlineConfirmCard`(大纲:有 feedback textarea)、
`DraftConfirmCard`(草稿:有「修改意见」textarea)、
`ReviewConfirmCard`(审核:有「补充修改指令」textarea)、
`SectionHelpCard`(素材不足:按钮组)。
**每张卡里都既有输入框又有确认/动作按钮**——本次要**去掉输入框、保留按钮**。
- 启动表单 `components/ai-writing/AIWritingForm.tsx`(idle 阶段的配置表单)——本次由底部输入框接管启动。
- **已存在的对话原型**(可借鉴):`components/ai-writing/WritingSetupChat.tsx`
(`useThreadStream` 起 lead_agent 线程 + `setup_writing` 审批卡回填表单;仅管启动前配置,不直接复用)。
- 底部输入框可直接复用 UI 组件:`@/components/ai-elements/prompt-input`
(`PromptInput` / `PromptInputTextarea` / `PromptInputSubmit` / `PromptInputFooter`,见 `WritingSetupChat`)。
---
## 2. 目标与范围
### 2.1 必须满足
1. **复制式新增**:新目录 / 新路由 / 新侧边栏入口,**旧页面、旧路由、旧组件零改动**(「初始的不用动」)。
2. 页面**底部单一多行智能输入框**接管全流程交互;四个阶段干预卡里的**输入框全部移除**。
3. **保留确认按钮**:每个阶段到达暂停点时,消息流里仍渲染**产物卡 + 原来的确认/动作按钮**
(素材「确认素材」、大纲「确认大纲」、草稿「让编辑审核 / 确认定稿」、审核「按编辑意见修改 / 强制定稿」、
素材不足的三选一按钮)。用户**点按钮**或**在底部输入框发自然语言意图**二选一均可推进。
4. **强意图理解**:把用户自由文本准确路由到正确动作,**覆盖现有全部交互 + 更多**(见 3.2)。
5. **阶段作用域**:意图解析必须知道「当前停在哪个专家阶段」,把同一句话按当前阶段翻译成对应 action。
6. **素材不足自动回退重搜**:修改意见需要的信息现有素材没有时,先重搜补素材、补完自动继续原意图。
7. **拿不准就协助**:低置信意图**不猜着执行**,走澄清追问(clarify)或用户协助。
8. 保留右侧草稿实时预览(可编辑)与时间线 / 进度展示。
### 2.2 明确不做(本期)
- 不改旧 `AIWritingPage` 及其 `AIWritingForm` / `InterventionCard`(这两个是要在**副本**里改的)。
- 不替换 `ai_writing` graph 四个阶段大脑逻辑,不动五个暂停点 / checkpoint / 持久化。
- 不引新状态管理库(继续 `useReducer` + `useStream`)。
### 2.3 复制策略(关键决策)
「复制一份」= **复制会被大改的表现层组件**(页面 + 干预卡 + 面板),**复用不改的引擎层**:
| 复制(新建副本,大改) | 复用(原样,不改;仅对 `types` 做**追加式**扩展) |
|------------------------|--------------------------------------------------|
| 新页面 `AIWritingChatPage.tsx` | `contexts/AIWritingContext.tsx`(状态机 + 流式) |
| 新面板 `WritingChatPanel.tsx`(消息流 + 底部输入框) | `hooks/useAIWritingStream.ts`(事件 → state) |
| 新消息卡 `chat-cards/*`(产物卡+确认按钮,**无输入框**) | `components/ai-writing/AIWritingDraftPanel.tsx`(右侧草稿预览) |
| 新意图客户端 `api/ai-writing-intent.ts` | 各流式展示子组件(`MaterialsCard`/`OutlineCard`/`ReviewCard`/`SkillStepsCard`…) |
| (可选)新 `contexts/WritingChatContext.tsx` 包一层「pending 意图 / 澄清态」 | `types/ai-writing.ts`(**只加字段不改旧字段**,保证旧页面不受影响) |
> **不复用、也不改** 的三个「输入框组件」:`AIWritingForm` / `InterventionCard` / `WritingFormContext`——
> 旧页面继续用它们,新页面完全不引用它们。这样「初始的不用动」得到硬保证。
>
> 为什么复用 `AIWritingContext` 而不复制它?它**不含任何输入框 UI**,只是「状态机 + 与后端 graph 的
> 流式桥」,复用它**不会改动旧页面的任何呈现**(旧页面照常在自己的 Provider 实例里跑)。复用能显著
> 降低维护成本、避免两套引擎漂移。若要绝对物理隔离,也可整目录复制 `AIWritingContext` +
> `useAIWritingStream` 到新目录——**推荐先复用**,仅当后续需要给对话态加大量图内新协议时再分叉。
---
## 3. 核心设计
### 3.1 三层结构
```
┌──────────────────────────────────────────────────────────────┐
│ 对话 UI 层(新) WritingChatPanel │
│ - 消息流:用户消息 + AI 阶段产物卡(含【保留的确认按钮】)+ 进度 │
│ - 底部:统一多行智能输入框(唯一自由输入入口) │
│ - 右侧:草稿实时预览(复用 AIWritingDraftPanel) │
└───────────────┬──────────────────────────────────────────────┘
│ 用户自然语言(+ 当前 status/pausePoint 上下文)
▼
┌──────────────────────────────────────────────────────────────┐
│ 意图解析层(新,核心) POST /api/ai-writing/sessions/{id}/intent │
│ 输出:{ intent, pausePoint, action, payload, │
│ needResearch, researchQuery, answer, confidence, clarify }│
└───────────────┬──────────────────────────────────────────────┘
│ 结构化 action + payload
▼
┌──────────────────────────────────────────────────────────────┐
│ 执行层(复用现有 AIWritingContext) │
│ idle → startWriting(AIWritingRequest) │
│ 暂停 → submitIntervention(UserInterventionPayload) │
│ 问答 → 旁路回答(不改写作状态) │
│ 素材不足 → 先重搜、缓存 pending、补完自动续跑 │
└──────────────────────────────────────────────────────────────┘
```
**设计原则**:意图解析层是「翻译官」——把自由文本翻译成**执行层已经懂的指令**。能复用
`action + payload` 的绝不新造协议;确认按钮点击**直接走执行层**(不经意图层,零延迟、零误判)。
### 3.2 意图分类体系(覆盖全流程 + 更多)
按「意图 → 触发时机(当前 status/pausePoint)→ 映射执行」组织,即意图解析引擎的目标 schema。
**「甚至更多」** = G(问答)、H(控制)、以及 B/C/D/E 里的「素材不足自动回退重搜」。
#### A. 启动类(status = `idle`)
| 意图 | 用户说法示例 | 映射 |
|------|-------------|------|
| `start_writing` | 「写一篇关于新能源出口的深度分析,2000 字」 | 解析成 `AIWritingRequest` → `startWriting()` |
| `start_with_outline` | 「按这个大纲写:…」 | `AIWritingRequest.userOutline` |
| `start_imitate` | 「仿照这篇样文写…」 | `writingModeType='imitate'` + `sampleText` |
#### B. 素材类(pausePoint = `material_confirm`)
| 意图 | 示例 | 映射 |
|------|------|------|
| `confirm_materials` | 「素材可以,继续 / 下一步」 | `{action:'confirm', approvedMaterialIds}` |
| `research_again` | 「重新搜索素材」 | `{action:'re_search'}`(无 userQuery=覆盖式重检) |
| `add_material`/`add_keyword` | 「再补点关于 X 的素材」「加个关键词 Y」 | `{action:'re_search', userQuery:'X/Y'}`(追加) |
| `select_materials` | 「只用第 1、3 条」 | `{action:'confirm', approvedMaterialIds:[…]}` |
| `drop_materials` | 「去掉第 2 条」 | 同上(反选后的子集) |
#### C. 大纲类(pausePoint = `outline_confirm`)
| 意图 | 示例 | 映射 |
|------|------|------|
| `confirm_outline` | 「大纲 OK,开始写」 | `{action:'confirm'}` |
| `reoutline` | 「重写大纲」 | `{action:'re_outline'}`(feedback 可空) |
| `revise_outline` | 「第二章拆成两节」「调整顺序」 | `{action:'re_outline', outlineFeedback:自然语言}` |
#### D. 写作 / 草稿类(pausePoint = `draft_confirm`)
| 意图 | 示例 | 映射 |
|------|------|------|
| `to_editor` | 「交给编辑审核」 | `{action:'to_editor'}` |
| `finalize` | 「就这样定稿」 | `{action:'finalize'}` **(高代价:低置信必澄清)** |
| `revise_draft` | 「第三段太啰嗦,精简」「补个 2024 案例」 | `{action:'user_revise', userRevisionNotes:意见}` |
| `rewrite_section` | 「重写第二章」 | `user_revise` + 章节定位写进 notes |
| `change_tone/style` | 「更口语一点 / 更正式」 | `user_revise` + notes |
| `apply_review`(若已有审核结果) | 「按编辑意见改」「只接受第 1、2 条」 | `{action:'user_revise', selectedIssueIndices:[…]}` |
#### E. 编辑审核类(pausePoint = `review_confirm`)
| 意图 | 示例 | 映射 |
|------|------|------|
| `accept_review` | 「按编辑意见改」 | `{action:'accept_review', selectedIssueIndices}` |
| `partial_accept_review` | 「只接受第 1、2 条」 | `accept_review` + `selectedIssueIndices` 子集 |
| `add_review_opinion` | 「再补一条:核查数据准确性」 | `accept_review` + `userRevisionNotes`(并入补充指令,现协议已支持) |
| `force_finalize` | 「不改了,强制定稿」 | `{action:'force_finalize', overrideVerdict:true}` **(高代价:必澄清)** |
#### F. 素材不足求助类(pausePoint = `section_help`)
| 意图 | 映射 |
|------|------|
| `section_supplement` | `{action:'section_help', sectionDecisions:[…'supplement']}` |
| `section_loose` | `sectionDecisions:[…'loose']` |
| `section_delete` | `sectionDecisions:[…'delete']` |
#### G. 问答类(**新**;任意 status;旁路,不改写作状态)
| 意图 | 示例 | 映射 |
|------|------|------|
| `ask_about_content` | 「第二章讲了啥?」「为什么用这个论点?」 | 意图节点直接带回 `answer`,对话流渲染(见 5.4) |
| `ask_meta` | 「现在到哪步了?」「用了哪些素材?」 | 读当前 state 直接回答,不走图 |
#### H. 控制类(**新 / 半新**)
| 意图 | 映射 |
|------|------|
| `next_step`(通用「继续/下一步」) | 按**当前 pausePoint** 映射到该阶段的默认确认(material/outline→`confirm`,draft→`to_editor`…;等价点确认按钮) |
| `restart_stage` | 重跑当前阶段(复用 `resumeWriting()` 空 command 续跑) |
| `run_background` | 转后台自动跑:`suspendAIWritingToBackground()` |
| `cancel` | `pauseWriting()`(`stream.stop()`) |
| `unknown/clarify` | 无法判定 → 反问澄清 / 用户协助(**防误触发硬指标**) |
### 3.3 「素材不足自动重搜」判定与回退(用户强调点)
触发:用户在**大纲/草稿/审核**阶段提出修改意见,但意见需要的信息现有素材里没有。
判定来源(组合):
1. **意图节点直接判**:把「素材摘要(keywords + 每条 title/source)」喂给意图 prompt,让它判断
「这条意见能否用现有素材满足」;不能 → `needResearch=true` + `researchQuery`。
2. **执行阶段兜底**:`writer_draft` 严格模式已有 `blocked_sections` → `section_help` 暂停点,
对话层把它翻译成「素材不足,是否重搜?」的追问。
回退动作(**首期纯前端实现,不动后端协议**):`needResearch=true` 时,前端把用户的修改
`payload` 缓存为 `pendingIntent`,先 `submitIntervention({action:'re_search', userQuery:researchQuery})`
补素材;监听到新一轮 `material_confirm`(素材追加完成)后,**自动提交** `pendingIntent`。
需处理「重搜期间用户又改主意」→ 允许覆盖 pending。
---
## 4. 意图解析引擎:方案与契约
**采用方案 A:后端 LLM 意图节点(独立 REST)**,叠加高频短句**规则快路径**优化。
理由:`needResearch` 判定需要**完整写作上下文**(素材/大纲/草稿),后端天然持有 checkpoint state;
与 `setup_writing` 一脉相承,离线模型选择策略统一;输出 schema 稳定、前端只消费。
### 4.1 后端入口
`app/gateway/routers/ai_writing.py` 新增:
```
POST /api/ai-writing/sessions/{session_id}/intent
Body: { text: string, status: string, pausePoint?: string }
Resp: IntentResult(见 4.3)
```
实现:读该 session 的 checkpoint state(素材摘要 / 大纲纲要 / 草稿字数·章节 / 审核意见)→
用 `ai_writing` 配置模型(复用 `intent_parser.py` 同套 `create_chat_model` + `parse_json` +
模型容错 `_model_fallback`)解析 → 返回结构化契约。**不改图拓扑**。
新增 prompt:`agents/ai_writing/prompts/intent_router_prompts.py`
- 输入:用户文本、`current_status`/`pause_point`、素材摘要、大纲纲要、草稿字数+章节标题、审核意见列表。
- 输出:严格 JSON(4.3 契约)。硬要求:**只在证据充分时给高 confidence,否则给 `clarify`**;
`finalize`/`force_finalize`/`re_search` 等高代价意图**必须**高置信才不澄清。
### 4.2 前端快路径(先跑规则,未命中再调后端)
`api/ai-writing-intent.ts` 里对**当前 pausePoint** 做少量确定性短语命中,直接产出 payload,省一次往返:
- 「继续/下一步/确认/可以/ok/好的」→ 当前阶段默认 `confirm`(draft 阶段=`to_editor`)。
- 「重新搜索/重搜」(material)→ `re_search`。「重写大纲」(outline)→ `re_outline`。
- 「定稿/强制定稿」→ **不进快路径**(高代价,一律走后端 + 可能澄清)。
- 命中即执行;未命中 → 调后端 `intent` 接口。
### 4.3 意图解析输出契约
```jsonc
{
"intent": "revise_draft", // 见 3.2 分类
"pausePoint": "draft_confirm", // 需要 resume 时;否则 null
"action": "user_revise", // 映射到现有 action
"payload": { // 直接可喂 submitIntervention 的字段(camelCase)
"userRevisionNotes": "第三段精简,并补一个 2024 年的案例"
},
"needResearch": true, // 素材是否不足
"researchQuery": "2024 行业案例", // needResearch 时的检索意图
"answer": null, // 问答类意图的直接回答(旁路)
"confidence": 0.86,
"clarify": null // 低置信时的反问话术(非空则不执行、只追问)
}
```
前端消费顺序:
1. `answer` 非空 → 对话流渲染回答(问答旁路,不动写作状态)。
2. `clarify` 非空 **或** `confidence < 阈值(建议 0.6)` → 渲染反问气泡,等用户澄清(**防误触发**)。
3. `needResearch=true` → 缓存 `pendingIntent=payload`,先重搜,收到新素材后自动提交。
4. 否则 → `idle` 走 `startWriting(...)`;暂停态走 `submitIntervention({action, ...payload})`。
---
## 5. 前端改造方案
### 5.1 新页面与路由(复制式)
- 新页面:`open-canvas/pages/AIWritingChatPage.tsx`
(骨架照抄 `AIWritingPage.tsx` 的 Provider 包裹与左右分栏;左栏换成 `WritingChatPanel`,右栏仍
`AIWritingDraftPanel`;idle 不再挂 `AIWritingForm`,改由底部输入框启动)。
- 路由注册(**新增,不动旧行**):
- `open-canvas/routes/OpenCanvasRoutes.tsx` 加 `path="ai-writing-chat/*"`。
- 侧边栏 `core/page-layout/sidebar-menu.ts`:在 `qa-research` 旁新增
`{ id:"qa-research-chat", label:"AI写作(对话版)", icon:FileText, path:"/page/canvas/ai-writing-chat" }`。
(或先不加、内部灰度直链验证。)
### 5.2 新面板 `WritingChatPanel.tsx`(左栏主体)
职责 = 消息流容器 + 底部输入框,替代 `AIWritingPanel` 里的「时间线 + InterventionCard + 状态栏」。
复用 `useAIWriting()` 读 state / 调 `startWriting` / `submitIntervention` / `pauseWriting` /
`suspendAIWritingToBackground`。
消息流渲染(把 `ProgressEvent` / 阶段产物适配成消息卡,复用现有展示子组件):
- 运行中:`research_progress`/`outline_chunk`/`draft_chunk`/`review_chunk` → 进度 / 流式卡
(复用 `SkillStepsCard`/`OutlineStreamingView`/`DraftGeneratingView`/`ReviewStreamingView` 的展示部分)。
- 到达暂停点:渲染 **产物卡 + 保留的确认按钮**(见 5.3),不再有输入框。
- 用户消息、AI 澄清追问、问答回答:普通气泡。
底部输入框:直接复用 `@/components/ai-elements/prompt-input`(`PromptInput`+`PromptInputTextarea`+
`PromptInputSubmit`),Enter 发送、Shift+Enter 换行;发送时读当前 `state.status`/`currentPause?.pausePoint`
交给意图路由(见 5.5)。运行中(非暂停点)可禁用发送或转「排队/提示当前在生成」。
### 5.3 新消息卡 `chat-cards/*`(**保留按钮、去掉输入框**)
把 `InterventionCard.tsx` 的五张卡各复制一份到 `open-canvas/components/ai-writing-chat/chat-cards/`,
**删掉其中的 textarea / MaterialsToolbar 输入部分,保留产物展示 + 确认/动作按钮**:
| 新卡 | 展示(复用) | 保留的按钮 | 删除的输入 |
|------|-------------|-----------|-----------|
| `MaterialConfirmChatCard` | `MaterialsCard`(勾选保留)+ `SkillStepsCard` | 「确认素材,规划大纲」「重新搜索」 | `MaterialsToolbar` 的 userQuery 输入框 |
| `OutlineConfirmChatCard` | `OutlineCard`(可点标题微调保留) | 「确认大纲,开始写作」 | feedback textarea + 发送 |
| `DraftConfirmChatCard` | `ReviewCard`(若有审核,勾选保留) | 「按编辑审核意见修改」「让编辑继续审核」「确认定稿」 | 「修改意见」textarea |
| `ReviewConfirmChatCard` | `ReviewCard`(勾选保留) | 「按编辑意见修改」「强制定稿」 | 「补充修改指令」textarea |
| `SectionHelpChatCard` | 章节 + 三选一按钮组 | 三选一 + 「提交并继续」 | (本就无自由输入,原样保留) |
> 勾选态(素材/审核意见)**保留**——它是「点按钮」路径的一部分,不算自由输入框。用户想用自然语言
> 「只用第 1、3 条」也能走底部输入框(意图层产出 `approvedMaterialIds`/`selectedIssueIndices`)。
> 按钮点击 **直接调 `submitIntervention`**,与旧卡完全一致,零改动风险。
### 5.4 问答旁路(新能力)
「对写作内容提问」不改写作 state。首期**轻量实现**:意图节点检出 `ask_*` 时读 state 直接带回 `answer`,
前端在消息流渲染为普通 AI 气泡即可(一次调用出答案)。完整版(后续)可另起只读 lead_agent 线程注入
草稿/大纲作背景,类似 `WritingSetupChat` 的 `useThreadStream`。
### 5.5 交互流程(对话版)串起来
1. **空闲**:底部输入「写一篇关于 X 的深度分析,2000 字」→ 意图 `start_writing` → 组 `AIWritingRequest`
→ `startWriting()`。(缺关键字段时先 `clarify` 追问字数/读者/类型。)
2. **运行中**:进度/流式卡渲染。
3. **到暂停点**:渲染产物卡 + 按钮 + 一句提示「你可以点上面的按钮,或直接说:确认继续 / 补充素材 / 改大纲…」。
- **点按钮** → 直接 `submitIntervention`(旧逻辑)。
- **发文字** → `resolveIntent(text, status, pausePoint)`(先快路径、后后端)→ 按 4.3 消费。
4. **问答**:任意时刻提问 → 旁路 `answer`,不打断写作。
5. **素材不足**:`needResearch` 或 `section_help` → 追问/执行「重搜 → 自动续跑 pending 意图」。
6. **拿不准**:`clarify`/低置信 → 反问气泡,不执行。
### 5.6 pending 意图 & 澄清态(新增本地状态)
在 `WritingChatPanel`(或新 `WritingChatContext`)维护:
- `pendingIntent: UserInterventionPayload | null` —— 素材不足重搜完成后自动提交。
- `awaitingClarify: { originalText: string } | null` —— 澄清态,用户下一句与上一句拼接再解析。
- pending 生命周期:设置 → 提交 `re_search` → 监听 reducer 里新一轮 `awaiting_material_confirm`
(`state.status` 从 `researching` 回到 `awaiting_material_confirm`)→ 自动 `submitIntervention(pending)` → 清空。
---
## 6. 后端改造方案
### 6.1 意图解析入口(新增,唯一后端改动主体)
- `app/gateway/routers/ai_writing.py`:新增 `POST /sessions/{id}/intent`(见 4.1)。
读 checkpoint state 用 `app.state.checkpointer` + `make_ai_writing_graph().aget_state(...)`
(参照 `ai_writing_job_executor.py` 的读法)取素材/大纲/草稿/审核摘要。
- `agents/ai_writing/prompts/intent_router_prompts.py`:新增意图 prompt(见 4.1)。
- 复用 `nodes/intent_parser.py` 的模型创建 / `parse_json` / `_model_fallback` 容错。
### 6.2 不需要改的部分
- 四个阶段大脑节点、五个暂停点、checkpoint、StreamBridge、持久化、sessions/transcript REST——**全不动**。
- 「素材不足自动续跑」「问答旁路」首期都在**前端 / 意图节点**实现,**不扩 resume 协议**。
### 6.3 可选增强(阶段 3,按需)
- `add_review_opinion` 完整版:`review_confirm` resume 增字段 `extra_review_notes`(首期已用现有
`userRevisionNotes` 降级承载,够用)。
- `resume_intent` 后端化(把「重搜完自动续跑」搬到后端,减少前端状态机复杂度)。
- undo / 回退到上一暂停点(依赖 checkpoint 回滚)。
---
## 7. 数据流时序(改稿 + 素材不足自动重搜)
```
用户(draft_confirm 暂停): "第三段补个2024年的行业案例"
│ 底部输入框 → resolveIntent(text, status='awaiting_draft_confirm', pausePoint='draft_confirm')
▼ POST /api/ai-writing/sessions/{id}/intent { text, status, pausePoint }
后端: 读 state(素材摘要) + LLM 解析
│ 返回 { intent:revise_draft, action:user_revise,
│ payload:{userRevisionNotes:"第三段…补2024案例"},
│ needResearch:true, researchQuery:"2024 行业案例", confidence:0.9 }
▼
前端: needResearch=true → pendingIntent = payload
│ submitIntervention({action:'re_search', userQuery:"2024 行业案例"})
▼ LangGraph resume → researcher 追加素材 → status 回到 awaiting_material_confirm
前端: 监听到新一轮素材确认 → 自动提交 pendingIntent
│ submitIntervention({action:'user_revise', userRevisionNotes:"第三段…补2024案例"})
▼ writer_draft 用新素材改稿 → draft_chunk… → draft_ready → draft_confirm
前端: 消息流展示新草稿卡 + "已按你的意见改写并补充了 2024 案例"
```
---
## 8. 关键实现细节与坑
1. **阶段作用域**:`resolveIntent` 必须带 `state.currentPause?.pausePoint` + `state.status`——
同一句「重新来」在 material 是重搜、在 outline 是重写大纲。`AIWritingContext` 已有这两个字段,直接读。
2. **确认按钮零改动**:新卡的按钮 `onClick` 原样调 `submitIntervention(payload)`,与旧卡逐字一致,
风险最低;**只删输入框**。
3. **防误触发**:低置信(<0.6)或 `clarify` 非空一律追问;`finalize`/`force_finalize`/`re_search`
即使命中也要求高置信,否则澄清。绝不盲目定稿/覆盖重搜。
4. **pending 意图队列**:素材不足是「先插重搜、再回原意图」,用 5.6 的小状态机;重搜完成前允许覆盖 pending。
5. **问答不污染 transcript**:问答/澄清消息在前端标记 `kind:'qa'|'clarify'`,与写作进度事件区分(
`AIWritingContext` 的 transcript 只存 progressEvents/completedInterventions,问答气泡是纯前端消息,
默认不入 transcript,避免历史回看错乱)。
6. **流式产物→消息卡**:复用 `OutlineStreamingView`/`DraftGeneratingView`/`ReviewStreamingView`/
`SkillStepsCard` 的**展示部分**,套进消息容器,不重写渲染。
7. **右侧草稿预览**:`AIWritingDraftPanel` + `DraftSync` 原样复用(`DraftSync` 依据 status/markdown
同步右侧画布)。
8. **离线内网**:意图模型走 `config.yaml → ai_writing` 配置模型;检索仍走技能/内网 ES,不联网。
9. **模型选择透传**:`submitIntervention` 的 resume 已把 `state.request?.modelName` 一并回传(见
`AIWritingContext`),新页面沿用即可。
10. **旧页面隔离验证**:改完后回归旧 `/page/canvas/ai-writing` 与 `/page/workspace/ai-writing`、
笔记本嵌入页,确认零变化(新代码不 import 旧的 `AIWritingForm`/`InterventionCard`/`WritingFormContext`)。
---
## 9. 分阶段实施路线图
**阶段 0 — 骨架(不含意图)**
- 复制 `AIWritingChatPage` + 注册新路由 + 侧边栏入口;复用 `AIWritingContext`/`useStream`/`DraftPanel`。
- 复制五张 `chat-cards`(删输入框、留按钮);底部输入框先只做 idle 直发 `start_writing`
(文本原样当 `userIntent`,其余字段取默认)+ 暂停点靠按钮推进。端到端跑通。
**阶段 1 — 意图解析(核心)**
- 后端 `POST /sessions/{id}/intent` + `intent_router_prompts.py`,返回 4.3 契约。
- 前端 `api/ai-writing-intent.ts`(快路径 + 后端)接入 `WritingChatPanel`,覆盖 A~F 类意图。
- 低置信 `clarify` 澄清态(5.6)。
**阶段 2 — 问答旁路 + 素材不足自动重搜**
- G 类问答(意图节点直接带 `answer`)。
- `needResearch` + pending 意图机制(前端实现重搜后自动续跑,5.6)。
**阶段 3 — 增强(按需)**
- `add_review_opinion` 扩协议、`resume_intent` 后端化、undo/回退、完整问答只读线程。
**阶段 4 — 打磨**
- 消息卡视觉、历史回看(transcript)、后台挂起入口、灰度到侧边栏。
---
## 10. 关键文件清单(落地对照)
### 新增(前端)
- `open-canvas/pages/AIWritingChatPage.tsx` — 新页面(复制 `AIWritingPage` 骨架改造)
- `open-canvas/components/ai-writing-chat/WritingChatPanel.tsx` — 消息流 + 底部输入框
- `open-canvas/components/ai-writing-chat/chat-cards/{MaterialConfirmChatCard,OutlineConfirmChatCard,DraftConfirmChatCard,ReviewConfirmChatCard,SectionHelpChatCard}.tsx` — 保留按钮、去掉输入框
- `open-canvas/components/ai-writing-chat/progressToMessage.ts` — `ProgressEvent` → 消息卡适配
- `open-canvas/api/ai-writing-intent.ts` — 意图解析客户端(快路径 + `POST …/intent`)
- (可选)`open-canvas/contexts/WritingChatContext.tsx` — pending 意图 / 澄清态
### 修改(前端,仅追加,不动旧逻辑)
- `open-canvas/routes/OpenCanvasRoutes.tsx` — 加一条 `ai-writing-chat/*` 路由
- `core/page-layout/sidebar-menu.ts` — 加一个侧边栏入口(可选)
- `open-canvas/types/ai-writing.ts` — **仅追加** `IntentResult` 等新类型,不改旧字段
### 新增(后端)
- `app/gateway/routers/ai_writing.py` — 加 `POST /sessions/{id}/intent`
- `agents/ai_writing/prompts/intent_router_prompts.py` — 意图 prompt
- `tests/test_ai_writing_intent.py` — 意图接口单测(TDD 强制)
### 复用(不改)
- `open-canvas/contexts/AIWritingContext.tsx`、`hooks/useAIWritingStream.ts`
- `open-canvas/components/ai-writing/{AIWritingDraftPanel,DraftSync,MaterialsCard,OutlineCard,ReviewCard,SkillStepsCard,OutlineStreamingView,DraftGeneratingView,ReviewStreamingView}.tsx`
- `agents/ai_writing/graph.py`、四个阶段节点、五个暂停点、`nodes/intent_parser.py`
### 绝不动(保证「初始的不用动」)
- `open-canvas/pages/AIWritingPage.tsx` 及其引用的
`components/ai-writing/{AIWritingForm,InterventionCard}.tsx`、`contexts/WritingFormContext.tsx`
- 旧路由 `/page/canvas/ai-writing`、`/page/workspace/ai-writing`、笔记本嵌入页
---
## 11. 待确认(默认取值已给出,可直接推进)
1. 意图引擎:**后端 LLM 节点(方案 A)+ 前端短句快路径** —— 默认采用。
2. `AIWritingContext` / `useAIWritingStream`:**复用**(不物理复制)——默认采用;需绝对隔离可改为复制。
3. 新页面入口:**侧边栏新增「AI写作(对话版)」** —— 默认加;若要先灰度可只留直链。
4. 「素材不足自动重搜」:**首期前端 pending 续跑**(不动后端 resume 协议)——默认采用。
5. 问答旁路:**首期意图节点直接带 `answer`** —— 默认采用。
> 以上默认按「A + 复用引擎 + 侧边栏入口 + 前端 pending + 意图节点带答案」推进,如需调整请指出。
@@ -0,0 +1,454 @@
# AI 写作「对话驱动 + 意图解析」改造方案
> 目标:在**不动现有 AI 写作页面**的前提下,新建一个「对话驱动」的写作工作台。
> 去掉素材收集 / 大纲规划 / 作家写作 / 编辑审核各阶段**分散的输入框/表单**,
> 用**底部一个统一的智能输入框**接管全流程交互;该输入框具备**强意图解析**能力,
> 能准确识别用户意图(重新搜索、加素材、加关键词、重写大纲、按要求改大纲、改写作、
> 改编辑、提编辑意见、对写作内容提问……),并在**素材不足**时自动回退去重新检索素材。
本文只做**方案与实现指引**,不含代码改动。落地时按第 9 节的路线图分阶段推进。
---
## 1. 现状梳理(改造的地基)
现有 AI 写作是一套**独立的 LangGraph 子系统**(不是 lead_agent),前后端都已成型。
### 1.1 后端:`ai_writing` graph
- 图工厂:`offline-backend-20260512/backend/packages/harness/deerflow/agents/ai_writing/graph.py`
- 状态:`.../agents/ai_writing/state.py`(`AIWritingState` + `UserInterventionPayload`)
- 注册:`offline-backend-20260512/backend/langgraph.json` → `assistant_id = "ai_writing"`
- 执行:与 lead agent **共用** RunManager + StreamBridge + checkpointer(`app/gateway/services.py` 里 `assistant_id=="ai_writing"` 分发到 `make_ai_writing_graph`)
节点拓扑(实际):
```
sample_analyzer → intent_parser → researcher
→ [cond] pause_material | writer_draft
→ writer_outline → pause_outline
→ writer_draft → [cond] pause_section_help | pause_draft | END
→ editor → [cond] pause_draft | pause_review
→ pause_review → END | writer_draft
```
四个「阶段大脑」节点:
| 阶段 | 节点 | 文件 |
|------|------|------|
| 素材收集 | `researcher` | `nodes/researcher.py` |
| 大纲规划 | `writer_outline` | `nodes/writer_outline.py` |
| 作家写作 | `writer_draft` | `nodes/writer_draft.py` |
| 编辑审核 | `editor` | `nodes/editor.py` |
五个**暂停点**(`interrupt()`,靠 `Command(resume=payload)` 续跑):
| pause_point | 语义 | 可用 action(现有) |
|-------------|------|---------------------|
| `material_confirm` | 素材确认 | `confirm` / `re_search` / `supplement_search` / `enable_skill_search` |
| `outline_confirm` | 大纲确认 | `confirm` / `re_outline` |
| `draft_confirm` | 草稿确认 | `to_editor` / `finalize` / `user_revise` / `custom_revise` |
| `review_confirm` | 编辑打回确认 | `accept_review` / `force_finalize` |
| `section_help` | 素材不足求助 | `supplement` / `loose` / `delete` |
> resume 载荷字段(`UserInterventionPayload`):`action`、`approved_material_ids`、
> `extra_keywords`、`user_query`(自然语言补充检索)、`edited_outline`、`outline_feedback`、
> `user_revision_notes`、`override_verdict`、`selected_issue_indices`、`section_decisions`。
> **关键点**:现有协议已经支持「自然语言 + 结构化 action」,这是对话改造的核心可复用资产。
REST(业务元数据,非图执行):`app/gateway/routers/ai_writing.py`,前缀 `/api/ai-writing`
(sessions CRUD、transcript 保存、article-types、后台挂起 `/background` + `/progress` 等)。
持久化:`ai_writing_sessions` 表(`transcript` 为 `PortableLongText`)
+ `ai_writing_article_types`(`deerflow/persistence/...`)。
配置:`config.yaml → ai_writing`(`keyword_model`、`rank_model`、`max_materials`、
`use_builtin_agents.{researcher,outliner,writer,editor}` 等)。
### 1.2 前端:`open-canvas` 子系统
- 主页面:`frontend-web/src/open-canvas/pages/AIWritingPage.tsx`
- 路由:`/page/canvas/ai-writing`、`/page/workspace/ai-writing`
- 状态机:`contexts/AIWritingContext.tsx`(`useReducer` + LangGraph `useStream`)
- 事件翻译/reducer:`hooks/useAIWritingStream.ts`
- 类型:`types/ai-writing.ts`(`WritingStatus`、`ProgressEvent`、`UserInterventionPayload`、`AIWritingRequest`…)
- 流式:LangGraph `useStream`,`assistantId: 'ai_writing'`,`streamMode: ['values','updates','custom','messages-tuple']`
- **要去掉的输入 UI**(改造重点):
- 启动表单 `components/ai-writing/AIWritingForm.tsx` + `WritingFormContext`
- 阶段暂停输入 `components/ai-writing/InterventionCard.tsx`(素材/大纲/草稿/审核四套内嵌表单)
- **已存在的对话原型**:`components/ai-writing/WritingSetupChat.tsx`
(用 `useThreadStream` 起一条 lead_agent 线程 + `setup_writing` 工具审批卡回填表单)——
这是「对话 → 结构化配置」的现成范式,可借鉴但**不直接复用**(它只管启动前配置)。
### 1.3 结论
- **状态机、流式、暂停/续跑协议、持久化都可复用**,无需重写引擎。
- 改造本质 = **把「分散表单」换成「一个对话输入框 + 意图路由层」**,
再把意图映射回**现有的 `action + payload`**(大部分场景),
少量新意图(如「对内容提问」「素材不足自动重搜」)需要**新增协议/节点**。
---
## 2. 目标与范围
### 2.1 必须满足
1. 新页面/新路由,**旧页面零改动**(用户要求「初始的不用动」)。
2. 底部**单一对话输入框**控制所有阶段交互,移除各阶段独立输入框。
3. **强意图解析**:准确识别用户自然语言意图并路由到正确动作,覆盖全流程 + 更多。
4. 用户给修改意见后,**若现有素材不足以满足要求 → 自动/建议重新检索素材**再继续。
5. 保留右侧草稿实时预览(可编辑)与时间线/进度展示。
### 2.2 明确不做(本期)
- 不改旧 `AIWritingPage` 及其表单/干预卡组件。
- 不替换底层 `ai_writing` graph 的四个阶段大脑逻辑(只加意图层与少量新协议)。
- 不引入新的状态管理库(继续 `useReducer` + `useStream`)。
---
## 3. 核心设计
### 3.1 总体思路:三层结构
```
┌─────────────────────────────────────────────────────────┐
│ 对话 UI 层(新) │
│ - 左:消息流(用户消息 + AI 阶段产物卡片 + 进度) │
│ - 底:统一智能输入框(唯一交互入口) │
│ - 右:草稿实时预览(复用 AIWritingDraftPanel) │
└───────────────┬─────────────────────────────────────────┘
│ 用户自然语言
▼
┌─────────────────────────────────────────────────────────┐
│ 意图解析层(新,核心) │
│ - 输入:用户文本 + 当前 WritingStatus + 上下文快照 │
│ - 输出:{ intent, action, payload, needResearch, ... } │
└───────────────┬─────────────────────────────────────────┘
│ 结构化 action + payload
▼
┌─────────────────────────────────────────────────────────┐
│ 执行层(复用现有) │
│ - 空闲态:startWriting(AIWritingRequest) │
│ - 暂停态:submitIntervention(UserInterventionPayload) │
│ - 运行中:stream.stop() → 续跑 / 新命令 │
│ - 提问态:旁路问答(不改写作状态) │
└─────────────────────────────────────────────────────────┘
```
**设计原则**:意图解析层是「翻译官」——把自由文本翻译成**现有执行层已经懂的指令**。
能复用 `action + payload` 的绝不新造协议;只有现有协议表达不了的才扩展。
### 3.2 意图分类体系(覆盖用户全流程 + 更多)
按「意图类别 → 触发时机(当前 status)→ 映射到的执行」组织。这是**意图解析引擎的目标 schema**。
#### A. 启动类(status = idle)
| 意图 | 说明 | 映射 |
|------|------|------|
| `start_writing` | 用户描述要写什么 | 解析成 `AIWritingRequest` → `startWriting()` |
| `start_with_outline` | 用户自带大纲 | `AIWritingRequest.userOutline` |
| `start_imitate` | 样文仿写 | `writingModeType=imitate` + 样文 |
#### B. 素材类(status ≈ awaiting_material_confirm / 运行中)
| 意图 | 用户说法示例 | 映射 |
|------|-------------|------|
| `confirm_materials` | 「素材可以,继续」 | `material_confirm` + `confirm`(可带勾选 ids) |
| `research_again` | 「重新搜索素材」 | `material_confirm` + `re_search` |
| `add_material` / `add_keyword` | 「补充关于 X 的素材」「加个关键词 Y」 | `material_confirm` + `supplement_search`,`user_query`=X/Y |
| `use_skill_search` | 「用 XX 技能查」 | `material_confirm` + `enable_skill_search`,`user_query`=技能/来源 |
| `select_materials` | 「只用第 1、3 条」 | `confirm` + `approved_material_ids` 子集 |
| `drop_materials` | 「去掉第 2 条」 | 同上,反选后 `approved_material_ids` |
#### C. 大纲类(status ≈ awaiting_outline_confirm)
| 意图 | 示例 | 映射 |
|------|------|------|
| `confirm_outline` | 「大纲 OK」 | `outline_confirm` + `confirm` |
| `reoutline` | 「重写大纲」 | `outline_confirm` + `re_outline`(`outline_feedback` 可空) |
| `revise_outline` | 「第二章拆成两节」「调整顺序」 | `re_outline` + `outline_feedback`=自然语言 |
| `edit_outline_manually` | 用户直接给出新大纲文本 | 解析成 `edited_outline` |
#### D. 写作/草稿类(status ≈ awaiting_draft_confirm / writing_draft)
| 意图 | 示例 | 映射 |
|------|------|------|
| `to_editor` | 「交给编辑审核」 | `draft_confirm` + `to_editor` |
| `finalize` | 「就这样定稿」 | `draft_confirm` + `finalize` |
| `revise_draft` | 「第三段太啰嗦,精简」「补个案例」 | `draft_confirm` + `user_revise`,`user_revision_notes`=意见 |
| `rewrite_section` | 「重写第二章」 | `user_revise` + 定位信息(章节)写进 notes |
| `change_tone/style` | 「更口语一点」 | `user_revise` + notes |
#### E. 编辑审核类(status ≈ awaiting_review_confirm)
| 意图 | 示例 | 映射 |
|------|------|------|
| `accept_review` | 「按编辑意见改」 | `review_confirm` + `accept_review`(可带 `selected_issue_indices`) |
| `partial_accept_review` | 「只接受第 1、2 条意见」 | `accept_review` + `selected_issue_indices` |
| `force_finalize` | 「不改了,强制定稿」 | `review_confirm` + `force_finalize` |
| `add_review_opinion` | 「你再补一条:检查数据准确性」 | 追加自定义审核意见(见 5.3 扩展) |
#### F. 素材不足求助类(status = awaiting_section_help)
| 意图 | 映射 |
|------|------|
| `section_supplement` | `section_help` + `supplement`(去重搜) |
| `section_loose` | `section_help` + `loose`(放宽续写) |
| `section_delete` | `section_help` + `delete` |
#### G. 问答类(**新**,任意 status,旁路,不改写作状态)
| 意图 | 示例 | 映射 |
|------|------|------|
| `ask_about_content` | 「第二章讲了啥?」「为什么用这个论点?」 | 旁路问答(见 5.4) |
| `ask_meta` | 「现在进行到哪一步?」「用了哪些素材?」 | 读当前 state 直接回答,不走图 |
#### H. 控制类(**新/半新**)
| 意图 | 映射 |
|------|------|
| `undo/back` | 回退到上一暂停点(依赖 checkpoint 回滚,见 8.4) |
| `restart_stage` | 重跑当前阶段 |
| `run_background` | 挂起后台自动跑 → `POST /sessions/{id}/background` |
| `cancel` | `stream.stop()` |
| `unknown/clarify` | 无法判定 → 反问澄清(对话追问,不误触发) |
> **覆盖「甚至更多」**:G(问答)、H(控制)、以及 D/E 里「素材不足自动回退重搜」都是超出原表单能力的新增。
### 3.3 「素材不足自动重搜」的判定与回退(用户强调的重点)
触发场景:用户在**大纲/草稿/审核**阶段提出修改意见,但意见需要的**信息现有素材里没有**。
判定放在**意图解析层**输出一个 `needResearch: boolean` + `researchQuery`,判定来源二选一(推荐组合):
1. **意图解析 LLM 直接判断**:把「当前素材摘要(keywords + 每条 title/来源)」喂给意图解析
prompt,让它判断「用户这条意见能否用现有素材满足」。不能 → `needResearch=true` 并给出检索词。
2. **执行阶段兜底**:`writer_draft` 严格模式本就有 `blocked_sections` → `pause_section_help`,
这是**已有的**素材不足闸门;对话层把它翻译成「素材不足,是否重新检索?」的对话追问。
回退动作:`needResearch=true` 时,先走 `material_confirm + supplement_search`(或新的
「带目标的重搜」协议,见 8.3)补素材,**补完自动继续**用户原本的修改意图(需要在对话层
记住「pending 修改意图」,重搜结束后再提交)。
---
## 4. 意图解析引擎:方案对比与推荐
| 方案 | 做法 | 优点 | 缺点 |
|------|------|------|------|
| **A. 后端 LLM 意图节点**(推荐) | 新增 `/api/ai-writing/intent/parse`(或图内新节点),后端用 LLM 把 `{text, status, contextSnapshot}` → 结构化意图 JSON | 能吃到完整 state(素材/大纲/草稿);可判 `needResearch`;prompt/模型集中可控;离线内网可用配置模型 | 多一次网络往返(可接受,交互本就等待) |
| B. 前端调模型接口分类 | 前端直接调现有 `/api/models` 聊天做分类 | 少一层后端改动 | 前端难拿全后端 state 快照;prompt 分散;鉴权/模型选择复杂 |
| C. 规则 + LLM 混合 | 常见短句走关键词规则快路径,兜底 LLM | 快、省 token | 规则易漏、维护成本高;中文表达多样命中率低 |
**推荐 A(后端 LLM 意图节点)**,并在其上**叠加 C 的快路径**做优化(如「确认/继续/定稿」等
高频短句先走轻量规则,未命中再调 LLM)。理由:
- 意图判定需要**当前写作上下文**(尤其 `needResearch` 判定),后端天然持有 state/checkpoint。
- 与现有「配置助手 `setup_writing`」一脉相承,模型选择/离线部署策略统一。
- 输出 schema 稳定,前端只消费结构化结果,UI 简单。
### 4.1 意图解析输出契约(建议)
```jsonc
{
"intent": "revise_draft", // 见第 3.2 分类
"pausePoint": "draft_confirm", // 若需 resume;否则 null
"action": "user_revise", // 映射到现有 action;新意图可为新值
"payload": { // 直接可喂 submitIntervention 的字段
"userRevisionNotes": "第三段精简,并补一个 2024 年的案例"
},
"needResearch": true, // 素材是否不足
"researchQuery": "2024 行业案例", // needResearch 时的检索意图
"answer": null, // 问答类意图的直接回答(旁路)
"confidence": 0.86,
"clarify": null // 低置信时的反问话术
}
```
前端拿到后:
- `answer` 非空 → 直接在对话流渲染回答(问答旁路,不动写作状态)。
- `clarify` 非空或 `confidence` 低 → 渲染反问,等用户澄清(**防误触发**)。
- `needResearch=true` → 先重搜,缓存 `payload` 为 pending,重搜完再提交。
- 否则 → `submitIntervention({action, ...payload})` 或 `startWriting(...)`。
---
## 5. 前端改造方案
### 5.1 新页面与路由
- 新目录:`frontend-web/src/open-canvas/pages/AIWritingChatPage.tsx`(或 `conversational/` 子目录)。
- 新路由:`/page/canvas/ai-writing-chat`(在 `OpenCanvasRoutes.tsx` 注册;旧路由保留)。
- 侧边栏:`sidebar-menu.ts` 加一个入口(如「AI 写作(对话版)」),或先不加、内部灰度。
### 5.2 复用 vs 新建
| 复用(尽量不改) | 新建 |
|------------------|------|
| `AIWritingContext` / `useAIWritingStream`(状态机 + 流式) | 统一对话输入框组件 `WritingChatComposer` |
| `AIWritingDraftPanel`(右侧草稿预览) | 消息流容器 `WritingChatThread`(渲染阶段产物为消息卡片) |
| `types/ai-writing.ts`(按需扩展) | 意图解析客户端 `api/ai-writing-intent.ts` |
| `ProgressEvent` 事件模型 | 阶段产物 → 消息卡片的适配器 `progressToMessage.ts` |
| 会话持久化 REST | 「pending 意图」暂存逻辑(重搜后续跑) |
**不复用**:`AIWritingForm` / `WritingFormContext` / `InterventionCard`(这三个就是要去掉的表单)。
### 5.3 交互流程(对话版)
1. 空闲:用户在底部输入「写一篇关于 X 的深度分析,2000 字」→ 意图解析 `start_writing`
→ 组装 `AIWritingRequest` → `startWriting()`。
2. 运行中:`ProgressEvent`(`research_progress`/`outline_chunk`/`draft_chunk`…)
→ 适配成消息流里的**进度卡片/流式卡片**(复用现有流式视图组件的展示部分)。
3. 到达暂停点:不再弹 `InterventionCard`,而是在消息流里展示**阶段产物卡片**
(素材列表 / 大纲 / 草稿 / 审核结果)+ 一句提示「你可以说:确认继续 / 补充素材 / 改大纲…」。
用户下一句自然语言 → 意图解析 → `submitIntervention`。
4. 问答:任意时刻用户提问 → 旁路回答,不打断写作状态。
5. 素材不足:意图解析 `needResearch` 或后端 `section_help` → 对话追问「素材不足,帮你重搜?」
→ 确认后重搜 → 自动续跑 pending 意图。
### 5.4 问答旁路(新能力)
「对写作内容提问」不应改写作 state。两种实现:
- **轻量(推荐先做)**:意图解析节点直接带回 `answer`(后端能读 state,一次调用出答案)。
- **完整**:新起一条**只读**问答线程(lead_agent,context 注入当前草稿/大纲作为背景),
类似 `WritingSetupChat` 的 `useThreadStream` 模式,但只读不回填。
---
## 6. 后端改造方案
### 6.1 意图解析入口(二选一)
- **方案 A1(推荐,独立 REST)**:`app/gateway/routers/ai_writing.py` 新增
`POST /api/ai-writing/sessions/{id}/intent`,入参 `{text}`,后端读该 session 的
checkpoint state(素材/大纲/草稿摘要)+ 用 `ai_writing` 配置模型解析,返回第 4.1 的契约。
- 好处:不改图拓扑;前端拿到结果后再决定调 `startWriting`/`submitIntervention`。
- 方案 A2(图内节点):在图里加 `conversation_router` 节点。改动大、状态耦合高,**不推荐**首期。
### 6.2 意图解析 prompt
新增 `agents/ai_writing/prompts/intent_router_prompts.py`(或复用/扩展 `intent_parser.py`):
- 输入:用户文本、`current_status`、素材摘要(keywords + 每条 title/source)、大纲纲要、
草稿字数/章节标题、审核意见列表。
- 输出:严格 JSON(第 4.1 契约)。要求模型**只在证据充分时给高 confidence**,
否则给 `clarify`(防误触发是硬指标)。
### 6.3 「带目标的重搜」协议扩展(可选增强)
现有 `supplement_search` 用 `user_query` 追加检索。为支持「改稿意见 → 缺素材 → 重搜 → 自动续跑」,
建议在 `material_confirm` 的 resume 里新增可选字段 `resume_intent`(重搜完成后要自动执行的原始意图)。
- 前端也可**纯前端**实现(重搜完成事件回来后再自动提交缓存的 pending payload),**首期优先前端实现**,避免动后端协议。
### 6.4 追加自定义审核意见(`add_review_opinion`)
`editor`/`pause_review` 目前只接受「接受/强制定稿」。要支持「你再补一条审核意见」,
需在 `review_confirm` resume 里接受 `extra_review_notes`,`editor` 或 `writer_draft`
修订时并入。首期可先降级为 `user_revise` + notes(把用户的审核诉求当作改稿意见),
**完整版**再扩协议。
### 6.5 不需要改的部分
- 四个阶段大脑节点(researcher/writer_outline/writer_draft/editor)逻辑不动。
- 五个暂停点、checkpoint、StreamBridge、持久化不动。
---
## 7. 数据流时序(改稿 + 素材不足自动重搜)
```
用户: "第三段补个2024年的行业案例"
│
▼ POST /api/ai-writing/sessions/{id}/intent { text }
后端: 读 state(素材摘要) + LLM 解析
│ 返回 { intent:revise_draft, action:user_revise,
│ payload:{userRevisionNotes:...},
│ needResearch:true, researchQuery:"2024 行业案例" }
▼
前端: needResearch=true → 缓存 pending=payload
│ 对话追问/直接执行: submitIntervention(material_confirm, supplement_search, user_query="2024 行业案例")
▼ LangGraph resume → researcher 补素材 → materials_ready
前端: 收到新素材 → 自动提交 pending
│ submitIntervention(draft_confirm, user_revise, userRevisionNotes=...)
▼ writer_draft 用新素材改稿 → draft_chunk... → draft_ready → pause_draft
前端: 消息流展示新草稿 + "已按你的意见改写并补充了案例"
```
---
## 8. 关键实现细节与坑
1. **暂停态识别**:对话层必须知道「现在停在哪个 pause_point」才能正确映射 action。
`AIWritingContext` 已有 `currentPause`/`status`,直接读。
2. **防误触发**:低置信意图一律走 `clarify` 反问,绝不猜着执行(尤其 `finalize`/`re_search` 这种代价大的)。
3. **pending 意图队列**:素材不足重搜是「先插一段、再回原意图」,需要一个小状态机记住 pending,
并处理「重搜后用户又改主意」的情况(重搜完成前允许覆盖 pending)。
4. **回退/undo(H 类)**:依赖 checkpoint 回滚,`runtime/runs/worker.py` 有 `rollback` 概念,
首期可**不做**或只做「重跑当前阶段」。
5. **问答旁路不污染 transcript**:问答消息可标记 `kind:'qa'`,与写作进度事件区分持久化。
6. **流式产物→消息卡片**:复用现有 `OutlineStreamingView`/`DraftStreamingPreview` 等的**展示部分**,
套进消息气泡即可,不必重写渲染。
7. **离线内网**:意图解析模型走 `config.yaml → ai_writing` 里的配置模型;检索仍走技能/内网 ES,
不联网(与现有并行席位「禁 web_search」的离线策略一致)。
---
## 9. 分阶段实施路线图
**阶段 0 — 骨架(不含意图)**
- 新路由 + 新页面 `AIWritingChatPage`,复用 `AIWritingContext`/`useStream`/`DraftPanel`。
- 底部对话框先只做「空闲 `start_writing` + 暂停点固定按钮」跑通端到端(相当于把干预卡换成消息)。
**阶段 1 — 意图解析(核心)**
- 后端 `POST /sessions/{id}/intent` + intent prompt,返回第 4.1 契约。
- 前端接入:自然语言 → 意图 → `startWriting`/`submitIntervention`,覆盖 A~F 类意图。
- 加高频短句规则快路径 + 低置信 `clarify` 反问。
**阶段 2 — 问答旁路 + 素材不足自动重搜**
- G 类问答(先用 intent 节点直接带 `answer`)。
- `needResearch` + pending 意图机制(前端实现重搜后自动续跑)。
**阶段 3 — 增强协议(按需)**
- `add_review_opinion` 扩 `review_confirm` 协议、`resume_intent` 后端化、undo/回退。
**阶段 4 — 打磨**
- 消息卡片视觉、历史回看(复用 transcript)、后台挂起入口、灰度到侧边栏。
---
## 10. 关键文件清单(落地时对照)
### 新增(前端)
- `open-canvas/pages/AIWritingChatPage.tsx` — 新页面
- `open-canvas/components/ai-writing-chat/WritingChatComposer.tsx` — 统一输入框
- `open-canvas/components/ai-writing-chat/WritingChatThread.tsx` — 消息流
- `open-canvas/components/ai-writing-chat/progressToMessage.ts` — 事件→消息适配
- `open-canvas/api/ai-writing-intent.ts` — 意图解析客户端
- 路由注册:`open-canvas/OpenCanvasRoutes.tsx`(+ 可选 `sidebar-menu.ts`)
### 新增(后端)
- `app/gateway/routers/ai_writing.py` — 加 `POST /sessions/{id}/intent`
- `agents/ai_writing/prompts/intent_router_prompts.py` — 意图 prompt
- (阶段 3)`state.py` / `nodes/*` — 扩 `review_confirm`、`resume_intent`
### 复用(尽量不改)
- `open-canvas/contexts/AIWritingContext.tsx`、`hooks/useAIWritingStream.ts`
- `open-canvas/components/ai-writing/AIWritingDraftPanel.tsx` 及各流式展示组件
- `open-canvas/types/ai-writing.ts`(按需扩字段)
- `agents/ai_writing/graph.py`、四个阶段节点、五个暂停点
### 不动
- 旧 `open-canvas/pages/AIWritingPage.tsx` 及 `AIWritingForm`/`WritingFormContext`/`InterventionCard`
---
## 11. 待确认
1. 意图解析引擎是否采用**推荐的方案 A(后端 LLM 节点)**?
2. 新页面是**独立入口**(侧边栏新增)还是先**内部灰度**(仅直链)?
3. 「素材不足自动重搜」首期是否接受**前端实现 pending 续跑**(不动后端 resume 协议)?
4. 问答旁路首期是否接受**意图节点直接带答案**(不新起只读线程)?
> 以上默认按「A / 内部灰度 / 前端 pending / 意图节点带答案」推进,如需调整请指出。
-787
View File
@@ -1,787 +0,0 @@
# AI 写作 — 故障排查与解决方案说明
> **本文档目的**:完整记录 AI 写作子系统在内网 Docker 部署后出现的问题、根因、已落地的修复、剩余风险、以及未来的解决方案路径。
>
> **适用读者**:维护 AI 写作功能的前端/后端开发者、内网部署运维。
>
> **更新日期**:2026-05-20
---
## 一、问题背景
### 起因
内网 Docker 部署后,AI 写作出现两类报错:
| 接口 | 报错 | 频率 |
|---|---|---|
| `PUT /api/ai-writing/sessions/{id}/transcript` | HTTP 500 | 经常 |
| `POST /api/ai-writing/{id}/resume` | HTTP 4xx(用户记忆为 400,实际可能是 404) | 经常,且没有 Docker 重启时也发生 |
### 这两个接口的作用
#### 1. `PUT /sessions/{id}/transcript` — 对话时间线持久化
- **职责**:保存前端组装的完整对话时间线(progressEvents + completedInterventions)到 MySQL
- **调用时机**:前端在写作过程中**反复 PUT**(事件累计、干预完成、草稿生成等节点全量覆盖)
- **存到哪**:MySQL 的 `ai_writing_sessions.transcript` 列(LONGTEXT)
- **用途**:用户**关闭页面后再回来 / 刷新 / 看历史会话**时,从 DB 拉回这段时间线,UI 上回显出「跟实时一样的对话历史」
- **定位**:**纯锦上添花** — 失败了用户当下写作完全不受影响,只是历史回显会缺失/不完整
#### 2. `POST /{id}/resume` — 写作流程的核心控制接口
- **职责**:提交用户在干预点的决策,让 LangGraph 从挂起的 interrupt 点继续推进
- **调用时机**:用户在 4 个 interrupt 点(素材确认 / 大纲确认 / 草稿确认 / 审核确认)做出决定后
- **传什么**:用户的决策内容(确认的素材 id、修改后的大纲、用户的修订意见、章节求助决策…)
- **定位**:**流程主干** — 它失败,用户就**真的卡死**在干预点
---
## 二、根因分析
### 根因 1:`transcript` 列容量不足 + 路由层无兜底
- MySQL `TEXT` 列上限 64 KB
- 用户写作过程中累计 `progressEvents`(含每个流式 chunk)+ `completedInterventions` 后,JSON blob 经常超过 64 KB
- `session.commit()` 抛 `DataError: Data too long for column 'transcript'`
- 原路由没有 try/except,异常直接冒泡成 HTTP 500
### 根因 2:内存中的会话状态在多 worker 部署下隔离
后端用了大量模块级 dict 维护会话状态:
```python
_event_queues: dict[str, asyncio.Queue] # SSE 事件队列
_session_pending_pause: dict[str, tuple] # 挂起的 await_user 事件
_session_model_names: dict[str, str] # 用户选的模型
_session_interventions: dict[str, list] # 累计干预历史
_session_repos: dict[str, repo] # DB 仓库引用
_session_user_ids: dict[str, str] # 用户 id
_session_article_types: dict[str, list] # 文章类型列表
```
**uvicorn / gunicorn 多 worker 是多进程共享 socket**,OS 内核决定哪个 worker 接到请求,应用层和 nginx 都管不着。所以:
```
T0: POST /start → worker A 创建 _event_queues[sid] = QueueA
graph 推进任务跑在 worker A
T1: GET /stream → 落 worker B,没有 QueueA 的引用
→ 触发 _recover_session,从 sqlite 重建 QueueB
→ SSE 推 QueueB 但事件都在 QueueA 里
T2: POST /resume → 落 worker C,同样无法看到 A/B 的状态
```
**结果**:SSE 时断时续、resume 偶发 404「会话状态已丢失」。
### 根因 3:Graph 用了内存 checkpointer
原代码:
```python
# ai_writing/graph.py
checkpointer = MemorySaver()
```
进程内的 `MemorySaver` 重启即丢,**容器重启或单 worker 进程被回收**后所有进行中会话都拿不到。
### 根因 4:路径配错
`config.yaml` 里 sqlite 路径写成了 Windows 绝对路径 `D:\cursor-work\...`,Linux 容器里根本无法解析。
---
## 三、已落地的修复(已合入 dhk-1 分支)
### 修复 1:`transcript` 列改 LONGTEXT + 路由兜底
| 文件 | 改动 |
|---|---|
| `packages/harness/deerflow/persistence/types.py` | 新增 `PortableLongText` 类型(MySQL→LONGTEXT,SQLite/PG→TEXT) |
| `packages/harness/deerflow/persistence/ai_writing_sessions/model.py` | `transcript` 列改成 `PortableLongText` |
| `packages/harness/deerflow/persistence/migrations/versions/20260519_02_ai_writing_transcript_longtext.py` | Alembic 迁移:MySQL 上 `ALTER ... type_=LONGTEXT()` |
| `app/gateway/routers/ai_writing.py` | `save_transcript` 整段 try/except 包裹,**任何异常都返回 `{success: false, reason}`,永远不抛 5xx** |
**结果**:transcript 500 永远不会再发生。前端已经做了 fire-and-forget 容错,失败只 `console.warn`,写作流程不阻断。
### 修复 2:Checkpointer 改为持久化 SQLite
| 文件 | 改动 |
|---|---|
| `packages/harness/deerflow/agents/ai_writing/graph.py` | `MemorySaver()` → 懒加载 `AsyncSqliteSaver` |
| 同上 | 新增 `get_ai_writing_graph()` / `get_ai_writing_checkpointer()` / `shutdown_ai_writing_graph()` |
| `offline-backend-20260512/config.yaml` | sqlite 路径改成相对路径 `.deer-flow/data/checkpoints.db` |
**关键容错**:sqlite 初始化失败(磁盘满 / 权限 / aiosqlite 未装 / 损坏)会**自动降级 InMemorySaver**,写作流程能跑完,但跨重启不可恢复。
### 修复 3:跨 worker / 进程重启会话恢复
| 文件 | 改动 |
|---|---|
| `app/gateway/routers/ai_writing.py` | 新增 `_recover_session(session_id, request)` |
当 worker 内存里没有该 session 时,从 sqlite checkpointer 读快照,重建 `_event_queues`、重新注入 `await_user` 事件。
**效果**:worker B 收到的 resume 请求,能从 sqlite 找到 worker A 写下的 checkpoint,**resume 接口本身能跑通**(但 SSE 事件流仍隔离 — 见下文剩余风险)。
### 修复 4:多层失败兜底,保证写作流程能继续
| 改动 | 作用 |
|---|---|
| `_sse(event, data)` 加 `default=str` + notice 帧降级 | JSON 序列化失败不会让 SSE 断开 |
| 所有 DB 写入(草稿/审核/干预/status)已包 try/except | DB 异常吞掉,graph 继续推 |
| 文章类型加载失败 → 退回 `[]` | intent_parser 仍能跑 |
| `/start` 加 503 兜底 | graph 构建失败时给前端可读错误而不是 500 |
### 修复 5:定期清理 + admin 触发接口
| 文件 | 改动 |
|---|---|
| `app/gateway/ai_writing_cleanup.py` | 新文件:cron 调度 + 联动清理(MySQL 行 + sqlite checkpointer thread) |
| `packages/harness/deerflow/persistence/ai_writing_sessions/sql.py` | 新增 `list_older_than()` / `delete_by_ids()` |
| `app/gateway/app.py` | lifespan 启动/停止清理任务 |
| `app/gateway/routers/ai_writing.py` | 新增 `POST /api/ai-writing/admin/cleanup` 手动触发接口(admin only) |
| `config.yaml` | 新增 `ai_writing.cleanup` 段(默认每天凌晨 3 点跑,保留 7 天) |
**关键安全机制**:清理永远跳过 `_event_queues` 里仍在跑的会话(**活跃保护**),即使 admin 手动传 `retention_days: 0` 也不会秒杀正在写作的用户。
### 修复 6:优雅关闭 — In-flight Drain
| 文件 | 改动 |
|---|---|
| `app/gateway/routers/ai_writing.py` | 新增 `_inflight_graph_tasks` + `_spawn_graph_task()` + `wait_for_inflight_graph_tasks(timeout)` |
| `app/gateway/app.py` | lifespan shutdown 顺序:取消清理 → **等 in-flight 写作 task 收尾(30s 超时)** → 关 checkpointer connection |
容器收到 SIGTERM 时,给正在跑的写作 30 秒窗口跑到下一个 interrupt / END,已生成的 checkpoint 都安全落盘。
### 修复 7:多 worker 配置陷阱检测
| 文件 | 改动 |
|---|---|
| `app/gateway/app.py` | lifespan startup 检测 `WEB_CONCURRENCY > 1` 或 `/proc` 里同名 uvicorn 进程数 > 1 → 打 ERROR 日志 |
下次启动容器看 docker logs 第一屏就能看到强提醒。
---
## 四、当前状态评估
### transcript 500
✅ **彻底修复**,跟 worker 数无关。LONGTEXT 列 + 路由兜底双保险。
### resume 报错
⚠️ **大幅缓解**:
- 接口本身(在 worker > 1 下)能跑通
- sqlite 共享让 worker B 也能恢复 worker A 创建的 session
❌ **未彻底解决**:
- SSE 事件流仍 per-worker 隔离
- 用户可能看到「进度时有时无、需要刷新页面才能看到草稿」
- 但**草稿、审核结果**都落到 MySQL,刷新 `/sessions/{id}` 总能看到最终成品
### 「写作流程能不能跑完」
✅ **能**。最坏情况下:
- 用户感受:进度断断续续,需要刷新几次
- 数据保证:草稿和审核都落 MySQL,**写出来的内容不会丢**
---
## 五、剩余风险
### 风险 A:多 worker 下 SSE 事件流隔离 ⚠️ 最重要
**症状**:用户 SSE 长连接绑在 worker B,但 graph 推进任务跑在 worker A,事件 put 进 A 的 queue → SSE 收不到。
**为什么不能用 `--workers 1` 解决**:业务团队反馈其他业务功能需要多 worker。
**解决方案见第六章**。
### 风险 B:容器优雅关闭时 in-flight 写作进度
**当前缓解**:30 秒 drain timeout 让 graph 跑到下一个 checkpoint。
**完美方案**(如有需求):无法 100% 防护,只能尽量缩短「未落 checkpoint」窗口。
### 风险 C:节点级别 LLM 抽风
某个写作节点调用 LLM 时网络抖动 / 限流 → astream 抛错 → session 结束。
**当前缓解**:astream level 已 try/except,推 error 事件。用户从 checkpoint 重试。
**改进方向**(不在本次修复范围):
- 给节点加 `tenacity.retry` 重试装饰器
- 节点抛错时把已生成的部分塞进 progress_events
### 风险 D:跨 worker 恢复时降级丢失
worker B 从 sqlite 恢复 worker A 的 session 时,以下数据回退到默认:
| 数据 | 默认值 | 影响 |
|---|---|---|
| `_session_model_names` | `""` | 退回默认模型 |
| `_session_interventions` | `[]` | 本次 resume 之前的干预历史从内存里丢(MySQL 里有副本,但内存累计不全) |
| `_session_article_types` | `[]` | 没影响(graph 早过了 intent_parser) |
**改进方向**:恢复时从 MySQL 反向填充内存元数据(约 20 行代码)。
---
## 六、Worker > 1 限制下的解决方案路径
### 三条路径对比
| 方案 | 是否引入新依赖 | 代码改动 | 运维改动 | 适用场景 |
|---|---|---|---|---|
| **B. Redis Pub/Sub 共享状态** | ⚠️ 需 Redis | ~150 行 | docker-compose 加 redis | 已有 Redis 或愿意上 |
| **C. AI 写作独立单 worker 进程** | 无 | ~30 行 | docker-compose 加一个容器 / 进程 + nginx 转发 | 不想上 Redis |
| **F. 多容器单 worker + nginx sticky** | 无 | ~5 行(nginx config) | 把 1 个多 worker 容器拆成 N 个单 worker 容器 | 已经在做容器编排 |
### 方案 B:Redis Pub/Sub(最彻底)
**改造点**:
```
之前(per-worker memory dict) 之后(Redis 共享)
───────────────────────── ─────────────────────
_event_queues[sid] = asyncio.Queue() → Redis Pub/Sub channel "ai_writing:events:{sid}"
_session_pending_pause → Redis Hash "ai_writing:pause"
_session_model_names → Redis Hash "ai_writing:meta:model"
_session_interventions → Redis Hash + JSON
_session_repos / _session_user_ids → Redis Hash
```
**关键设计**:
1. `/start` 在 worker A:graph 推进任务跑在 A,事件 publish 到 Redis channel
2. `/stream` 在 worker B:subscribe Redis channel,把消息转 SSE 推前端
3. `/resume` 在 worker C:用 Redis 分布式锁保证「同一 session 同时只有一个 worker 驱动 graph」
**优点**:根治。任何 worker 数、任何部署形态都能跑。
**缺点**:
- 引入 Redis 依赖(运维负担)
- 代码改动较大(约 150 行)
- 需要处理 Redis 断连 / 分布式锁释放等边缘情况
### 方案 C:AI 写作独立服务(次推荐)
**做法**:在同一个容器里多起一个 uvicorn 进程,专门处理 `/api/ai-writing/*`,**显式 `--workers 1`**。
```bash
# 主 gateway(多 worker,处理其他业务)
uvicorn app.gateway.app:app --host 0.0.0.0 --port 8001 --workers 4
# AI 写作专用单 worker
uvicorn app.gateway.app:app --host 0.0.0.0 --port 8002 --workers 1
```
nginx 配置:
```nginx
location /api/ai-writing/ {
proxy_pass http://localhost:8002;
proxy_buffering off;
proxy_read_timeout 3600s;
}
location / {
proxy_pass http://localhost:8001;
}
```
**优点**:
- 零代码改动
- 不引入新依赖
- AI 写作彻底单 worker,问题根除
**缺点**:
- 容器内多一个进程
- 内存占用 +1 份 Python runtime(约 200 MB)
### 方案 F:多容器单 worker + nginx sticky
**做法**:把当前 1 个 4 worker 容器,拆成 4 个 1 worker 容器,nginx 用 `ip_hash` 做 sticky。
```yaml
# docker-compose.yml
services:
gateway-1: { ports: ["8001:8001"], command: ["...", "--workers", "1"] }
gateway-2: { ports: ["8002:8001"], command: ["...", "--workers", "1"] }
gateway-3: { ports: ["8003:8001"], command: ["...", "--workers", "1"] }
gateway-4: { ports: ["8004:8001"], command: ["...", "--workers", "1"] }
nginx:
# upstream 配 ip_hash,让同一个客户端粘到同一个容器
```
```nginx
upstream gateway_pool {
ip_hash;
server gateway-1:8001;
server gateway-2:8001;
server gateway-3:8001;
server gateway-4:8001;
}
```
**优点**:零代码改动,标准做法
**缺点**:
- 改动 docker-compose
- 客户端 IP 不均匀时负载不均衡(但 AI 写作低并发场景影响小)
### 推荐顺序
1. **方案 C(AI 写作独立单 worker 进程)** — 改动最小、风险最低、立刻可上
2. **方案 F(多容器 sticky)** — 如果你们已经在做多容器编排
3. **方案 B(Redis)** — 长期方案,等真正需要水平扩容时再上
---
## 六-A、方案 C 在 Docker 容器内的详细实施指南
> **目标**:在不引入新依赖、不动业务代码、不拆容器的前提下,让 AI 写作走专门的单 worker 进程,其它业务继续走多 worker。
>
> **基础设施**:本项目镜像基于 `python:3.12-slim-bookworm`,用 `uv` 管理依赖,Dockerfile 位于 `offline-backend-20260512/backend/Dockerfile`,默认入口是
>
> ```
> CMD ["sh", "-c", "cd backend && PYTHONPATH=. uv run --no-sync uvicorn app.gateway.app:app --host 0.0.0.0 --port 8001"]
> ```
### 总览:单容器双 uvicorn 进程
```
┌─────────────── nginx (容器外或前置) ───────────────┐
│ │
/api/ai-writing/ ──┼──► container:8002 (uvicorn --workers 1) ───► AI 写作专用
其余 /api/* ──┼──► container:8001 (uvicorn --workers N) ───► 其他业务
└────────────────────────────────────────────────────┘
▲
│ (两个进程跑在同一个容器里,共享 .deer-flow 卷
│ /同一个 MySQL /同一个 sqlite checkpoints.db)
```
两进程都用 **同一个 `app.gateway.app:app`**,区别只在:
- `8002` 单 worker,专门接 `/api/ai-writing/*`
- `8001` 多 worker,接其他所有路由
- 容器内用 `supervisord` 同时托管这两个 uvicorn
### 步骤 1:在镜像里加 supervisord
编辑 `offline-backend-20260512/backend/Dockerfile`,给 **runtime stage**(第 67 行 `FROM python:3.12-slim-bookworm` 之后)补一段:
```dockerfile
# 安装 supervisord(约 4 MB,纯 Python,无需编译)
RUN apt-get update \
&& apt-get install -y --no-install-recommends supervisor \
&& rm -rf /var/lib/apt/lists/*
```
如果内网无法访问 debian 源,可用现有的 `APT_MIRROR` build-arg:
```bash
docker build \
--build-arg APT_MIRROR=mirrors.aliyun.com \
-f offline-backend-20260512/backend/Dockerfile \
-t deerflow-gateway:dual .
```
### 步骤 2:写 supervisord 配置
新建 `offline-backend-20260512/backend/deploy/supervisord.conf`:
```ini
[supervisord]
nodaemon=true ; 容器主进程,必须前台
user=root
logfile=/dev/null ; 让子进程日志直接走 stdout/stderr,由 docker logs 接管
logfile_maxbytes=0
pidfile=/tmp/supervisord.pid
; ─── 主 Gateway:多 worker,处理除 ai-writing 以外的所有业务 ───
[program:gateway-main]
command=uv run --no-sync uvicorn app.gateway.app:app
--host 0.0.0.0 --port 8001
--workers %(ENV_GATEWAY_MAIN_WORKERS)s
--proxy-headers --forwarded-allow-ips=*
directory=/app/backend
environment=PYTHONPATH=".",AI_WRITING_DEDICATED_PORT="8002"
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stopsignal=TERM
stopwaitsecs=35 ; 给 lifespan 的 30s drain 留点余量
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; ─── AI 写作专用:单 worker,处理 /api/ai-writing/* ───
[program:gateway-aiwriting]
command=uv run --no-sync uvicorn app.gateway.app:app
--host 0.0.0.0 --port 8002
--workers 1
--proxy-headers --forwarded-allow-ips=*
directory=/app/backend
environment=PYTHONPATH=".",DEER_FLOW_ROLE="ai-writing"
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stopsignal=TERM
stopwaitsecs=35
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
```
**几个关键点**:
- `nodaemon=true` 让 supervisord 自己变成 PID 1,docker stop 发的 SIGTERM 才能正确传给它,它再传给两个 uvicorn 子进程
- `stopasgroup=true` + `killasgroup=true` 确保 uvicorn 多 worker 模式下所有子进程一起退
- `stopwaitsecs=35` 必须大于 lifespan 的 30s drain 超时,否则 in-flight 写作会被 SIGKILL
- `%(ENV_GATEWAY_MAIN_WORKERS)s` 让主进程 worker 数走环境变量,下面会传
把这个配置文件 COPY 进镜像(在 Dockerfile runtime stage `COPY --from=builder /app/backend ./backend` 之后加):
```dockerfile
COPY backend/deploy/supervisord.conf /etc/supervisor/conf.d/deerflow.conf
```
### 步骤 3:把 Dockerfile 入口换成 supervisord
把 Dockerfile **runtime stage 最后一行** 改成:
```dockerfile
# 之前
CMD ["sh", "-c", "cd backend && PYTHONPATH=. uv run --no-sync uvicorn app.gateway.app:app --host 0.0.0.0 --port 8001"]
# 之后
EXPOSE 8001 8002 2024
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/deerflow.conf"]
```
> **`dev` stage 不用改**:开发环境本来就是单 worker、reload 模式,方案 C 是为生产准备的,dev stage 维持原 CMD。
### 步骤 4:暴露端口 / 挂卷 / 环境变量
启动容器时:
```bash
docker run -d --name deerflow-gateway \
-p 8001:8001 \
-p 8002:8002 \
-e GATEWAY_MAIN_WORKERS=4 \
-e DEER_FLOW_CONFIG_PATH=/app/config.yaml \
-v /your/host/path/.deer-flow:/app/.deer-flow \
-v /your/host/path/config.yaml:/app/config.yaml:ro \
-v /your/host/path/extensions_config.json:/app/extensions_config.json:ro \
deerflow-gateway:dual
```
**两个进程必须共享 `.deer-flow` 卷** —— 因为 `checkpoints.db` 在里面(`offline-backend-20260512/config.yaml` 里配的是相对路径 `.deer-flow/data/checkpoints.db`)。两个进程跑在同一个容器内,天然共享文件系统,**这一步不用做任何额外配置**,只要确认数据卷挂出去就行。
> ⚠️ 即便 8002 是单 worker,仍然推荐把 checkpointer 持久化到磁盘,因为:① 容器重启会重建进程;② 如果哪天临时改回多容器/多 worker,数据不丢;③ 跟主 gateway 共享 checkpoint,未来想做读副本也方便。
### 步骤 5:nginx 路由
如果你前面已经有 nginx(容器外或者另一个容器),把 AI 写作的路由独立出来:
```nginx
upstream gateway_main { server gateway-host:8001; }
upstream gateway_aiwriting { server gateway-host:8002; }
server {
listen 80;
server_name deerflow.example.com;
# SSE 长连接必须关 buffering
proxy_buffering off;
proxy_request_buffering off;
proxy_http_version 1.1;
proxy_set_header Connection "";
# AI 写作 → 单 worker 后端
location /api/ai-writing/ {
proxy_pass http://gateway_aiwriting;
proxy_read_timeout 3600s; # graph 跑得久,给足时间
proxy_send_timeout 3600s;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 其它一切 API → 多 worker 后端
location /api/ {
proxy_pass http://gateway_main;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 前端静态资源不变
location / {
proxy_pass http://frontend:5174;
}
}
```
**`proxy_buffering off` 是必须的** —— 不关 buffering,nginx 会把 SSE 流缓冲到响应结束才一次性吐给前端,等于把流式写作变成「等几分钟啥都看不到 → 一下吐一整篇」。
如果前端是 Vite 直连后端(开发态没走 nginx),就只需要把 `frontend-web` 里 AI 写作相关的 `fetch`/`EventSource` 改成 `:8002`,但更推荐 **始终走 nginx**,对前端透明。
### 步骤 6:如果你用 docker-compose
完整 compose 示例:
```yaml
services:
gateway:
image: deerflow-gateway:dual
container_name: deerflow-gateway
restart: unless-stopped
environment:
GATEWAY_MAIN_WORKERS: "4"
DEER_FLOW_CONFIG_PATH: /app/config.yaml
ports:
- "8001:8001"
- "8002:8002" # 如果有外层 nginx,且 nginx 跟 gateway 同网段,可去掉这行只走内网
volumes:
- ./data/deer-flow:/app/.deer-flow
- ./config.yaml:/app/config.yaml:ro
- ./extensions_config.json:/app/extensions_config.json:ro
healthcheck:
test: ["CMD", "sh", "-c", "curl -fsS http://localhost:8001/health && curl -fsS http://localhost:8002/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
stop_grace_period: 45s # 给 supervisord 的 35s + 余量,让两路 drain 跑完
nginx:
image: nginx:1.27-alpine
depends_on: [gateway]
ports: ["80:80"]
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
```
`stop_grace_period: 45s` 这一行很关键 —— docker-compose 默认只给 10s,到点直接 SIGKILL,in-flight 写作会全部丢。设到 45s 等于 supervisord 的 35s + 10s 余量。
### 步骤 7:验证(按这个清单逐项过)
```bash
# 1) 两个进程都起来了
docker exec deerflow-gateway sh -c 'ps -ef | grep -E "uvicorn|supervisord" | grep -v grep'
# 期望看到:
# 1 root supervisord -c /etc/supervisor/conf.d/deerflow.conf
# N root uvicorn app.gateway.app:app --port 8001 --workers 4
# M root uvicorn app.gateway.app:app --port 8002 --workers 1
# (8001 那一行会有 N 个 worker 子进程,8002 那一行只有 1 个)
# 2) 8002 只有 1 个 worker(这是方案 C 的命脉)
docker exec deerflow-gateway sh -c 'pgrep -f "port 8002" | wc -l'
# 期望 = 2(1 个 master + 1 个 worker);如果 > 2,单 worker 没生效
# 3) 8001 不再警告多 worker
docker logs deerflow-gateway 2>&1 | grep -i 'WEB_CONCURRENCY'
# 期望:没有 ERROR 警告(因为 8001 走的是其他业务,8002 走的是单 worker)
# 4) 8002 进程能看到 ai_writing 持久化日志
docker logs deerflow-gateway 2>&1 | grep 'AsyncSqliteSaver'
# 期望至少 1 行:ai_writing: 使用 AsyncSqliteSaver (...)
# 5) /api/ai-writing/* 走 8002,其他走 8001
curl -sI http://deerflow.example.com/api/ai-writing/health # 看 nginx access log 落到 gateway_aiwriting
curl -sI http://deerflow.example.com/api/models # 看落到 gateway_main
# 6) 真跑一次 AI 写作,确认全程没有「resume 404 / 进度断流」
```
### 步骤 8:监控两个进程的健康
supervisord 自带 `unix_http_server` + `supervisorctl`,但对容器化场景更直接的是看 docker logs:
```bash
# 实时看两个进程的日志
docker logs -f deerflow-gateway 2>&1 | grep -E '(gateway-main|gateway-aiwriting)'
# 进程级状态
docker exec deerflow-gateway supervisorctl -c /etc/supervisor/conf.d/deerflow.conf status
# 期望:
# gateway-main RUNNING pid 7, uptime 0:05:12
# gateway-aiwriting RUNNING pid 18, uptime 0:05:12
# 单独重启 AI 写作进程(不影响主业务,前端只是 AI 写作页几秒不可用)
docker exec deerflow-gateway supervisorctl -c /etc/supervisor/conf.d/deerflow.conf restart gateway-aiwriting
```
### 资源开销(实测预估)
| 项 | 单 worker 镜像 | 双进程镜像 | 增量 |
|---|---|---|---|
| 镜像大小 | 基线 | +约 5 MB | supervisord 依赖 |
| 启动时 RSS | ~250 MB | ~450 MB | 多一份 Python runtime + 模型客户端预加载 |
| 稳态 RSS | 视业务而定 | +约 200 MB | 第二个 worker 的常驻内存 |
| CPU | 不变 | 不变 | 单 worker 进程空闲基本不占 CPU |
**结论**:内存额外占用约 200 MB,对 4 GB 以上的部署机基本无压力。
### 常见坑位
1. **`stop_grace_period` 没改大 → 重启时 in-flight 写作被秒杀**
表现:每次 `docker compose restart` 都有用户报告「写到一半没了」。修复见步骤 6。
2. **8002 没暴露 / nginx 没改 → 所有请求还是落 8001**
表现:症状跟没做方案 C 一样。验证步骤 5 的 curl 即可发现。
3. **两路用了不同的 `config.yaml`**
表现:8001 跟 8002 行为不一致。务必让两个进程**只读同一个文件**(在 compose 里只挂一次卷)。
4. **`.deer-flow` 卷没挂 → 8002 重启后会话全丢**
表现:用户刷新页面,AI 写作历史空白。修复:步骤 4 的 `-v` 必须有。
5. **AI 写作进程崩溃后 supervisord 反复重启 → 日志爆炸**
表现:`gateway-aiwriting` 状态在 RUNNING/EXITED/BACKOFF 间反复。
修复:先 `supervisorctl tail gateway-aiwriting stderr` 看真正原因(多半是 sqlite 权限或配置文件路径),再修,**别盲目调 `autorestart=false`**。
6. **想做 K8s 部署但还想用方案 C**
不要把两个进程塞一个 Pod,应该直接拆成两个 Deployment、共享 PVC(checkpoints.db)。这种情况下方案 C 已经变形成方案 F 的子集,建议直接走方案 F。
### 回滚方案
如果上线后发现问题,回滚只需要 1 步:
```bash
# 把 Dockerfile 最后一行换回原来的 CMD,重新 build + 重启
CMD ["sh", "-c", "cd backend && PYTHONPATH=. uv run --no-sync uvicorn app.gateway.app:app --host 0.0.0.0 --port 8001"]
```
数据完全兼容(checkpoints.db、MySQL 表结构都跟单进程模式一致),**不会丢任何用户数据**,只是回到「resume 偶发 404、SSE 断断续续」的旧体验。
---
## 七、运维操作清单
### 部署前验证
```bash
# 1) 确认 .deer-flow 数据卷挂出来了(持久化的命脉)
docker exec <gateway> ls -la /app/.deer-flow/data/
# 应该能看到 checkpoints.db 文件(首次启动后会自动创建)
# 2) 确认 alembic 迁移跑完了
docker exec <gateway> sh -c "cd /app/backend && PYTHONPATH=. uv run alembic current"
# 应该看到包含 20260519_02 的 head
# 3) 确认 transcript 列已扩容
docker exec <mysql> mysql -uroot -p<pwd> deerflow -e \
"SHOW COLUMNS FROM ai_writing_sessions LIKE 'transcript';"
# Type 列应该是 longtext
# 4) 查 worker 数
docker exec <gateway> ps -ef | grep -E 'uvicorn|gunicorn'
# 如果 > 1,且没做任何方案 C/F/B,启动日志会打 ERROR 警告
```
### 启动时关注的日志
```bash
docker logs <gateway> 2>&1 | head -100 | grep -iE 'ai_writing|checkpointer|worker'
```
期望看到:
- `ai_writing: 使用 AsyncSqliteSaver (xxx.db)` — 持久化生效
- `ai_writing_cleanup: 已启动 cron=...` — 清理任务起来了
警告:
- `⚠ 检测到 WEB_CONCURRENCY=N` — 多 worker 配置警告
- `ai_writing: 持久化 checkpointer 不可用,退回 InMemorySaver` — sqlite 初始化失败,需立刻排查
### 用户报告「会话丢失」时的排查
```bash
# 1) 查 sqlite 里这个 session 的快照
docker exec <gateway> sh -c "sqlite3 /app/.deer-flow/data/checkpoints.db \
\"SELECT thread_id, checkpoint_ns FROM checkpoints WHERE thread_id='<session_id>' LIMIT 5;\""
# 2) 查 MySQL 里这条会话
docker exec <mysql> mysql -uroot -p<pwd> deerflow -e \
"SELECT id, status, draft_title, updated_at FROM ai_writing_sessions WHERE id='<session_id>';"
# 3) 看 gateway 日志里这个 session 的活动轨迹
docker logs <gateway> 2>&1 | grep '<session_id>' | tail -50
# 4) 看是否有 recover_session 调用
docker logs <gateway> 2>&1 | grep 'ai_writing: recovered' | tail -20
# 5) 看是否有节点异常
docker logs <gateway> 2>&1 | grep -E 'ai_writing graph segment failed|ai_writing.*error' | tail -20
```
### 手动触发清理(admin only)
```bash
# 用 admin 账号登录后,取 cookie,调清理接口
curl -X POST 'http://<gateway>/api/ai-writing/admin/cleanup' \
-H 'Content-Type: application/json' \
-H 'Cookie: <admin session cookie>' \
-d '{"retention_days": 7}'
```
返回:
```json
{
"deleted_db": 12,
"deleted_checkpoints": 12,
"skipped_active": 1,
"elapsed_seconds": 0.234,
"params": { "retention_days": 7, "only_finished": false, "batch_size": 500 }
}
```
`skipped_active` > 0 表示有正在跑的会话被活跃保护拦下来,不会被误删。
---
## 八、相关文件索引
### 后端
- `offline-backend-20260512/backend/app/gateway/routers/ai_writing.py` — 路由 + 内存状态字典 + drain
- `offline-backend-20260512/backend/app/gateway/ai_writing_cleanup.py` — 定期清理
- `offline-backend-20260512/backend/app/gateway/app.py` — lifespan / 多 worker 检测
- `offline-backend-20260512/backend/packages/harness/deerflow/agents/ai_writing/graph.py` — Graph 定义 + 持久化 checkpointer
- `offline-backend-20260512/backend/packages/harness/deerflow/persistence/ai_writing_sessions/` — MySQL repo
- `offline-backend-20260512/backend/packages/harness/deerflow/persistence/types.py` — `PortableLongText`
- `offline-backend-20260512/backend/packages/harness/deerflow/persistence/migrations/versions/20260519_02_*.py` — LONGTEXT 迁移
- `offline-backend-20260512/config.yaml` — `checkpointer:` + `ai_writing.cleanup:` 配置
### 前端
- `frontend-web/src/open-canvas/pages/AIWritingPage.tsx` — 页面顶部有快速排查注释
- `frontend-web/src/open-canvas/api/ai-writing-sessions.ts` — transcript 保存(已做 fire-and-forget 容错)
- `frontend-web/src/open-canvas/api/ai-writing.ts` — resume / stream
### 测试
- `tests/test_ai_writing_cleanup.py` — 清理 + drain + checkpointer 降级 + SSE 序列化(21 个测试)
- `tests/test_ai_writing_session_recovery.py` — 跨 worker 会话恢复(8 个测试)
- `tests/test_ai_writing_session_repo.py` — Repo(7 个测试)
- `tests/test_ai_writing_transcript_endpoint.py` — transcript 兜底(5 个测试)
- `tests/test_portable_long_text.py` — LONGTEXT 列类型(5 个测试)
总测试:**51 个,全过**。
---
## 九、变更历史
| 日期 | Commit | 内容 |
|---|---|---|
| 2026-05-19 | c3d0c82 | 报错兜底(transcript LONGTEXT 迁移 + 路由 try/except + session 恢复) |
| 2026-05-20 | (本次) | checkpointer 持久化 + 定期清理 + admin 接口 + 多层兜底 + drain + 多 worker 检测 |
---
## 十、决策摘要(给未来的你/同事)
> **如果你现在第一次接手这个问题**,按这个清单往下走:
>
> 1. ✅ **transcript 500 不用管** — 已彻底修复
> 2. ⚠️ **resume 报错的根因是多 worker** — sqlite 持久化已减轻,但 SSE 事件流仍隔离
> 3. ⚠️ **写作能跑完,但用户体验断断续续** — 草稿数据安全,刷新就能看到
> 4. 🎯 **要彻底解决,从方案 C / F / B 选一个**(建议从 C 开始)
> 5. 🚨 **务必确认 `.deer-flow` 数据卷挂出来了** — 否则 sqlite 持久化白做
> 6. 📊 **关注的日志关键字**:`ai_writing:`、`checkpointer`、`AsyncSqliteSaver`、`WEB_CONCURRENCY`
如有疑问,先看本文件的「七、运维操作清单」做基础排查,再问当前维护者。
File diff suppressed because it is too large. Load diff
+70
View File
@@ -0,0 +1,70 @@
# 我的项目
入口:全量与简洁导航中的「我的项目」,路由 `/page/strategy/qa/projects`。旧地址 `/page/workspace/projects` 仅保留兼容跳转,不再展示独立入口或旧页面。
## 使用流程
1. 新建项目,选择普通问答、策略优选或方案生成。三类项目独立保存和展示,方案生成不会复用或标记策略优选项目。
2. 选择项目默认智能体,填写目标、约束等项目说明。新建项目对话时仍可换用另一个可访问的智能体。
3. 创建后进入项目工作区。普通问答项目可包含多条独立问答;方案项目可包含多条方案记录。最近对话根据 `analysis_project_mode` 回到普通问答分组或方案项目。
4. 方案生成可从「工作流配置 · 报告结构」选择、启停、编辑、删除结构,选择后自动填充项目报告结构配置;也可直接编辑大纲及固定/弹性约束。
5. 策略智能项目保存默认 Strategy Lens;每轮依次进行问题重构、各 Lens 独立分析、策略辩论和方案生成,并分为「意图理解」「多视角策略分析」「完整策略方案」三栏。右栏以文档形式给出执行摘要、目标原则、分阶段行动、资源配置、风险应对、评估复盘、形成依据与备选策略切换条件;原始对话和引用仍可切换查看。
6. 策略智能对话底部提供改变约束、增删视角、重新推演和挑战当前策略快捷动作;项目主页面可直接添加或删除 Lens。
模式在创建后不可修改,前后端都不提供修改入口。项目、对话归属和智能体访问权限在服务端校验;方案结构及每条对话所选智能体也以服务端配置为准。
## 普通问答跨会话记忆
- 仅普通问答项目显示「跨会话项目记忆」。它只受项目自身开关控制,与系统「问答记忆」总开关相互独立;成功完成的会话会在后台整理,状态包括等待沉淀、整理中、已就绪和异常。
- 新会话提问时会召回同一账号、同一项目中其他会话的事实、决策、约束、偏好、术语与未决事项。不会读取其他项目或其他账号,也不会混用普通聊天/智能体的通用记忆。
- 项目设置和问答页头部均可打开「项目记忆」面板,查看精简快照、条目可信度/重要度和来源对话;支持手工新增、编辑、固定、删除、清空以及从当前项目历史对话重建。项目暂停后仍可清空已有数据,但不能重建。
- 编辑、删除或清空原对话时,服务端先让对应记忆失效,再修改消息;重建期间不注入旧快照。固定或手工条目在重建时保留,自动条目按来源 checkpoint 时间判断新旧,较早会话不会因后台任务晚完成而覆盖新的纠正。
- 交互问答在首包前使用有界关键词召回,避免等待远程向量编码;后台整理仍可写入向量供显式或离线检索使用,编码不可用不影响跨会话记忆。输入提示块有条数与 token 上限,历史内容只作为非指令资料,当前消息优先。
## 代码与运行
- `src/pages/AnalysisProjectsPage.tsx`:普通问答与方案项目的新建、设置、历史和工作台布局。
- `src/strategy-selection/StrategyProjectsPage.tsx`:「我的项目」三类项目列表及创建入口。
- `src/pages/analysis-projects/ProjectConversation.tsx`:现有聊天、研究进度、方案画布的项目级组合。
- `src/core/analysis-projects/api.ts`:Gateway 项目 API 与按账号隔离的缓存。
- `src/pages/analysis-projects/ProjectMemoryPanel.tsx`:项目记忆状态、快照、来源和管理操作。
- `src/core/analysis-projects/memory-status.ts`:总开关/项目开关、状态和按钮可用性映射。
- 后端:`/api/analysis-projects`,对话仍通过现有 `/api/threads/{thread_id}/runs/*` 流式接口发送;服务端从不可变归属读取项目配置。
启动新版 Gateway 后自动创建项目表。生产持久化依赖已配置的数据库;memory 模式中的项目随服务重启丢失。前端沿用仓库的 Vite 开发与构建命令。
## 验证范围
后端回归命令:在 `offline-backend-20260512/backend` 执行
```shell
python -m pytest tests/test_analysis_projects.py tests/test_deep_research_report_tool.py tests/test_writing_mode_report_middleware.py -q
```
涵盖内存与 SQLite 存储、跨用户隔离、禁止修改模式、运行时覆盖伪造模式与知识库、更新配置、对话归属与失败清理、固定方案模板及知识库资料进入研究管线。
跨会话记忆专项:
```shell
python -m pytest tests/test_analysis_project_memory.py tests/test_analysis_project_memory_store.py tests/test_analysis_project_memory_runtime.py tests/test_analysis_project_memory_integration.py tests/test_analysis_projects.py -q
```
前端专项:`node --experimental-strip-types --test src/core/analysis-projects/memory-status.test.ts`,并执行 `pnpm build`。
部署前还需使用实际知识库和模型验证三类问答、流式断线续接及方案后续修改。接口模拟与单元测试不能替代真实模型联调。
## 2026-09-14 我的项目与知识库验收修复
日常使用复查:我的项目侧栏历史保持 `qa/projects/groups` 上下文,官方侧栏同样识别项目归属;手机选择历史后收起菜单;项目表单不重复显示侧栏按钮。设置保存后默认智能体同步到新对话选择器。读取项目对话失败提供重试,项目列表失败可原地重试。助手知识检索隔离过期响应,清空输入时禁用检索,无结果提供目录入口。ScrollArea 固定为包含 React 19 引用回调修复的 1.2.18。详细记录见 `docs/daily-usage-audit-20260914.md`。
- 简洁模式的「我的项目」列表、策略工作台和普通问答项目恢复工作区功能导航;窄屏提供展开菜单按钮。
- 普通问答先创建具名项目,再在项目内创建多个对话。列表读取 `/api/analysis-projects` 的 `qa` 项目,不再读取、标记或自动归入全局普通聊天。
- 项目设置更新保留既有知识库绑定。旧「项目空间」入口已移除并跳转「我的项目」;普通问答路由为 `qa/projects/groups/*`,方案生成路由为 `qa/projects/solutions/*`。
- 策略生成卡片统一先显示思考/执行过程,再显示正文;评判、方案及展开视图沿用相同顺序。
- 策略优选工作台拆为三步:意图与任务定义、策略生成与智能评判、综合方案生成。第二步不重复展示问答记录,突出当前任务并扩大策略回答、评判正文;第三步将生成过程默认收起并为方案正文保留固定可视空间,集中完成方案生成、Markdown 编辑、项目保存以及 Markdown/Word 直接下载。保存后的项目卡也提供 Markdown/Word 下载;`?module=solution` 直接进入第三步,历史方案即使任务已修改仍可查看下载。
- 资料库把已完成的策略优选综合方案作为独立「策略生成」来源展示,并标注具体策略项目名称;条目可回到策略项目第三步,也可直接下载 Markdown/Word。普通策略项目线程生成的文件沿用原文件下载链路并显示同类来源标识。
- 方案生成使用独立项目和固定报告结构,通过 `deep_research_report` 直接生成并打开方案画布;策略优选项目不再出现在方案生成分类中。
- 知识库管理页读取上游最新目录,避免远端删除后命中旧缓存;检索调用仍共享短期目录缓存。
- 普通用户访问尚未初始化的助手知识库时显示明确空态及刷新按钮。
验证:后端相关回归 273 项、前端策略/项目回归 31 项通过;真实 BAAI/bge-m3 编码、指定库向量检索与草稿隔离通过;本地隔离服务的问答项目创建/分组、真实问答、方案整理、助手库创建/编辑/文件入库/向量检索/详情均通过。完整验收记录见仓库 `docs/ji-knowledge-projects-acceptance.md`。不在源码或文档中保存接口密钥。
File diff suppressed because it is too large. Load diff
+436
View File
@@ -0,0 +1,436 @@
# 工作台问答 · iframe 嵌入开发说明
本文档说明如何将 DeerFlow **通用工作台问答**(与 `/page/workspace/chats/*` 同一套 LangGraph 流式能力)以**普通 iframe** 形式嵌入第三方页面,并在**父页面无法读取子 frame 内 `thread_id`** 的前提下,轮询「本次问答是否已结束」。
后端公开 API 实现见:`offline-backend-20260512/backend/app/gateway/routers/public_embed.py`
数据表:`embed_sessions`(迁移 `20260602_01`)
---
## 0. 速读
| 角色 | 要做的事 |
|------|----------|
| **父页面** | 自己生成 `sessionId`(UUID),拼进 iframe `src`;用 `sessionId` 调公开 API 轮询 `finished` |
| **iframe(DeerFlow)** | 打开 `/embed/chats/...`,自动登录、自动发问、登记 `sessionId → thread_id` |
| **不需要** | 无界(wujie)、父页面拿 `thread_id`、DeerFlow 登录态 Cookie |
**完成条件**:`GET .../sessions/{sessionId}/status` 返回 `finished === true`(且无进行中的 run,非澄清中断)。
---
## 1. 背景与约束
### 1.1 业务目标
- 第三方系统用 **iframe** 嵌 DeerFlow 问答 UI。
- 传入:**问题文案**、**用户名**(走现有 `login/username`)、**主题色**。
- 展示:**消息列表** + **沙箱/产物侧栏**(与主聊天相同的 `ChatBox`);**隐藏**页面左侧栏、Workspace 侧栏、底部输入框。
- 进入后 **自动发送** 首条用户消息并走流式问答。
### 1.2 为何需要 `sessionId`
iframe 与父页面通常 **跨域**,父页面 **不能** 读取子应用 URL 里的 `thread_id`(hash 路由在子 frame 内)。
因此约定:
1. **父页面**在打开 iframe 前生成全局唯一的 `sessionId`;
2. **子页面**在创建/确定 `thread_id` 后,调用后端 **登记接口** 写入 `session_id → thread_id`;
3. **父页面**只凭 `sessionId` 查询状态,必要时响应里会带上 `thread_id`(可选使用)。
---
## 2. 端到端流程
```mermaid
sequenceDiagram
participant Parent as 父页面
participant Iframe as DeerFlow iframe
participant API as Gateway /api/public/embed
Parent->>Parent: sessionId = crypto.randomUUID()
Parent->>Iframe: iframe src 含 sessionId、message、username、theme
Iframe->>Iframe: loginByUsername + 自动 sendMessage
Iframe->>API: POST /sessions { session_id, thread_id }
loop 每 1–3s
Parent->>API: GET /sessions/{sessionId}/status
API-->>Parent: registered, finished, thread_id
end
```
---
## 3. 前端路由与页面
### 3.1 路由(独立于 `/page/*`)
在 `App.tsx` 注册,**不经过** `PageRoutes` / `PageSidebar`,因此无外层导航与 Workspace 侧栏。
| 路由 | 组件 | 说明 |
|------|------|------|
| `/embed/chats/:thread_id` | `EmbedChatPage`(外包 `ChatRuntime`) | `thread_id` 可为 `new` 或已有 UUID |
示例(HashRouter,注意 `#`):
```
http://localhost:5173/#/embed/chats/new?sessionId=...&message=...&username=guest&theme=red
```
开发环境端口以本地 Vite 为准(如 5173 / 5174)。
### 3.2 URL 查询参数
| 参数 | 必填 | 说明 |
|------|------|------|
| `sessionId` 或 `session_id` | **是** | 父页面生成的关联 id,8–128 位,仅字母数字 `_` `-` |
| `message` / `question` / `text` | 建议 | 首条用户问题;有则进入后自动发送 |
| `username` / `userName` | 否 | 默认 `guest`,对应 `POST /api/v1/auth/login/username` |
| `theme` | 否 | `dark-blue` → 深色;`red` 等 → 浅色(与 `LoginPage` 一致) |
缺少 `sessionId` 时,嵌入页会提示错误,不会发起登记。
### 3.3 相关源码
| 路径 | 职责 |
|------|------|
| [src/pages/EmbedChatPage.tsx](../src/pages/EmbedChatPage.tsx) | 嵌入页:登录、自动发问、登记 session、仅消息列表 + ChatBox |
| [src/core/embed/params.ts](../src/core/embed/params.ts) | 从 URL 解析嵌入参数 |
| [src/core/embed/status-api.ts](../src/core/embed/status-api.ts) | 登记 / 轮询 API 封装 |
| [src/App.tsx](../src/App.tsx) | 路由注册 |
### 3.4 UI 行为说明
- **隐藏**:`PageSidebar`、`WorkspaceSidebar`、`InputBox`、顶栏标题栏等(相对完整 `ChatPage`)。
- **保留**:`MessageList`、流式指示、澄清卡片(若 agent 触发 `ask_clarification`)、右侧 **产物/沙箱**(`ChatBox` 内 60/40 分栏逻辑与主聊天一致)。
- **线程 id**:新建会话时客户端先分配 UUID,`onStart` 后 `history.replaceState` 更新 hash 为 `/embed/chats/{真实id}`(与主聊天 `ChatPage` 相同手法,避免整页重载)。
---
## 4. 公开 HTTP API(无需鉴权)
前缀:`/api/public/embed/`(走 Gateway,与 `VITE_BACKEND_BASE_URL` 一致,默认 `http://47.88.25.99:7001/`)。
CSRF / Auth 中间件对 `/api/public/` 放行;请求 **不需要** Cookie。
### 4.1 登记映射(iframe 内自动调用)
```http
POST /api/public/embed/sessions
Content-Type: application/json
{
"session_id": "parent-generated-uuid",
"thread_id": "e9c7d09e-821d-421f-ae24-e5ddfe0cff5b"
}
```
**响应:**
```json
{
"session_id": "parent-generated-uuid",
"thread_id": "e9c7d09e-821d-421f-ae24-e5ddfe0cff5b",
"registered": true
}
```
同一 `session_id` 再次 POST 会 **更新** `thread_id`(例如 `onStart` 后 id 变化)。
### 4.2 轮询状态(父页面使用)
```http
GET /api/public/embed/sessions/{session_id}/status
```
**尚未登记**(iframe 仍在加载或未 POST):
```json
{
"session_id": "parent-generated-uuid",
"registered": false,
"thread_id": null,
"finished": false,
"thread_status": "pending",
"has_active_run": false,
"latest_run_status": null
}
```
**已登记且问答进行中:**
```json
{
"session_id": "parent-generated-uuid",
"registered": true,
"thread_id": "e9c7d09e-821d-421f-ae24-e5ddfe0cff5b",
"finished": false,
"thread_status": "idle",
"has_active_run": true,
"latest_run_status": "running"
}
```
**已登记且已结束:**
```json
{
"session_id": "parent-generated-uuid",
"registered": true,
"thread_id": "e9c7d09e-821d-421f-ae24-e5ddfe0cff5b",
"finished": true,
"thread_status": "idle",
"has_active_run": false,
"latest_run_status": "success"
}
```
#### 字段说明
| 字段 | 含义 |
|------|------|
| `registered` | 是否已收到 iframe 的 POST 登记 |
| `finished` | **父页面应以此为准**:无 inflight run,且线程非 running/busy,且非 `interrupted`(澄清等待用户) |
| `thread_status` | 从 checkpoint 推导:`idle` / `interrupted` / `error` 等 |
| `has_active_run` | 是否存在 pending/running 的 LangGraph run |
| `latest_run_status` | 该线程最近一次 run 的状态:`success` / `error` / … |
| `thread_id` | 解析出的 DeerFlow 线程 id(父页面可选用,非必须) |
### 4.3 获取生成结果(父页面使用)
问答结束后(建议先确认 `finished === true`),拉取本次模型输出:
```http
GET /api/public/embed/sessions/{session_id}/result
```
**尚未登记:**
```json
{
"session_id": "parent-generated-uuid",
"registered": false,
"thread_id": null,
"finished": false,
"thread_status": "pending",
"has_active_run": false,
"latest_run_status": null,
"messages": [],
"generated_text": "",
"generated_files": []
}
```
**已登记且已有内容:**
```json
{
"session_id": "parent-generated-uuid",
"registered": true,
"thread_id": "e9c7d09e-821d-421f-ae24-e5ddfe0cff5b",
"finished": true,
"thread_status": "idle",
"has_active_run": false,
"latest_run_status": "success",
"messages": [
{ "type": "human", "content": "请总结要点", "id": "..." },
{ "type": "ai", "content": "根据分析,要点如下:...", "id": "..." }
],
"generated_text": "根据分析,要点如下:...",
"generated_files": [
"/mnt/user-data/outputs/summary.md",
"/mnt/user-data/outputs/chart.png"
]
}
```
#### 结果字段说明
| 字段 | 含义 |
|------|------|
| `messages` | 完整消息列表(与 checkpoint 中序列化结构一致,含 human / ai / tool 等) |
| `generated_text` | 所有 `ai` / `assistant` 消息正文按顺序拼接(段落间空一行) |
| `generated_files` | 本次会话产物的虚拟路径列表(与 UI 产物栏 `artifacts` 一致) |
未结束时也可调用,会返回当前已有内容;`finished` 仍为 false 表示可能还会继续生成。
### 4.4 按 thread_id 查询(可选)
调试或父页面已持有 thread_id 时:
```http
GET /api/public/embed/threads/{thread_id}/status
GET /api/public/embed/threads/{thread_id}/result
```
状态接口响应不含 `messages` / `generated_text` / `generated_files`;结果接口字段与 §4.3 相同(无 `session_id` / `registered`)。
### 4.5 前端封装
```ts
import {
getEmbedSessionResult,
getEmbedSessionStatus,
registerEmbedSession,
} from "@/core/embed/status-api";
// 父页面(或你们自己的脚本)
const status = await getEmbedSessionStatus(sessionId);
if (status.registered && status.finished) {
const result = await getEmbedSessionResult(sessionId);
console.log(result.generated_text, result.generated_files);
}
// 仅 iframe 内需要
await registerEmbedSession(sessionId, threadId);
```
`fetch` 使用 `credentials: "omit"`,不携带 DeerFlow 会话。
---
## 5. 父页面集成示例
### 5.1 拼接 iframe
```html
<iframe
id="deerflow-embed"
title="DeerFlow 问答"
style="width:100%;height:600px;border:0"
></iframe>
```
```javascript
const sessionId = crypto.randomUUID();
const base = "http://localhost:5173"; // 换成你们部署的前端 origin
const params = new URLSearchParams({
sessionId,
message: "请根据附件总结要点",
username: "guest",
theme: "red",
});
document.getElementById("deerflow-embed").src =
`${base}/#/embed/chats/new?${params.toString()}`;
```
### 5.2 轮询直到结束
```javascript
const API = "http://47.88.25.99:7001/"; // VITE_BACKEND_BASE_URL
async function pollUntilFinished(sessionId) {
const res = await fetch(
`${API}/api/public/embed/sessions/${encodeURIComponent(sessionId)}/status`,
{ credentials: "omit" },
);
if (!res.ok) throw new Error(`status HTTP ${res.status}`);
const data = await res.json();
if (!data.registered) return { done: false, reason: "pending" };
if (data.finished) return { done: true, data };
return { done: false, reason: "running" };
}
const timer = setInterval(async () => {
try {
const poll = await pollUntilFinished(sessionId);
if (poll.done) {
clearInterval(timer);
const output = await fetch(
`${API}/api/public/embed/sessions/${encodeURIComponent(sessionId)}/result`,
{ credentials: "omit" },
).then((r) => r.json());
console.log("问答已结束", output.generated_text, output.generated_files);
}
} catch (e) {
console.error(e);
}
}, 2000);
```
### 5.3 跨域注意
父页面从浏览器 `fetch` Gateway(如 `http://47.88.25.99:7001/`)时,**Origin 必须是后端 CORS 白名单里的完整地址**(含协议、主机、端口),与 API 地址是否写 `localhost` / `127.0.0.1` 无关。
**本地开发**(前端默认 `5174`)请在 Gateway 环境变量中配置:
```bash
# offline-backend-20260512/.env 或启动脚本注入
GATEWAY_CORS_ORIGINS=http://localhost:5174,http://127.0.0.1:5174,http://localhost:5173,http://127.0.0.1:5173
```
修改后**重启 Gateway**(`make dev` / `make gateway`)。若父页面部署在其它域名,把该域名的 origin 一并加入逗号分隔列表。
临时调试(勿用于公网生产):
```bash
GATEWAY_CORS_ALLOW_ALL=1
```
常见报错:`No 'Access-Control-Allow-Origin' header` → 当前页面的 origin 未出现在 `GATEWAY_CORS_ORIGINS` 中。
### 5.4 其它部署注意
---
## 6. 部署与数据库
1. **跑迁移**(SQL 持久化后端):
```bash
cd offline-backend-20260512/backend
# 按项目惯例执行 alembic upgrade head
```
表:`embed_sessions(session_id PK, thread_id, created_at, updated_at)`。
2. **重启 Gateway**,确认路由已挂载:`public_embed.router`(`app/gateway/app.py`)。
3. **前端构建** 后,将嵌入地址配给第三方;`VITE_BACKEND_BASE_URL` 指向可达的 Gateway。
无 SQL 时开发环境会退化为 **内存** `MemoryEmbedSessionStore`(进程重启后映射丢失);生产请使用持久化库。
---
## 7. 安全说明
- `sessionId` 与 `thread_id` 均视为 **不透明能力令牌**:知晓即可查询状态(公开 API **无登录**)。
- 建议:父系统自行生成不可猜测的 UUID;敏感场景在贵司 API 网关再加鉴权或 IP 限制。
- 登记接口为 **POST upsert**,不校验「session 是否属于某租户」——若需多租户隔离,请在业务层约定 `sessionId` 命名空间或增加网关校验。
---
## 8. 与主聊天 `/page/workspace/chats` 的差异
| 项目 | 主聊天 | iframe 嵌入 |
|------|--------|-------------|
| 路由 | `/page/workspace/chats/:id` | `/embed/chats/:id` |
| 布局 | 完整 Workspace + 输入框 | 仅消息区 + 产物栏 |
| 登录 | 常规登录流 | URL `username` 自动 `login/username` |
| 首条消息 | 用户输入 | URL `message` 自动发送 |
| 完成态查询 | 无公开 API | `sessionId` + `/api/public/embed/sessions/.../status` |
能力上仍走同一 `useThreadStream` + `lead_agent` 流式链路,沙箱与产物行为与主聊天一致。
---
## 9. 常见问题
**Q:`registered` 一直为 false?**
A:检查 iframe URL 是否带 `sessionId`;子页是否登录成功;Network 里是否有 `POST /api/public/embed/sessions` 且 200。
**Q:`finished` 一直 false?**
A:可能仍在流式生成(`has_active_run: true`),或 agent 进入澄清(`thread_status: interrupted`)。嵌入模式无底部输入框,澄清需产品侧另行处理或避免触发澄清类工具。
**Q:父页面能否不用轮询?**
A:当前标准方案为公开 GET 轮询。若同源可考虑 `postMessage` 扩展(未默认实现)。
**Q:能否继续用已有 thread_id 嵌入?**
A:可以:`#/embed/chats/{thread_id}?sessionId=...`,可选再带 `message` 追加一轮;登记会在已知 id 上 upsert。
---
## 10. 变更记录
| 日期 | 说明 |
|------|------|
| 2026-06-02 | 初版:iframe 嵌入路由、`sessionId` 映射表、公开登记与状态 API |
| 2026-06-02 | 新增 `GET /sessions/{session_id}/result`:返回 messages、generated_text、generated_files |
@@ -0,0 +1,154 @@
# 公开页 · iframe 嵌入外观对接说明(主题 / 背景色)
本文档面向**嵌入方(宿主系统)**,说明如何在用 `<iframe>` 嵌入 DeerFlow 公开页时,从外部控制页面的**整体明暗主题(light/dark)**与**背景色 / 文字色**,使其与宿主站点的视觉风格保持一致。
前端实现见:`src/core/embed/background.ts`(参数解析与 postMessage 监听)、`src/App.tsx`(主题接入 `forcedTheme`)。
---
## 0. 速读
| 想做什么 | 怎么做 |
|----------|--------|
| 嵌入时指定深色主题 | iframe `src` 加 `?theme=dark` |
| 嵌入时指定背景/文字色 | iframe `src` 加 `?bg=%23001529&text=%23ffffff`(`#` 需编码为 `%23`) |
| 宿主切主题时同步切换 | `postMessage({ type: "deerflow:set-theme", theme: "dark" }, "*")` |
| 宿主动态改背景色 | `postMessage({ type: "deerflow:set-bg", bg: "#001529", text: "#fff" }, "*")` |
| 什么都不传 | 页面使用 DeerFlow 自带默认配色,互不影响 |
---
## 1. 适用页面
以下公开页(免登录、只读)均支持本文档的全部参数:
| 页面 | 路由 |
|------|------|
| 会话分享页 | `/#/share/{shareCode}` |
| 圆桌分享页 | `/#/roundtable-share/{shareCode}`、`/#/roundtable-share/{shareCode}/report` |
| 用户排行榜 | `/#/public/leaderboard` |
| 定时任务公开页 | `/#/public/scheduled-tasks/{taskId}`(含 `/runs/{runId}/fullscreen` 全屏页) |
> 注意:站点使用 **hash 路由**,路径在 `#` 之后。
> 嵌入聊天页(`/#/embed/chats/*`、`/#/embed/roundtable`)有自己的主题约定,见 `embed-iframe-chat.md`,不在本文范围内。
---
## 2. URL 查询参数(嵌入时一次性指定)
### 2.1 参数列表
| 参数 | 别名 | 作用 | 合法值 |
|------|------|------|--------|
| `theme` | — | 切整体明暗主题 | 见 2.2 取值映射表 |
| `bg` | `background` | 页面根容器背景色 | 见 2.3 颜色格式 |
| `text` | `fg` | 页面根容器文字色 | 见 2.3 颜色格式 |
三个参数相互独立,可任意组合;不传或传非法值时该项忽略、沿用默认。
### 2.2 `theme` 取值映射
| 传入值(不区分大小写) | 实际主题 |
|------|------|
| `dark`、`dark-blue`、`深蓝`、`深色` | 深色 |
| `light`、`red`、`红白`、`浅色` | 浅色 |
| 其他 / 不传 | 忽略,沿用站内默认(浅色) |
### 2.3 颜色格式(`bg` / `text`)
颜色值经过白名单校验,仅接受以下写法,其余一律丢弃(防注入):
- **hex**:`#fff`、`#ffffffcc` 等 3/4/6/8 位(`#` 可省略;URL 里 `#` 必须编码为 `%23`)
- **函数式**:`rgb()` / `rgba()` / `hsl()` / `hsla()`,括号内仅允许数字、逗号、百分号、空格、`/`
- **命名色**:纯英文字母,如 `white`、`transparent`
### 2.4 参数位置
参数放在 hash 路由之后(推荐)或 `#` 之前都能识别;两处都传时**hash 路由内的优先**:
```
https://<host>/#/public/leaderboard?theme=dark ← 推荐
https://<host>/?theme=dark#/public/leaderboard ← 也支持
```
### 2.5 示例
```html
<!-- 深色主题 -->
<iframe src="https://<host>/#/public/leaderboard?theme=dark"></iframe>
<!-- 浅色主题 + 自定义背景与文字色(# 编码为 %23) -->
<iframe src="https://<host>/#/share/Ab3xYz?theme=light&bg=%23f5f7fa&text=%23333333"></iframe>
<!-- 主题与背景叠加:整页走深色变量,根背景用宿主品牌色 -->
<iframe src="https://<host>/#/roundtable-share/Ab3xYz?theme=dark&bg=%23001529"></iframe>
```
---
## 3. postMessage(嵌入后动态切换)
适用于宿主站点支持用户切主题、需要 iframe 实时跟随的场景。向 iframe 的 `contentWindow` 发消息即可,**无需等待子页面回执**(监听器在应用挂载时注册)。
### 3.1 消息格式
```js
const frame = document.getElementById("deerflow-frame");
// 切整体明暗主题(theme 取值同 2.2)
frame.contentWindow.postMessage({ type: "deerflow:set-theme", theme: "dark" }, "*");
// 改背景色 / 文字色(字段名与 URL 参数一致,bg/background、text/fg 均可)
frame.contentWindow.postMessage({ type: "deerflow:set-bg", bg: "#001529", text: "#fff" }, "*");
// 兼容别名:type 也可写 "deerflow:set-background"
```
说明:
- 两类消息相互独立,可只发其一;`set-bg` 里 `bg`、`text` 也可只传其一,未传的字段保持当前值。
- 非法颜色值 / 不认识的 `theme` 取值会被忽略,不会清空已有设置。
- targetOrigin 建议按需收紧(写 DeerFlow 站点的 origin 而非 `"*"`)。
### 3.2 宿主主题联动示例
```js
function syncDeerflowTheme(isDark) {
const win = document.getElementById("deerflow-frame").contentWindow;
win.postMessage({ type: "deerflow:set-theme", theme: isDark ? "dark" : "light" }, "*");
win.postMessage(
{ type: "deerflow:set-bg", bg: isDark ? "#001529" : "#ffffff" },
"*",
);
}
// iframe 首次加载用 URL 参数兜底,之后切换走 postMessage
myThemeStore.subscribe((theme) => syncDeerflowTheme(theme === "dark"));
```
---
## 4. 优先级与默认行为
同一项配置多处传入时,按以下优先级取值(高 → 低):
1. **postMessage** 动态设置的值
2. hash 路由内的 URL 参数(`#/路由?theme=...`)
3. `#` 之前的 URL 参数(`?theme=...#/路由`)
4. 都没传 → DeerFlow 默认配色(浅色主题 + 页面自带 Tailwind 配色)
其他保证:
- 外部主题只影响**当前 iframe 的渲染**,不写 localStorage——不会污染用户直接访问 DeerFlow 主站时自己选择的主题。
- `bg`/`text` 是内联样式,作用在页面根容器上,优先级高于主题变量;与 `theme` 叠加时以 `bg`/`text` 为准。
---
## 5. 常见问题排查
| 现象 | 排查 |
|------|------|
| `theme=dark` 不生效 | 确认路由属于第 1 节列出的公开页;确认参数拼在 hash 路由后(`/#/share/xx?theme=dark`),而不是写成了 `/#/share/xx#theme=dark` |
| `bg=#fff` 不生效 | URL 里 `#` 没编码会被浏览器截断,必须写 `%23fff`;或直接省略 `#` 写 `bg=fff` |
| postMessage 无反应 | 确认消息体是对象且 `type` 拼写为 `deerflow:set-theme` / `deerflow:set-bg`;确认在 iframe `load` 之后发送 |
| 颜色被忽略 | 检查是否符合 2.3 白名单格式(如 `linear-gradient(...)` 等复杂值不支持) |
| 主题切了但个别区域颜色没变 | 该区域可能使用了固定配色;把页面路由与截图反馈给 DeerFlow 维护方补充 `dark:` 样式 |
-140
View File
@@ -1,140 +0,0 @@
# App.tsx 路由与页面结构重构需求(首页与业务页分离)
## 一、需求背景
当前 `frontend-web/src/App.tsx` 同时承载了:
1. 登录/首页相关路由(如 `/login`、`/landing`)
2. 工作台业务相关路由(如 `/workspace/chats`、`/workspace/agents`、`/workspace/scheduled/*`)
3. 业务页所需布局与运行时包装(`WorkspaceLayout`、`ChatRuntime`)
这会导致 `App.tsx` 过重,职责不够单一,不利于后续维护和扩展。
---
## 二、目标(你提出的核心诉求)
你希望:
1. **除了登录与首页入口内容外**,将 `App.tsx` 中其余业务页面路由整体迁移到 `pages` 下一个新组件中。
2. 再创建一个“承接导航/入口”的页面(或路由容器),用于放置这些导航逻辑。
3. `App.tsx` 最终只保留顶层路由分发和基础 Provider,变得更薄。
> 你提到“`App.tsx 74-75 login`”,可理解为:保留登录/首页相关入口,其他工作台内容抽离。
---
## 三、重构范围
### 1)保留在 `App.tsx` 的内容
- 全局 Provider:`HashRouter`、`AppProviders`
- 登录/首页路由:
- `/`
- `/login`
- `/login/:username`
- `/landing`
- 404 路由(可留在 `App.tsx` 或交给新路由容器统一处理,二选一)
### 2)迁移出 `App.tsx` 的内容
将以下与工作台有关的路由从 `App.tsx` 抽离:
- `/workspace`(重定向)
- `/workspace/chats`
- `/workspace/chats/:thread_id`
- `/workspace/agents`
- `/workspace/agents/new`
- `/workspace/agents/:agent_id/chats`(重定向)
- `/workspace/agents/:agent_id/chats/:thread_id`
- `/workspace/scheduled`
- `/workspace/scheduled/tasks`
- `/workspace/scheduled/runs/:run_id`
以及配套的包装组件职责:
- `WorkspaceLayout`
- `ChatRuntime`
---
## 四、建议的新结构(方案)
## 方案 A(推荐):新增“业务路由容器组件”
在 `pages` 下新增一个路由容器组件,例如:
- `src/pages/WorkspaceRoutes.tsx`(或 `src/pages/AppWorkspaceRoutes.tsx`)
职责:
- 专门维护 `/workspace/*` 相关路由
- 内部统一使用 `WorkspaceLayout` 与 `ChatRuntime`
- 输出一个可被 `App.tsx` 挂载的路由节点
同时在 `App.tsx` 里只保留:
- 登录/首页/404
- 一个 `Route path="/workspace/*" element={<WorkspaceRoutes />} />`
---
## 五、“再建立一个页面放置导航”的落地解释
你说的“建立一个页面放置这些导航”,可以有两种理解:
1. **路由容器页(推荐)**:
- 不强调视觉 UI,重点是集中管理导航与路由跳转规则。
- 即上面的 `WorkspaceRoutes.tsx`。
2. **可见的导航页(可选)**:
- 例如新建 `WorkspaceHomePage.tsx`,展示聊天/Agents/定时任务入口按钮。
- 路由上把 `/workspace` 指向该页,而不是直接重定向到 `/workspace/chats/new`。
当前从你的描述看,优先建议第 1 种(先做结构整理),之后若有产品需求再做第 2 种可见导航页。
---
## 六、实施步骤(开发任务拆解)
1. 新建 `WorkspaceRoutes` 组件(`pages` 目录下)。
2. 把所有 `/workspace/*` 路由从 `App.tsx` 搬入该组件。
3. 把 `WorkspaceLayout` 与 `ChatRuntime` 移入该组件(或抽到共享 layout/runtime 文件)。
4. 在 `App.tsx` 中保留登录/首页路由,并挂载 `/workspace/*` 到新组件。
5. 校验以下访问路径行为一致:
- `/workspace` 重定向
- chats/agents/scheduled 各页面可正常进入
- 动态参数路由(`thread_id`、`agent_id`、`run_id`)正常
- 404 不受影响
6. 运行前端并做手工回归。
---
## 七、验收标准
1. `App.tsx` 明显瘦身,主要负责顶层入口路由。
2. `/workspace/*` 全部由新建组件统一管理。
3. 功能行为与改造前一致(或符合新定义)。
4. 代码可读性提升:登录入口与业务入口职责分离。
---
## 八、注意事项
1. 当前项目使用 `HashRouter`,路由写法需保持兼容。
2. `Navigate` 重定向逻辑要完整迁移,避免出现死循环或空白页。
3. `WorkspaceLayout` 与 `ChatRuntime` 的包裹层级不能错,否则可能影响侧边栏、输入区、子任务/Artifacts 状态。
4. 若后续再加模块(例如 `/workspace/settings`),优先在 `WorkspaceRoutes` 中扩展。
---
## 九、建议的命名(可直接采用)
- 新增组件文件:`src/pages/WorkspaceRoutes.tsx`
- (可选)可见导航页:`src/pages/WorkspaceHomePage.tsx`
---
## 十、后续可选优化
1. 将 `WorkspaceLayout` 抽到 `src/layouts/WorkspaceLayout.tsx`。
2. 将 `ChatRuntime` 抽到 `src/runtime/ChatRuntime.tsx`。
3. 把路由常量集中到 `src/core/router/paths.ts`,减少硬编码路径。
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,514 @@
# 多智能体规划 · 后台挂起执行 + 进度可视化 —— 分步实现方案
> 目标:在「多智能体规划」第二步增加**后台挂起**能力——把当前任务挂到后台,自动一路跑到
> 最后一步(Step3 结果绘制完成)为止;历史记录下拉框里进行中的任务显示加载动画;点击进行中
> 的任务弹出一个**大弹窗**,里面是**横向的智能体派活链路流程图**(节点 = 各席位智能体,图标 +
> 名称,不同颜色,正在发言的节点和它的连接线带加载动画);弹窗里有「查看」按钮,点击进入正在
> 进行中的任务实时观察。
---
## 0. 现状与架构事实(动手前必读)
研究自现有代码,决定了整套方案的形态。**关键结论:当前编排循环跑在前端,离开页面即中断。**
### 0.1 前端现状
| 事实 | 位置 |
|------|------|
| Step2 编排循环(leader → special → leader …;到全局 `roundtable_room_limit.max_cycles` 配置轮次进入无工具的总控正文收口)**完全由前端 hook 驱动** | `src/roundtable-planning/hooks/useStep2Orchestration.ts`(recommend / chain / dag) |
| 循环由 `currentStep===2` 的 `useEffect` 启停;离开 Step2 的 cleanup 会 `orchestrationCancelRef.current=true` + `abortAllInFlight()` 中断 | `useStep2Orchestration.ts:1468-1541`(尤其 cleanup `1534-1537`、`1471-1477`) |
| 共识判定:`leaderRes.dispatched.length===0` → `setHasConsensus(true)` | `useStep2Orchestration.ts:1091-1099` |
| 进入 Step3:手动点按钮,前置 `hasConsensus===true` | `Step2Panel.tsx:370-381`、`RoundtablePlanningPage.tsx:586-595` |
| Step3「结果绘制」:前端流式调 `roundtable-report` 智能体,写出 `outputs/方案总览.html`,`phase→"done"` 即完成 | `src/roundtable-planning/hooks/useStep3Report.ts:36,51,165,560-596,636-652` |
| 草稿持久化:`/api/roundtable-drafts`,含 step1/step2/step3 三段快照 + `furthestStep(1|2|3)`,**无显式 status 字段** | `src/roundtable-planning/api/drafts.ts:25-110,112,184-225` |
| 历史下拉 UI(触发按钮 + 列表 + 重命名/删除) | `RoundtablePlanningPage.tsx:771-892` |
| 自动保存触发点(Step1 回复完 / Step2 每轮气泡收尾 / Step3 报告保存 / 步骤前进) | `useDraftPersistence.ts:248-316` |
| 加载草稿恢复:`handleLoadDraft` → `getDraft` → `cancelAllStreams` → hydrate → `setCurrentStep(furthestStep)` | `useDraftPersistence.ts:308-368` |
### 0.2 后端现状
| 事实 | 位置 |
|------|------|
| `/api/multi-agent/init`:为各席位并行建 thread + 单例总控 `roundtable-coordinator`,SSE 返回 `seat_ready`/`coordinator_ready`/`init_done(thread_ids)` | `app/gateway/routers/multi_agent.py:647-823` |
| `/api/multi-agent/run/stream`:驱动**单轮** leader 或 special 的 LLM 执行,末尾 JSON 帧 `status`(派活列表 / `[]` 共识 / `clarification` / `error`) | `multi_agent.py:1076-1142` |
| `/api/multi-agent/report/init`:为 Step3 报告建 thread | `multi_agent.py`(report/init) |
| **后端不存在编排循环**——leader 派活由前端解释后再逐个发 `run/stream`;后端只做单轮执行 + 把派活/完成「广播」追加进各 thread 历史消息 | `multi_agent.py:24-29,487-502,1108-1142` |
| 派活格式:`agent_orchestration` 工具调用 `{agent_name, task}`(旧式 bash 解析兼容) | `multi_agent.py:525-552` |
### 0.3 可复用模板:AI 写作的「后台多阶段流程」
AI 写作已经把「后台跑多阶段流程 + 前端 SSE 订阅 + 可 resume + 定时清理」跑通了,**圆桌后台作业直接照搬这套**:
| 模板要素 | 位置 |
|------|------|
| LangGraph 图驱动多阶段(researching/writing_outline/writing_draft/reviewing/…),条件路由推进,`interrupt()` 暂停点等用户输入 | `packages/harness/deerflow/agents/ai_writing/graph.py`、`nodes/*`(`pause_material_confirm` 等 `45-290`) |
| Session 持久化表 `ai_writing_sessions`:`id/user_id/title/status/draft_*/transcript(LONGTEXT)/...`,`status∈{in_progress,done,error}` | `packages/harness/deerflow/persistence/ai_writing_sessions/model.py:14-39` |
| `transcript` 用 `PortableLongText`(MySQL LONGTEXT,避开 64KB),时间用 `BeijingDateTime` | 同上 `27-38` |
| 进度走 LangGraph Server 标准流 `stream_mode=["messages-tuple","values"]`,**graph 在 langgraph runtime 里跑,任意 worker 可 join stream**(这是后台健壮性的关键) | `ai_writing.py:1-17`、`langgraph.json:16-18` |
| Checkpointer 共享 `AsyncSqliteSaver`,落 `.deer-flow/data/checkpoints.db`(需挂数据卷) | `runtime/checkpointer/async_provider.py` |
| Cleanup cron(leader 文件锁、活跃保护、先删 CP 再删 DB、admin 手动触发) | `app/gateway/ai_writing_cleanup.py:26,34-59,111-135,193-215,307-367` |
| **多 worker 坑**:模块级内存 dict(`_event_queues`)每 worker 一份会丢会话;SSE 进程内直调会整段 buffer。解法:状态进 DB+checkpointer、SSE 走真 TCP loopback `127.0.0.1`(`trust_env=False` 禁代理) | `multi_agent.py:271-293`、`AIWritingPage.tsx` 文件头注释 §3/§5 |
### 0.4 决策(已与产品确认)
1. **后端真后台执行**:把编排循环搬到后端 run,刷新 / 关页 / 换设备都不中断。
2. **流程图节点 = 智能体派活链路**:横向排列的席位节点,正在发言的节点 + 连接线加载动画。
> ⚠️ **本方案最大的工作量在 Phase 2**:把目前跑在前端 TS 里的编排循环(`runOrchestration`/`runChainOrchestration`)
> 移植成一个后端 **LangGraph「圆桌总控编排图」**。这是与 AI 写作一致、可在 LangGraph runtime 里
> 后台跑且天然 checkpoint 的健壮路径。下文每个阶段都给出验收标准,可独立提测。
---
## 1. 总体架构
```
┌─────────────────────────────── 前端 (frontend-web) ───────────────────────────────┐
│ Step2Panel ──「后台挂起」按钮──▶ POST /api/roundtable-jobs (start) │
│ HistoryDropdown ── 进行中任务显示 spinner ──▶ 点击 ──▶ DispatchChainModal(大弹窗) │
│ DispatchChainModal ── 订阅 GET /api/roundtable-jobs/{id}/stream(SSE) │
│ 横向派活链路流程图(节点=席位, 活动节点+连线动画) ──「查看」──▶ 进入任务实时观察 │
└───────────────────────────────────────────────────────────────────────────────────┘
│ SSE 进度 / 快照
┌─────────────────────────────── 后端 (backend) ─────────────────────────────────────┐
│ /api/roundtable-jobs 路由层(start/get/stream/resume/cancel) ── 仿 ai_writing.py │
│ │ 启动后台 run │
│ LangGraph「圆桌总控编排图」 roundtable_orchestrator ── 仿 ai_writing graph │
│ init → leader_call → parse_dispatch → dispatch_seats(顺序) → loop ↺ │
│ → consensus → report_draw(写 HTML) → done (clarification 点 interrupt()) │
│ │ 每次状态转移持久化进度 │
│ roundtable_jobs 表(status/phase/dispatch_chain/active_speaker/...) + 共享 checkpointer│
│ cleanup cron (仿 ai_writing_cleanup.py) │
└───────────────────────────────────────────────────────────────────────────────────┘
```
**核心思路**:后台作业 = 一个 LangGraph 图的一次 run。图节点内部复用现有的单轮执行能力
(`multi_agent.py` 里 leader/special 的 run 逻辑),把「解释派活 → 顺序派活 → 回到 leader」的
循环从前端搬进图节点。前端从「驱动者」退化为「观察者」:通过 SSE 订阅进度渲染。
---
## 2. 数据契约(前后端共享,先定义后实现)
### 2.1 作业状态机 `JobStatus`
```
queued # 已创建,等待 worker 拉起
running # 编排进行中(Step2 派活循环 / Step3 绘制)
awaiting_input # 命中 clarification,等用户回答(interrupt 挂起)
done # 已跑到 Step3 绘制完成
error # 出错终止
cancelled # 用户取消
```
### 2.2 作业阶段 `JobPhase`(细化给流程图/进度条用)
```
initializing # 建 thread / 总控就绪
leader_thinking # 总控在决策派活
dispatching # 正在顺序派活给席位(配合 active_speaker)
consensus # 共识达成(dispatched=[])
report_drawing # Step3 报告绘制中
report_done # 绘制完成
```
### 2.3 派活链路节点 `DispatchChainNode`(流程图核心数据)
```ts
interface DispatchChainNode {
agentId: string; // 席位 agent_id(小写)
name: string; // 显示名
avatarType: string; // 复用 getAvatarTypeFor(agentId, index) → 决定颜色
order: number; // 横向排列次序(chain 模式=链条顺序;recommend 模式=席位/发言顺序)
state: 'pending' | 'active' | 'done'; // 节点状态(驱动颜色/动画)
lastSpokeCycle?: number; // 最近发言轮次(可选,做 tooltip)
}
```
### 2.4 进度事件 `JobProgressEvent`(SSE 推送的归一化事件)
```ts
type JobProgressEvent =
| { type: 'status'; status: JobStatus }
| { type: 'phase'; phase: JobPhase; cycle: number }
| { type: 'chain'; nodes: DispatchChainNode[] } // 派活链路全量/增量
| { type: 'active'; agentId: string | null } // 当前发言席位(null=总控/无)
| { type: 'consensus'; percentage: number }
| { type: 'dialogue'; bubble: Step2DialogueLike } // 新增/收尾的对话气泡(供「查看」实时渲染)
| { type: 'clarification'; question: string } // 命中澄清
| { type: 'done'; step3: DraftStep3Snapshot } // 终态:最终报告快照
| { type: 'error'; detail: string };
```
> SSE 通道可直接复用 LangGraph Server 的 `values` 流(图状态快照),由前端 hook 把 `values`
> 映射成上述归一化事件;也可在路由层做映射后再下发。**推荐前端映射**(少一层后端耦合)。
### 2.5 作业记录 `RoundtableJob`(持久化 + 列表展示)
```ts
interface RoundtableJob {
id: string;
draftId: string; // 关联的草稿
userId: string;
status: JobStatus;
phase: JobPhase;
cycle: number; // 当前轮次(0..MAX_CYCLES)
dispatchChain: DispatchChainNode[];
activeAgentId: string | null;
consensusPercentage: number;
pendingClarification: string | null;
threadIds: Record<string,string> | null; // 复用 ThreadIdMap
coordinatorName: string | null;
orchestrationMode: 'recommend' | 'chain';
chain?: { id: string; title: string } | null;
error: string | null;
createdAt: string;
updatedAt: string;
}
```
---
## Phase 1 —— 后端:圆桌作业持久化模型
**目标**:建一张 `roundtable_jobs` 表(仿 `ai_writing_sessions`),存作业状态/阶段/派活链路,
并在 `roundtable_drafts` 列表里能 join 出当前作业状态。
**涉及文件(新增/改)**
- 新增 `packages/harness/deerflow/persistence/roundtable_jobs/model.py`(ORM 模型,仿 `ai_writing_sessions/model.py:14-39`)
- 新增 `.../roundtable_jobs/sql.py`(Repository:`create / get / update_progress / list_by_user / list_older_than / delete`,仿 `ai_writing_sessions/sql.py`)
- 新增 alembic 迁移 `persistence/migrations/versions/<date>_create_roundtable_jobs.py`
- 改 `roundtable_drafts` 的列表查询:返回里带上 `status`/`jobId`(LEFT JOIN roundtable_jobs,或在 draft 行上冗余一个 `status` 字段,二选一,见下)
**步骤**
1. 字段设计(对齐 §2.5):`id(PK)`、`draft_id`、`user_id`、`status`、`phase`、`cycle(Int)`、
`dispatch_chain(PortableLongText/JSON)`、`active_agent_id`、`consensus_percentage(Int)`、
`pending_clarification(Text)`、`thread_ids(JSON)`、`coordinator_name`、`orchestration_mode`、
`chain(JSON)`、`error(Text)`、`created_at/updated_at(BeijingDateTime)`。
2. `dispatch_chain` / `thread_ids` / `chain` 用 `PortableLongText` 存 JSON 字符串,repo 层序列化。
3. 列表 join:给 `DraftMeta` 增加 `status?: JobStatus` 与 `jobId?: string`。
**推荐方案**:草稿与作业 1:1(一个草稿最多一个活跃作业),在 draft 列表查询 LEFT JOIN
`roundtable_jobs` 取最新作业的 `status`。
4. 索引:`(user_id, updated_at)`、`(draft_id)`、`(status)`(cleanup/列表用)。
**验收**
- 迁移可 `alembic upgrade head` 跑通,MySQL 上 `dispatch_chain` 为 `longtext`。
- 单测:create→update_progress→get 往返;`list_by_user` 按 `updated_at` 倒序;`list_older_than` 分批。
---
## Phase 2 —— 后端:圆桌总控编排 LangGraph 图(核心 / 最大工作量)
**目标**:把前端的编排循环移植成一个后端 LangGraph 图,可在 LangGraph runtime 里后台跑、天然
checkpoint,一路跑到 Step3 绘制完成。
**涉及文件(新增)**
- `packages/harness/deerflow/agents/roundtable_orchestrator/graph.py`(图装配,仿 `ai_writing/graph.py`)
- `.../roundtable_orchestrator/state.py`(图状态 schema:intent、selectedAgents、threadIds、coordinatorName、
mode/chain、dialogues、dispatchChain、activeAgentId、cycle、consensus、phase、step3 等)
- `.../roundtable_orchestrator/nodes/*.py`(各节点)
- 在 `langgraph.json` 注册新 assistant `roundtable_orchestrator`(仿 ai_writing assistant 注册,参考 `langgraph.json:16-18`)
**图节点设计(把前端循环逐段翻译过来)**
| 节点 | 职责 | 对应前端逻辑 |
|------|------|------|
| `init` | 复用 `_create_thread_direct` 批量建席位 thread + 总控就绪(或接收前端已建好的 `threadIds` 直接用) | `useStep2Orchestration.ts:1485-1531` / `multi_agent.py:647-823` |
| `leader_call` | 跑一轮总控(agent_type=leader),拿 `status`(派活列表 / `[]` / `clarification`) | 单轮逻辑 `multi_agent.py:1076-1142` |
| `route_after_leader`(条件边) | `clarification`→`interrupt`;有派活→`dispatch_seats`;`[]`→`consensus` | `useStep2Orchestration.ts:1091-1181` |
| `dispatch_seats` | **顺序**派活:对 dispatched 里每个席位依次跑 special run;每开始一个就更新 `activeAgentId` + 进度持久化 | `useStep2Orchestration.ts:1101-1181`(务必串行,勿并行,详见前端 §5.4 注释) |
| `clarification_pause` | `interrupt()` 挂起,`status→awaiting_input`,写 `pending_clarification` | 仿 ai_writing `pause_*` `45-290` |
| `consensus` | `setHasConsensus`、`consensus=100`,落库后进入 `report_draw` | `1091-1099` |
| `report_draw` | 跑 `roundtable-report`(先 report/init 建 thread),流式写 `outputs/方案总览.html`,产出 `DraftStep3Snapshot` | `useStep3Report.ts:91-149,636-652,560-596` |
| `done` | `status→done`、写 `step3` 进作业 + 回写草稿 step3 快照 | `RoundtablePlanningPage.tsx:613-617` |
**关键实现要点**
1. **复用单轮执行**:节点内部不要重写 LLM 调用,抽出 `multi_agent.py` 里 leader/special/report 的
单轮 run 为可被图节点直接 `await` 的内部函数(去掉 HTTP 层,进程内调 LangGraph)。
2. **派活广播**:保留现有把「总控给 X 派了活 / X 完成」追加进各 thread 历史的广播
(`multi_agent.py:487-502`),让席位读到全局上下文。
3. **MAX_CYCLES 兜底**:图里维护 `cycle`,≥8 强制收敛(对齐 `roundtable-constants.ts:13`)。
4. **chain 模式**:`orchestration_mode==='chain'` 时按 `chain.seats` 固定顺序派活,跳过总控自由决策的
部分(对齐 `runChainOrchestration` `1228-1439`)。
5. **进度落库**:每个节点结束 `update_progress(jobId, {phase, cycle, dispatchChain, activeAgentId,
consensus, dialogues_delta})`,前端 SSE 才有实时数据。
6. **dialogues 累积**:把每轮气泡写进图状态 `dialogues`,既供「查看」实时渲染,也供作业结束回写草稿 step2。
**验收**
- 用脚本(仿 `scripts/probe_ai_writing_assistant.py`)直接对图发起一次 run,不开前端,能从 intent +
selectedAgents 一路跑到写出 `方案总览.html`,作业 `status` 终态 `done`。
- 命中 clarification 时图 `interrupt`,`status=awaiting_input`,`pending_clarification` 有值。
- chain 模式按链条顺序派活,recommend 模式由总控自由派活,两条路径都能收敛。
---
## Phase 3 —— 后端:作业控制 + 进度 SSE 接口
**目标**:暴露 start/get/stream/resume/cancel,后台 run 走 LangGraph Server(任意 worker 可 join)。
**涉及文件(新增/改)**
- 新增 `app/gateway/routers/roundtable_jobs.py`(仿 `ai_writing.py` 的 CRUD + 控制壳)
- 在 gateway `app.py` 注册路由
- 新增 `app/gateway/roundtable_jobs_cleanup.py`(仿 `ai_writing_cleanup.py`)+ 在启动处挂 cron
**接口契约**
| 方法 | 路径 | 说明 |
|------|------|------|
| `POST` | `/api/roundtable-jobs` | 入参:`{draftId, intent, selectedAgents, threadIds?, coordinatorName?, model, orchestrationMode, chain?}`。建作业记录(`queued`) + 启动图 run(LangGraph Server thread),返回 `RoundtableJob` |
| `GET` | `/api/roundtable-jobs/{id}` | 作业快照(轮询兜底 / 弹窗首帧) |
| `GET` | `/api/roundtable-jobs/{id}/stream` | SSE 进度流:透传图 `values`/`messages-tuple`,或映射成 §2.4 事件下发。**走真 TCP loopback**(`multi_agent.py:271-293`),禁代理 |
| `POST` | `/api/roundtable-jobs/{id}/resume` | 入参 `{answer}`,回填 clarification → 图 resume,`status→running` |
| `POST` | `/api/roundtable-jobs/{id}/cancel` | 取消图 run,`status→cancelled` |
| `GET` | `/api/roundtable-jobs?draftId=` | 按草稿查活跃作业(页面恢复用) |
| `POST` | `/api/roundtable-jobs/admin/cleanup` | 管理员手动清理(仿 ai_writing admin cleanup `307-367`) |
**多 worker 健壮性(务必遵守,照搬 ai_writing 教训)**
- 作业状态只存 **DB + checkpointer**,**不要**用模块级内存 dict 存 per-session 状态。
- SSE 必须经真 TCP `127.0.0.1` loopback,不能 `httpx.ASGITransport(app=...)` 进程内直调(会整段 buffer)。
- 图 run 跑在 LangGraph runtime(独立于处理 HTTP 的 worker),刷新/换 worker 都能重新 join stream。
- 数据卷:`.deer-flow/data/checkpoints.db` 必须挂出,否则容器重启丢状态。
**验收**
- `POST /start` 后立刻 `GET /{id}` 能拿到 `queued/running`;关掉 SSE 再重连能继续收进度。
- 杀掉发起 start 的 worker(或多 worker 轮询),`resume`/`stream` 仍命中同一作业。
- cleanup 干跑:活跃作业永不删,先删 CP 再删 DB。
---
## Phase 4 —— 前端:作业 API 客户端 + 数据模型扩展
**目标**:前端有一层干净的作业 API 与类型,历史列表能拿到 status。
**涉及文件(新增/改)**
- 新增 `src/roundtable-planning/api/roundtable-jobs.ts`:
```ts
export async function startJob(payload: StartJobPayload): Promise<RoundtableJob>
export async function getJob(id: string): Promise<RoundtableJob>
export function streamJob(id: string, on: (e: JobProgressEvent) => void): () => void // 返回 unsubscribe
export async function resumeJob(id: string, answer: string): Promise<void>
export async function cancelJob(id: string): Promise<void>
```
- `streamJob` 复用项目现有 SSE/`streamMultiAgent` 的封装方式(`api/multi-agent.ts:403+`),把
LangGraph `values` 映射成 §2.4 的归一化事件。
- 改 `src/roundtable-planning/api/drafts.ts`:`DraftMeta` 增 `status?: JobStatus; jobId?: string`
(`drafts.ts:76-83` + 字段映射 `122-178` 加 snake_case 转换)。
- 新增 `src/roundtable-planning/lib/job-types.ts`:把 §2.1–2.5 的类型集中导出。
**验收**:`pnpm typecheck` 通过;`getJob`/`streamJob` 能拉到 Phase 3 的数据。
---
## Phase 5 —— 前端:Step2「后台挂起」按钮
**目标**:Step2 顶栏/底栏加按钮,点击把当前任务交给后端后台跑,前端停止本地循环、转为观察者。
**涉及文件(改)**
- `src/roundtable-planning/components/Step2Panel.tsx`(按钮放在现有「进入第三步」附近 `370-381`)
- `src/roundtable-planning/pages/RoundtablePlanningPage.tsx`(接线 + 观察者模式)
- `src/roundtable-planning/hooks/useStep2Orchestration.ts`(暴露「停止本地循环并交后台」的方法)
**步骤**
1. Step2Panel 加「⏼ 后台挂起」按钮,`onBackgroundSuspend` 回调。
2. 页面 `handleBackgroundSuspend`:
- `ensureDraft(2)` 拿到 `draftId`(`useDraftPersistence.ts` ensureDraft)。
- 收集当前状态:`intentReady`、`selectedAgents`、`threadIds`、`coordinatorName`、`model`、
`orchestrationMode`、`chain`(全部来自 `step2`/`step1` 现有状态)。
- `startJob(...)` → 拿到 `jobId`。
- **停止前端本地编排**:调用 `step2.stopOrchestration()` + 置一个 `backgroundedJobId` 标记,
让 `currentStep===2` 的 useEffect **不再自启本地循环**(在 `useStep2Orchestration.ts:1468-1541`
的启动条件里加 `&& !backgrounded`)。
- toast「已转入后台,可离开页面,任务会自动跑到结果绘制完成」。
- 刷新历史列表(`drafts` 重新拉,进行中项即出现 spinner)。
3. **观察者模式**:若当前停留在 Step2 且该 draft 有 running 作业,订阅 `streamJob`,把进度事件渲染成
对话气泡/活动席位(复用现有 Step2 渲染),而不是本地驱动。
**注意:避免「双跑」**——后台已接管后,前端绝不能再并行驱动同一批 thread。用 `backgroundedJobId`
互斥;加载草稿时若发现有 running 作业,直接进观察者模式。
**验收**:点「后台挂起」→ 可立即切到别的任务/路由;回来仍在跑;不会出现前后端同时派活。
---
## Phase 6 —— 前端:历史下拉框「进行中」加载动画
**目标**:历史下拉里 `status==='running'`(或 `awaiting_input`)的草稿条目显示加载动画;点击进行中
条目不直接 load,而是打开流程图弹窗。
**涉及文件(改)**
- `src/roundtable-planning/pages/RoundtablePlanningPage.tsx` 的 `HistoryDropdown`(`771-892`)
**步骤**
1. 列表项左侧名称前/后,按 `d.status` 渲染状态标记:
- `running` → 旋转的 `Loader2`(`animate-spin`)+「进行中」。
- `awaiting_input` → 呼吸点 +「待澄清」(琥珀色)。
- `done`/无 → 维持现状(显示 `Step {furthestStep}`)。
- `error` → 红点 +「出错」。
2. 点击行为分流:
- `running`/`awaiting_input` → `openDispatchChainModal(d.jobId)`(Phase 7),**不**直接 `onLoad`。
- 其它 → 维持 `onLoad(id)`。
3. 列表需要 `status`,确保 Phase 4 的 `DraftMeta.status` 已就位;下拉打开时 `refresh()` 拉最新。
**验收**:后台挂起后,历史下拉对应条目转圈;点击弹出流程图弹窗。
---
## Phase 7 —— 前端:派活链路流程图弹窗(横向 / 大弹窗 / 动画)
**目标**:大弹窗,横向排列的智能体派活链路。节点 = 席位(图标 + 名称),不同颜色;正在发言的
节点和它的连接线带加载动画;含「查看」按钮。
**涉及文件(新增)**
- `src/roundtable-planning/components/DispatchChainModal.tsx`
**实现选型**:链路是「总控 → 席位序列」的线性结构 + 需要对**单个节点和单条连线**做精确动画,
**推荐手写 flex 横向布局 + CSS 动画连接线**(轻、可控)。项目已装 `@xyflow/react@12`(带 `animated`
边)作为备选,但手写对本场景的「节点 loading + 连线流动」更直接。
**结构(手写方案草图)**
```tsx
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[88vh] flex-col gap-0 sm:max-w-5xl"> {/* 大弹窗 */}
<DialogHeader>… 任务标题 + 阶段标签(leader_thinking/dispatching/report_drawing…) …</DialogHeader>
{/* 横向链路:总控 ──▶ 席位1 ──▶ 席位2 ──▶ … ──▶ [共识] ──▶ [报告绘制] */}
<div className="custom-scrollbar overflow-x-auto py-8">
<div className="flex items-center gap-0 min-w-max px-6">
<CoordinatorNode active={phase==='leader_thinking'} />
{nodes.map((n,i)=>(
<Fragment key={n.agentId}>
<Connector active={n.state==='active'} /> {/* 活动连线:流动虚线动画 */}
<ChainNode node={n} /> {/* 活动节点:彩色+脉冲光环 */}
</Fragment>
))}
<Connector active={phase==='consensus'} />
<MilestoneNode label="共识" done={consensus===100} />
<Connector active={phase==='report_drawing'} />
<MilestoneNode label="报告绘制" active={phase==='report_drawing'} done={phase==='report_done'} />
</div>
</div>
<DialogFooter className="border-t pt-3 sm:justify-between">
<span className="text-xs text-muted-foreground">轮次 {cycle}/8 · {statusLabel}</span>
<Button onClick={onView}>查看</Button> {/* Phase 8 */}
</DialogFooter>
</DialogContent>
</Dialog>
```
**节点颜色**:`avatarType = getAvatarTypeFor(agentId, order)` → `chainTagClasses(avatarType)`
(复用 `lib/business-chain.ts:56-72` + `lib/roundtable-constants.ts`),与业务链条卡片同一套色。
**节点状态样式**
- `pending`:灰色描边、低透明度。
- `active`:席位色填充 + 外圈 `animate-ping`/脉冲光环 + 图标旋转或呼吸。
- `done`:席位色实心 + 右上角 ✓。
**连接线加载动画(active 连线)**:CSS 流动虚线(marching-ants)或渐变扫光:
```css
/* roundtable-planning.css 追加 */
@keyframes chain-flow { to { background-position: 20px 0; } }
.chain-connector--active {
background-image: linear-gradient(90deg, var(--brand-500) 50%, transparent 50%);
background-size: 20px 100%;
animation: chain-flow 0.6s linear infinite;
}
```
**数据来源**:弹窗 mount 时 `getJob(jobId)` 取首帧,随后 `streamJob(jobId, onEvent)` 实时更新
`nodes`/`activeAgentId`/`phase`/`consensus`/`cycle`;`done` 事件后停止动画、全节点置 `done`。
弹窗关闭时 `unsubscribe`。
**验收**:弹窗够大、横向滚动;活动席位节点和它左侧连线在动;阶段推进时高亮顺移;`done` 后静止。
---
## Phase 8 —— 前端:「查看」进入进行中任务并实时观察
**目标**:弹窗「查看」→ 进入该任务,停在 Step2 实时看后台进度(气泡/活动席位随 SSE 刷新),
跑完自动呈现 Step3 结果。
**涉及文件(改)**
- `RoundtablePlanningPage.tsx`(接 `onView`)
- `useDraftPersistence.ts`(`handleLoadDraft` 增「带作业」分支)
- `useStep2Orchestration.ts`(观察者渲染)
**步骤**
1. `onView`:关弹窗 → `handleLoadDraft(draftId)` 恢复该草稿到 Step2(`useDraftPersistence.ts:308-368`),
但**跳过本地编排自启**(识别到有 running 作业 → 进观察者模式,对齐 Phase 5 的互斥标记)。
2. 订阅 `streamJob(jobId)`,把 `dialogue` 事件 append 进 `step2RoundtableDialogues`、`active` 事件
驱动 `activeSpeakerId` 高亮、`consensus` 更新百分比。
3. 命中 `awaiting_input`:在 Step2 弹出澄清输入(复用现有 `pendingClarification` UI),用户回答 →
`resumeJob(jobId, answer)`(而非本地 `submitClarification`)。
4. `done` 事件:用返回的 `DraftStep3Snapshot` 走 `hydrateStep3` + 允许切到 Step3 查看报告
(`useStep3Report.hydrateSaved` `708-767`);作业列表该项变「已完成」。
**验收**:从历史「查看」进入能实时看到后台在跑;澄清能在前端回答并续跑;跑完能看到最终报告。
---
## Phase 9 —— 边界、健壮性与收尾
1. **双跑互斥**:任一 draft 同一时刻只允许一个执行者(前端本地 or 后台作业)。加载草稿/进入 Step2
前先 `GET /api/roundtable-jobs?draftId=`,有 running 就进观察者模式。
2. **后台命中澄清**:`awaiting_input` 时历史下拉显示「待澄清」徽标;流程图弹窗显示「等待澄清」;
只有「查看」进去才能回答(或在弹窗里直接给一个回答框,调用 `resumeJob`)。
3. **取消**:流程图弹窗/Step2 提供「停止后台」→ `cancelJob`,`status→cancelled`,前端可恢复本地编辑。
4. **错误恢复**:`error` 事件展示 detail;允许「重试」= 重新 `startJob`(沿用已建 threadIds)。
5. **max_cycles / 预算**:后台与前端统一读取全局 `roundtable_room_limit.max_cycles`(默认 8,2..100),一次会商启动时锁定;到达配置轮次调用 `finalize_only=True`,关闭全部工具并要求总控输出最终总结正文。不能把到顶表现成“已停止”,也不能跳过总结直接进入 Step3。
6. **多 worker**:严格遵守 Phase 3 的「状态进 DB+checkpointer、SSE 走 loopback」;部署若多 worker
需 sticky 或全靠 DB 态(推荐后者)。
7. **清理**:`roundtable_jobs` cleanup cron(活跃保护、先删 CP 再删 DB),与 draft 生命周期对齐。
8. **历史列表性能**:draft 列表 join 作业 status 时注意 N+1;用一次 LEFT JOIN 取最新作业。
---
## 端到端验证清单(提测前逐条过)
- [ ] Step2 点「后台挂起」→ 立刻可离开页面 / 切到别的任务,后台继续跑。
- [ ] 历史下拉里该任务显示加载动画(转圈)。
- [ ] 点击进行中任务 → 大弹窗、横向派活链路、活动节点+连线在动、节点不同颜色。
- [ ] 阶段推进(leader→派活→共识→报告绘制)时弹窗高亮顺移。
- [ ] 弹窗「查看」→ 进入任务实时观察气泡/活动席位。
- [ ] 后台命中澄清 → 列表「待澄清」+ 弹窗提示 + 可回答续跑(`resumeJob`)。
- [ ] 一路自动跑到 Step3「绘制完成」,最终报告可在 Step3 查看,作业 `done`。
- [ ] 浏览器刷新 / 关页重开后,任务仍在后台跑、状态可恢复(真后台验证)。
- [ ] 取消后台 → `cancelled`,无残留双跑。
- [ ] 多 worker(或杀 worker)下 stream/resume 不丢会话。
- [ ] cleanup 干跑不误删活跃作业。
---
## 工作量与排期建议
| 阶段 | 内容 | 粗估 | 依赖 |
|------|------|------|------|
| P0 | 数据契约定型(本文 §2) | 0.5d | — |
| P1 | 后端作业表 + repo + 迁移 | 1d | P0 |
| **P2** | **后端编排图(移植循环)** | **3–5d(核心难点)** | P0,P1 |
| P3 | 后端控制 + SSE + cleanup | 1.5d | P1,P2 |
| P4 | 前端作业 API + 类型 + draft status | 0.5d | P3 |
| P5 | Step2 后台挂起按钮 + 互斥 | 1d | P4 |
| P6 | 历史下拉 loading 动画 | 0.5d | P4 |
| P7 | 派活链路流程图弹窗 | 1.5d | P4 |
| P8 | 「查看」实时观察 + 澄清续跑 | 1.5d | P5,P7 |
| P9 | 边界/健壮性/清理 | 1d | 全部 |
> 建议先打通 **P1→P2→P3** 的后端最小闭环(脚本验证图能后台跑到出报告),再做前端 P4–P8。
> P2 是整条链路成败的关键,务必先用脱离前端的探针脚本(仿 `scripts/probe_ai_writing_assistant.py`)跑通。
---
## 附:关键参考代码索引
- 前端编排循环(待移植到后端):`useStep2Orchestration.ts:992-1204,1228-1439,1468-1541`
- 共识判定 / 进 Step3:`useStep2Orchestration.ts:1091-1099`、`Step2Panel.tsx:370-381`、`RoundtablePlanningPage.tsx:586-595`
- Step3 绘制完成标志:`useStep3Report.ts:51,165,560-596,636-652`
- 草稿模型 / API / 自动保存 / 加载恢复:`api/drafts.ts:25-110,184-225`、`useDraftPersistence.ts:248-316,308-368`
- 历史下拉 UI:`RoundtablePlanningPage.tsx:771-892`
- 后端单轮执行 / 派活 / 广播:`multi_agent.py:647-823,1076-1142,525-552,487-502`、loopback `271-293`
- AI 写作模板:`agents/ai_writing/graph.py`、`ai_writing_sessions/model.py:14-39`、`ai_writing.py`、`ai_writing_cleanup.py:307-367`、`AIWritingPage.tsx` 文件头注释
- 颜色体系复用:`lib/business-chain.ts:56-72`、`lib/roundtable-constants.ts`(`getAvatarTypeFor`)
- 流程图备选库:`@xyflow/react@12`(已安装)
```
Loaded 100 of 3905 files, more files were not shown because too many files have changed in this diff. Show more