Compare commits

..
1493 Commits
Author SHA1 Message Date
董宏凯 428588f1c4 代码提交 2026-08-05 22:20:46 +08:00
董宏凯andCursor 1a080311bd fix(maf): harden phase-3 dispatch recovery and participant writes
Make ensure_participants concurrent-safe, restore clarification checkpoints without re-planning, and only create threads for validated seats.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 21:47:46 +08:00
董宏凯 ddf83f7728 代码提交 2026-08-03 19:27:54 +08:00
董宏凯 d93cc62806 Merge branch 'master-nj' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-dev 2026-08-03 12:13:59 +08:00
董宏凯 4fcd96af29 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-dev 2026-08-03 12:12:01 +08:00
董宏凯andCursor 99642fca6c feat(maf): conversation-driven MAF roundtable (R1/R2) + server-owned stage-3 dispatch
Backend:
- Conversation API at /api/maf-roundtable/conversations: create/list/detail,
  paginated messages, atomic send+run start, owner-only isolation,
  admin read-only diagnostic access
- SSE real-time event stream (GET /conversations/{id}/stream) backed by
  ConversationEventHub + conversation_events store; multi-worker deployment doc
- Deterministic server-owned stage-3 dispatch contracts (dispatch_contracts.py):
  routing resolved from trusted MAF deployment config instead of manager-chosen
  agent ids; config.yaml keeps stage-3 routing deployment-owned
  (default_manager_agent_id / seat ids / business_routes / max_seats_per_run)
- Conversation persistence (conversations/messages stores) + v2 migration script
- Tests: conversations, conversation stream, migration, phase3 conversation dispatch

Frontend:
- Vitest test infra for MAF (vitest.maf.config.ts + test:maf script) with
  component tests for ApprovalCard/RunHeader/SessionsPage and use-maf-events
- Session form lib, flow-graph dialog / run-detail / sessions page updates,
  routes and nav tweaks
- Docs: R0 legacy interaction baseline mapping, updated implementation plan

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 12:09:47 +08:00
董宏凯 df408831e5 feat(maf): unified safe display + decision lock for approvals
Stage-6 MAF frontend foundation plus P1 approval safety hardening:

- Add lib/safe-display.ts: single-source safeDisplayJson that deletes
  sensitive keys (never renders as ***), recurses with depth/array/field/
  string caps, returns hiddenCount + truncated.
- MafApprovalCard & MafActionAuditPanel both use safeDisplayJson; remove
  private sanitize duplicates. Panels hide entirely when nothing is left.
- Lock the card on both approve AND reject (resuming state) since the
  backend advances the workflow on either decision; add a decisionLockRef
  sync guard so a double-click before React re-render cannot fire a second
  mutate. Status text becomes '正在同步工作流…'.
- Stage-6 base shipped here as prerequisite: self-contained maf-flow-graph
  (no roundtable-planning dep), MafFlowGraphDialog/MafFactLedgerPanel/
  MafActionAuditPanel, shared risk-theme/action-audit/approval-state/
  run-resume libs, mergeBySeq export, canResume wiring, TButton icon fixes.
- Tests import real functions only; 48 pass (adds 8 safeDisplayJson cases).
2026-08-02 22:55:27 +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
fengxiangdebaozi 889a97a04d feat(maf): Phase 6 - migrate frontend workbench to tdesign-react and extract shared desensitize hook 2026-08-02 14:33:57 +08:00
董宏凯 a55992e31c fix(maf): harden phase 5 approval safety 2026-08-02 14:32:49 +08:00
董宏凯andCursor f82363d81f feat(maf): Phase 5 - action coordinator, approval flow, frontend MAF roundtable pages
- Backend: action_coordinator, capability_snapshot, event_normalizer, tool_executor updates
- Backend: approved_tool_executor with write guard, action leases, migration script
- Frontend: maf-roundtable module (API client, event timeline, approval cards, fact flow panel)
- Frontend: MafRoutes, MafSessionsPage, MafRunDetailPage
- Tests: action_leases, migration_phase5, phase5_entry_e2e, real_write_e2e/http_e2e
- Docs: update implementation plan

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 13:07:21 +08:00
董宏凯 21c4c898e7 feat(maf): complete resilient roundtable workflow 2026-08-02 00:23:25 +08:00
董宏凯 bd4131b4e2 feat(maf): add secure roundtable workflow runtime 2026-08-01 17:51:53 +08:00
董宏凯andCursor e690475e6e feat(maf-roundtable): add Phase-1 multi-agent roundtable infrastructure
Ship an independent, feature-flag-gated MAF roundtable skeleton with six
isolated tables, atomic single-transaction run launch/cancel, owner-scoped
read/write split, shared config enums, and HTTP/concurrency regression tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 01:07:05 +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
xu hd a8a545690f Merge branch 'xuhd' into 'master'
feat: 智能体创建流程优化与管理员记忆页面

See merge request knowledge-base-bj/deerflow-server!31
2026-05-21 03:50:02 +00:00
xuhdandClaude Sonnet 4.6 3748513996 feat: 智能体创建流程优化与管理员记忆页面
- 创建智能体页面:保存后自动跳转列表页、技能列表增加搜索过滤框
- Bootstrap 模式:开放全部技能可见性,注入专属提示词(skill_list 匹配意图、禁止 skill_manage)
- 管理员记忆页面:新增 AdminMemoryPage 及路由,支持查看/编辑用户记忆条目
- 内存配置与管理员用户接口同步更新

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 11:43:59 +08:00
董宏凯 18c2a4122f Merge branch 'dhk-1' into 'master'
更新

See merge request knowledge-base-bj/deerflow-server!30
2026-05-21 00:32:37 +00:00
董宏凯 04664c8d42 更新 2026-05-21 08:31:33 +08:00
董宏凯 628bbe14a8 Merge branch 'dhk-1' into 'master'
样式修改

See merge request knowledge-base-bj/deerflow-server!29
2026-05-20 14:47:15 +00:00
董宏凯 abae7c9d67 样式修改 2026-05-20 22:46:37 +08:00
董宏凯 eeee00f6cd 样式修改 2026-05-20 22:17:59 +08:00
吉鑫升andClaude Opus 4.7 6971ea5f9c fix: 修正 config.yaml 中 minimax 模型条目缩进,避免 YAML 解析失败
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 19:45:52 +08:00
吉鑫升 cee38f93c8 Merge remote-tracking branch 'origin/master' into ji 2026-05-20 19:38:00 +08:00
吉鑫升andClaude Opus 4.7 fa5a6b8176 fix: 技能详情弹窗宽度自适应
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 19:37:46 +08:00
董宏凯 97f8940b15 样式修改 2026-05-20 17:21:29 +08:00
董宏凯 556d23ade5 样式修改 2026-05-20 17:13:59 +08:00
吉鑫升 313290b22c Merge remote-tracking branch 'origin/master' 2026-05-20 17:06:06 +08:00
吉鑫升andClaude Opus 4.7 d339db4799 feat: 公开定时任务页面、Word 导出、定时任务实时刷新与技能详情重构
- 新增 /public/scheduled-tasks/:taskId 公开只读访问页与对应的
  /api/public/scheduled-tasks 后端路由(无需登录)
- 新增对话整体 / 单条消息 / Markdown 工件 "另存为 Word (.docx)" 能力
- 定时任务列表与运行列表在任务执行中自动轮询刷新,并新增"正在执行"标记
- 定时任务运行消息接口在事件存储为空时回退到 LangGraph checkpoint,
  让正在执行的任务也能立即看到提示词与流式输出
- 技能详情对话框由折叠面板改为 Tab 切换(Detail / SKILL.md),
  并支持 Rendered / Raw 切换、一键复制
- config.yaml 增加 database (MySQL) 与 checkpointer (SQLite) 配置块

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:04:58 +08:00
董宏凯 03dff2ce77 样式修改 2026-05-20 15:21:23 +08:00
董宏凯 c2c44f8d29 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-20 15:10:09 +08:00
董宏凯 13130c7f27 展开收起动画 2026-05-20 15:09:50 +08:00
董宏凯 30b986bb33 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!28
2026-05-20 06:06:30 +00:00
董宏凯 0196b0a445 文档修改 2026-05-20 14:05:53 +08:00
董宏凯 8edd06fb67 文档配置文件修改 2026-05-20 14:03:26 +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
董宏凯 4fbd0bb5c5 ai写作 2026-05-20 13:06:29 +08:00
董宏凯 c2563661d0 Merge branch 'dhk-1' into 'master'
容错处理

See merge request knowledge-base-bj/deerflow-server!27
2026-05-20 04:54:00 +00:00
董宏凯 f358cfb7c7 容错处理 2026-05-20 12:51:04 +08:00
董宏凯 ef11d3e0ed Merge branch 'dhk-1' into 'master'
报错兜底

See merge request knowledge-base-bj/deerflow-server!26
2026-05-19 14:56:01 +00:00
董宏凯 f44e2ccf52 报错兜底 2026-05-19 22:54:36 +08:00
吉鑫升 7e75c5b9b9 Merge remote-tracking branch 'origin/master' into ji 2026-05-19 19:58:59 +08:00
董宏凯 15ae11f966 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!25
2026-05-19 11:54:42 +00:00
董宏凯 226439ef36 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-19 19:54:18 +08:00
董宏凯 81aca93b81 章节问答 2026-05-19 19:51:44 +08:00
吉鑫升andClaude Opus 4.7 777c3b0079 fix: 定时任务执行过程实时刷新——RunJournal 增加按时间 flush
RunJournal 原本只在缓冲满 20 条或运行结束时才把事件落库,短运行会在结束前一直查不到消息,导致定时任务执行详情页的「执行过程」一直显示「暂无执行消息」。

新增 _FLUSH_INTERVAL_SECONDS=3s 的按时间 flush(由 _put 驱动);flush 失败时退回缓冲并重新抛出以便区分成败;flush 成功后若缓冲仍有残留则补一次 flush,失败则不重试避免空转。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 18:18:14 +08:00
董宏凯 ab85e4df72 效果优化 2026-05-19 18:10:15 +08:00
吉鑫升 cf8185498a Merge branch 'ji' 2026-05-19 17:22:45 +08:00
吉鑫升andClaude Opus 4.7 bf34b7df4e fix: 修复 Memory V2 合并导致的启动崩溃
master 的 Memory V2 重构删除了 memory/updater.py,admin_users.py 仍从中导入 get_memory_data 导致启动 ImportError。改用 BuiltinFileProvider 读取 V2 的 USER.md / 各 agent MEMORY.md;前端 MemoryBucketView 同步改为渲染 V2 条目列表。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 17:22:27 +08:00
吉鑫升andClaude Opus 4.7 028c5a34e6 fix: 速度胶囊每轮只显示一次 + 技能调用按 run 合并统计
速度胶囊:原本每条 AI 消息都渲染,agentic 多轮 LLM 调用会出现多个胶囊。改为只在每轮 turn-final 消息(下一条 human 之前的最后一条 AI 消息)显示。

技能统计:tool_call_metrics 改为按 (run_id, skill_name) upsert 合并——同一 run 内同一技能的多次调用/重试合并为一行;任一成功即记成功,全部失败则记一行 error 并累积所有报错信息;非技能调用不受影响。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 17:22:17 +08:00
xuhd c0ea0b0f5a 标题生成 2026-05-19 16:30:41 +08:00
吉鑫升 4c38055d38 Merge remote-tracking branch 'origin/master' into ji 2026-05-19 16:28:39 +08:00
吉鑫升andClaude Opus 4.7 87fcbc5bfb chore: vite 构建产物使用相对路径 (base: "./")
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 16:28:29 +08:00
ZyGuo 043a1aab21 update git ignore 2026-05-19 16:12:12 +08:00
xu hd 9f86c8e40d Merge branch 'xuhd' into 'master'
feat(memory): Memory V2 重写 - 可插拔 provider + Hindsight 集成

See merge request knowledge-base-bj/deerflow-server!22
2026-05-19 08:10:25 +00:00
xuhd 3330da0e59 记忆的config.yaml修改 2026-05-19 16:06:51 +08:00
xuhd 64492bec43 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-05-19 16:05:11 +08:00
董宏凯 2402a84c71 检索逻辑修改 2026-05-19 15:14:51 +08:00
董宏凯 294d06f22b 文档修改 2026-05-19 13:00:40 +08:00
xuhd d6e788dc89 修复 2026-05-19 09:55:20 +08:00
xuhd 070cd07199 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-05-19 09:40:19 +08:00
xuhd 4ded0ccd4f 补充 2026-05-19 09:38:20 +08:00
xuhd 6253a2bca9 修改优化 2026-05-19 09:38:00 +08:00
吉鑫升 bd1efd8026 Merge branch ji into master: 工具/技能调用统计 + 用户活动审计 + 标签多选筛选 2026-05-19 09:28:44 +08:00
吉鑫升andClaude Opus 4.7 4940e0d8ed feat: 工具/技能调用统计 + 用户活动审计 + 标签多选筛选
- 任务1: 用户管理/定时任务管理移入左下角菜单, 从侧边栏删除原入口
- 任务2: 管理员查看用户问答(读 LangGraph checkpoint)与记忆, 新增 admin_users 路由与审计页
- 任务3: 标签筛选改为顶部多选标签栏(OR), agents/skills/scheduled_tasks 三端
- 任务4: 新增 tool_call_metrics 表 + ToolMetricsMiddleware + tool-metrics 路由,
  工具/技能调用统计并入大模型统计页, 含错误分类
- 技能识别: lead agent 经 read_file 加载 /mnt/skills/<cat>/<name>/SKILL.md 调用技能,
  中间件扫描工具参数里的 skills/{public,custom}/{name}/ 路径还原 skill_name
- 单元测试 tests/test_tool_metrics_middleware.py (18 项全过)
- 附: SQLite->MySQL 切换后清理脚本

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:59:15 +08:00
董宏凯 8d6cc65530 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!21
2026-05-18 15:08:25 +00:00
董宏凯 b8adefbb88 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-18 23:08:02 +08:00
董宏凯 2c56a84bb7 接口报错异常处理 2026-05-18 23:06:59 +08:00
董宏凯 613e22d6ca Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!20
2026-05-18 14:53:35 +00:00
董宏凯 73e76fc72f 依赖安装 2026-05-18 22:46:57 +08:00
董宏凯 1e5e2581c8 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-18 22:45:25 +08:00
董宏凯 b25c4e33cb 异常处理 2026-05-18 22:41:44 +08:00
董宏凯 17b28f43f8 大纲规划 2026-05-18 21:43:48 +08:00
吉鑫升andClaude Opus 4.7 e3cde9be25 feat: 定时任务运行详情执行过程视图 + 管理员下载删除 + MySQL 迁移修复
定时任务:
- 运行详情页新增「执行过程」标签页,按 agent_run_id 拉取该次运行的
  agent 消息(GET /scheduled-tasks/runs/{id}/messages),运行中每 4s
  自动刷新,可观察卡住的任务停在哪一步
- 详情页「返回」按钮回到来源列表(普通/管理员)并重新选中原任务
- 管理员可下载、删除任意用户的执行记录(DELETE /runs/{id} 加管理员兜底)

MySQL 兼容修复:
- 合并迁移 20260518_06 汇合 ai-writing 与 thread-shares 两个 head
- 20260517_02 改用 SQLAlchemy Core 构造,规避保留字 key 的 1064 报错
- list_messages_by_run 各事件存储补 user_id 形参以保持接口一致

测试: 新增 test_scheduled_task_admin_run_delete.py

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 21:13:58 +08:00
吉鑫升 449703a6f0 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	offline-backend-20260512/backend/app/gateway/deps.py
2026-05-18 19:35:16 +08:00
吉鑫升andClaude Opus 4.7 358d5c72a6 feat: 业务库切换 MySQL + 修复定时任务运行详情递归与重名 500
- 业务 ORM 数据支持 MySQL 后端(asyncmy),新增 PortableJSON/
  BeijingDateTime 可移植列类型、迁移脚本与切库脚本
- 修复 GET /api/scheduled-tasks/runs/{id} 的 _load_run 无限递归
  (误调用自身,应委托 service.get_run)导致的 RecursionError 500
- 定时任务名按用户唯一:create/update/admin_update 主动校验,
  冲突抛 DuplicateTaskNameError,路由转 409 而非裸 IntegrityError 500
- 补充回归测试 test_scheduled_task_run_lookup / _name_uniqueness

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 19:34:14 +08:00
董宏凯 abd2ced4b4 Merge branch 'dhk-1' into 'master'
ai写作

See merge request knowledge-base-bj/deerflow-server!19
2026-05-18 09:55:50 +00:00
董宏凯 49e5aaea6b Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-18 17:47:33 +08:00
董宏凯 d1f431d121 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-18 17:45:10 +08:00
fengxiangdebaozi fd759d6845 依赖更新 2026-05-18 17:44:08 +08:00
董宏凯 5be5531722 容错显示 2026-05-18 17:41:51 +08:00
吉鑫升 2a4fccde70 Merge remote-tracking branch 'origin/likun' 2026-05-18 15:41:36 +08:00
吉鑫升 d6f018e581 Merge branch 'master' into ji 2026-05-18 15:39:57 +08:00
吉鑫升andClaude Opus 4.7 e0c1cb6581 feat: 定时任务管理 + 会话只读分享
定时任务:
- 管理员可查看/编辑/删除/触发全部用户的定时任务(新增 /api/scheduled-tasks/admin/* 接口与管理页)
- 卡死任务恢复:单次执行超 30 分钟超时重试(最多 3 次),耗尽后标记 failed;看门狗回收服务重启遗留的「执行中」任务

会话分享:
- 新增「只读链接」分享模式,生成公开免登录的只读对话快照页(/share/:code)
- 公开接口 /api/public/shares/* 提供对话快照与图片附件

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:39:40 +08:00
xuhdandClaude Opus 4.7 f80a00e211 feat(skills): curator 面板加 pinned 计数 + 运行时输出技能名日志
- get_curator_status 的 agent_created_skills 增加 pinned 计数,与
  active/stale/archived 正交;前端技能进化面板同步展示「被钉住」一项
  (curator/types.ts、skill-evolution-panel.tsx、zh-CN/en-US/types i18n)。
- run_curator_review 每次运行时把涉及的技能名输出到日志:新增
  _log_scanned_skills(扫描到的技能名)与 _candidate_skill_names
  (候选技能名),logger 与 curator_log 双写。

新增 test_curator_status_counts.py、test_curator_skill_logging.py。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:25:13 +08:00
xuhdandClaude Opus 4.7 4aee413680 revert(memory): Hindsight document_id 改回每轮独立文档
commit dba821a 把 document_id 从带时间戳改成按 thread_id 确定性派生
(同一 thread 累积成一个文档)。经复核,改回原来的带微秒时间戳写法 ——
每轮对话的 retain 重新落到各自独立的 Hindsight 文档。

retain_every_n_turns 轮次节流(turn_index)与 aiohttp 客户端泄漏修复
保持不动,仅回退 document_id 这一处。

test_hindsight_provider.py 的 TestDocumentId 按"每轮独立文档"重写。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:24:13 +08:00
likun 2a91e2e7ad 知识库补充到p6 2026-05-18 15:18:22 +08:00
xuhd dba821a70e @
fix(memory): 修复 Hindsight provider 生命周期的三处缺陷

HindsightProvider 被 build_memory_manager 每轮重新构造,以下三个问题
都源于这个无状态特性未被正确处理:

1. document_id 每轮漂移 —— 原 _reset_retain_batch 用微秒时间戳拼接,
   导致同一 thread 的每轮 retain 落到不同文档,文档数随对话轮数线性膨胀。
   改为按 thread_id 确定性派生 (thread-{thread_id}),同一 thread 累积成一份。

2. retain_every_n_turns 失效 —— 进程内 _turn_counter 每轮被 initialize
   重置,retain_every_n_turns > 1 时永不触发。新增 turn_index 参数贯穿
   sync_turn/sync_all,由 MemoryMiddleware 按对话历史 (count_user_turns)
   算出并传入;_turn_counter 仅作缺省退路。

3. aiohttp ClientSession 泄漏 —— 缓存的客户端从不 shutdown,且 _run_coro
   每次新建事件循环使缓存客户端失效,触发 "Unclosed client session"。
   改为客户端即开即关:_run_with_client 在 finally 保证关闭,_client_factory
   作为可覆盖的测试注入点。

测试:test_hindsight_provider.py 全量重写 (含 TestDocumentId /
TestRetainEveryNTurnsAcrossRecreation / TestClientLifecycle),
新增 test_memory_message_processing.py,test_memory_manager.py 补
turn_index 透传用例。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@
2026-05-18 14:34:22 +08:00
董宏凯 836dd73446 容错处理 2026-05-18 11:29:40 +08:00
xuhd 8f88427d4e Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-05-18 10:25:51 +08:00
xuhd 817585a4ce Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd-v2 2026-05-18 10:22:23 +08:00
xuhdandClaude Opus 4.7 0386f54449 feat(skills): 接入技能使用埋点,修复活跃技能被 curator 误归档
技能正文不进 system prompt,Agent 按 Progressive Loading 用 read_file
加载 SKILL.md 才算真正用到该技能。此前 read_file 与 skill_manage 的
patch/edit 都不更新 .usage.json,curator 的年龄流转据 latest_activity_at
判断闲置,导致每天都在用的 agent 创建技能在 30/90 天后被误标陈旧并归档。

- sandbox/tools.py: 新增 _custom_skill_name_from_path / _record_skill_read,
  read_file 读取 custom 技能目录下文件时 bump_use(best-effort,失败不影响主流程)
- skill_manage_tool.py: patch/edit 经 _bump_patch_best_effort 记 patch_count
- tests/test_skill_usage_signals.py: 12 项,覆盖路径解析、埋点与异常兜底

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 10:22:15 +08:00
吉鑫升 4761677676 Merge remote-tracking branch 'origin/master' into ji 2026-05-18 10:03:49 +08:00
吉鑫升andClaude Opus 4.7 f61d053010 feat(skills): 新增技能详情字段并统一发布图标
- 技能新增 detail 字段(skills 表新增列 + Alembic 迁移),
  由管理员或技能发布者编辑,内置/公开技能仅管理员可编辑
- 新增 PUT /api/skills/{name}/detail 接口,GET/列表接口返回 detail
- 新增可复用的技能详情弹窗组件,支持 Markdown 渲染与内联编辑
- 智能体创建/编辑选技能、智能体卡片技能徽章均可查看技能详情
- 将定时任务/智能体/技能的发布图标统一为 Globe/Lock

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 10:03:37 +08:00
fengxiangdebaozi 8440d02198 Merge branch 'dhk-1' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-18 10:03:06 +08:00
xuhd ebcdf847d2 222 2026-05-18 10:02:00 +08:00
fengxiangdebaozi 5c553aae19 文档更新 2026-05-18 09:58:34 +08:00
董宏凯 0af8ca5f78 历史记录回显 2026-05-17 22:55:01 +08:00
董宏凯 52ba178c4e 字数要求修改 2026-05-17 22:33:43 +08:00
董宏凯 166016a741 检索结果过程添加 2026-05-17 22:01:29 +08:00
董宏凯 20786e690d 自动下滑 2026-05-17 21:33:24 +08:00
董宏凯 c19417a706 暂停继续 2026-05-17 21:19:12 +08:00
董宏凯 b768e0affb 改写弹窗出现的位置 2026-05-17 20:38:35 +08:00
董宏凯 05ff10df1b ai改写调用 2026-05-17 20:18:11 +08:00
董宏凯 a0a6227368 文章类型添加 2026-05-17 19:50:52 +08:00
董宏凯 918e65d8d3 ai写作 2026-05-17 19:29:10 +08:00
董宏凯 6cab62d140 作家大纲拖拽调整顺序 2026-05-17 18:00:07 +08:00
董宏凯 9526268f1f 加载框顺序调整 2026-05-17 17:55:42 +08:00
董宏凯 016ec1877a ai写作 2026-05-17 17:39:41 +08:00
董宏凯 772e75f04d ai写作 2026-05-17 17:25:18 +08:00
董宏凯 10d7190ea4 ai写作 2026-05-17 14:22:25 +08:00
董宏凯 cc8703577d ai写作 2026-05-17 13:08:45 +08:00
董宏凯 4533755704 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-16 22:03:41 +08:00
董宏凯 da4a08dfe1 智能选中文字 2026-05-16 22:00:34 +08:00
xuhd 48ddbf0412 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-05-16 15:51:49 +08:00
xuhdandClaude Opus 4.7 39def1c20b feat(skills): curator 健壮性加固 + 评审模型可配置 + 手动触发体验
调度健壮性:
- 技能进化总开关 skill_evolution.enabled 真正生效;CuratorConfig
  与 CuratorSubConfig 默认 enabled 改为 false(显式 opt-in)
- 新增 per-user 运行锁(.curator_state 的 running/started_at),
  防定时器与手动触发并发重复运行;6h stale 检测防进程残留死锁
- maybe_run_curator 改用 ThreadPoolExecutor 限并发(上限 5),
  防首次部署所有用户同时到期的惊群
- 首次运行持续失败时按 6h 退避重试,不再每个 tick 烧 LLM 配额
- should_run_now 时间解析容忍 naive 时间串;损坏的 last_run_at
  触发重跑而非永久死锁
- SkillStore 新增 list_published_names 批量接口,curator 一轮
  只查一次 published,取代逐技能查库

LLM 评审超时:
- _run_llm_review 给 agent.invoke 套整体超时
  (curator.review_timeout_seconds,默认 600s),超时中止本次评审
  并在 curator 日志输出,curator 正常收尾、释放运行锁
- copy_context 把 user 上下文传入工作线程

模型可配置:
- 新增 curator.model_name;curator 评审与技能安全审核共用该模型,
  未配置则回退主模型
- 移除独立的 moderation_model_name 配置
- 前端进化面板新增模型下拉选择器

手动触发体验:
- /api/curator/run 派发后台线程前先预检,返回 {triggered, reason},
  不再无论开关状态都提示"已开始"
- 前端:总开关/curator 开关未开时禁用"立即执行"按钮,
  被预检拦下时按原因(开关未开 / 已有任务在跑)给出准确提示

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 15:50:15 +08:00
董宏凯 e8a31b5d37 代码修改 2026-05-16 14:24:44 +08:00
董宏凯 5a25dd08f6 Merge branch 'dhk-2' into 'master'
文档修改

See merge request knowledge-base-bj/deerflow-server!18
2026-05-16 01:07:56 +00:00
fengxiangdebaozi b34219ce86 文档修改 2026-05-16 09:07:18 +08:00
董宏凯 05548b0fa6 Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!17
2026-05-15 15:28:24 +00:00
董宏凯 e08e7be24c Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-15 23:27:48 +08:00
董宏凯 1be600155b openCanvas 2026-05-15 23:27:34 +08:00
xuhd be757b1f2f @
feat(skills): skill_list 可见性过滤 + skill 只读工具常驻 + 进化面板对照展示

- skill_list:默认 lead agent 改为只暴露未归档、且内置或属于当前用户的技能;
  自定义 agent 仍严格按白名单。SkillStore 不可用时降级放行全部自定义技能。
- prompt:注入系统提示词的技能列表剔除已归档(state=archived)技能。
- tools:skill_list/skill_view 只读工具改为常驻提供;skill_manage 写工具仍按
  生效配置(含 per-user 覆盖)的 skill_evolution.enabled 门控。
- curator:should_run_now 解析异常时改为不运行;get_curator_status 返回上次
  LLM 建议与实际工具调用两份记录,供前端对照。
- 前端:技能进化面板新增建议 vs 实际动作对照展示 + 配套 i18n。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@
2026-05-15 20:39:13 +08:00
xuhdandClaude Opus 4.7 d592e1e535 fix(skills): curator 自我进化周期调度 + 并发/配置/安全修复
调度:
- app.py 新增常驻 curator 调度器,每小时检查一次"需不需要进化",
  替代原来"仅启动跑一次";多 worker 下用跨平台文件锁做 leader 选举,
  只有一个进程跑调度;启动延迟 5 分钟避开启动高峰

curator 逻辑修复:
- C1: should_run_now / apply_automatic_transitions / get_curator_status
  调用 _get_curator_config 时传 user_id,使 per-user 配置在运行时生效
- C3: usage.py 的 .usage.json 读-改-写加进程内锁,bump_* 改回调式,
  避免 curator 多线程并发丢状态更新
- C4a: curator 受限版 skill_manage 在工具层屏蔽 delete,
  堵住绕过 skill_archive 安全网删技能的口子
- C4b: 进化记录同时保存 LLM 自述(suggestions)与真实工具调用(actual_actions)
- 无候选技能时跳过 LLM 评审,省掉无意义的模型调用

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 19:31:05 +08:00
xuhd e381e9f52e 222 2026-05-15 18:00:11 +08:00
吉鑫升 3b951efd13 Merge remote-tracking branch 'origin/master' into ji 2026-05-15 16:54:56 +08:00
吉鑫升 33161c5bad Merge remote-tracking branch 'origin/likun' into ji
# Conflicts:
#	frontend-web/src/components/workspace/artifacts/artifact-file-detail.tsx
#	frontend-web/src/components/workspace/code-editor.tsx
#	frontend-web/src/components/workspace/input-box.tsx
#	frontend-web/src/pages/ChatPage.tsx
#	offline-backend-20260512/backend/app/gateway/routers/artifacts.py
2026-05-15 16:54:10 +08:00
xuhd 8b6236c796 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd-v2 2026-05-15 16:42:48 +08:00
xuhdandClaude Opus 4.7 a59d80d7f3 feat(i18n): 全局将「专家」文案改为「智能体」
统一智能体功能的 UI 文案:侧边栏、智能体页、新建/保存流程、
审批卡片、登录提示及后端审批消息中的「专家」均改为「智能体」。
保留 prompt 人设、QA 子应用等非该功能语义的「专家」表述。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:42:40 +08:00
xuhdandClaude Opus 4.7 a5c76591ac feat(i18n): 全局将「专家」文案改为「智能体」
统一智能体功能的 UI 文案:侧边栏、智能体页、新建/保存流程、
审批卡片、登录提示及后端审批消息中的「专家」均改为「智能体」。
保留 prompt 人设、QA 子应用等非该功能语义的「专家」表述。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:42:11 +08:00
xuhd c2a975af9e @
feat(i18n): 全局将「专家」文案改为「智能体」

统一智能体功能的 UI 文案:侧边栏、智能体页、新建/保存流程、
审批卡片、登录提示及后端审批消息中的「专家」均改为「智能体」。
保留 prompt 人设、QA 子应用等非该功能语义的「专家」表述。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@
2026-05-15 16:41:44 +08:00
xuhd ab48cd5b55 111 2026-05-15 16:36:02 +08:00
吉鑫升andClaude Opus 4.7 ed4909a28d chore: 纳入 skill_evolution 运行时配置文件
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:29:26 +08:00
吉鑫升 afc517b3a7 Merge remote-tracking branch 'origin/master' into ji
# Conflicts:
#	frontend-web/src/components/workspace/agents/agent-gallery.tsx
#	frontend-web/src/components/workspace/settings/skill-settings-page.tsx
2026-05-15 16:27:56 +08:00
likun de9f6b6711 feat: 新增写作画布系统 2026-05-15 16:22:04 +08:00
吉鑫升andClaude Opus 4.7 646cb8caeb feat: 标签管理功能 + 问答前缀对用户隐藏
标签管理:
- 新增 tags/tag_assignments 持久化层、迁移、/api/tags 路由
- 标签分智能体/技能/定时任务三类, 仅同类型可互打, 仅 admin 可增删改与打标签
- 三类资源列表支持按名称模糊检索与按标签筛选(走后端查询参数)
- 前端新增标签管理页、TagPickerDialog(点击即时绑定)、彩色标签 chip

问答前缀:
- 前缀不再拼入消息 content, 改存 additional_kwargs 由 PromptPrefixMiddleware
  在调模型前临时注入, 用户界面看不到前缀但模型仍收到
- 修正 thread_existed 闸门导致首轮前缀被跳过的问题

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:19:08 +08:00
likun d533ddde88 feat: 补充知识库内容p4 2026-05-15 16:17:55 +08:00
xuhdandClaude Opus 4.7 9664cb653a feat(frontend): 记忆从设置弹窗移至侧边栏独立入口
- 新增 MemoryPage 及路由 /page/workspace/memory
- 侧边栏在「技能」下方新增「记忆」入口
- 设置弹窗注释掉「记忆」标签页

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:47:49 +08:00
xuhd 1574d44cc3 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-05-15 15:26:16 +08:00
xuhdandClaude Opus 4.7 6981fc06ca feat(skills): 点击技能展示 SKILL.md 详情弹窗
- 后端新增 GET /api/skills/{name}/content 接口,返回公共/自定义技能的 SKILL.md 原文
- 前端技能行内容区可点击,弹窗以等宽原文展示 SKILL.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:23:34 +08:00
xuhdandClaude Opus 4.7 12798c00bc feat(frontend): 设置弹窗移除「技能」标签页
技能管理已有侧边栏独立入口(/page/workspace/skills),设置弹窗内的入口冗余,移除。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:10:43 +08:00
xuhdandClaude Opus 4.7 ebb6be816b feat(frontend): 技能/专家广场展示调整 + 通知合并入设置菜单
- 技能与专家「广场」标签只展示内置和已发布项,Tab 顺序调为「我的」在前并默认选中
- 「智能体」全量更名为「专家」
- 通知由侧边栏铃铛改为「设置和更多」菜单内的弹窗入口,合并通知列表与通知设置

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:08:56 +08:00
likun ae4e4f67c2 新增大模型知识库技能 2026-05-15 14:51:16 +08:00
xuhdandClaude Opus 4.7 013aafde17 feat(frontend): 记忆页面迁移到 Memory V2
前端记忆模块整体迁到后端 Memory V2 接口,修复调旧端点 /api/memory
返回 404 的问题。

- core/memory/{types,api,hooks}.ts 重写为 V2 数据模型与端点
  (USER.md / MEMORY.md 条目增删改、配置读写、Hindsight 检索)
- memory-settings-page.tsx 重写:用户画像 + 工作笔记两区的条目
  增删改、记忆设置面板(白名单字段)、Hindsight 检索面板
- 工作笔记按专家隔离,顶部专家下拉(默认助手 + useAgents 列出的
  用户专家),专家列表取自 agents 注册表
- settings-dialog 记忆分区移到技能下方
- i18n(zh-CN/en-US/types)memory 文案整体替换

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 14:14:08 +08:00
董宏凯 050b1ad78e 代码提交 2026-05-15 14:08:01 +08:00
xuhdandClaude Opus 4.7 21a76f5e7c refactor(memory): Memory V2 P3 - 舍弃后台抽取 + Gateway 端点收口
P3 在 P1/P2 基础上完成 Memory V2 收尾:

舍弃后台抽取:
- 删除 updater/queue/storage/prompt/summarization_hook 五个模块
- 移除 background_extraction 配置段、扁平字段兼容、storage 字段
- 理由:Hindsight auto_retain 已自动留存每轮对话,后台抽取冗余

Hindsight 召回注入改用 wrap_model_call:
- 由 before_model 改为 wrap_model_call —— 召回只注入单次模型请求、
  不落持久 state,从根上消除 <memory-context> 泄漏给前端的风险
- builtin frozen snapshot 仍走系统提示词

Gateway 端点收口为 /api/memory/v2*:
- 删除旧 facts/history 端点 (/api/memory、/memory/facts 等)
- 新增 entries 增删改 (POST/PUT/DELETE /memory/v2/entries)
- 新增 POST /memory/v2/search —— Hindsight recall/reflect 检索代理
- client.py memory 方法重写为 V2 等价方法

文档同步更新 CLAUDE.md 与 MEMORY_V2_DESIGN_ZH.md。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 13:08:18 +08:00
xuhdandClaude Opus 4.7 f9d7610679 feat(memory): Memory V2 重写 - 可插拔 provider + Hindsight 集成
以 Hermes 的可插拔记忆架构为骨架重写 deerflow 记忆模块,兼容原有
结构化数据,并新增 Hindsight 作为外部记忆后端。

P1 - 抽象层 + builtin 本地记忆:
- MemoryProvider 抽象基类 + MemoryManager 编排层(builtin + ≤1 外部)
- BuiltinFileProvider:USER.md/MEMORY.md 二元存储、字符配额、文件锁、
  原子写、frozen snapshot
- memory 工具(LangChain @tool):LLM 主动写入用户画像/工作笔记
- 记忆内容安全扫描(注入/外渗模式 + 不可见 unicode)
- memory_config 改为嵌套结构 + 旧扁平字段兼容 + per-user 三层覆盖
- 迁移脚本 migrate_memory_to_v2.py:旧 memory.json -> USER.md/MEMORY.md
- Gateway 新增 /api/memory/v2 与 v2/config 端点(用户可配置白名单字段)

P2 - Hindsight 外部 provider:
- HindsightProvider:双 bank 隔离(user bank 跨 agent 共享 + work bank
  agent 私有)、并发召回合并、auto-retain、on_memory_write 镜像
- hindsight_recall/reflect/retain 三个 LangChain 工具
- MemoryMiddleware.before_model 注入 Hindsight 动态召回
- context/tools/hybrid 三种 memory_mode
- hindsight-client 作为可选依赖,未装时自动退回纯 builtin

注入走系统提示词(builtin frozen snapshot)+ before_model(Hindsight
动态召回)。后台抽取保留但默认关闭,P3 期重接入。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 12:15:55 +08:00
吉鑫升 aeba15eb16 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji
# Conflicts:
#	frontend-web/src/pages/WorkspaceRoutes.tsx
#	offline-backend-20260512/backend/packages/harness/deerflow/persistence/models/__init__.py
2026-05-15 11:21:48 +08:00
董宏凯 b81f64a253 Merge branch 'dhk-2' into 'master'
Dhk 2

See merge request knowledge-base-bj/deerflow-server!16
2026-05-15 02:43:25 +00:00
fengxiangdebaozi a0d04cba50 文档修改 2026-05-15 10:42:44 +08:00
xu hd 43bdbcf89c Merge branch 'xuhd' into 'master'
feat(skills): 自我进化后端 — curator 配置可编辑 + 运行日志可读

See merge request knowledge-base-bj/deerflow-server!15
2026-05-15 01:36:33 +00:00
xuhdandClaude Opus 4.7 6947a3ffa7 chore(tests): ignore tests/ 目录 + 同步现有测试到新 skill_archive 签名
- .gitignore: 新增 offline-backend-20260512/backend/tests/* 规则,
  让后续新增的测试文件不再误进入版本控制
- test_skills_multitenancy.py: 同步上次 feat(skills) 提交里
  skill_archive(name, reason) 必填 reason 的签名变更

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 00:03:07 +08:00
xuhdandClaude Opus 4.7 62d525dae7 feat(skills): 自我进化 - 软归档/恢复 + Agent 归属 + 状态分层 UI
后端:
- 新增 PUT /api/skills/custom/{name}/state 与 /pinned 软归档/恢复 + 钉选 API
- skill_manage 工具: agent 创建写 DB 归属; 删除清理 .usage.json + DB row + cascade 引用; 加 ownership 预校验
- curator 全部软归档(文件保留在 custom/), 加 reason 必填(中文), 修 user_context 跨线程传播 / 协程泄漏 / archive 文件不再移动
- LLM 评审接 ToolErrorHandlingMiddleware, 工具异常自动重试不中止本轮; 替换 create_react_agent 为 create_agent
- skill_list 按当前 agent config.yaml 的 skills 字段过滤(custom agent), lead agent 仍可见全部
- 自我进化提示词对齐 Hermes 风格: 主动询问保存, reason 强制中文且面向用户
- 控制台日志增强: 自动归档/标过时/LLM 合并/删减建议 都按条目输出原因

前端:
- 技能管理页 Tab 改「全部 / 我的」, 正确包含他人发布的 custom 技能(修复 isCustom 互斥 bug)
- 新增「过时 N / 归档 N」右侧抽屉(恢复/查看/立即归档 ⋯ 菜单)
- 新增徽章: 钉选 / 来源(Agent 创建 / 用户上传) / 使用次数展示
- 内置技能徽章修复(原 isBuiltin && isCustom 永远 false)
- 自我进化日志 run_started sentinel 在前端展示为中文分隔条
- 移除冗余 enabled 开关(归档已覆盖此能力, 减少术语)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 00:00:52 +08:00
xuhd f8bc74b27f Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-05-14 23:45:10 +08:00
董宏凯 044370f13c 沙箱内容可保存 2026-05-14 22:12:20 +08:00
xuhd a2c45492cb 2222 2026-05-14 20:45:22 +08:00
xuhd 9a67ca7c03 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd 2026-05-14 20:45:02 +08:00
xuhdandClaude Sonnet 4.6 40cd8a24af feat: admin skill public upload + user management page
- Admin users can choose to install skills to public (built-in) or custom category via UI radio selector in InstallSkillDialog
- Backend: SkillStorage.ainstall_skill_from_archive accepts target_category param; non-admin 403 on public install
- Backend: AgentStore/SkillStore add count_owned(user_id); UserRepository/LocalAuthProvider add list_users()
- Backend: GET /api/v1/auth/users endpoint (admin-only) returns all users with skill_count and agent_count
- Frontend: admin-only "用户管理" nav item in sidebar; /page/workspace/admin/users route with user table
- i18n: added sidebar.users and adminUsers section in zh-CN/en-US

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 20:40:23 +08:00
吉鑫升andClaude Sonnet 4.6 28948975db Merge: 解决 ScheduledTaskRunDetailPage 合并冲突
保留 HEAD 的编辑功能 import(useCallback、Edit3、Loader2、Save、X),
同时采用 b78672 中的 useRouteNavigate 自定义导航 hook。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 19:29:35 +08:00
fengxiangdebaozi 1ce1db9689 代码处理 2026-05-14 19:28:07 +08:00
fengxiangdebaozi 86cdeed6ef Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-2 2026-05-14 19:26:01 +08:00
fengxiangdebaozi d6ec0afbd6 路由嵌套修改 2026-05-14 19:25:39 +08:00
吉鑫升 3ea33e1dee 大模型速度增加提示 2026-05-14 19:12:14 +08:00
xuhdandClaude Opus 4.7 3e6e3c08d5 feat(skills): curator 三条件过滤 — agent 创建 + 未发布 + 无引用
Curator 之前只过滤 source=='agent',导致两类 skill 仍会被自动归档:
1. owner 已 published 的 skill(user B 在用,结果被 curator 收走)
2. 加进 agent.skills 但 .usage.json 活动不够频繁的 skill

新规则:curator transitions 和 LLM 合并候选**只**作用于同时满足
三条件的 skill —— source=='agent' + published==False + 不被任何
agent.config.yaml 的 skills 字段引用。

curator.py
- 新 helper _collect_referenced_skill_names():扫所有
  .deer-flow/agents/*/config.yaml 把 skills 字段聚合成 set,一次
  curator run 内只调一次
- 新 helper _is_skill_published(name):通过 SkillStore 查 published
  状态,失败时返回 False(保守降级到旧行为)
- 新 helper _eligible_for_curation(name, entry, owned_set, referenced_set)
  三条件合一判定
- apply_automatic_transitions 应用三条件过滤;返回的 counters 加
  skipped_referenced / skipped_published 计数
- _render_candidate_list 应用同一过滤,LLM 看不到 protected skill
- _make_skill_archive_tool safety net:即使 LLM 编造名字调 archive,
  工具内部再做一次"被引用 + published"检查,违规拒绝并记 warning

测试 tests/test_skills_multitenancy.py 新增 5 用例:
- test_curator_skips_skill_referenced_by_any_agent
- test_curator_skips_published_skill
- test_curator_archives_orphan_unpublished_skill
- test_skill_archive_tool_refuses_referenced_or_published
- test_collect_referenced_skill_names_aggregates_from_disk

跑测试:tests/test_skills_multitenancy.py 17/17,全套 36/36 全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 18:49:22 +08:00
xuhdandClaude Opus 4.7 6155a2ec2b fix: curator + notifications react-query cache 按 user_id 隔离
切换账号在同一 tab 里时,旧 cache key (["curator","config"] 等) 会
让新账号"看到"上一个账号的值。如果用户没意识到、直接点保存,就会
把上一个账号的配置原样写到新账号的 per-user JSON 里去。

修复:在 useCuratorKeys / useNotificationKeys hook 里读
getStoredAuth().user_id 织进 queryKey。每个用户拥有独立 cache
桶,切换账号绝不命中对方的数据。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 18:20:41 +08:00
董宏凯 4e0787ec77 Merge branch 'dhk-2' into 'master'
页面接口整体修改

See merge request knowledge-base-bj/deerflow-server!14
2026-05-14 10:14:39 +00:00
fengxiangdebaozi 8ecc32da6d 页面结构修改 2026-05-14 18:13:58 +08:00
xuhdandClaude Opus 4.7 eb41da78f2 fix: 四处 router.push 缺 /page 前缀导致 404
HashRouter 顶层路由是 /page/*,所有 workspace 子路由必须带这个前缀
才能命中。以下四处 router.push 字面量遗漏,点击后落到 NotFoundPage:

- skill-evolution-panel.tsx 返回技能按钮
- NewAgentPage.tsx 返回 agents
- NewAgentPage.tsx 创建后“开始对话”
- agent-card.tsx 列表卡片“聊天”按钮

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 17:56:32 +08:00
xuhdandClaude Opus 4.7 a508969331 chore: 忽略 skill_evolution.json 运行时文件
前端 PUT /api/curator/config 会把 per-user 覆盖写到
backend/skill_evolution.json(全局 fallback),属于运行时
数据不该入库。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 17:46:36 +08:00
xuhdandClaude Opus 4.7 99febda256 feat(skills/notifications): 多租户阶段 4 — 测试 + 前端
后端:
tests/test_skills_multitenancy.py(12 个用例,全部通过)
- SkillStore: 可见性 / 全局重名拒绝 / owner-only update+delete /
  admin override / ensure_legacy 仅补 NULL owner
- 路由助手 _get_editable_skill_or_raise / _get_owned_skill_or_raise
  的 owner / admin / 403 / 404 分流
- cascade_skill_unpublished_or_deleted:
  · unpublish 同时扫两个用户的 agent,剥掉 skill;自己改自己不发
    通知,其他人收 agent_skill_removed
  · admin_takedown 额外给 skill owner 发 skill_taken_down
- NotificationStore CRUD + unread_count + 跨用户隔离
- 同步版 apply_automatic_transitions 用户隔离:A 跑 curator 不
  动 B 的 skill;curator_log per-user 分桶

前端 — core/notifications/{types,api,hooks,index}.ts
- 类型对齐 routers/notifications.py 的 NotificationItem
- listNotifications / getUnreadCount / markRead / markAllRead /
  deleteNotification
- useNotifications / useUnreadCount(refetchInterval=30s) / mutation 钩子

前端 — components/workspace/notification-bell.tsx
- 顶部铃铛图标 + 未读红点(>99 显示 99+)
- 复用 DropdownMenu 作为弹层(项目暂无 Popover 原语)
- 列表项:未读蓝点 + 标题 + body + 相对时间,悬停露出删除按钮
- 标记单条已读 / 全部已读 / 删除
- 接入 workspace-nav-menu.tsx,作为 SidebarMenuItem 放在设置入口上方

前端 — Skill 多租户字段
- core/skills/type.ts 加 owner_user_id / published / builtin
- core/skills/api.ts 加 setSkillPublished + deleteCustomSkill
- core/skills/hooks.ts 加 useSetSkillPublished + useDeleteCustomSkill

前端 — settings/skill-settings-page.tsx
- 抽出 SkillRow 子组件,每项渲染 owner badge(内置/我的/来自他人/
  已发布),样式抄自 agent-card.tsx 的 isBuiltin/isOwned/isFromOthers
- canManage = isOwned || isAdmin;canTogglePublish 同上但排除内置
- 发布/取消发布按钮(Eye / EyeOff),调用 setSkillPublished
- 删除按钮 + 二次确认 Dialog,调用 deleteCustomSkill
- 启用开关保持原样

前端 — i18n
- types.ts: 新增 NotificationsTranslations + Translations.notifications;
  settings.skills 加 badgeBuiltin/badgeMine/badgeFromOthers(+Title) /
  badgePublished(+Title) / publishAction / unpublishAction /
  publishSuccess / unpublishSuccess / deleteAction / deleteConfirm /
  deleteSuccess
- zh-CN.ts / en-US.ts 同步补齐对应文案

验证
- PYTHONPATH=. uv run pytest tests/test_skills_multitenancy.py -v →
  12 passed in 2.08s
- 与现有 test_agents_backend / test_skill_evolution_runtime /
  test_skills_install_upload 并行跑:41 通过 + 1 个 pre-existing 失败
  (test_validate_rejects_missing_skill_md 期望 "SKILL.md" 但收到
  "Skill archive is empty",与本期改动无关)
- pnpm typecheck:本次新增/修改的文件零新增错误;剩余报错全部为
  pre-existing 的 next/link、next/navigation 别名声明缺失、
  workspace-nav-menu.tsx 的 SettingsSection 类型不匹配、nextra
  缺失、markdown-docx 第三方库等

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 17:35:02 +08:00
fengxiangdebaozi 543d78e040 路由调整 2026-05-14 17:24:45 +08:00
xuhdandClaude Opus 4.7 4ef96c7930 feat(skills): 多租户阶段 3 — Curator + 配置 per-user
curator_log.py
- ring buffer 从单一 deque 改为 dict[user_id -> deque],每个用户
  自己的运行日志互不可见
- start_new_run / record / get_recent / clear 全部接 user_id
  关键字参数;未传时落入 __default__ 桶兼容旧调用
- 新增 clear_all() 用于跨用户清理(仅测试用)

curator.py
- 状态文件路径从 skills/.curator_state 改为
  .deer-flow/users/{user_id}/.curator_state(per-user 隔离)
- 所有公开 API 接受 user_id 参数:should_run_now /
  apply_automatic_transitions / _render_candidate_list /
  run_curator_review / _curator_thread_target /
  get_curator_status / _make_skill_archive_tool / _run_llm_review
- 新增 _list_user_owned_skill_names(user_id):通过 SkillStore
  查询当前用户拥有的 skill 名集合,用于过滤 transitions / LLM
  candidates,保证 user A 跑 curator 不会动 user B 的 skill;
  SkillStore 不可达时退化为"全部 agent-created skill"(兼容旧部署)
- _get_curator_config(user_id) 通过 load_skill_evolution_config_for_user
  叠加 per-user override,让阈值/间隔/moderation_model 也是 per-user
- maybe_run_curator 启动时枚举 UserRow,按用户检查 should_run_now
  并各起一个 daemon 线程跑

skill_evolution_runtime.py
- 全局 backend/skill_evolution.json 语义保留作为 fallback
- 新增 per-user API:resolve_user_path / load_user_overrides /
  save_user_overrides / get_user_overrides_mtime,文件落到
  .deer-flow/users/{user_id}/skill_evolution.json
- 新增 load_skill_evolution_config_for_user(user_id):读全局
  SkillEvolutionConfig 作为 baseline,浅合并 per-user JSON,
  返回 Pydantic 实例。验证失败时回落到 baseline

routers/skills.py
- /api/curator/status / run / config GET+PUT / logs 全部接
  _current_user_id 注入运行上下文
- update_curator_config 改为 per-user:保存到
  users/{user_id}/skill_evolution.json,不再 reset_app_config
- _build_curator_config_response 接受 SkillEvolutionConfig 实例
  (而不是 AppConfig)以适配 per-user 合并结果

旧 19 个测试继续通过;未引入新依赖。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 17:09:05 +08:00
fengxiangdebaozi 7a7c99f752 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-2 2026-05-14 16:51:58 +08:00
fengxiangdebaozi 6b1f17d6a8 页面导入 2026-05-14 16:51:32 +08:00
xuhdandClaude Opus 4.7 cf191ef874 feat(skills/notifications): 多租户阶段 2 — 路由 + 级联 + 启动迁移
后端工作:

deps.py
- 挂载 skill_store / notification_store 到 app.state
- 启动时 set_notification_store(...) 注入到 harness sender;
  关闭时清空,保证测试和 embedded 模式不留状态
- 加 get_skill_store / get_notification_store FastAPI 依赖

routers/skills.py
- 加 _current_user_id / _is_admin_user / _get_owned_skill_or_raise /
  _get_editable_skill_or_raise(对齐 routers/agents.py)
- SkillResponse 加 owner_user_id / published / builtin 字段,
  _skill_to_response 接受 SkillStore 记录映射
- GET /api/skills 与 GET /api/skills/custom 改 per-user 可见性过滤
- POST /api/skills/install + /install-upload 预解析 archive 名校验
  全局 name 不被他人持有;安装后 ensure_legacy 注册 owner=current
- DELETE /api/skills/custom/{name} 走 _get_editable_skill_or_raise,
  调 cascade(owner 自删 = delete,admin 跨用户 = admin_takedown),
  SkillStore.delete / delete_admin 同步清除 DB 记录
- 新增 PUT /api/skills/custom/{name}/published 切换发布状态;
  从 published → unpublished 时触发 cascade(unpublish / admin_takedown)

skills/cascade.py(新)
- 扫所有 .deer-flow/agents/{id}/config.yaml,把指定 skill 从其 skills
  数组移除,并通过 deerflow.persistence.notifications.notify 给受
  影响 agent 的 owner 发站内信;admin 强制下架时另给 skill owner 发
  一条
- 操作类型:unpublish / delete / admin_takedown,对应不同文案

routers/notifications.py(新)+ app.include_router
- GET /api/notifications(unread_only / limit)
- GET /api/notifications/unread_count(红点用)
- POST /api/notifications/{id}/read
- POST /api/notifications/read_all
- DELETE /api/notifications/{id}

app.py lifespan
- _sync_legacy_skills(app):每次启动扫 skills/custom/ 把没在 DB
  的 skill 落库为 admin owner + published=True,幂等、非阻塞失败
- 调用顺序:_ensure_admin_user → _sync_legacy_skills → 启动 curator

测试:19 个旧用例继续通过;阶段 4 会写 test_skills_multitenancy.py

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 16:24:42 +08:00
董宏凯 f6d3d013fd Merge branch 'dhk-2' into 'master'
样式修改

See merge request knowledge-base-bj/deerflow-server!13
2026-05-14 08:04:28 +00:00
fengxiangdebaozi e6ad3c414f 页面布局调整 2026-05-14 16:01:25 +08:00
xuhdandClaude Opus 4.7 8162719e36 feat(skills/notifications): 多租户阶段 1 — 持久化层
新增两套 persistence 模块,仿 persistence/agents/ 模板:

1. persistence/skills/
   - SkillRow ORM (PK=name, owner_user_id, published, timestamps)
   - SkillStore 抽象:list_visible / get_visible / get_any /
     get_owned / create / ensure_legacy / update / update_admin /
     delete / delete_admin
   - SqlAlchemy 实现 SkillRepository
   - MemorySkillStore 用于测试
   - 可见性 = owner OR published OR builtin

2. persistence/notifications/
   - NotificationRow ORM (id, user_id, type, title, body, payload JSON,
     read, created_at)
   - NotificationStore 抽象:create / list_for_user / unread_count /
     mark_read / mark_all_read / delete
   - SqlAlchemy 实现 NotificationRepository
   - MemoryNotificationStore 用于测试
   - sender.notify(user_id, type, ...) 全局接口;harness 不能 import
     app.*,所以用 set_notification_store / get_notification_store
     注入模式

3. persistence/models/__init__.py 注册 SkillRow + NotificationRow

后续阶段会接入路由、cascade、curator per-user 重构、前端。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:44:36 +08:00
xuhdandClaude Opus 4.7 f5bc02d598 fix: skills 路由两个小修复
skills.py:
- update_curator_config 直接 await get_curator_config() 报错
  ('Depends' object has no attribute 'skill_evolution')。FastAPI 路由
  默认参数 Depends(...) 只在请求时被框架解析,直接调用拿到的是依赖标记。
  抽出 _build_curator_config_response(config) 让 GET 和 PUT 共用。

skill_manage_tool.py:
- 模型把 action='list' 当成可用动作误调 skill_manage 报
  Unsupported action。补两个 read-only 别名 list/view,分别委派到
  skill_list_tool 和 skill_view_tool,docstring 同步更新。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:43:26 +08:00
fengxiangdebaozi 139dfb76e4 bug修改 2026-05-14 14:59:12 +08:00
fengxiangdebaozi f4769c4046 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-2 2026-05-14 14:28:31 +08:00
fengxiangdebaozi fea3cc741f 系统合并 2026-05-14 14:28:17 +08:00
xuhdandClaude Opus 4.7 4e764350a4 feat(agents): 创建专家页面加模型选择
NewAgentPage 在两处加 Select 下拉:
- 左侧聊天框上方 "当前对话模型":透传给 useThreadStream 的
  context.model_name,控制当前 bootstrap 对话调用的 LLM
- 右侧表单 "模型":写入 agent.model,控制专家保存后被使用时调用
  的 LLM

两个下拉互相独立,复用 useModels() 拉 /api/models。页面加载完
模型列表后自动 seed 到列表第一个(与 config.yaml 全局默认对齐),
用户可随时切换。

杂项:.gitignore 忽略 skills/ 与 hermes-agent-main/ 运行时目录。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 12:59:10 +08:00
xuhd c63811367e 123 2026-05-14 12:45:04 +08:00
xuhdandClaude Opus 4.7 4cc8b3198b fix: 修复 setup_agent 创建专家流程的多个问题
后端 (setup_agent_approval_middleware.py):
- 拦截策略从 wrap_tool_call + Command(goto=END) 改为
  after_model + jump_to="end"。在 tool_node 执行前直接终止图,
  避免模型并行调多个 tool_call 时 Command 输出被稀释、graph
  路由不稳定的问题(症状:审批 ToolMessage 发出后流不结束)。
- 用 @hook_config(can_jump_to=["end"]) 装饰器声明跳转能力,
  否则 LangChain 不会为该 hook 构造 conditional edge。

前端 (NewAgentPage.tsx):
- 聊天阶段不再调 ensureAgent / POST /api/agents,placeholder
  agent 不再落库;agent 仅在用户点右上角“保存”时创建。
- 自动生成的占位名 "未命名专家-xxx" 不再回写到输入框,保持空白
  直到用户输入或 setup_agent 审批回填。
- handleApproveSetupAgent 仅把模型 propose 的 payload 填入表单,
  不再 PUT /api/agents/{id};落库交给手动保存按钮。
- onToolEnd 不再 getAgentWithRetry —— 工具被 middleware 拦截、
  根本不会执行,没有 agent 状态可拉。清理对应死代码(getAgent
  import、wait()、AGENT_READ_RETRY_DELAYS_MS、getAgentWithRetry)。
- 路由跳转补齐 /page 前缀:返回按钮、“开始对话”按钮。
- 右侧表单:SOUL.md textarea 加 max-h-[400px],技能列表外框加
  max-h-[240px],各自 overflow-y-auto,避免长内容撑高整列。

前端 (agent-card.tsx):
- 列表卡片“聊天”按钮的跳转路径补齐 /page 前缀,避免点击后 404。

无新依赖。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 12:35:49 +08:00
xuhdandClaude Opus 4.7 5c6ac06656 feat(skills): 自我进化前端 — Skills 独立侧边栏 + /skills/evolution 页面
UI 重构:
- settings-dialog.tsx:把 Skills section 从设置弹窗移除
- workspace-nav-chat-list.tsx + WorkspaceRoutes.tsx + SkillsPage.tsx:
  Skills 提升为独立侧边栏导航项,/workspace/skills 路由直接渲染
  SkillSettingsPage(同事原型已就绪)
- skill-settings-page.tsx:顶部追加 "自我进化" 跳转按钮

自我进化页面:
- /workspace/skills/evolution 子路由 → SkillEvolutionPage 包装
- skill-evolution-panel.tsx:三段式
  · 状态卡:启用/暂停徽章 + 累计运行次数 + 上次运行时间/摘要 +
    技能计数 (total/active/stale/archived) + 立即执行按钮
  · 配置表单:enabled / curator.enabled / interval_hours /
    stale_after_days / archive_after_days / moderation_model_name
    本地暂存 → 保存调 PUT,热生效
  · 日志面板:拉 GET /api/curator/logs,2 秒自动刷新,monospace
    展示,warning 黄、error 红
- core/curator/api.ts + hooks.ts + types.ts:TanStack Query 包装
  status / config (GET/PUT) / run / logs

i18n:
- types.ts 新增 settings.skillEvolution.* 类型签名
- zh-CN.ts / en-US.ts:状态卡 / 配置表单 / 日志面板文案,
  以及 settings.skills.goToEvolution

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 12:00:54 +08:00
xuhdandClaude Opus 4.7 9b6b94d919 feat(skills): 自我进化后端 — curator 配置可编辑 + 运行日志可读
后端骨架:
- curator.py / usage.py / skill_tools.py:基于使用计数的生命周期管理
  + LLM 合并/归档建议(同事已有原型,集中提交)
- skill_evolution_config.py:CuratorConfig 嵌套模型
- app.py:启动时按间隔触发 curator 后台线程
- tools.py:开启自我进化时一并注册 skill_list / skill_view 工具
- skill_manage_tool.py:agent 创建技能时标记 source=agent

本次新增:
- skill_evolution_runtime.py:skill_evolution.json 读写,原子写入
- app_config.py:把 overrides 深合并到 AppConfig.skill_evolution,
  并把 overrides 的 mtime 纳入缓存失效条件,前端 PUT 后热生效
- curator_log.py:进程内 ring buffer (maxlen=200),所有 record/get
  操作内部兜异常,保证 logging 永远不会让 curator 跑挂
- curator.py 关键节点插桩:run_started / 自动转换计数 / 候选数 /
  LLM agent invoke / 解析结果 / archive 动作 / run complete
- routers/skills.py:GET/PUT /api/curator/config(写到
  skill_evolution.json + reset_app_config)+ GET /api/curator/logs

测试:
- tests/test_skill_evolution_runtime.py:overrides 往返、损坏 JSON
  容错、AppConfig 合并、ring buffer 线程安全、record 异常吞咽

杂项:
- .gitignore:忽略 .deer-flow/* 与 skills/* 等运行时目录
- uv.lock:跟随依赖锁更新
- 清理已废弃的 agent runtime 数据 SOUL.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 12:00:21 +08:00
董宏凯 8f4af5ece4 Merge branch 'dhk-2' into 'master'
添加提示词权限

See merge request knowledge-base-bj/deerflow-server!12
2026-05-14 03:52:27 +00:00
fengxiangdebaozi 2d9248889f Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-2 2026-05-14 11:51:51 +08:00
fengxiangdebaozi 804f37dcfa 提示词权限配置 2026-05-14 11:51:29 +08:00
董宏凯 bf98713a55 Merge branch 'dhk-2' into 'master'
推荐问题接口添加

See merge request knowledge-base-bj/deerflow-server!11
2026-05-14 03:08:14 +00:00
fengxiangdebaozi 2f2ba44c7c 添加推荐问题修改接口 2026-05-14 11:07:28 +08:00
fengxiangdebaozi 62292500ba Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-2 2026-05-14 10:52:08 +08:00
fengxiangdebaozi a7f1e89ce9 提示词修改 2026-05-14 10:51:29 +08:00
董宏凯 20c7e2841c Merge branch 'dhk-2' into 'master'
提示词修改

See merge request knowledge-base-bj/deerflow-server!10
2026-05-14 02:45:46 +00:00
fengxiangdebaozi c79f5c5a7a 样式修改 2026-05-14 10:42:37 +08:00
xu hd d3771ed31f Merge branch 'xuhd' into 'master'
feat: skill 名字允许下划线分隔

See merge request knowledge-base-bj/deerflow-server!9
2026-05-14 02:42:15 +00:00
xuhdandClaude Opus 4.7 230eec1baf feat: skill 名字允许下划线分隔
放宽 skill 命名校验:除连字符外也接受下划线作为分隔符,首尾和连续
分隔符的限制扩展到 _ 与混合分隔(--、__、-_、_- 都拒绝)。前置
frontmatter 校验与存储层正则同步放宽。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 10:41:37 +08:00
xu hd 0bae393e07 Merge branch 'xuhd' into 'master'
fix: /login/admin 自动把历史 admin 账户升级为 admin 角色

See merge request knowledge-base-bj/deerflow-server!8
2026-05-14 02:28:42 +00:00
xuhdandClaude Opus 4.7 434cf40b36 fix: /login/admin 自动把历史 admin 账户升级为 admin 角色
历史上以 username=admin 自动注册的账户曾被建成 system_role=user,
登录时按 username 修正一次,避免老库需要手工改表。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 10:25:24 +08:00
xu hd 7417a1c950 Merge branch 'xuhd' into 'master'
feat: admin可删除内置专家

See merge request knowledge-base-bj/deerflow-server!7
2026-05-14 02:18:33 +00:00
xu hd 799ccbe300 Merge branch 'xuhd' into 'master'
feat: admin可编辑内置专家 + agent列表Tab分组

See merge request knowledge-base-bj/deerflow-server!6
2026-05-14 02:06:42 +00:00
xuhdandClaude Opus 4.7 43044232bb feat: admin可删除内置专家
复用 _get_editable_or_raise 分支,给 AgentStore 增加 delete_builtin,
路由按 edit_mode 决定走 delete 还是 delete_builtin;前端 agent-card
为 admin 显示内置 agent 的删除按钮。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 09:53:13 +08:00
董宏凯 4567db8836 Merge branch 'dhk-2' into 'master'
页面结构调整

See merge request knowledge-base-bj/deerflow-server!5
2026-05-14 01:43:08 +00:00
fengxiangdebaozi e286e59431 页面结构调整 2026-05-14 09:42:12 +08:00
fengxiangdebaozi 65e89a4248 样式修改 2026-05-14 09:36:45 +08:00
fengxiangdebaozi db63086c38 文档修改 2026-05-14 09:35:15 +08:00
xuhdandClaude Sonnet 4.6 2abdf28eba feat: admin可编辑内置专家 + agent列表Tab分组
- /login/admin 登录时自动赋予 admin 角色,允许编辑内置专家
- agent列表页新增「全部」(内置+已发布) 和「自己的」两个Tab

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:16:18 +08:00
董宏凯 2476f04a26 Merge branch 'dhk-1' into 'master'
接口地址填写

See merge request knowledge-base-bj/deerflow-server!4
2026-05-13 14:29:34 +00:00
董宏凯 e458f1eab4 接口地址填写 2026-05-13 22:29:05 +08:00
fengxiangdebaozi b15b2649f8 文档修改 2026-05-13 22:22:59 +08:00
fengxiangdebaozi 4fce7ba09a Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server 2026-05-13 22:19:02 +08:00
fengxiangdebaozi 1a1369f115 代码提交 2026-05-13 22:18:55 +08:00
董宏凯 9434ffabdc Merge branch 'dhk-1' into 'master'
Dhk 1

See merge request knowledge-base-bj/deerflow-server!3
2026-05-13 14:17:47 +00:00
董宏凯 6aeb428796 Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1 2026-05-13 22:17:25 +08:00
董宏凯 8cabf32ebe 提交 2026-05-13 22:16:59 +08:00
董宏凯 85a98fcfd6 Merge branch 'dhk-v3' into 'master'
ceshi1

See merge request knowledge-base-bj/deerflow-server!2
2026-05-13 14:09:07 +00:00
董宏凯 aa1f81a30a ceshi1 2026-05-13 22:08:37 +08:00
fengxiangdebaozi 1c50c73aa4 样式修改 2026-05-13 21:41:13 +08:00
fengxiangdebaozi 6cc28c7edd Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server 2026-05-13 21:25:40 +08:00
fengxiangdebaozi 1c2cf768f8 样式修改 2026-05-13 21:25:29 +08:00
吉鑫升 481e718d86 Merge remote-tracking branch 'origin/master' 2026-05-13 21:02:27 +08:00
吉鑫升andClaude Opus 4.7 29f74afbf6 fix(scheduler): give every scheduled run its own throwaway thread
All scheduled tasks for a user shared one scheduler thread, so each run
appended its messages to the same LangGraph checkpoint. Over time the
history blew past the model's input window and every task on that
account started failing with context-too-long.

_execute_task now mints a fresh thread_id per run and threads it through
ensure_thread_meta / snapshot / start_run / extract_*. The per-task
scheduler_thread_id column is left in place for backwards compatibility
but no longer drives the LLM call.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 20:58:23 +08:00
fengxiangdebaozi 02111ab5b8 文档修改 2026-05-13 20:22:14 +08:00
吉鑫升 a2f7157bc3 chore: remove .claude/settings.local.json from tracking
Followup to previous commit which only landed the .gitignore rule but
left the file still tracked in the index.
2026-05-13 20:14:37 +08:00
吉鑫升 e6591abfbc chore: stop tracking .claude/settings.local.json
This file holds per-user Claude Code permission allowlists and should not
be shared across the team. Adding it to .gitignore and removing from the
index; existing working copies are preserved.
2026-05-13 20:14:00 +08:00
吉鑫升 50bda1ddee Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji
# Conflicts:
#	frontend-web/src/components/workspace/agents/agent-card.tsx
#	frontend-web/src/pages/NewAgentPage.tsx
2026-05-13 20:10:21 +08:00
吉鑫升 31abad86d5 智能体配置 2026-05-13 20:04:06 +08:00
fengxiangdebaozi af7e90c87a Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server 2026-05-13 18:23:25 +08:00
fengxiangdebaozi 2e4bdf122e 页面结构修改 2026-05-13 18:18:05 +08:00
吉鑫升 83d7fa26fe Merge remote master docs 2026-05-13 17:28:04 +08:00
fengxiangdebaozi efc4d89fdf 文档 2026-05-13 17:17:46 +08:00
吉鑫升 a27206c543 Update local frontend and backend changes 2026-05-13 17:17:42 +08:00
吉鑫升 faca2c9a2d Merge branch 'likun' into master 2026-05-13 17:02:22 +08:00
fengxiangdebaozi 0cbd137b4f wendang1xiug1 2026-05-13 16:38:34 +08:00
likun cdf41d3e5e feat:完成技能化适配的意图识别功能 2026-05-13 16:01:00 +08:00
吉鑫升 aa034f8669 定时任务订阅模式 2026-05-13 14:59:27 +08:00
likun aee5a50b9f bug修复 2026-05-13 14:57:16 +08:00
likun b8926f00d7 新增用户意图确认功能 2026-05-13 14:36:44 +08:00
吉鑫升 839386f0b4 test: verify new remote push 2026-05-13 14:23:55 +08:00
吉鑫升 cf2e4bdd9c 智能体分权 2026-05-13 11:36:17 +08:00
吉鑫升 e7a455f22e Initial commit: deerflow-server (frontend-web + offline-backend-20260512) 2026-05-13 09:36:15 +08:00
1233 changed files with 56755 additions and 199429 deletions

No files matched your search

-20
View File
@@ -1,20 +0,0 @@
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()
+119
View File
@@ -0,0 +1,119 @@
# Workspace/editor
.vscode/
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
frontend-web/vite-dev.log
frontend-web/vite-dev.err.log
# Frontend local packages/archives/docs (non-source)
frontend-web/pnpm-lock.yaml
frontend-web/README.md
frontend-web/doc.md
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
offline-backend-20260505.zip
offline-backend-20260505/output/
offline-backend-20260505/bundle/.env
offline-backend-20260505/bundle/.env.example
offline-backend-20260505/bundle/DEPLOY_BACKEND_OFFLINE_ZH.md
offline-backend-20260505/bundle/SHA256SUMS
offline-backend-20260505/bundle/config.yaml
offline-backend-20260505/bundle/config.yaml.example
offline-backend-20260505/bundle/data/
offline-backend-20260505/bundle/deerflow-backend-offline-image-20260505.tar
offline-backend-20260505/bundle/extensions_config.json
offline-backend-20260505/bundle/frontend-vite.zip
offline-backend-20260505/bundle/skills/
offline-backend-20260505/bundle/start_backend.0509.sh
offline-backend-20260505/bundle/start_backend.sh
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/DEPLOY_BACKEND_OFFLINE_ZH.md
offline-backend-20260512/SHA256SUMS
offline-backend-20260512/config.yaml.example
offline-backend-20260512/data/
offline-backend-20260512/deerflow-backend-offline-image-20260505.tar
offline-backend-20260512/extensions_config.json
offline-backend-20260512/skills/
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/start_backend.sh
offline-backend-20260512/stop_backend.sh
offline-backend-20260512/check_backend.sh
hermes-agent-main/
skills/*
offline-backend-20260512/backend/.deer-flow/*
# Per-user skill_evolution overrides — runtime data written by the API
offline-backend-20260512/backend/skill_evolution.json
skills/
hermes-agent-main/
.gitignore
offline-backend-20260512/backend/tests/*
# MAF roundtable tests must be tracked (excepted from the broad tests/* ignore above)
!offline-backend-20260512/backend/tests/test_maf_*.py
!offline-backend-20260512/backend/tests/maf_test_helpers.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
.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/
# uv lockfile (not tracked per project preference)
offline-backend-20260512/backend/uv.lock
# Local-only scratch directory (not committed)
0622/
# Python bytecode cache
__pycache__/
# misc
.DS_Store
-6
View File
@@ -1,6 +0,0 @@
{
"recommendations": [
"ms-python.python",
"ms-python.debugpy"
]
}
-66
View File
@@ -1,66 +0,0 @@
{
"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
@@ -1,6 +0,0 @@
{
"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
@@ -1,175 +0,0 @@
{
"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": []
}
]
}
@@ -1,61 +0,0 @@
# 深度研究第三轮:检索稳定性修复 + 参考文献确定性 + 页面对齐 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,122 @@
# MAF 多智能体会商 Phase-4 前端实施计划
## 决策回顾(已与用户确认)
- **入口**:独立顶级菜单 `/page/maf/*`,新增侧边栏一级项「MAF 会商」
- **实时更新**:纯前端轮询,`GET /runs/{id}/events?after_seq=N&limit=1000`,间隔 1.8s,复用现有后端,零 SSE、零后端改动
- **流程图**:要。基于 `confirmed_facts`(来自 `run.maf_checkpoint.fact_ledger`)+ 末轮 `final_result.content` 解析的 `flow-json`,复用 `@xyflow/react` + `flow-graph.ts` + `FlowGraphPanel`
- **审批**:卡片式,仿 `IntentClarificationCard` 的视觉/交互模式(参数摘要 + 批准/拒绝按钮 + 备注 textarea),落到 `POST /approvals/{id}/decision`
## 关键数据契约(已核实后端源码)
- **后端只读**:16 个端点全部命中,无改动。`GET /health` 返回 `enabled` 决定页面内容(入口仍可见,未启用时显示空态)。
- **事件流**:单调 `(run_id, seq)`,`GET /events?after_seq=N` 返回 `{events:[...], latest_seq}`;前端推进 `after_seq=latest_seq`。payload 已在后端**写入时脱敏**(`sanitize_payload`),前端直接渲染。
- **事件分类**(`event_normalizer.py`):`run.started/completed/failed/cancelled`、`agent.turn_started/message.delta/message.completed`、`tool.requested/started/completed/failed`、`skill.started/completed/failed/selected`、`artifact.created`、`action.waiting_approval/approved/rejected`、`workflow.checkpointed`。
- **事实账本**(`fact_ledger.empty_ledger`):`candidate_facts`/`confirmed_facts`/`evidence`/`tool_results`/`executed_actions`/`pending_actions`/`failed_or_unknown_actions`/`conflicts`。`confirmed_facts` 条目含 `{candidate_id, text, agent_id, confirmed_by, evidence_refs[]}`。
- **Run 字段**(`run_to_dict`):`id, session_id, status, maf_checkpoint(含 fact_ledger + final_result + seat_outcomes), last_event_seq, started_at, finished_at, error_code, error_message_safe, token_usage, latency_ms`。
- **终态判定**:`runIsLive(status) = ["pending","running","waiting_approval","cancelling","cancel_failed"].includes(status)`,非 live 即停轮询。
- **Action/Approval**:`GET /runs/{id}/actions`、`GET /runs/{id}/approvals`;`POST /approvals/{id}/decision` `{decision:"approved"|"rejected"}`。
## 复用清单(已定位到文件:行)
- `apiFetch`(`core/api/fetch-client.ts`):内部自动注入 `Authorization`(`getAuthorizationHeaderValue()`)+ `credentials:"include"`,**返回 Response 不解析、不拼 URL**。调用方拼 `${getBackendBaseURL()}/api/maf-roundtable/...`,自行 `res.ok` 检查 + `res.json()`。
- `getBackendBaseURL`(`core/config/index.ts`):未设时返回 `""`,相对路径同源可用。
- TanStack Query 模式(`strategy-components/api/task-buttons.ts`):`useQuery`+`refetchOnWindowFocus:false`;`useMutation`+`onSuccess invalidate`;queryKey 用嵌套数组 `["maf-roundtable", runId, "events"]`。
- 轮询模式(`core/scheduled-tasks/hooks.ts:105-115`):函数式 `refetchInterval: (query) => runIsLive(query.state.data?.status) ? ms : false`。
- `FlowGraphPanel`(`roundtable-planning/components/FlowGraphPanel.tsx`):props `{data: FlowGraphData, streaming, onClose, ...}`,自动 `useTheme()` 取明暗。`FlowGraphData = {title, nodes:[{id,label,type,detail?,group?}], edges:[{from,to,label?}]}`。`extractFlowGraph(text)`(`flow-graph.ts:263`)容错解析 ```flow-json``` 代码块(含半截 JSON)。
- `IntentClarificationCard`(`roundtable-planning/components/IntentClarificationCard.tsx`):卡片视觉模板(`rounded-xl border-red-100` + 「需要确认」徽标 + 选项按钮 + textarea + 提交)。
- 时间线 feed(`roundtable-planning/components/Step1Panel.tsx` + `MessageBubble` + `useAutoScroll` + `ScrollToBottomButton`):数组入、按 seq 序渲染。
- `useDesensitizeSubtree`(`roundtable-planning/lib/use-desensitize-subtree.ts`):仅挂 header/面板框架;时间线 body 不挂(payload 已脱敏 + hook 自身警告勿用于消息列表)。
- 路由(`pages/PageRoutes.tsx:143-169`):`<Route path="maf/*" element={<MafRoutes/>}/>`(仿 `RoundtableRoutes.tsx`)。
- 菜单(`core/page-layout/sidebar-menu.ts`):在 `sidebarMenuItems` 数组加一级项,`icon` 用 lucide 组件(非字符串 key)。新节点经 `use-sidebar-menu.ts` 自动走 static→inject→override→role→desensitize 流水线,无需额外注册。
## 文件夹结构(镜像 `roundtable-planning/`,全新 `src/maf-roundtable/`)
```
frontend-web/src/maf-roundtable/
├── api/
│ ├── types.ts # TS 类型(snake_case 直传,后端即 snake_case)
│ ├── client.ts # BASE()=getBackendBaseURL()+"/api/maf-roundtable";apiFetch 封装 + readJson<T>/parseDetail
│ ├── sessions.ts # 会话 CRUD hooks(list/get/create/update/delete)
│ ├── runs.ts # run hooks(get/list/create/cancel/resume/recover)+ useMafHealth
│ ├── events.ts # listEvents(runId, afterSeq) 原始 fetch(供轮询 hook 用)
│ └── approvals.ts # 审批 hooks(list + decide mutation)
├── hooks/
│ ├── use-maf-run-status.ts # GET /runs/{id} useQuery,函数式 refetchInterval 停终态
│ └── use-maf-events.ts # ★ cursor 轮询 hook(核心)
├── lib/
│ ├── event-timeline.ts # 纯函数:events[] → TimelineEntry[](delta 聚合、tool 生命周期折叠、approval 锚点)
│ └── fact-flow-graph.ts # 纯函数:confirmed_facts+evidence → FlowGraphData
├── components/
│ ├── MafRunHeader.tsx # 状态徽标 + token/延迟 + 取消/恢复/重试
│ ├── MafEventTimeline.tsx # 时间线 feed(MessageBubble + useAutoScroll)
│ ├── MafSeatStatusPanel.tsx # 席位状态矩阵 + execution_stage 徽标
│ ├── MafFactFlowPanel.tsx # 包一层 FlowGraphPanel,数据来自 fact-flow-graph
│ ├── MafApprovalCard.tsx # 卡片式审批(批准/拒绝 + 备注)
│ └── MafHealthGate.tsx # health.enabled=false → 空态
├── pages/
│ ├── MafSessionsPage.tsx # 会话列表 + 新建
│ └── MafRunDetailPage.tsx # 单 run 工作区(三栏)
└── index.ts
```
## 核心:cursor 轮询 hook(`hooks/use-maf-events.ts`)
不用纯 `useQuery+refetchInterval`:cursor `after_seq` 需每次推进,queryFn 不持有「上次 latest_seq」,塞 queryKey 会抖动。**用自定义 hook**(结合 scheduled-tasks 的 refetchInterval 思路 + roundtable-planning 的 reader-loop 家族):
```ts
export function useMafEvents(runId?: string, active=false) {
const [events, setEvents] = useState<MafEvent[]>([]);
const afterSeqRef = useRef(0); // 避免 setInterval 闭包旧值
useEffect(() => {
if (!runId || !active) return;
let cancelled = false;
const poll = async () => {
const res = await listEvents(runId, afterSeqRef.current);
if (cancelled || !res.events.length) return;
setEvents(prev => mergeBySeq(prev, res.events)); // seq 去重
afterSeqRef.current = res.latest_seq;
};
poll(); // 进入即补拉(after_seq=0 全量历史)
const id = setInterval(poll, 1800);
return () => { cancelled = true; clearInterval(id); };
}, [runId, active]);
return events;
}
```
- **补拉历史**:进入页面 `after_seq=0` 立即拉全部已落库事件 → 天然支持断线补拉/刷新恢复。
- **终态停止**:`active` 由 `useMafRunStatus` 的 `runIsLive(status)` 传入,终态时 effect 清理 interval。
- **去重**:后端 `(run_id,seq)` + `source_event_id` 双重去重,前端再按 `seq` 做 `mergeBySeq`,幂等。
- **切换 run**:`runId` 变 → effect 重置(events 清空、afterSeq 归零)。
## 流程图数据流(`lib/fact-flow-graph.ts`)
两源按优先级合并 → `FlowGraphData`:
1. **`confirmed_facts`(主)**:每条已确认事实 → `task` 节点(label=text 截断、detail=全文、group=confirmed_by);`evidence_refs` 连到 `evidence`(→ `role`)或 `tool_results`(`tool:{name}:{turn}` → `deliverable`)节点;证据根用 `start`。
2. **`final_result.content` 的 ```flow-json```(次)**:用现成 `extractFlowGraph(text)` 解析叠加为「结论流程图」。
输出喂 `<FlowGraphPanel data={...} streaming={!terminal}/>`(非终态蚂蚁线动)。两源皆空 → 空态「尚无可绘制事实」。
## 页面布局(`MafRunDetailPage`,三栏 / 窄屏堆叠)
- **左:时间线**(`MafEventTimeline`)—— `event-timeline.ts` 折叠成可读条目(delta 聚合气泡、tool 折叠「调用 X→完成」、action.waiting_approval 插锚点),复用 MessageBubble + useAutoScroll + ScrollToBottomButton。
- **中上:席位状态**(`MafSeatStatusPanel`)—— `maf_checkpoint.seat_outcomes` 的 agent × status 矩阵 + `execution_stage` 徽标。
- **中下:事实/结论流程图**(`MafFactFlowPanel`)—— 折叠面板,默认展开。
- **右:审批卡片**(`MafApprovalCard` 列表)—— 仅 pending 时显示;含工具名、参数摘要(脱敏)、批准/拒绝按钮 + 备注 textarea → `POST /approvals/{id}/decision`,成功后 invalidate `["maf-roundtable","approvals",runId]`,事件轮询自然看到 `action.approved/rejected`。
## 路由 + 菜单接入(3 处)
1. **新建** `pages/MafRoutes.tsx`(仿 `RoundtableRoutes.tsx`):`index→MafSessionsPage`、`runs/:runId→MafRunDetailPage`、`*→重定向`。
2. **改** `pages/PageRoutes.tsx`:加 `import MafRoutes` + `<Route path="maf/*" element={<MafRoutes/>}/>`(插 `notebook` 后)。
3. **改** `core/page-layout/sidebar-menu.ts`:数组末尾加 `{ id:"maf-center", label:"MAF 会商", icon:Network, children:[{id:"maf-roundtable", label:"会商列表", icon:MessageSquareText, path:"/page/maf"}] }`。**不加 `adminOnly`**(全员可见;`/health.enabled=false` 由 `MafHealthGate` 客户端控制页面空态)。
## 实施顺序
1. `api/types.ts` + `api/client.ts`(地基)
2. `api/{sessions,runs,events,approvals}.ts`(端点 hook)
3. `hooks/{use-maf-run-status,use-maf-events}.ts`(轮询核心)
4. `lib/{event-timeline,fact-flow-graph}.ts`(纯函数)
5. `components/*`(6 个组件)
6. `pages/*`(2 个页面)+ `index.ts`
7. `pages/MafRoutes.tsx` + 接入 `PageRoutes.tsx` + `sidebar-menu.ts`
8. `pnpm typecheck` + 手动核对路由/菜单显隐
## 文件清单
- **新建**(14):`maf-roundtable/api/{types,client,sessions,runs,events,approvals}.ts`、`maf-roundtable/hooks/{use-maf-run-status,use-maf-events}.ts`、`maf-roundtable/lib/{event-timeline,fact-flow-graph}.ts`、`maf-roundtable/components/{MafRunHeader,MafEventTimeline,MafSeatStatusPanel,MafFactFlowPanel,MafApprovalCard,MafHealthGate}.tsx`、`maf-roundtable/pages/{MafSessionsPage,MafRunDetailPage}.tsx`、`maf-roundtable/index.ts`、`pages/MafRoutes.tsx`
- **改动**(2):`pages/PageRoutes.tsx`、`core/page-layout/sidebar-menu.ts`
- **后端**:无改动
## 验证
- `pnpm typecheck`(tsc --noEmit)通过
- 手动:菜单「MAF 会商」→ 列表 → 新建会话 → 启动 run → 时间线滚动 → 席位状态更新 → 流程图随 confirmed_facts 增长 → 审批可批准 → 终态停轮询
- 退路:`/health.enabled=false` → 入口可见但页面显示未启用提示;旧 `roundtable-planning` 零改动
+2 -15
View File
@@ -11,13 +11,6 @@ This is a customized offline deployment of **DeerFlow** — a LangGraph-based AI
Managed together via shell scripts in `scripts/`. 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 ## Commands
### Full Application (from repo root) ### Full Application (from repo root)
@@ -80,8 +73,6 @@ 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). **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 ### Frontend
The frontend (`frontend-web/`) is a React 19 + Vite SPA: The frontend (`frontend-web/`) is a React 19 + Vite SPA:
@@ -90,19 +81,15 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA:
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps) - **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
- **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`. - **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`.
- **轻应用中心 (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). - **轻应用中心 (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). **简介模式** uses a separate overlay: every compact workspace menu item can be placed in `sidebar`(左侧菜单)、`settings`(设置和更多)or `toolbox`(右侧工具箱); `CompactToolbox` (`components/workspace/compact-toolbox.tsx`, mounted by `PageRoutes.tsx`) opens only when the square right-edge trigger is clicked, then slides a compact, content-height right-side drawer over a backdrop above global dropdowns; configured items render top-to-bottom as centered square cards with a large icon above the label while the effective layout is compact. `/api/compact-menu-overrides` stores two independent sets (type `A` / `B`); each website picks one via `runtime-config.js` `VITE_COMPACT_MENU_TYPE`. - **菜单管理 (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).
- **舆情分析智能体(前端虚拟智能体)**: 智能体管理页新增「舆情分析」类型 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. - **敏感词管理 (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/`。 - **技能地址管理 (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 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 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`. - **按钮管理 (Task Button Management, admin-only)**: configures the **可配置跳转按钮** rendered in the left task panel of the task deep-link workspaces (rwfx / 3qfx / xdfx, see `TaskFxWorkspace`). Each button = `{business, label, linkType, target, appendTaskId, idParam, idKind, enabled, sortOrder}`; `linkType` is `url` (外链 `window.open`, optional append of `?{idParam}={id}` — **`idParam` is the editable query-param name**, e.g. `id`/`task_id`), `business` (内部切换到另一业务, reuses `resolveTaskDeeplinkTarget`, always task id), or `purpose` (弹出当前任务的「任务目的」表格 via the shared `TaskPurposeDialog`, no target — configurable for any page incl. xdfx). **`idKind` (`task`/`action`) only matters for xdfx**: its deep-link `?taskId=` is an 行动id and the 任务id is resolved at login (`fetchTaskIdFromAction`) — `TaskContext` now also stashes the raw `actionId`, so a url button can append either (default `task`). Page `TaskButtonsPage.tsx` (route `/page/strategy/admin/task-buttons`, **admin-gated**, entry「按钮管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both full + collapsed modes) has per-business tabs, edits name/type/target/启停/排序/增删, saves the **whole set atomically** (replace-all), plus 「导入默认」 to merge code-seed defaults. **Seed/fallback** (like 敏感词管理): only when the whole table is empty (fresh deploy, never saved) do the workspace + page fall back to `defaultTaskButtons(cfg)` — rwfx's url buttons (编辑/下一步/3q详情) built from the **live** `/api/public/config/task-deeplink` plus cross-business switch buttons for **all three** businesses (each switches to the other two — rwfx→三情/行动, 3qfx→任务/行动, xdfx→任务/三情). Once saved, the store is the sole source of truth. The old hardcoded jump buttons were migrated out: `TaskFxWorkspace` no longer hardcodes 切换到三情分析, `TaskActionsPanel` keeps only the non-jump 清除记录, and `TaskPurposePanel` dropped its 3q详情 button (now configurable) **and defaults the 目的树 table to collapsed** (chevron toggle). Helpers `core/auth/task-buttons.ts` (`TaskButton`, `defaultTaskButtons`, `resolveTaskButtons`, `buttonsForBusiness`, `runTaskButton`), client+hooks `strategy-components/api/task-buttons.ts`. Backend: `/api/task-buttons` (global/shared; open read, admin replace-all), store `deerflow.persistence.task_buttons` (table `task_buttons`, auto-created by `create_all`), wired `app.state.task_button_store`. Tests: `tests/test_task_buttons.py`.
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes` - **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 - **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/` - **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) - **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A 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.taskId` AND `metadata.agent_id` so the three businesses' conversations staLine truncated - **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). **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.taskId` AND `metadata.agent_id` so the three businesses' conversations staLine 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 提示。 - **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
### Configuration ### Configuration
+3 -5
View File
@@ -73,8 +73,6 @@ 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). **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 ### Frontend
The frontend (`frontend-web/`) is a React 19 + Vite SPA: The frontend (`frontend-web/`) is a React 19 + Vite SPA:
@@ -84,13 +82,13 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA:
- **定时任务「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. - **定时任务「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`. - **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`.
- **轻应用中心 (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). - **轻应用中心 (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`. - **菜单管理 (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).
- **白名单管理 (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`. **账号级「登录口令」(per-account password — 临时开通)**: the same page also lets an admin assign one specific account an individual **plaintext** password (`users.login_password` column, migration `20260625_04`, nullable; auto-added on startup by `_ensure_orm_columns_sync`). Once set, **that account's** username login (`POST /api/v1/auth/login/username`) **requires** `?password=` to exactly match it and that personal password **takes precedence over** the global shared-password gate (`username_login.require_password`); accounts without one keep today's shared-gate / passwordless behavior. The user then logs in via the **existing** frontend URL `#/login/<用户名>?password=xxxx` (LoginPage already forwards `?password=`; `<用户名>` = the account's email `@`-prefix). **Plaintext is intentional** — the password rides in the URL query anyway, so storing it readably lets the admin re-copy the full login link from the page; it is exposed only on the **admin-only** `GET /api/v1/auth/users` (`UserListItem.login_password`) and the new admin-only `PUT /api/v1/auth/users/{id}/login-password` (set non-empty / clear with null·empty; doesn't touch `token_version`). The whitelist page renders a per-user 「登录口令」 column with a set/修改 editor + a live 「复制登录链接」 button (`useSetUserLoginPassword` in `core/auth/hooks.ts`, `setUserLoginPassword` in `core/auth/api.ts`). Backend gate helper `_lookup_user_by_username` (lookup-only, no auto-register) in `routers/auth.py`; tests `tests/test_login_personal_password.py`. - **白名单管理 (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`. **账号级「登录口令」(per-account password — 临时开通)**: the same page also lets an admin assign one specific account an individual **plaintext** password (`users.login_password` column, migration `20260625_04`, nullable; auto-added on startup by `_ensure_orm_columns_sync`). Once set, **that account's** username login (`POST /api/v1/auth/login/username`) **requires** `?password=` to exactly match it and that personal password **takes precedence over** the global shared-password gate (`username_login.require_password`); accounts without one keep today's shared-gate / passwordless behavior. The user then logs in via the **existing** frontend URL `#/login/<用户名>?password=xxxx` (LoginPage already forwards `?password=`; `<用户名>` = the account's email `@`-prefix). **Plaintext is intentional** — the password rides in the URL query anyway, so storing it readably lets the admin re-copy the full login link from the page; it is exposed only on the **admin-only** `GET /api/v1/auth/users` (`UserListItem.login_password`) and the new admin-only `PUT /api/v1/auth/users/{id}/login-password` (set non-empty / clear with null·empty; doesn't touch `token_version`). The whitelist page renders a per-user 「登录口令」 column with a set/修改 editor + a live 「复制登录链接」 button (`useSetUserLoginPassword` in `core/auth/hooks.ts`, `setUserLoginPassword` in `core/auth/api.ts`). Backend gate helper `_lookup_user_by_username` (lookup-only, no auto-register) in `routers/auth.py`; tests `tests/test_login_personal_password.py`.
- **敏感词管理 (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. - **敏感词管理 (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/`。 - **技能地址管理 (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 - **按钮管理 (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). **`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`) 默认指向**应用内**「大屏绘制」页,在 **both** 单智能体 (`TaskFxWorkspace`) 与 多智能体会商 (`RoundtablePlanningPage` 深链 rwfx-A) 都显示(共用 `TaskJumpBar`)。**`runTaskButton` 的 `url` 类型支持应用内路由**:target 以单个 `/` 开头时按内部路由处理——`self` 走 react-router 同窗导航(不刷新),`blank` 拼成当前源的 hash 路由新标签打开;外链行为不变。 The old hardcoded jump buttons were migrated out: `TaskFxWorkspace` no longer hardcodes 切换到三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」. - **实时并发监控 (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」.
- **会话冲突 409 中文化**: 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` now returns a **Chinese** detail「当前对话还在生成回答…」). `core/threads/hooks.ts` `onError` detects the conflict (`isActiveRunConflictError`: 409 / "already has an active run" / the Chinese text). A premature SSE close (SDK treats it as success and restores the send button while the backend run is still occupying the thread) is recovered by `confirmOrRejoin`: hold the stop button, `joinStream` the live run, and on 409 auto-reconnect instead of a fake AI bubble. `sse_consumer` no longer ends a resumable (`on_disconnect=continue`) stream on a false-positive `is_disconnected()`. - **会话冲突 409 中文化**: 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` now returns a **Chinese** detail「当前对话还在生成回答…」). `core/threads/hooks.ts` `onError` detects the conflict (`isActiveRunConflictError`: 409 / "already has an active run" / the Chinese text) and shows a friendly `toast.info` instead of a raw error.
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes` - **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 - **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/` - **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
-3
View File
@@ -1,3 +0,0 @@
# deerflow-code
deerflow-code
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.
@@ -5,9 +5,6 @@ const LEGACY_LOCAL_API_BASE_URL = "http://localhost:8001";
const LEGACY_LOCAL_WEB_BASE_URL = "http://localhost:5174"; const LEGACY_LOCAL_WEB_BASE_URL = "http://localhost:5174";
let pollTimer = null; let pollTimer = null;
let isPolling = false; let isPolling = false;
let startupPromise = null;
const POLLING_SCHEDULE_SETTING_KEYS = new Set(["taskPollingEnabled", "taskPollIntervalSeconds"]);
function delay(ms) { function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
@@ -15,14 +12,6 @@ function delay(ms) {
async function getSettings() { async function getSettings() {
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS); const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
const discovered = await chrome.storage.local.get({
discoveredApiBaseUrl: "",
discoveredWebBaseUrl: "",
});
if (settings.autoDiscoverServiceUrl) {
settings.apiBaseUrl = discovered.discoveredApiBaseUrl || settings.apiBaseUrl;
settings.webBaseUrl = discovered.discoveredWebBaseUrl || settings.webBaseUrl;
}
const updates = {}; const updates = {};
if (!settings.apiBaseUrl || settings.apiBaseUrl === LEGACY_LOCAL_API_BASE_URL) { if (!settings.apiBaseUrl || settings.apiBaseUrl === LEGACY_LOCAL_API_BASE_URL) {
updates.apiBaseUrl = DEER_CLIPPER_DEFAULTS.apiBaseUrl; updates.apiBaseUrl = DEER_CLIPPER_DEFAULTS.apiBaseUrl;
@@ -80,7 +69,10 @@ function apiCandidatesForWebBase(webBase, currentApiBase) {
} }
}; };
add(currentApiBase);
add(webBase); add(webBase);
add(DEER_CLIPPER_DEFAULTS.apiBaseUrl);
add(LEGACY_LOCAL_API_BASE_URL);
try { try {
const url = new URL(normalizeServiceBase(webBase)); const url = new URL(normalizeServiceBase(webBase));
@@ -93,10 +85,6 @@ function apiCandidatesForWebBase(webBase, currentApiBase) {
// Ignore invalid candidates. // Ignore invalid candidates.
} }
add(currentApiBase);
add(DEER_CLIPPER_DEFAULTS.apiBaseUrl);
add(LEGACY_LOCAL_API_BASE_URL);
return candidates; return candidates;
} }
@@ -105,12 +93,6 @@ async function browserContextStatus(apiBaseUrl) {
const response = await fetch(`${apiBaseUrl}/api/browser-context/status`, { const response = await fetch(`${apiBaseUrl}/api/browser-context/status`, {
credentials: "include", credentials: "include",
}); });
// The gateway may enforce authentication globally before this otherwise
// public discovery endpoint is reached. A 401/403 still proves that this
// candidate is the zncm API paired with the open frontend tab.
if (response.status === 401 || response.status === 403) {
return { enabled: true, authenticationRequired: true };
}
if (!response.ok) { if (!response.ok) {
return null; return null;
} }
@@ -219,12 +201,9 @@ async function discoverServiceBases(settings, force = false) {
settings.webBaseUrl !== next.webBaseUrl || settings.webBaseUrl !== next.webBaseUrl ||
settings.lastServiceSyncSource !== next.lastServiceSyncSource settings.lastServiceSyncSource !== next.lastServiceSyncSource
) { ) {
// Discovered endpoints are runtime state, not user-authored preferences. await chrome.storage.sync.set({
// Keep them in storage.local so Chrome sync write quotas cannot break task apiBaseUrl: next.apiBaseUrl,
// polling. The options page may still persist explicit user choices. webBaseUrl: next.webBaseUrl,
await chrome.storage.local.set({
discoveredApiBaseUrl: next.apiBaseUrl,
discoveredWebBaseUrl: next.webBaseUrl,
lastServiceSyncAt: next.lastServiceSyncAt, lastServiceSyncAt: next.lastServiceSyncAt,
lastServiceSyncSource: next.lastServiceSyncSource, lastServiceSyncSource: next.lastServiceSyncSource,
}); });
@@ -847,50 +826,19 @@ async function pollOnce() {
} }
} }
async function initializePolling() { async function startup() {
let settings = await getSettings(); let settings = await getSettings();
try {
settings = await discoverServiceBases(settings); settings = await discoverServiceBases(settings);
} catch (error) {
// Service discovery persists diagnostic metadata in storage.sync. Chrome can
// temporarily reject those writes after its quota is reached; polling must
// still start with the last known settings.
console.warn("zncm service discovery failed during startup", error);
}
try {
settings = await syncAuthToken(settings); settings = await syncAuthToken(settings);
} catch (error) {
// A failed status/token write must not prevent alarms from being installed.
// pollOnce() will retry token synchronization before claiming each task.
console.warn("zncm token sync failed during startup", error);
}
await refreshAlarm(settings); await refreshAlarm(settings);
await scheduleNextPoll(1000); await scheduleNextPoll(1000);
} }
function startup() { chrome.runtime.onInstalled.addListener(() => void startup());
if (!startupPromise) { chrome.runtime.onStartup.addListener(() => void startup());
startupPromise = initializePolling().finally(() => {
startupPromise = null;
});
}
return startupPromise;
}
async function restartPollingSchedule() {
const settings = await getSettings();
await refreshAlarm(settings);
await scheduleNextPoll(0);
}
chrome.runtime.onInstalled.addListener(() => void startup().catch((error) => console.warn("zncm startup failed", error)));
chrome.runtime.onStartup.addListener(() => void startup().catch((error) => console.warn("zncm startup failed", error)));
chrome.storage.onChanged.addListener((changes, areaName) => { chrome.storage.onChanged.addListener((changes, areaName) => {
if ( if (areaName === "sync") {
areaName === "sync" && void startup();
Object.keys(changes || {}).some((key) => POLLING_SCHEDULE_SETTING_KEYS.has(key))
) {
void restartPollingSchedule().catch((error) => console.warn("zncm polling reschedule failed", error));
} }
}); });
chrome.alarms.onAlarm.addListener((alarm) => { chrome.alarms.onAlarm.addListener((alarm) => {
@@ -954,4 +902,4 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
return true; return true;
}); });
void startup().catch((error) => console.warn("zncm startup failed", error)); void startup();
@@ -1,130 +0,0 @@
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 BACKGROUND_PATH = path.join(__dirname, "background.js");
function createHarness() {
let storageChangedListener;
let alarmCreateCount = 0;
const settings = {
apiBaseUrl: "http://localhost:8001",
webBaseUrl: "http://localhost:5174",
autoDiscoverServiceUrl: false,
accessToken: "",
tokenSyncEnabled: false,
taskPollingEnabled: true,
workerId: "test-worker",
taskPollIntervalSeconds: 5,
};
const chrome = {
alarms: {
clear: async () => {},
create: async () => {
alarmCreateCount += 1;
},
onAlarm: { addListener: () => {} },
},
cookies: { get: async () => null },
runtime: {
onInstalled: { addListener: () => {} },
onMessage: { addListener: () => {} },
onStartup: { addListener: () => {} },
},
storage: {
local: {
get: async (defaults) => ({ ...defaults }),
set: async () => {},
},
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 () => {
throw new Error("offline test");
},
importScripts: () => {},
setTimeout: () => 1,
clearTimeout: () => {},
URL,
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,
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),
);
});
+1 -41
View File
@@ -7,8 +7,6 @@
const HOST_ID = "zncm-page-assistant-host"; const HOST_ID = "zncm-page-assistant-host";
const state = { const state = {
enabled: true, enabled: true,
taskPollingEnabled: true,
webBaseUrl: "",
open: false, open: false,
busy: false, busy: false,
threadId: "", threadId: "",
@@ -711,58 +709,20 @@
async function loadSettings() { async function loadSettings() {
const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS); const settings = await chrome.storage.sync.get(DEER_CLIPPER_DEFAULTS);
state.enabled = Boolean(settings.pageAssistantEnabled); state.enabled = Boolean(settings.pageAssistantEnabled);
state.taskPollingEnabled = Boolean(settings.taskPollingEnabled);
state.webBaseUrl = deerNormalizeBaseUrl(settings.webBaseUrl || DEER_CLIPPER_DEFAULTS.webBaseUrl);
ensureWidget(); ensureWidget();
} }
chrome.storage.onChanged.addListener((changes, areaName) => { chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== "sync") { if (areaName !== "sync" || !changes.pageAssistantEnabled) {
return; return;
} }
if (changes.pageAssistantEnabled) {
state.enabled = Boolean(changes.pageAssistantEnabled.newValue); state.enabled = Boolean(changes.pageAssistantEnabled.newValue);
ensureWidget(); ensureWidget();
if (state.enabled) { if (state.enabled) {
setStatus("页面问答框已开启。"); 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(() => { setInterval(() => {
if (!state.enabled || !ui.pageTitle) { if (!state.enabled || !ui.pageTitle) {
return; return;
-117
View File
@@ -1,117 +0,0 @@
# 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、技能面板没有出现在错误清单中。
浏览器实际页面与跳转已验证,但不能声称全项目构建通过。
@@ -1,719 +0,0 @@
# 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. 响应式、键盘、对比度、加载反馈和错误恢复通过验收。
@@ -1,481 +0,0 @@
# 报告协作工作台 — 前端对接指南
> **适用版本:** 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/report-collaboration/sessions/{sessionId}/messages
Content-Type: application/json
{ "text": "请写一份…", "target_node_id": null, "agent_run_id": null }
```
- `useReportCollaborationSession.send()`:当 `session.status` 不是 `running` / `awaiting_input` / `reviewing` 时走 `sendMessage`。
- 会话状态:`empty` → `clarifying` → `planning` → `proposal_ready`。
- 澄清问题以 `CollaborationMessage` 进入时间线;业务卡通过 `MessageList` 的 `businessCardSlot` 渲染(`additional_kwargs.report_collaboration_card`)。
### 5.3 阶段 2:候选方案
```http
POST /api/report-collaboration/sessions/{sessionId}/plan-requests
POST /api/report-collaboration/sessions/{sessionId}/plans/{planId}/select
```
- **预览方案**(`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
File diff suppressed because it is too large. Load diff
@@ -1,304 +0,0 @@
# 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 后再作为受控的内部多人平台发布。
+1 -4
View File
@@ -8,7 +8,7 @@ VITE_USE_REAL_DATA=true
VITE_MOCK_COP_TASK_DETAIL=true VITE_MOCK_COP_TASK_DETAIL=true
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:true 走本地样例假数据(真实接口未就绪时调试用);联调通过后置 false。 # 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:true 走本地样例假数据(真实接口未就绪时调试用);联调通过后置 false。
VITE_MOCK_SQ_REPORT=false VITE_MOCK_SQ_REPORT=true
# 深链任务详情(cop-task-detail:任务名称/描述)数据源:true 走本地假数据(真实接口未就绪时调试用);联调通过后置 false。 # 深链任务详情(cop-task-detail:任务名称/描述)数据源:true 走本地假数据(真实接口未就绪时调试用);联调通过后置 false。
VITE_MOCK_COP_TASK_DETAIL=true VITE_MOCK_COP_TASK_DETAIL=true
@@ -17,9 +17,6 @@ VITE_MOCK_COP_TASK_DETAIL=true
VITE_BACKEND_BASE_URL=http://127.0.0.1:8001 VITE_BACKEND_BASE_URL=http://127.0.0.1:8001
VITE_LANGGRAPH_BASE_URL=http://127.0.0.1:8001/api VITE_LANGGRAPH_BASE_URL=http://127.0.0.1:8001/api
# 开发环境普通登录后进入 Vite 内隔离的官方风格页面;/page/* 仍访问当前定制版。
VITE_USE_OFFICIAL_DEERFLOW_ENTRY=true
# 轻应用「新建笔记」系列接口 # 轻应用「新建笔记」系列接口
VITE_NOTE_API_BASE_URL=http://47.88.25.99:8000 VITE_NOTE_API_BASE_URL=http://47.88.25.99:8000
# CMZS后端接口 # CMZS后端接口
-9
View File
@@ -56,13 +56,4 @@
# VITE_STATIC_WEBSITE_ONLY= # VITE_STATIC_WEBSITE_ONLY=
# 部署级紧凑导航:true 时固定收起工作台左侧栏,并隐藏换肤与全量/简洁模式切换。 # 部署级紧凑导航:true 时固定收起工作台左侧栏,并隐藏换肤与全量/简洁模式切换。
# VITE_FORCE_COLLAPSED_SIDEBAR=false # VITE_FORCE_COLLAPSED_SIDEBAR=false
# 简介模式左侧菜单类型:与菜单管理页「简介模式」的类型 A / B 对应。两套网页分别填 A 或 B。
# 不填或留空时按类型 A,继续使用原来的简介菜单数据。
# VITE_COMPACT_MENU_TYPE=A
# VITE_GITHUB_OAUTH_TOKEN= # VITE_GITHUB_OAUTH_TOKEN=
# --- 官方 DeerFlow 风格页面入口(仅 Vite,不引入 Next.js)---
# true 时,普通登录后进入同一 Vite 应用中隔离的 /official/*。
# 已指定 redirect 或 taskId/goPath 的登录仍保持原来的优先级。
# 仅 .env.development 默认 true;其余环境保持 false。
# VITE_USE_OFFICIAL_DEERFLOW_ENTRY=false
-3
View File
@@ -17,9 +17,6 @@ VITE_MOCK_COP_TASK_DETAIL=false
VITE_BACKEND_BASE_URL=http://10.19.200.5:2026 VITE_BACKEND_BASE_URL=http://10.19.200.5:2026
VITE_LANGGRAPH_BASE_URL=http://10.19.200.5:2026/api 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 VITE_NOTE_API_BASE_URL=http://47.88.25.99:8000
# CMZS后端接口 # CMZS后端接口
-3
View File
@@ -14,9 +14,6 @@ VITE_MOCK_SQ_REPORT=false
VITE_BACKEND_BASE_URL=https://ch1.b.uat.4.cn/deerflow VITE_BACKEND_BASE_URL=https://ch1.b.uat.4.cn/deerflow
VITE_LANGGRAPH_BASE_URL=https://ch1.b.uat.4.cn/deerflow/api 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 VITE_NOTE_API_BASE_URL=https://your-intranet-host/note-api
# CMZS后端接口 # CMZS后端接口
-3
View File
@@ -17,9 +17,6 @@ VITE_MOCK_COP_TASK_DETAIL=false
VITE_BACKEND_BASE_URL=https://ch1.b.sit.4.cn/deerflow VITE_BACKEND_BASE_URL=https://ch1.b.sit.4.cn/deerflow
VITE_LANGGRAPH_BASE_URL=https://ch1.b.sit.4.cn/deerflow/api 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 VITE_NOTE_API_BASE_URL=https://your-intranet-host/note-api
# CMZS后端接口 # CMZS后端接口
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,198 @@
# MAF-R0 阶段 0 交付文档:旧会商交互基线与组件映射
> 状态:已完成
> 更新时间:2026-08-03
---
## 1. 实验原型隐藏说明
### 已完成的操作
- `/page/maf/*` 路由(`MafSessionsPage` + `MafRunDetailPage`)已从正式菜单移除。
- `workspace-nav-chat-list.tsx:199` 保留了墓碑注释:`{/* [MAF-R0] 实验原型已从正式菜单隐藏,仅保留路由供开发诊断:/page/maf */}`
- `MafRoutes.tsx` 文件头部标注为 `[MAF-R0 实验原型 — 仅供开发诊断,已从正式菜单移除]`。
- 该原型仅可通过手动输入 URL `/page/maf` 访问,不在任何侧边栏、导航菜单或工作区入口中出现。
- 停止在该原型上新增业务功能。
### 原型文件位置
| 文件 | 用途 |
|------|------|
| `src/pages/MafRoutes.tsx` | 路由定义(index → MafSessionsPage, runs/:runId → MafRunDetailPage) |
| `src/maf-roundtable/pages/MafSessionsPage.tsx` | 会话列表页(642 行) |
| `src/maf-roundtable/pages/MafRunDetailPage.tsx` | 单 run 工作区(195 行) |
| `src/maf-roundtable/` | 完整模块(33 文件:api/hooks/components/lib/tests) |
| `vitest.maf.config.ts` | MAF 专用测试配置 |
| `package.json` → `test:maf` | MAF 测试脚本 |
---
## 2. 旧会商 8 类页面状态交互地图
旧会商入口:`src/roundtable-planning/pages/RoundtablePlanningPage.tsx`(4376 行,三步合一)。
### 状态 1:空白 / 新建
- 触发:点击「新建会商」或首次进入。
- 表现:中心区域显示欢迎语 + 业务链选择入口 + 底部输入框。左侧历史列表为空或显示已有草稿。
- 关键组件:`RoundtablePlanningPage`(currentStep=1 初始态)、`Step1Panel`(空消息列表 + 输入栏)。
- 数据:`useDraftPersistence` 创建新草稿记录。
### 状态 2:历史切换
- 触发:点击左侧草稿列表中的某一条。
- 表现:加载该草稿的 Step1/Step2/Step3 快照,恢复到对应步骤。
- 关键组件:`useRoundtableDrafts`(列表)、`useDraftPersistence`(加载 + hydrate)。
- 数据:`GET /api/roundtable-drafts/{id}` 或 `GET /api/roundtable-task-drafts/{id}`。
### 状态 3:用户提问
- 触发:用户在 Step1 输入框输入任务文本并点击发送。
- 表现:用户气泡立即插入,随后出现 `MessageLoadingPlaceholder`(spinner + 跳动点),等待 SSE 首帧。
- 关键组件:`Step1Panel`(输入栏 → 发送)、`MessageBubble`(用户气泡)、`MessageLoadingPlaceholder`。
- 数据:`POST /api/intent/init` → `POST /api/intent/stream`(SSE)。
### 状态 4:意图澄清
- 触发:总控/意图智能体判断信息不足,返回 `ask_clarification` 帧。
- 表现:对话流中嵌入 `IntentClarificationCard`(单选/多选 + 自定义输入),用户选择后提交。
- 关键组件:`IntentClarificationCard`(选项卡)、`Step1Panel`(澄清提交逻辑)。
- 数据:SSE 帧 `phase=clarification`,用户回答后继续 `POST /api/intent/stream`。
### 状态 5:总控派活
- 触发:Step1 完成(INTENT_READY)→ 进入 Step2 → 总控输出派活计划。
- 表现:总控气泡显示派活计划(谁做什么),`ParallelSeatStrip` 显示参与席位头像条(running/done/error 徽章)。
- 关键组件:`Step2Panel`(派活叙事)、`ParallelSeatStrip`(席位条)、`MessageBubble`(总控气泡)。
- 数据:`POST /api/multi-agent/init`(SSE,建立 thread map)→ `POST /api/multi-agent/run/stream`。
### 状态 6:席位发言
- 触发:总控派活后,各席位按序/并行执行。
- 表现:每个席位的气泡流式出现(`StreamingCursor` 闪烁尾标),工具调用显示为 `MessageStepsCard`(ChainOfThought 折叠卡)。
- 关键组件:`MessageBubble`(席位气泡 + avatar)、`StreamingCursor`、`MessageStepsCard`(工具步骤)、`DialogueSpeedMeter`(tok/s)。
- 数据:SSE delta 帧按 message id 合并。
### 状态 7:审批
- 触发:席位执行外部写操作,WriteGuard 拦截并请求审批。
- 表现:对话流中嵌入审批卡(工具名 + 风险等级 + 摘要),用户点击批准/拒绝。
- 关键组件:MAF 原型中为 `MafApprovalCard`;旧会商中审批通过 `roundtable-jobs` 的 clarify-resume 机制。
- 数据:`POST /api/maf-roundtable/approvals/{id}/decision`(MAF)或 `POST /api/roundtable-jobs/{id}/clarify-resume`(旧)。
### 状态 8:完成 / 失败恢复
- 触发:所有席位完成 + 总控收束 → Step3;或 SSE 错误帧 / 网络断开。
- 表现(完成):Step3 显示最终报告(Markdown 总结 / HTML 看板 / 大屏),可追问。
- 表现(失败):错误提示 + 恢复按钮;后台任务可挂起/恢复。
- 关键组件:`Step3Panel` → `HighFidelityReport`(Report/Dashboard/Summary/FileBrowse 模式);失败时 `RoundtableJobNotifier`。
- 数据:`useStep3Summary` / `useStep3Report` / `useStep3Dashboard`;失败恢复 via `POST /api/roundtable-jobs/{id}/resume`。
---
## 3. 旧组件 → 新 MAF view-model 映射表
| 旧组件 / hook | 新 MAF 对应 | 映射说明 |
|---|---|---|
| `RoundtablePlanningPage`(三步壳) | `MafRoundtableConversationPage` | 不再有步骤切换;单一连续时间线。 |
| `Step1Panel`(意图问答) | `ConversationTimeline` + `ClarificationCard` | 意图理解变为 `manager.intent` 事件卡。 |
| `Step2Panel`(研讨对话流) | `ConversationTimeline` + `SeatMessageBubble` | 席位发言由 SSE `agent.message.*` 驱动。 |
| `Step3Panel` / `HighFidelityReport` | `FinalResultCard` | 结论作为时间线中的结果卡。 |
| `MessageBubble` | `SeatMessageBubble` / 总控气泡 | 重写为 MAF view model;不复用旧 props。 |
| `MessageStepsCard` | `ToolProgressCard` | 工具过程由 `tool.started/progress/completed` 事件驱动。 |
| `IntentClarificationCard` | `ClarificationCard` | 由 `clarification.required` 事件触发。 |
| `ParallelSeatStrip` | `ParticipantStrip` | 状态改由 `manager.dispatch` + `seat.delivery.submitted` + `manager.review.decision` 驱动。 |
| `useStep1Intent` | 删除 | 意图理解完全服务端化。 |
| `useStep2Orchestration` | 删除 | 编排完全服务端化;前端只消费 SSE。 |
| `useDraftPersistence` | `use-maf-conversations` | 历史改为 conversation 列表。 |
| `useRoundtableDrafts` | `use-maf-conversations` | 同上。 |
| `useStep3Summary/Report/Dashboard` | 删除 | 结论由服务端生成,前端只渲染结果卡。 |
| `useAutoScroll` | 可复用(无业务依赖) | 纯 UI 滚动逻辑。 |
| `useDialogueSpeedMetrics` | 可复用(无业务依赖) | 纯 UI 速度指标。 |
| `MafApprovalCard`(原型) | `ApprovalMessageCard` | 重写为 conversation 时间线内卡片。 |
| `MafEventTimeline`(原型) | 删除 | 不再暴露 run/event 管理后台。 |
| `MafSeatStatusPanel`(原型) | `ParticipantStrip` | 合并到右侧席位条。 |
---
## 4. 禁止复用的旧业务 hook / API / 状态清单
以下模块 **严禁** 被新 MAF conversation 页面直接 import 或调用:
### 4.1 旧会商 API 客户端(`src/roundtable-planning/api/`)
| 文件 | 禁止原因 |
|------|----------|
| `multi-agent.ts` | 调用 `/api/multi-agent/*`,包含前端 thread map 和编排逻辑 |
| `intent.ts` | 调用 `/api/intent/*`,前端驱动意图流 |
| `drafts.ts` | 调用 `/api/roundtable-drafts`,旧草稿状态 |
| `task-drafts.ts` | 调用 `/api/roundtable-task-drafts`,旧任务草稿 |
| `roundtable-jobs.ts` | 调用 `/api/roundtable-jobs`,旧后台任务 |
| `chains.ts` | 调用 `/api/roundtable-chains`,旧业务链 CRUD |
| `recommend.ts` | 调用 `/api/recommend/stream`,旧推荐流 |
| `flow-extract.ts` | 调用 `/api/flow-extract/*`,旧流程图提取 |
| `ingest.ts` | 调用 `/api/flow-extract/ingest-eligibility` |
| `dashboard-sessions.ts` | 调用 `/api/dashboard-sessions` |
| `diagnostics-report.ts` | 调用 `/api/roundtable-diagnostics/report` |
### 4.2 旧会商业务 Hook(`src/roundtable-planning/hooks/`)
| 文件 | 禁止原因 |
|------|----------|
| `useStep1Intent.ts` | 前端驱动意图状态机 |
| `useStep2Orchestration.ts` | 前端编排循环(thread map、派活、轮次控制) |
| `useDraftPersistence.ts` | 旧草稿持久化逻辑 |
| `useRoundtableDrafts.ts` | 旧草稿列表 |
| `useStep3Summary.ts` | 前端驱动总结生成 |
| `useStep3Report.ts` | 前端驱动看板生成 |
| `useStep3Dashboard.ts` | 前端驱动大屏生成 |
### 4.3 旧会商业务状态类型
- `Step1Snapshot`、`Step2Snapshot`、`Step2Dialogue`、`StubAiMessage`、`ParallelSeatView`
- `ThreadIdMap`、`ClarificationPayload`、`LeaderDispatch`、`StreamPhase`
- `DraftRecord`、`DraftMeta`、`DraftStep1Snapshot`、`DraftStep2Snapshot`、`DraftStep3Snapshot`
- `RoundtableJob`、`JobStatus`、`DispatchChainNode`、`StartJobPayload`
- `IntentSummary`、`IntentFileRef`、`IntentStreamPhase`
### 4.4 MAF 原型中禁止继续扩展的模块
| 文件 | 禁止原因 |
|------|----------|
| `src/maf-roundtable/pages/MafSessionsPage.tsx` | 实验原型,不作为产品主界面 |
| `src/maf-roundtable/pages/MafRunDetailPage.tsx` | 实验原型,暴露 run/session 管理 |
| `src/maf-roundtable/hooks/use-maf-events.ts` | 原型轮询 hook |
| `src/maf-roundtable/api/sessions.ts` | 原型 session CRUD |
| `src/maf-roundtable/api/runs.ts` | 原型 run 管理 |
| `src/maf-roundtable/api/events.ts` | 原型事件轮询 |
| `src/maf-roundtable/lib/session-form.ts` | 原型表单逻辑 |
### 4.5 允许参考但必须重写的视觉组件
以下组件的 **交互模式和信息架构** 可作为参考,但新 MAF 页面必须使用独立实现(MAF view model + tdesign-react),不得直接 import:
- `MessageBubble.tsx`(气泡布局)
- `MessageStepsCard.tsx`(工具步骤折叠)
- `IntentClarificationCard.tsx`(澄清选项卡)
- `ParallelSeatStrip.tsx`(席位头像条)
- `ScrollToBottomButton.tsx`(回到底部按钮)
- `Avatars.tsx`(头像 SVG)
### 4.6 可安全复用的无业务依赖工具
- `useAutoScroll.ts`(纯滚动逻辑)
- `useDialogueSpeedMetrics.ts`(纯速度指标)
- `src/lib/use-desensitize-subtree.ts`(DOM 脱敏,已标注多模块共享)
- `markdown-components.tsx`(markdown 渲染配置,需确认无旧状态依赖)
---
## 5. 验收确认
- [x] 旧会商 `RoundtablePlanningPage` 无代码行为变化(未修改任何 `src/roundtable-planning/` 文件)。
- [x] `/page/maf/*` 原型已从菜单隐藏,仅保留路由供开发诊断。
- [x] 8 类页面状态已记录,含触发条件、表现、关键组件和数据流。
- [x] 旧组件到新 MAF view-model 的映射表已完成。
- [x] 禁止复用的 hook/API/状态清单已明确。
- [x] 任何人可根据本文档判断新版是否「像原页面」。
@@ -0,0 +1,645 @@
# MAF 多智能体会商升级版实施计划(V2:保留原会商体验,替换底层编排)
> 文档状态:**V2 重写,待按本计划重新实施**
> 更新时间:2026-08-02
> 本轮决策:原 `/page/maf/*` 的「会话列表 + run 详情 + 前端轮询」原型不再作为目标产品继续扩展。
> 产品目标:新 MAF 会商是**原多智能体会商页面的底层升级版**,不是另造一套会商产品。
---
## 1. 本次重新确认的产品目标
用户认可的是现有多智能体会商的视觉语言和交互链路:左侧历史会话、中心对话流、输入框发问、意图理解、总控派活、席位发言、过程卡片、澄清与审批、最终结论。
本次升级只替换以下“看不见的发动机”:
- 旧的前端驱动编排、多个前端可见线程和旧会商作业,替换为 MAF Workflow + DeerFlow Agent Adapter;
- 浏览器定时轮询,替换为一条可恢复的 SSE 对话事件流;
- 用户手动创建/管理多个智能体线程,收敛为服务端按需创建和持久化的内部执行线程;
- 保留现有工具、技能、MCP、沙箱、WriteGuard、审批和审计能力,并让它们在原有会商体验中自然出现。
**不能接受的结果:** 新页面没有对话列表、没有输入框、让用户先创建 session/run、需要用户选择或理解多个内部线程、靠多个定时 GET 拼出实时效果,或把审批/流程图做成脱离聊天主链路的独立后台页。
### 1.1 必须保留的用户体验
| 原会商能力 | 升级版要求 |
|---|---|
| 左侧会商历史、新建会商 | 保留。一个条目就是一个用户可见会商,不暴露 MAF session/run/thread。 |
| 中央连续对话流 | 保留。用户消息、总控消息、席位发言、工具进度、澄清、审批、最终报告按时间顺序呈现。 |
| 底部对话输入框 | 保留。用户可在首轮发起任务、在澄清时回答、在会商结束后追问/继续会商。 |
| 意图理解 | 保留并服务端化。先识别“可直接会商 / 需要澄清 / 只回答问题 / 需要工具或写入”。 |
| 总控智能体派活 | 保留。总控是唯一能选择席位、分派任务、收束轮次和生成结论的主体。 |
| 业务链、席位与过程可视化 | 保留其信息架构和交互,不复用旧业务状态;数据改由 MAF 事件驱动。 |
| 澄清、取消、恢复、审批 | 保留,并成为对话流中的卡片,而不是跳转到 run 管理页。 |
### 1.2 明确不保留的实现方式
- 不在浏览器端 `setInterval` 轮询 run、events、actions、approvals;
- 不让浏览器创建或维护 seat thread、manager thread、thread map;
- 不让用户先填写“经理、席位、模式、最大轮数”才能开始一次正常会商;
- 不把 `MafSessionsPage` / `MafRunDetailPage` 当作新产品主界面继续堆功能;
- 不调用旧的 `/api/roundtable-*`、`/api/multi-agent/*`、`roundtable_jobs`、旧草稿或旧会商状态;
- 不修改旧 `RoundtablePlanningPage` 的业务状态机、历史数据和对外行为。
---
## 2. 总体架构与边界
```mermaid
flowchart LR
U[用户:会商对话页] -->|POST 新建/发送消息| API[MAF Conversation API]
API --> C[(MAF Conversation / Message)]
API --> D[MAF Dispatcher]
D --> W[MAF Workflow]
W --> M[总控:意图、派活、收束]
M --> S[服务端按需创建席位执行线程]
S --> A[DeerFlow Agent Adapter]
A --> T[工具 / 技能 / MCP / 沙箱]
T --> G[WriteGuard + 审批]
W --> E[(持久化会商事件)]
E --> H[SSE Hub:重放 + 实时推送]
H -->|一条 SSE 流| U
```
### 2.1 前后端职责
| 层 | 职责 | 禁止事项 |
|---|---|---|
| 前端 | 呈现会商、发送用户消息、消费 SSE、执行用户明确点击的取消/审批/重试 | 编排席位、决定下一位发言者、创建内部线程、轮询事件。 |
| MAF Conversation Service | 会话聚合、消息持久化、运行创建、SSE 重放、所有权校验 | 让浏览器传入 user_id、工具能力快照、目标键或内部幂等键。 |
| MAF Workflow | 意图判断、总控派活、席位协作、交叉审查、结论、恢复 | 把模型输出直接当作可写外部系统的授权。 |
| DeerFlow Adapter | 为总控/席位提供既有模型、工具、技能、MCP、沙箱和用户上下文 | 从 `packages/harness/deerflow/**` 导入 `app.*`。 |
| WriteGuard | 风险识别、审批、目标租约、一次执行、审计 | 将密钥、target_key、idempotency_key 回传给浏览器或模型。 |
### 2.2 新旧隔离规则
1. 旧会商继续运行,旧路由、旧 API、旧数据表、旧任务深链全部不变。
2. 新页面独立使用 `/api/maf-roundtable/*` 和 `maf_roundtable_*` 表;只允许参考旧页面的布局、文案、交互和通用视觉规范。
3. 旧 `roundtable-planning/**` 中的业务 hook、草稿、Job、SSE 消费器和状态类型不能被新页面直接 import。
4. 若需要复用旧组件的视觉效果,必须复制/迁移为 `maf-roundtable/legacy-compatible/**` 中的新组件,替换为 MAF view model;或抽到无业务依赖的公共展示组件。旧页面不得因此改变行为。
5. 新旧页面都只能使用仓库本地依赖;UI 基础组件统一采用 **`tdesign-react`**,不接远程 UI、CDN 或外部运行时。
---
## 3. 用户可见的新版会商流程
### 3.1 首次进入
1. 用户点击独立菜单“MAF 会商(升级版)”,进入与旧会商相同层级的页面壳。
2. 左侧显示自己的 MAF 会商历史和“新建会商”。新建只创建一个**用户可见会商**,不显示 session/run/thread 表单。
3. 中心区域显示欢迎语、业务链/任务上下文入口和对话输入框。
4. 用户输入任务后,前端立即插入本地的用户气泡,调用一次 `POST /messages`,然后消费同一会商的 SSE 流。
### 3.2 一次会商轮次
1. SSE 推送“正在理解任务”事件;页面以旧会商的过程卡/总控气泡表现。
2. 若信息不足,推送 `clarification.required`,页面显示可回复的澄清卡;用户回答后仍通过输入框或卡片提交。
3. 若可以执行,总控输出“派活计划”;页面以旧的席位条、派活卡和消息气泡展示。
4. 每个席位的可见发言、工具进度、技能过程、交叉审查和总控收束都写入同一条时间线。
5. 出现外部写操作时,SSE 推送审批卡。用户批准/拒绝后,后端恢复工作流,SSE 继续推送;前端不手工轮询 run 状态。
6. 最终结论、事实账本、执行动作和报告作为对话流中的结果卡呈现;用户可以继续在同一会商输入追问。
### 3.3 “一个会商”与内部线程的关系
- 用户只认识 `conversation_id`;左侧历史、URL 和前端状态都以它为主键。
- 一个 conversation 可以有多轮用户消息,每轮消息产生一个内部 `maf_run`。
- `maf_session`、manager/seat thread、seat run 都是服务端内部执行身份。服务端使用既有 `ExecutionPrincipal` 绑定当前用户,并在真正需要某席位执行时懒创建/复用线程。
- 浏览器只收到经过脱敏的消息和事件,不会收到内部 thread id、能力快照、目标键、幂等键、密钥或原始工具结果。
### 3.4 总控质量闸门:派活不是“发出即完成”
当前旧会商的问题不是没有派活,而是席位只说一两句话、格式和证据都不合格时,总控仍把它当作完成并直接进入下一步。新版 MAF 必须把总控从“消息转发者”升级为**每项席位交付的验收责任人**。
每一个由总控发布的席位任务都必须有服务端持久化的 `task_contract`:
| 字段 | 含义 |
|---|---|
| `objective` | 本席位要回答的具体问题,不能只写泛泛角色描述。 |
| `expected_deliverable` | 交付类型和结构,例如“风险清单 + 依据 + 优先级 + 建议”。 |
| `acceptance_criteria` | 由总控给出的可验收标准:覆盖范围、最少关键点、证据/工具依据、格式与约束。 |
| `required` | 是否为本阶段必需交付;必需项不能被静默跳过。 |
| `max_rework_attempts` | 同一席位最多返工次数,默认 **2**(初稿之外最多两次返工),服务端配置且写入快照。 |
| `fallback_policy` | 到达返工上限后的策略:改派、请求用户澄清,或带缺口受控推进。 |
#### 3.4.1 席位交付与总控验收状态机
```mermaid
stateDiagram-v2
[*] --> assigned
assigned --> delivering
delivering --> submitted
submitted --> manager_review
manager_review --> accepted: 达到合同标准
manager_review --> rework: 不合格且未到返工上限
rework --> delivering: 带明确退回意见
manager_review --> reassigned: 达到上限且可改派
reassigned --> delivering
manager_review --> exhausted: 达到上限且无合适改派
exhausted --> controlled_gap: 记录缺口、风险与原因
accepted --> [*]
controlled_gap --> [*]
```
验收规则如下:
1. 席位先提交结构化 `delivery`,至少包含结论、依据/证据、未解决项、自检结果;不能只输出“已完成”或一两句空泛结论。
2. 进入 `manager_review` 前先执行确定性检查:空内容、最小有效长度、必须章节、必填字段、所需证据/工具引用、重复文本、错误 schema。确定性不通过时不允许直接 accepted。
3. 总控随后根据 `task_contract` 做结构化审查,决策只能是 `accept`、`return_for_rework`、`reassign`、`ask_user`、`controlled_gap`,并必须写明 `reason` 和针对性修改要求。
4. **总控的模型自评不是验收证据。** 席位自评分只作为参考;验收由确定性规则 + 总控审查 + 必要时交叉审查共同决定。
5. 对同一席位,默认最多两次返工。每次打回都必须把“缺什么、怎样补、哪些原结论不可用”带入下一次任务上下文。
6. 到达上限后绝不把不合格结果伪装成合格:总控应优先改派给一个合适备用席位(默认最多一次改派);仍无法满足时生成 `controlled_gap`,明确标记未覆盖问题、风险和对最终结论的影响,再受控进入下一阶段。
7. 一个阶段的所有 `required` 任务必须处于 `accepted` 或 `controlled_gap` 等明确终态,阶段闸门才可通过。总控不能因为“轮数到了”或“已有部分回答”跳过未决必需项。
8. 最终报告不得将 `controlled_gap` 的内容写成已验证事实;它必须在结论中的风险/待补信息部分可追溯显示。
这既满足“打回几次后不要死循环”的要求,也避免“超过次数就把垃圾答案强行推进”的错误行为。
#### 3.4.2 对话页必须可见的质量反馈
- 总控派活卡展示任务目标、交付要求和当前第几次尝试;
- 席位提交后显示“总控审核中”,而不是立即标为完成;
- 打回时以总控消息卡显示具体退回理由和补充要求;
- 改派时显示原席位未通过和新席位承接范围,但不羞辱性展示内部评分;
- 受控降级时显示“存在未解决缺口”,并在最终结果卡中保留风险提示;
- 右侧席位条区分“执行中、待返工、已验收、已改派、存在缺口”,不能只显示“发过言”。
---
## 4. API 与 SSE 契约(必须先定,前端不得猜测)
### 4.1 Conversation API
以下接口全部位于 `/api/maf-roundtable`,身份只从服务端鉴权上下文读取。
| 接口 | 用途 | 前端调用时机 |
|---|---|---|
| `GET /conversations` | 左侧历史列表(分页) | 首次进入、用户显式刷新、创建/删除后失效刷新;**无定时轮询**。 |
| `POST /conversations` | 创建空白用户会商 | 点击“新建会商”。只接收 title、任务上下文等安全字段。 |
| `GET /conversations/{id}` | 获取会商快照、权限和当前状态 | 进入会商或浏览器刷新时。 |
| `GET /conversations/{id}/messages` | 获取历史消息分页 | 进入会商、向上滚动加载历史。 |
| `POST /conversations/{id}/messages` | 原子写入用户消息并启动 MAF run | 用户点击发送或提交澄清。返回 `message_id`、`run_id`、`conversation_id`。 |
| `POST /conversations/{id}/cancel` | 取消当前活跃 run | 用户显式点击取消。 |
| `POST /approvals/{id}/decision` | 批准/拒绝写入动作 | 审批卡点击;成功后由后端恢复 workflow。 |
| `POST /conversations/{id}/recover` | 显式恢复异常中断的活跃会商 | 仅在后端判定可恢复时展示。 |
不再让页面以“创建 session → 创建 run → GET events 循环”的方式驱动会商。原有低层 session/run 接口可以作为内部诊断 API 暂时保留,但从用户页面和导航移除。
### 4.2 SSE:唯一的实时通道
```text
GET /api/maf-roundtable/conversations/{conversation_id}/stream?after_seq={last_seen_seq}
Accept: text/event-stream
Authorization: 与现有 fetch 客户端一致
```
- 前端在进入一个 conversation 后只建立**一条** fetch-reader SSE 连接;切换会商、卸载页面、权限失效时 Abort。
- 浏览器不能用定时 GET 代替 SSE。连接断开后采用指数退避重连,并携带最后已确认的 `after_seq`;不产生全量重复气泡。
- `after_seq` 是 conversation 维度、服务端单调递增的序号,不能复用每个 run 独立的 `seq`。
- 首次连接先由 `GET messages` 加载历史,再从该历史的最大 `seq` 订阅 SSE;服务端也必须支持重放,避免“历史请求和订阅之间”丢事件。
- SSE 使用 `fetch` + `ReadableStream` 解析,以复用项目鉴权头;响应必须带 `Content-Type: text/event-stream`、`Cache-Control: no-cache`、`X-Accel-Buffering: no`,并每 15 秒发送心跳。
- 服务端负责等待和推送。单 worker 可用进程内 conversation event hub;生产多 worker 部署前必须接入 Redis Pub/Sub 或等价分布式广播,不能退回浏览器轮询。
### 4.3 SSE 事件信封
所有事件统一为:
```json
{
"seq": 42,
"event_id": "evt_...",
"conversation_id": "conv_...",
"run_id": "run_...",
"type": "agent.message.delta",
"occurred_at": "2026-08-02T12:00:00Z",
"data": {}
}
```
允许的首批 `type`:
| 类型 | 对话页表现 |
|---|---|
| `conversation.snapshot` | 首帧状态同步,不重复插入消息。 |
| `user.message.created` | 刷新/多标签同步时补齐用户气泡。 |
| `manager.intent` | 总控“正在理解/已理解”的过程卡。 |
| `clarification.required` / `clarification.resolved` | 澄清卡及其回答状态。 |
| `manager.dispatch` | 总控派活卡、席位条状态更新。 |
| `seat.delivery.submitted` | 席位提交交付,进入总控审核而非直接完成。 |
| `manager.review.decision` | 展示验收、打回、改派或受控降级及其安全摘要。 |
| `seat.rework.assigned` / `seat.reassigned` | 更新第几次返工、原/新席位和新的任务要求。 |
| `stage.quality_gate` | 阶段质量闸门通过、阻塞或带缺口推进。 |
| `agent.message.start` / `delta` / `complete` | 席位或总控流式气泡。 |
| `tool.started` / `tool.progress` / `tool.completed` | 现有步骤卡/工具过程,不显示敏感参数。 |
| `approval.required` / `approval.decided` | 嵌入对话流的审批卡。 |
| `fact.confirmed` / `review.completed` | 事实/交叉审查摘要卡。 |
| `run.status` / `run.error` / `run.completed` | 顶部状态、失败重试与最终结果。 |
事件 `data` 必须先经过现有 MAF 安全规范化和二次展示脱敏;前端不负责猜测工具风险或修复敏感数据。
---
## 5. 后端改造计划
### MAF-R0:冻结错误原型并建立旧会商基线
**难度:D2(中低)|负责人:前端/测试各 1 人|前置:无**
- 将现有 `/page/maf/*` 标记为“实验原型”,从正式菜单移除;不得在其上继续新增业务功能。
- 记录旧会商的页面状态:空会商、发送后、意图澄清、总控派活、席位流式发言、审批、完成、失败恢复、历史切换。
- 为每种状态保存可复现的测试数据与截图基线;截图只作为视觉验收参考,不作为数据契约。
- 输出旧组件到新 MAF view-model 的映射清单,禁止直接搬旧 hook。
**验收:** 旧会商无行为回归;团队对“复制体验、替换编排”有书面映射表。
### MAF-R1:Conversation 聚合与消息持久化
**难度:D5(高)|负责人:后端资深 1 人|前置:R0**
新增/迁移 MAF 专用持久化模型:
- `maf_roundtable_conversations`:用户可见会商,至少包含 id、owner_user_id、title、task_context、安全状态、active_run_id、created_at、updated_at;
- `maf_roundtable_messages`:用户消息、总控/席位消息、澄清/审批/结果卡的稳定历史表示;
- `maf_roundtable_conversation_events`:conversation 维度严格递增的 `seq`、event_id、run_id、type、安全 data、created_at;
- 现有 `maf_roundtable_sessions/runs/events/seat_runs/actions/approvals` 保留为底层执行与审计记录;conversation 与内部 session/run 显式关联。
要求:
1. 发送用户消息、创建/占用 run、写入首个用户消息事件必须在清晰的事务边界内完成;失败不留“消息已显示但未运行”的孤儿状态。
2. 消息历史必须可在刷新后重建对话;不能只依赖内存或 SSE 临时帧。
3. 所有读写继续 owner-only;管理员诊断只读不扩大写权限。
4. 新迁移必须 SQLite/PostgreSQL/MySQL 可重复执行;旧 MAF 原型数据可保留,不强制伪造为新对话历史。
**验收:** 会话创建、连续发消息、刷新恢复、并发发送冲突、跨用户隔离、迁移幂等都有 API 和存储测试。
### MAF-R2:服务端 SSE Hub 与断线续传
**难度:D5(高)|负责人:后端流式/并发经验者 1 人|前置:R1**
- 新增 conversation stream 路由和 `ConversationEventHub`;Workflow/Dispatcher 的规范化事件落库后再发布,顺序是“先持久化、后通知”。
- SSE 连接先按 `after_seq` 重放,再订阅实时事件;重放和订阅切换期间必须有序、不丢帧、不重复。
- workflow 终态、审批等待、审批恢复、取消、失败重试都必须通过同一流通知。
- 不允许每个 SSE 客户端创建数据库轮询循环。服务端可以阻塞等待 hub 通知,事件重放只在连接/重连时发生。
- 写出单 worker 与多 worker 的实现边界;若部署配置多 worker,未接入分布式广播时健康检查必须明确告警并禁止该模式上线。
**验收:** 测试覆盖慢客户端、断线重连、`after_seq` 重放、同时打开两个标签、切换会商、取消、审批后恢复、进程内 hub 异常和终态自动关流。
### MAF-R3:总控意图理解与派活语义对齐
**难度:D5(高)|负责人:MAF/Agent 负责人 1 人|前置:R1,可与 R2 并行**
在现有 MAF Workflow 上增加用户对话入口状态,而不是让前端预先填 manager/seat/run:
1. 总控首先进行意图判断:普通问答、需要澄清、单席位任务、并行专家会商、链式业务会商、需要工具/写入。
2. 总控产出受 schema 校验的派活计划;只有服务端可将计划转成实际席位执行。
3. 每个计划项必须生成并冻结 `task_contract`(目标、交付结构、验收标准、必需性、返工上限和降级策略),席位的发言不等于交付完成。
4. 席位完成后先做确定性完整性检查,再由总控做结构化验收;总控可接受、打回同一席位、改派、请求用户补充或记录受控缺口。所有决策、次数和理由持久化到 checkpoint 与审计事件。
5. 默认初稿后最多两次同席位返工;到达上限优先改派一次,仍失败才以带风险标记的 `controlled_gap` 结束。严禁自动把不合格交付推进为合格事实。
6. 阶段迁移需经过质量闸门:所有必需任务均有 `accepted` 或受控缺口终态;最终总结只能消费已验收事实,缺口必须显式传入风险章节。
7. 席位集合来自业务链、可信能力快照和上下文;前端可呈现“建议/已参与席位”,但不能提交任意工具权限或 thread id。
8. 总控每轮应吸收已确认事实、验收结果、退回原因和用户追问;弱模型无效派活、重复派活、无收敛时走确定性纠偏/终止策略。
9. 已有 structured/group_chat、事实账本、交叉审查、审批 checkpoint、执行阶段身份均继续复用;只重构其输入输出为 conversation event。
**验收:** 用同一任务对照旧会商的意图澄清、总控派活、席位协作、打回/改派和收束结论;弱模型的短答、空答、错误 schema、缺证据、重复派活、非法席位、超轮次、返工上限和受控降级都有确定性保护测试。
#### R3 当前实施记录(2026-08-03)
后端已先完成 R3 的服务端核心骨架,作为 R1/R2 Conversation API/SSE 的后续:
- `app/maf_roundtable/dispatch_contracts.py` 提供确定性意图分类、服务端业务路线解析、schema 校验的 `MafDispatchPlan` 和弱模型防护;请求、模型输出都不能提供 agent id、thread id、tool metadata 或能力快照。
- `MafRoundtableConfig` 增加 `default_manager_agent_id`、`default_seat_agent_ids`、`business_routes` 和 `max_seats_per_run`。仓库配置保持空路线;上线前必须由部署配置填入实际 agent catalog 中的精确 id,未知业务路线失败关闭。
- 首条消息在同一事务内创建内部 session、服务端选定的 manager/seat participants 和冻结能力快照;澄清意图进入 `waiting_input`,不创建 run,用户补充信息后才允许重新 claim。
- Conversation service 已接入现有 `MafRunDispatcher`/`WorkflowRunner`,持久化 `manager.intent`、`manager.dispatch` 和 run 状态桥接事件;现有结构化工作流的席位集合仍只来自服务端 participants,manager 文本不能扩席或改派非法席位。
- V2 `POST /conversations/{id}/messages` 只返回 `message_id`、`conversation_id`、`seq`;`run_id` 仍是持久层/服务端内部关联字段,不返回给浏览器。
- 新增 `tests/test_maf_phase3_conversation_dispatch.py`,覆盖未知业务路线、默认路线、澄清、完成状态桥接、重复/越权派发计划等确定性用例。R3 尚未整体验收完成:仍需完成新页面、完整真实 MAF Workflow E2E、质量门禁和与旧会商体验的浏览器对照验收。
### MAF-R4:将审批和外部写入嵌回对话主链路
**难度:D4(较高)|负责人:后端安全 + 前端各 1 人|前置:R2、R3**
- 保留 Phase 5 的 WriteGuard、能力快照、HMAC 目标键、租约、加密参数、一次执行和审计;不得为了 SSE 改弱任何安全边界。
- `approval.required` 只携带白名单展示字段和安全摘要。审批决定后由后端自动续跑,前端只等待同一 SSE 流中的新事件。
- 拒绝、过期、执行失败、unknown 均形成清晰对话卡和可恢复状态;不得把“未知结果”伪装成成功。
- 行为审计可在最终结果区展开查看,但不能替代对话中的关键用户反馈。
**验收:** HTTP → MAF → ToolNode/outbox → 审批 → SSE → 前端卡片 的端到端测试;确保 target_key、idempotency_key、internal_canary、密钥和原始工具结果从不进入消息/API/SSE。
---
## 6. 前端改造计划:复刻体验,替换状态源
### MAF-R5:新会商页面壳与历史列表
**难度:D4(较高)|负责人:熟悉旧会商的前端 1 人|前置:R0、R1**
新建 `src/maf-roundtable/conversation/**`,建议结构:
```text
maf-roundtable/conversation/
pages/MafRoundtableConversationPage.tsx
components/
ConversationSidebar.tsx
ConversationTimeline.tsx
ConversationComposer.tsx
ManagerDispatchCard.tsx
SeatMessageBubble.tsx
ToolProgressCard.tsx
ClarificationCard.tsx
ApprovalMessageCard.tsx
FinalResultCard.tsx
ParticipantStrip.tsx
hooks/
use-maf-conversations.ts
use-maf-conversation-stream.ts
use-maf-conversation-reducer.ts
api/conversations.ts
lib/event-reducer.ts
styles/maf-roundtable-legacy-compatible.css
```
页面要求:
- 左侧 `ConversationSidebar` 的层级、历史列表、新建、激活态、删除/重命名交互对齐旧会商;
- 中间 `ConversationTimeline` 使用连续消息流,保留旧会商的用户气泡、总控气泡、席位气泡和时间锚点;
- `ConversationComposer` 常驻底部;发送、停止、澄清回答、追问都在该入口完成;
- 右侧仅保留旧体验中真正有用的参与席位、当前阶段和业务链摘要,不再摆放 run/session 管理后台;
- 使用本地 `tdesign-react` 组件实现按钮、输入、Dialog、Tag、Tabs 等基础交互,同时通过 scoped CSS 对齐旧视觉;
- 视觉相似不等于 import 旧业务组件。旧组件仅作参考,数据类型、hook 和 API 必须是 MAF 专用实现。
**验收:** 不连接后端时,使用固定 MAF 事件样本可完整演示旧会商同等的 8 种关键状态;没有 session/run/thread 表单。
### MAF-R6:SSE 客户端、事件 reducer 与刷新恢复
**难度:D5(高)|负责人:前端流式经验者 1 人|前置:R2、R5**
- `use-maf-conversation-stream` 只维护一个连接、一个 cursor、一个 AbortController;不得含 `setInterval`、`refetchInterval` 或轮询 fallback。
- reducer 以 `(conversation_id, seq)` 去重并排序,将原始事件转为稳定 view model;流式 delta 必须按 `message_id` 合并,不能用数组下标。
- 切换会商时先 abort 旧流并增加 generation;旧 SSE 帧永远不能污染新会商。
- 刷新时先加载消息历史,再以最后 seq 订阅;网络断开显示“正在重连”,重连成功不重复气泡。
- 只有历史列表等非实时资源可在用户主动操作后调用 GET;不能靠后台刷新伪装实时性。
**验收:** 模拟 1 万条历史、跨页加载、慢旧流切换、新流先到、断线重连、重复帧、乱序帧、终态关流和多标签同步;所有案例必须组件级测试。
### MAF-R7:意图/派活/审批卡的旧体验兼容
**难度:D4(较高)|负责人:前端业务负责人 1 人|前置:R3、R4、R6**
- 用旧 `IntentClarificationCard`、`MessageStepsCard`、`ParallelSeatStrip`、`MessageBubble` 的交互作为视觉和信息架构参照,重新实现 MAF 版本。
- 总控派活计划必须先显示“将由谁做什么”,席位开始/结束、工具过程和交叉审查要回到原有对话叙事中。
- 席位“发言结束”只能显示为“已提交,待总控审核”;只有收到 `manager.review.decision=accept` 才能显示“已验收”。打回次数、改派和缺口必须清楚可见。
- 审批卡需要同步防双击锁、二次脱敏、拒绝/通过后的“等待工作流继续”状态;不可另外跳转到 action 审计页。
- 最终结论卡要区分“建议动作”“审批中动作”“已执行动作”“失败/未知动作”。
- 继续追问时,页面不新建多个用户可见线程;后端根据 conversation 上下文决定是否创建新 run 或继续恢复。
**验收:** 产品人员可在不看技术术语的情况下完成“发起会商 → 澄清 → 观察派活 → 审批 → 查看结论 → 追问”全链路。
---
## 7. 测试、上线与回滚
### 7.1 必须新增的自动化测试
| 类别 | 核心用例 |
|---|---|
| 后端事务 | 发消息/创建 run 原子性、并发发送、跨用户隔离、迁移幂等。 |
| SSE 服务端 | 重放、顺序、心跳、取消、断线、审批恢复、多订阅者、终态关流。 |
| Workflow | 意图澄清、总控派活、弱模型格式错误、重复派活、最大轮次、恢复。 |
| 质量闸门 | 短答/空答、缺少必填章节、无证据、总控打回、两次返工上限、一次改派、受控缺口、阶段阻塞和最终报告不把缺口伪装成事实。 |
| 安全 | SSE/API/历史消息不泄露敏感键和值;审批和一次写入仍保持现有 Phase 5 保证。 |
| 前端 reducer | delta 合并、去重、乱序、切换代次隔离、重连 cursor。 |
| 前端组件 | 输入发送、澄清、派活、审批锁、取消、失败恢复、历史切换、无轮询断言。 |
| E2E | 从用户输入到真实 MAF Workflow、ToolNode/outbox、审批、最终结果的 SSE 全链路。 |
| 回归 | 旧 `roundtable-planning`、旧 DeerFlow、AI 写作以及既有 MAF Phase 1–5 用例全部通过。 |
### 7.2 人工视觉验收
在同一浏览器尺寸下对照旧会商,至少核对:
1. 空白页和新建会商;
2. 左侧历史/当前会商切换;
3. 用户输入、流式总控消息、席位消息;
4. 意图澄清和总控派活;
5. 工具过程、审批、取消、失败恢复;
6. 最终结论和连续追问;
7. 窄屏滚动、长内容、断线重连和页面刷新。
### 7.3 灰度与回滚
- 新入口使用独立 feature flag,例如 `maf_roundtable.conversation_ui_enabled`;旧会商不受该开关影响。
- 先仅向内部账号开放,记录连接数、重连率、事件延迟、工作流失败率、审批耗时和前端异常。
- 出现问题时关闭新入口即可;不迁移或删除旧会商数据,也不需要回滚旧页面。
- 当前错误原型可保留为仅开发者诊断路由,或在新版稳定后删除;它不应继续出现在用户菜单。
---
## 8. 分阶段任务分配、难度与交付顺序
本节是分工的唯一依据。难度定义:D1=很低(局部文案/样式),D2=低(明确边界的小模块),D3=中(跨 2–3 个模块),D4=较高(跨前后端或需回归),D5=高(并发、状态机、安全或 Agent 行为,必须由有经验者负责)。
### 阶段 0:冻结错误原型,提取旧会商交互基线(R0)
**难度:D2|建议人员:1 名熟悉旧会商的前端 + 1 名测试|依赖:无**
具体要做:
1. 将现有 `/page/maf/*` 的 session/run 详情原型从正式菜单隐藏,标注为开发诊断原型,停止继续加功能。
2. 逐一记录旧会商的 8 类页面状态:空白/新建、历史切换、用户提问、意图澄清、总控派活、席位发言、审批、完成/失败恢复。
3. 给每种状态保留可复现 mock 数据、页面截图和操作步骤;梳理旧组件到新 MAF view-model 的映射。
4. 明确哪些只能参考视觉和交互,哪些旧业务 hook/API/状态禁止复用。
交付物:旧会商交互地图、截图基线、组件映射表、被隐藏的原型入口说明。
验收:旧会商没有代码行为变化;任何人可以根据基线判断新版是否“像原页面”。
### 阶段 1:建立用户可见 Conversation 与消息历史(R1)
**难度:D5|建议人员:1 名资深后端|依赖:阶段 0**
具体要做:
1. 新增 `maf_roundtable_conversations`、`maf_roundtable_messages`、`maf_roundtable_conversation_events`,设计 owner、标题、消息、conversation 全局序号、活跃 run 和安全状态字段。
2. 建立 conversation 与现有 MAF session/run/seat-run 的内部关联;用户只得到 conversation id,不能看到内部 thread id。
3. 实现会商历史列表、创建空白会商、读取会商快照、读取消息分页、发送用户消息五类 API。
4. 发送消息时,用户消息持久化、run 创建/占用和首个事件必须有明确事务边界;并发发送、重复请求、失败回滚都要处理。
5. 完成 SQLite/PostgreSQL/MySQL 迁移与 owner-only 权限测试。
交付物:迁移脚本、repository/service/router、API schema、后端事务与隔离测试。
验收:刷新后能从消息历史恢复完整会商;跨用户不可读写;失败不会留下“已显示但没有实际运行”的孤儿消息。
### 阶段 2:服务端 SSE 对话流、事件 Hub 与断线续传(R2)
**难度:D5|建议人员:1 名熟悉 FastAPI 异步流与并发的后端|依赖:阶段 1**
具体要做:
1. 实现 `GET /conversations/{id}/stream?after_seq=`,按 conversation 全局 seq 先重放、后订阅实时事件。
2. 新建 `ConversationEventHub`;所有 workflow 事件先安全落库,再按顺序广播。禁止 SSE 客户端通过定时查库等待更新。
3. SSE 实现心跳、连接取消、权限校验、终态关流、异常帧和断线后的 cursor 续传。
4. 明确多 worker 部署方案:单 worker 可进程内广播;多 worker 必须 Redis Pub/Sub 或等价方案,未满足时不能灰度上线。
5. 把 run 状态、总控派活、席位消息 delta、工具过程、审批、质量审核、最终结论全部映射为统一事件信封。
交付物:SSE router/hub、事件发布适配器、集成测试、部署说明。
验收:慢连接、断线重连、乱序/重复防护、多标签订阅、审批后续跑、取消和终态均不丢事件;前端不需要轮询任何实时资源。
### 阶段 3:总控意图理解、业务链选择与服务端派活(R3)
**难度:D5|建议人员:1 名 MAF/Agent 工程师|依赖:阶段 1;可与阶段 2 并行**
具体要做:
1. 将旧会商的意图理解能力迁到 MAF 总控入口:识别直接问答、需澄清、单席位、并行会商、链式业务会商、工具/写入请求。
2. 总控根据业务链、用户上下文、可信能力快照选择席位,生成 schema 校验的派活计划;前端只展示,不参与编排。
3. Dispatcher 在服务端按需创建/复用 manager 和 seat 的内部执行线程,并由 `ExecutionPrincipal` 绑定当前用户。
4. 对弱模型增加确定性保护:非法席位、空派活、重复派活、无效 schema、超轮次、无法收束必须被拒绝、纠偏或终止。
5. 保持既有工具、技能、MCP、沙箱、事实账本、交叉审查和 checkpoint 恢复可用。
交付物:总控状态 schema、workflow executor、派活事件、弱模型测试矩阵。
验收:用户只输入任务,就能看到“意图理解 → 总控派活 → 席位执行”;浏览器没有 thread map 和派活决策代码。
### 阶段 4:席位任务合同、总控验收、打回与强制收束(R3-Q)
**难度:D5|建议人员:1 名 Agent/MAF 工程师 + 1 名后端状态机工程师|依赖:阶段 3**
具体要做:
1. 总控发布任务时冻结 `task_contract`:具体目标、交付格式、验收标准、必需性、返工次数、改派与降级策略。
2. 为每项席位任务持久化状态机:`assigned → delivering → submitted → manager_review → accepted/rework/reassigned/controlled_gap`。
3. 席位提交后先做确定性质量检查:空答、过短、必填章节缺失、格式错、无证据、重复内容等均不能自动完成。
4. 总控必须生成结构化验收决定和原因;不合格时打回并带精确补充要求。默认最多两次同席位返工,之后最多一次改派。
5. 改派仍失败时只能产生 `controlled_gap`,标记风险、缺失项和最终报告影响;严禁伪装为成功。
6. 增加阶段质量闸门:所有必需任务处于 `accepted` 或 `controlled_gap`,才允许进入交叉审查/下一阶段/最终总结。
7. 将尝试次数、退回理由、验收结果和缺口写入 checkpoint、审计和 SSE。
交付物:任务合同模型、持久化表/迁移、质量状态机、总控审查 prompt/schema、事件和测试。
验收:席位只说一两句话、无依据或内容垃圾时会被明确打回;达到上限不会死循环,也不会被当作合格产出;最终报告可追溯所有缺口。
### 阶段 5:审批、WriteGuard 与外部动作嵌入对话流(R4)
**难度:D4|建议人员:1 名安全后端 + 1 名前端|依赖:阶段 2、3、4**
具体要做:
1. 保留现有 Phase 5 的可信能力快照、WriteGuard、目标租约、HMAC、加密参数、一次执行与审计,不允许为新页面降低安全性。
2. 将工具开始、审批请求、批准/拒绝、执行成功/失败/unknown 变成安全 SSE 事件和对话卡。
3. 审批点击只调用明确决策 API;后端负责恢复 checkpoint/workflow,浏览器只等待 SSE。
4. 安全展示统一二次脱敏,禁止 target_key、idempotency_key、internal_canary、密钥、凭据和原始工具结果进入 API、消息、SSE 或 DOM。
交付物:事件映射、审批消息卡契约、端到端 ToolNode/outbox 测试。
验收:一次真实测试写入能在对话里经历“申请 → 审批 → 继续 → 结果”;重复点击或断线都不会重复外部写入。
### 阶段 6:复刻旧会商页面壳、历史列表和输入框(R5)
**难度:D4|建议人员:1 名熟悉旧会商代码的前端|依赖:阶段 0、1**
具体要做:
1. 新建 MAF 专用 conversation 页面、路由和独立 feature flag;不修改旧 `RoundtablePlanningPage`。
2. 依据阶段 0 的映射,复刻左侧历史会话、新建会商、中心时间线、常驻输入框、参与席位区和业务链摘要的视觉与交互层级。
3. 基础组件使用本地 `tdesign-react`,旧页面仅参考;需要的视觉组件在 MAF 目录重写或抽无业务依赖公共组件。
4. 接上 Conversation API:创建、历史、切换、消息分页。此阶段不允许先做任何轮询实时逻辑。
5. 删除新页面中暴露给用户的 manager/seat/max round/session/run 创建表单。
交付物:新页面壳、MAF 专用 view model、静态/接口 mock 组件测试、视觉对照截图。
验收:即使 SSE 未接通,用户也能看到与旧会商同类的历史、对话与输入体验;新旧业务状态零耦合。
### 阶段 7:前端 SSE 消费、对话 reducer 与过程交互(R6 + R7)
**难度:D5|建议人员:1 名前端流式工程师 + 1 名前端业务工程师|依赖:阶段 2、4、5、6**
具体要做:
1. 实现单连接 `use-maf-conversation-stream`:fetch-reader SSE、cursor、AbortController、指数退避重连和会商切换 generation 隔离。
2. 实现 event reducer:按 `conversation_id + seq` 去重排序;按 message_id 合并 delta;刷新后历史与 SSE 无缝衔接。
3. 重写旧会商对应的 MAF 版组件:总控意图卡、派活卡、席位条、席位气泡、工具步骤、澄清卡、审批卡、质量审核/打回卡、结果卡。
4. 所有卡片在时间线内叙事,不另开 run/session 管理后台;继续追问仍使用同一输入框。
5. 页面必须显示待审核、已验收、返工次数、改派、受控缺口和恢复状态,不能把“发过言”显示为“已完成”。
6. 代码审查和测试中检查不存在 `setInterval`、`refetchInterval` 或事件轮询 fallback。
交付物:SSE hook、reducer、对话组件、组件/API mock 测试、无轮询静态检查。
验收:切换会商、断线重连、审批续跑、慢旧流回包、长会话翻页均不污染、不丢消息、不重复;整个会商过程只依赖 SSE 实时更新。
### 阶段 8:端到端验收、灰度和回滚演练(R8)
**难度:D4|建议人员:1 名测试/集成人 + 各阶段负责人配合|依赖:阶段 1–7**
具体要做:
1. 跑完后端事务/SSE/Workflow/质量闸门/WriteGuard 测试、前端 reducer/组件测试、旧会商与 DeerFlow 回归。
2. 在真实浏览器按阶段 0 截图基线逐项对照,并完成用户任务:发起、澄清、派活、短答打回、两次返工、改派、审批、受控缺口、结论和追问。
3. 内部账号灰度,观测 SSE 建连/重连、事件时延、派活/验收/返工次数、workflow 失败率、审批耗时和前端错误。
4. 验证关闭 feature flag 后立即回到旧会商入口,旧数据和旧任务不受影响。
5. 若需生产外部写入,补齐 UAT 系统、最小权限凭据、核验 API、补偿联系人和生产 `MAF_ACTION_SECRET_KEY`。
交付物:自动化结果、人工验收记录、灰度指标面板、回滚演练记录、上线清单。
验收:满足第 9 节全部条件后才允许标记开发完成。
### 8.1 可并行边界
- 阶段 2 与阶段 3 可在阶段 1 的 schema/API 定稿后并行,但二者必须共用同一事件信封。
- 阶段 6 可在阶段 1 的 API mock 契约定稿后提前开始;不得自行发明事件字段。
- 阶段 5 必须等待阶段 2、3、4 的安全事件与状态机定稿。
- 阶段 7 必须等待阶段 2、4、6,不能以轮询临时替代 SSE。
- 阶段 8 只做集成、验收和上线准备,不补写前面阶段缺失的核心设计。
建议主顺序:`阶段 0 → 阶段 1 → (阶段 2 + 阶段 3 + 阶段 6) → 阶段 4 → 阶段 5 → 阶段 7 → 阶段 8`。
---
## 9. 最终验收定义
只有同时满足以下条件,才可以说“本次 MAF 会商升级开发完成”:
- 新页面在视觉和主交互上可被用户认作原多智能体会商的升级版;
- 页面具备历史会话、连续对话流、输入框、意图理解、总控派活、席位协作、澄清、审批、结果和追问;
- 每个必需席位任务都有任务合同、总控验收、有限返工和改派/受控缺口处理;席位短答或垃圾产出不能自动被当作完成;
- 浏览器没有会商事件/run/approval 的定时轮询;实时交互通过可重连 SSE 完成;
- 用户不需要创建或管理多个智能体线程,内部线程由服务端按用户身份安全创建和恢复;
- 新页面未调用旧会商业务 API/状态,旧会商零回归;
- 工具、技能、MCP、沙箱、审批、WriteGuard、一次写入和审计都仍可用;
- 自动化测试、SSE 故障测试、真实浏览器人工验收和旧功能回归全部通过;
- 真实 UAT 写入系统、最小权限凭据、外部核验 API、补偿协议及生产 `MAF_ACTION_SECRET_KEY` 已按 Phase 5 前置条件完成。
在这之前,任何“会话/run 原型页面通过构建或轮询测试”的结果,都只能算技术验证,不算产品升级验收。
---
## 阶段 3 实施记录(当前代码基线)
本轮已补齐阶段 3 的服务端安全路由与真实 MAF Workflow 入口,范围仅针对新 MAF 会商;旧 DeerFlow、旧 roundtable 和 AI 写作行为不变。
### 配置与入口闸门
- 仓库默认 `maf_roundtable.enabled: false`。部署环境必须注入真实的 `default_manager_agent_id`、席位 ID 和业务路由后再开启,避免出现“入口显示正常但首条消息必然 503”的空配置。
- 健康接口返回非敏感的 `conversation_dispatch_ready` 与 `conversation_dispatch_status`;新会商入口只有在配置路由可用且服务已启用时才开放。
- 首条消息使用服务端可信能力快照校验 manager/seat 的可访问性;浏览器、会话请求和模型输出都不能提供或扩大 agent、thread、tool、capability 范围。
- 配置模型会清理并校验 manager/seat ID,拒绝 manager 出现在 seat 列表、重复席位、超过 `max_seats_per_run` 的路由和非法业务 code。
### 受约束的总控派活
服务端先由业务链与可信 capability snapshot 生成候选席位集合。总控模型只能返回严格 JSON:`intent_type`、`selected_seat_agent_ids`、每席 `task_goal`/`delivery_requirements`、`execution_mode`、`convergence_path` 和 `reason`。Pydantic schema、服务端 allowlist 和顺序校验全部通过后,最终计划才会写入 checkpoint,并产生 `manager.dispatch` 审计/SSE 投影。
非法席位、重复席位、空任务、错误 schema、席位超限、缺少收敛路径或链式顺序错误,统一回退到服务端安全计划,不会扩大权限或启动越权席位。
四种结构化拓扑已固定为:
- `direct_answer`:manager-only Workflow,不创建专家席位任务;
- `single_seat` / `tool_write`:一个可信席位;
- `parallel_consultation`:至少两个可信席位并行;
- `chain_consultation`:按服务端业务链顺序串行。
### 阶段 3 验证状态
已覆盖配置校验、候选路由、非法总控计划回退、manager-only 真实 `WorkflowBuilder` 拓扑、线程/执行阶段回归、旧 DeerFlow 回归和会话 API 回归。当前仍不能据此标记整个 MAF 项目或阶段 5 为“验收完成”;真实 UAT 写入系统、最小权限凭据、外部核验 API、补偿协议和生产 `MAF_ACTION_SECRET_KEY` 仍按阶段 5/8 前置条件保持阻塞。
### Stage 3 P0 dispatch correction
- New MAF conversations no longer classify user text with server keyword rules. The server first freezes only the business-route candidate set and trusted, redacted capability summary; `ManagerDispatchExecutor` then returns the strict intent-and-dispatch JSON contract.
- The final plan is Pydantic-validated and allowlisted before it is checkpointed. Invalid JSON, illegal intent or seat, missing convergence, manager failure, and timeout all finish on the clarification branch; they do not create expert threads or start expert/tool work.
- A conversation initially persists and binds the manager only. After a valid decision, only `selected_seat_agent_ids` are added to the participant store and receive internal threads.
- Every non-clarification route, including `group_chat`, starts at the same manager dispatch node. Group speakers are limited to the verified selected seats; static candidate configuration cannot bypass the plan.
@@ -1,15 +0,0 @@
# 岗位会商沙箱文档
本目录存放**岗位会商文件预览沙箱**的对接与排障说明,独立于 `src/position-roundtable/docs/`,避免与模块内其它文档互相覆盖。
| 文档 | 说明 |
| --- | --- |
| [沙箱打开关闭与步骤条.md](./沙箱打开关闭与步骤条.md) | **详细版**:打开/关闭完整时序、步骤条关系、对接接口字段说明、必守规则、历史 bug 根因、排障手册、自测清单、接线示例与代码索引 |
模块总览仍见:`frontend-web/src/position-roundtable/README.md`。
建议读法:
- **从零对接新页面**:正文第 3、5、6、7、8、12、15、16 节
- **线上排障**:第 13、14 节
- **只要一页纸**:文末「附录 A」
@@ -1,988 +0,0 @@
# 岗位会商 · 沙箱打开 / 关闭与步骤条(详细对接与排障指南)
> **文档位置**:`frontend-web/docs/position-roundtable-sandbox/`
> **读者**:下次重做或对接岗位会商页面的同事;线上「沙箱不实时 / 卡死 / 第二次不刷新」时的排障同学。
> **最后依据**:当前仓库 `PositionRoundtablePage` + `PositionNodeChat` 实现(含临时名打开、外部 store、前沿节流、按 tool-call 重挂)。
---
## 目录
1. [文档用途与读法](#1-文档用途与读法)
2. [背景:为什么岗位会商要单独做沙箱](#2-背景为什么岗位会商要单独做沙箱)
3. [用户可见的正确行为(验收标准)](#3-用户可见的正确行为验收标准)
4. [整体架构与数据流](#4-整体架构与数据流)
5. [职责划分:谁拥有什么状态](#5-职责划分谁拥有什么状态)
6. [对接接口详解](#6-对接接口详解)
7. [打开沙箱的完整步骤](#7-打开沙箱的完整步骤)
8. [关闭沙箱的完整步骤](#8-关闭沙箱的完整步骤)
9. [步骤条与沙箱的关系](#9-步骤条与沙箱的关系)
10. [流式内容如何进入沙箱(性能关键)](#10-流式内容如何进入沙箱性能关键)
11. [与普通对话页的对照](#11-与普通对话页的对照)
12. [重做页面时的必守规则](#12-重做页面时的必守规则)
13. [历史问题与根因(务必读)](#13-历史问题与根因务必读)
14. [排障手册(按症状)](#14-排障手册按症状)
15. [对接自测清单](#15-对接自测清单)
16. [最小接线示例](#16-最小接线示例)
17. [关键代码索引](#17-关键代码索引)
18. [术语表](#18-术语表)
---
## 1. 文档用途与读法
### 1.1 这份文档解决什么问题
岗位会商右侧「文件预览沙箱」看起来像普通对话页的产物预览,但实现路径完全不同。历史上这块反复出过:
- 沙箱不实时打开,要等全文写完才弹;
- 打开了但内容冻住,生成完才一口气灌进去;
- 整页卡顿,连消息列表文字都不实时;
- 同轮「重新生成」第二次写入时,步骤条变了,沙箱却不动;
- 第一次正常,关掉后再问就不实时。
这些 bug **特别容易在「重做页面 / 换布局 / 自己重写开沙箱逻辑」时复现**。本文把正确对接方式、时序、接口、禁区和排障步骤写全,方便下一位同事直接按文档接线,而不是再靠猜。
### 1.2 建议读法
| 你的目标 | 先读哪些章节 |
| --- | --- |
| 从零接一个新页面壳 | 第 3、5、6、7、8、12、15、16 节 |
| 只改对话子组件探测逻辑 | 第 7、9、12、13 节 |
| 线上排障 | 第 13、14 节,必要时回看第 10 节 |
| 理解为什么不能用页面 state | 第 2、10、13 节 |
### 1.3 对照代码(以仓库为准)
| 角色 | 路径 |
| --- | --- |
| 页面壳(唯一沙箱宿主) | `frontend-web/src/position-roundtable/pages/PositionRoundtablePage.tsx` |
| 节点对话(探测 write_file、上报预览) | `frontend-web/src/position-roundtable/components/PositionNodeChat.tsx` |
| 收口对话 | `frontend-web/src/position-roundtable/components/PositionBuiltinAgentChat.tsx` |
| 预览 UI(共享组件,勿分叉逻辑) | `frontend-web/src/components/workspace/artifacts/artifact-file-detail.tsx` |
| 流式正文读取 | `frontend-web/src/core/artifacts/loader.ts` → `loadArtifactContentFromToolCall` |
| 普通对话页对照(步骤条自动开) | `frontend-web/src/components/workspace/messages/message-group.tsx` |
| 模块总览 | `frontend-web/src/position-roundtable/README.md` |
---
## 2. 背景:为什么岗位会商要单独做沙箱
### 2.1 普通对话页怎么开沙箱
普通对话页(`ChatPage`)大致是:
```text
ArtifactsProvider(页面级)
└─ ChatBox / MessageList
└─ message-group 渲染 write_file 步骤
└─ 发现 path 且 autoOpen → artifacts.select + setOpen(true)
└─ 右侧 ArtifactFileDetail 读同一套 ThreadContext
```
要点:
- 对话和预览共享同一套 `ThreadContext`(同一个 `useThreadStream`)。
- 步骤条组件自己就能触发打开。
- 流式 `content` 本来就在当前 React 树的 thread 里,不需要「把 thread 镜像到别的地方」。
### 2.2 岗位会商为什么不能照搬
岗位会商页面同时有:
- 左侧任务 / 意图 / 流程图;
- 中间某个节点的对话(`PositionNodeChat`);
- 右侧配置抽屉;
- **以及一个页面级单例沙箱**,它是对话区的**兄弟节点**,不在 `PositionNodeChat` 的 ThreadContext 里面。
因此:
1. 沙箱拿不到节点对话内部的 `thread`,除非节点主动上报;
2. 若把每次流式 thread 写进**页面级 `useState`**,整页(任务卡、意图、流程图、对话)都会按流式频率重渲染,主线程会被打爆;
3. 页面必须自己决定「开 / 关 / 抑制自动再开 / 切节点时清理」,不能让多个子组件各自 `setOpen`。
所以岗位会商采用:
```text
对话子组件探测 + 上报
→ 页面壳统一打开唯一 ArtifactFileDetail
→ 流式 thread 走外部 store,只让沙箱子树订阅
```
### 2.3 和「多智能体会商 Step2 沙箱」的区别
仓库里还有 `frontend-web/docs/roundtable-step2-sandbox-progress.md`,那是另一套圆桌 Step2 沙箱进度文档,**不是**岗位会商这条链路。对接岗位会商时以本文为准。
---
## 3. 用户可见的正确行为(验收标准)
重做或对接完成后,下列行为必须全部成立(用户感知对齐普通对话页):
| # | 行为 | 说明 |
| --- | --- | --- |
| A | 步骤条刚出现「写入文件」时,沙箱应已打开 | **不必等**步骤条上出现文件名 |
| B | 沙箱源码边写边滚;消息列表也实时出字 | 不能整页卡死、不能「生成完一口气刷」 |
| C | content 先于 path 时:先临时名打开,path 到了再改名 | 不闪屏、不重挂 |
| D | 同轮第二次同路径 `write_file`(重新生成) | 沙箱清空并重新流式 |
| E | 整轮结束后自动切 Markdown 预览 | 「正在生成,完成后自动预览」消失 |
| F | 用户手动关闭后,同一次写入不再自动弹 | 下一轮新写入仍可自动开 |
| G | 切岗位 / 切节点 / 新会话 / 切历史 | 沙箱关掉且不串内容 |
**不要误判的正常现象:**
- 流式期间沙箱停在「源码 / 编辑」视图,结束后才切「预览」——这是 `ArtifactFileDetail` 对 markdown/html 的既定行为,与普通对话页相同,**不是**打开时机 bug。
- 步骤条长时间显示「写入文件」、没有路径,但沙箱已经打开并在滚动——content-first 模型下这是**预期**。
---
## 4. 整体架构与数据流
```text
┌──────────────────────────────────────────────────────────────────────────┐
│ PositionRoundtablePage(页面壳) │
│ │
│ state: sandboxArtifact | null │
│ ref: sandboxArtifactRef / closedSandboxKeyRef / latestSnapshotRef │
│ store: createSandboxThreadStore() ←── 禁止改成 useState │
│ │
│ handlePreviewArtifact(artifact) ←──────────────────────────────────┐ │
│ handleNodeThreadSnapshot(...) ←───────────────────────────────┐ │ │
│ closeSandbox() │ │ │
│ │ │ │
│ {sandboxOpen && ( │ │ │
│ SandboxThreadProvider(store) │ │ │
│ └─ ArtifactFileDetail key=sandboxCloseKey(...) │ │ │
│ )} │ │ │
└───────────────────────────────────────────────────────────────────│──│───┘
│ │
┌───────────────────────────────────────────────────────────────────│──│───┐
│ PositionNodeChat / PositionBuiltinAgentChat │ │ │
│ │ │ │
│ useThreadStream → thread.messages / thread.isLoading │ │ │
│ │ │ │ │
│ ├─ MessageList → 步骤条(只展示 tool call) │ │ │
│ │ │ │ │
│ ├─ latestStreamingWriteFile(messages) │ │ │
│ │ → onPreviewArtifact({..., auto:true}) ───────────────────┘ │
│ │ │
│ └─ useEffect → onThreadSnapshot({threadId, thread}) ───────────────┘
└──────────────────────────────────────────────────────────────────────────┘
```
一句话:
- **谁打开**:对话子组件决定「该不该开、开哪次交付」;
- **谁真正开面板**:页面壳;
- **内容怎么更新**:子组件持续上报 thread 快照 → 页面壳 store → 只有沙箱子树重渲染。
---
## 5. 职责划分:谁拥有什么状态
### 5.1 页面壳必须拥有
| 状态 / 能力 | 为什么必须在页面壳 |
| --- | --- |
| `sandboxArtifact` | 唯一预览目标;切节点时要清 |
| `closedSandboxKeyRef` | 用户关过后的抑制;跨子组件生命周期 |
| `sandboxThreadStore` | 流式内容通道;不能进大页面 state |
| `closeSandbox()` | 切岗位 / 切节点 / 新会话统一入口 |
| 唯一 `ArtifactFileDetail` | 避免双实例、关闭失效、深度异常 |
### 5.2 对话子组件必须拥有
| 状态 / 能力 | 作用 |
| --- | --- |
| `autoPreviewRunArmedRef`(armed) | 只有本轮用户发送后才允许自动开 |
| `autoPreviewBaselineCallKeysRef`(baseline) | 忽略发送前已有的历史 write_file |
| `activeWriteFilePreviewRef` | 记录当前打开的 previewKey / path / toolCallId |
| `autoPreviewedArtifactKeyRef` | 同一次 identity 去重,避免每 chunk 重复上报 |
| `latestStreamingWriteFile` | 从 streaming messages 探测可预览的 write |
| `onThreadSnapshot` 上报 | 把 thread 喂给页面壳 |
### 5.3 明确禁止
1. 在 `PositionNodeChat` 内再挂一套 `ArtifactFileDetail`。
2. 让步骤条组件直接 `setOpen(true)` 作为岗位会商主路径(对照普通页可以,岗位会商不行)。
3. 把 `onThreadSnapshot` 落到 `PositionRoundtablePage` 的 `useState`。
4. 用「整个 threadId」做关闭抑制。
5. 用「path 相同」复用 `previewKey`。
---
## 6. 对接接口详解
### 6.1 `PositionArtifactPreview`
```ts
type PositionArtifactPreview = {
threadId: string; // 必填:LangGraph thread id
path: string; // 必填:真实路径,或 write-file: 虚拟 URL,或临时文件名路径
name: string; // 展示名(文件名)
mimeType: string | null; // 如 text/markdown;帮助预览语言判断
previewKey?: string; // 强烈建议:一次交付身份,推荐 `${messageId}:${toolCallId}`
auto?: boolean; // true = 流式自动打开;缺省/false = 用户点击打开
};
```
字段说明:
| 字段 | 详细含义 |
| --- | --- |
| `threadId` | 沙箱用来匹配 `onThreadSnapshot` 的线程;也对关闭抑制键有贡献 |
| `path` | 传给 `ArtifactFileDetail.filepath`。流式阶段通常是 `write-file:...` 虚拟 URL;落盘后的手动打开可以是真实 artifacts 路径 |
| `name` | UI 展示用;临时名阶段可能是 `未命名文件.md` |
| `mimeType` | 当 path 还不稳定时,帮助把语言判成 markdown/html,避免落成 TEXT |
| `previewKey` | **一次交付的身份**。同一次 tool call 的 path 升级要保持不变;新的 tool call 必须变 |
| `auto` | 自动打开才走关闭抑制;手动打开应清抑制 |
### 6.2 `onPreviewArtifact(artifact)` —— 对话 → 页面
页面壳 `handlePreviewArtifact` 当前逻辑顺序:
1. 校验 `threadId`、`path`,缺则 toast 并 return。
2. 计算 `artifactKey = sandboxCloseKey(artifact)`。
3. 若 `artifact.auto === true` 且 `closedSandboxKeyRef.current === artifactKey` → **抑制,直接 return**。
4. 清 `closedSandboxKeyRef`(手动打开或新的自动打开)。
5. `ArtifactsContext.select(path, true)` + `setOpen(true)`。
6. 判断是否同一预览 / 是否仅 path upgrade:
- `isSamePreview`:threadId + path + previewKey 全同 → 不重复 setState。
- `isPathUpgrade`:previewKey 相同、path 不同 → 更新 artifact,**不要**再折叠右侧抽屉。
7. 若不是 same preview:
- `setSandboxArtifact(artifact)`;
- **同步** `sandboxArtifactRef.current = artifact`(关键!flush 会立刻读 ref);
- `sandboxSnapshotAppliedAtRef.current = 0`(允许立刻推首帧内容)。
8. 若 store 里已有别的 thread 快照,先 `publish(null)`。
9. 若 `latestNodeThreadSnapshotRef` 的 threadId 匹配,立刻 `queueSandboxThreadSnapshot`。
10. 非 path upgrade 时 `setRightPanelOpen(false)`。
`sandboxCloseKey`:
```ts
if (artifact.previewKey) {
return `${artifact.threadId}:write:${artifact.previewKey}`;
}
return `${artifact.threadId}:${normalizePreviewArtifactPath(artifact.path)}`;
```
`ArtifactFileDetail` 的 React `key` 必须用这个 key:
**新 previewKey → 组件重挂 → 视觉上「清空再生成」。**
### 6.3 `onThreadSnapshot({ threadId, thread })` —— 对话 → 页面
每次 `thread` 引用变化(消息 chunk 到达)子组件都会调:
```ts
onThreadSnapshot?.({ threadId: activeThreadId, thread });
```
页面壳应:
1. 计算 `signature = sandboxThreadSignature(thread)`(用 isLoading、messages 长度、最近 write_file 的 path/content 长度/尾部等拼签名,用于去重)。
2. 写入 `latestNodeThreadSnapshotRef`(即使沙箱还没开,打开瞬间也要用)。
3. 若当前没有打开的沙箱,或打开的沙箱 threadId 不一致 → **只更新 ref,不 publish**。
4. 若一致 → `queueSandboxThreadSnapshot`(前沿节流后 `store.publish`)。
### 6.4 虚拟 URL 与正文读取
流式阶段 path 形如:
```text
write-file:${sourcePath}?message_id=${messageId}&tool_call_id=${toolCallId}&language=markdown
```
`loadArtifactContentFromToolCall`:
1. 解析 URL 的 `message_id`、`tool_call_id`;
2. 在 `thread.messages` 里找对应 AI message 的 tool call;
3. 返回 `toolCall.args.content`。
结论:
- 沙箱跟的是 **tool call 身份**,不是磁盘文件是否已经写完;
- 没有真实 path 也能显示正文;
- 临时文件名只影响展示名和语言猜测。
### 6.5 对话子组件 → 页面壳的其它相关回调
| 回调 | 用途 |
| --- | --- |
| `onPreviewArtifact` | 打开 / 更新沙箱 |
| `onThreadSnapshot` | 推送流式 thread |
| 页面壳 `closeSandbox` 传给 `ArtifactFileDetail.onClose` | 用户点关闭 |
手动从流程图 / 产物列表打开时,也可以直接调 `handlePreviewArtifact`(通常不带 `auto`,或不带 previewKey)。
---
## 7. 打开沙箱的完整步骤
### 7.1 武装(arm):只有「本轮用户提交」才允许自动开
在 `PositionNodeChat.handleSubmit` 真正 `sendMessage` 之前:
```text
activeWriteFilePreviewRef = null
autoPreviewBaselineCallKeysRef = writeFileCallKeys(thread.messages) // 历史 write 的 messageId:toolCallId
autoPreviewRunArmedRef = true
→ sendMessage(...)
```
发送失败要把 `armed` 设回 `false`。
为什么要 baseline?
线程里往往已经有上几次问答写过的 `write_file`。如果只看「messages 里有没有 write_file」,一提问就会把旧文件再打开一次。baseline 的含义是:**只有这次提交之后新出现的 tool call 才能自动开沙箱**。
### 7.2 探测 `write_file`:不要等完整 path
`write_file` 参数是一整段 JSON 流,**键顺序由模型决定**。
| 模型吐参顺序 | 步骤条表现 | 错误做法的后果 |
| --- | --- | --- |
| path / description 先到,再 content | 很快显示描述和文件名 | 普通对话页常见;等 path 也能开 |
| **content 先到,最后才 path** | 长时间只有「写入文件」,文件名很晚才出现 | 若硬等完整 path,沙箱会晚几十秒甚至一分钟 |
岗位会商报告类 agent **经常是第二种**。
`latestStreamingWriteFile` 规则:
1. 倒序扫描 AI messages 的 `tool_calls`;
2. 工具名是 `write_file` 或 `str_replace`;
3. **有完整扩展名的 path**(`hasCompleteArtifactExtension`)→ 用真实路径;
4. **尚无可用 path,但 `write_file` 的 content 已有非空字符** → 临时文件名:
- 正文头像 HTML → `未命名文件.html`
- 否则 → `未命名文件.md`
5. `str_replace` 必须等真实 path(它改已有文件);
6. 组装:
- `key = messageId:toolCallId`
- `path = write-file:虚拟URL`(write_file)或真实 path(str_replace)
- `mimeType`:markdown 则 `text/markdown`
为什么扩展名必须完整?
流式 path 会经历 `/a/b/report.m` → `/a/b/report.md`。若在 `.m` 时就当真实文件打开,预览语言可能被永久判成 TEXT。
### 7.3 上报 effect 的四个门闩
自动上报 `onPreviewArtifact` 前必须同时满足:
1. `thread.isLoading === true`
2. 探测到 streaming artifact,且其 key **不在** baseline
3. 已有 `previewThreadId`
4. `autoPreviewRunArmedRef === true`
然后处理 previewKey:
```text
若与 activePreview 是同一次 tool call(含 tool-start 前缀兼容)
→ 复用旧 previewKey // 用于临时名 → 真实 path
否则
→ previewKey = 新的 messageId:toolCallId
```
去重键:
```text
`${previewThreadId}:${previewKey}:${sourcePath}`
```
把 `sourcePath` 算进去,是为了:**同 previewKey 下临时名变成真实 path 时,还要再报一次**(path upgrade),但不会每来一个 content chunk 都报。
### 7.4 线程绑定竞态(不要误 disarm)
首轮对话常出现:
1. 用户发送(本地 draft threadId / 稍后 SDK 创建真实 id);
2. 流已经开始、armed=true;
3. 会话 API 把 `node.threadId` 从 `null` 写成真实 id。
这是「本节点绑定自己的新线程」,**不是**切节点。若绑定 effect 无脑清空 armed / baseline,首轮会永远开不了沙箱。
正确:识别 `isOwnThreadBinding`(同 nodeKey、旧 threadId 为空、新 threadId 等于当前 boundThreadId)时 **直接 return,不清 armed**。
### 7.5 path upgrade(改名)≠ 第二次交付
同一次 tool call:
```text
T1 content 到达 → path=未命名文件.md, previewKey=msg:tc1 → 打开
T2 真实 path 到达 → path=/mnt/.../报告.md, previewKey=msg:tc1 → 只改名
```
页面壳看到相同 previewKey、不同 path → `isPathUpgrade`:
- 更新 `sandboxArtifact`;
- **不**重挂(React key 仍基于 previewKey);
- **不**再折叠右侧抽屉。
### 7.6 同路径二次写入(重新生成)
同一次问答里模型可能:
```text
1) write_file → 步骤条「写入文件」→ 打开沙箱
2) 再 write_file 同 path,description=「重新生成优化版…」
```
这是**两次 tool call**,必须两个 previewKey。
若错误地「path 相同就复用 previewKey」:
- 步骤条出现第二条;
- 沙箱 React key 不变;
- 用户看到「重新生成了,但沙箱没变化」。
正确:身份只看 tool call。
### 7.7 时序总图(content-first)
```text
T0 用户发送 → armed=true,拍 baseline
T1 步骤条出现「写入文件」(尚无 path)
T1+ args.content 首字符到达 → 临时名打开沙箱,源码开始滚动
… store 约每 160ms 推一次 thread 快照 …
T2 args.path 拼完整(含 .md)→ path upgrade,标题改真实文件名(不重挂)
T3 write 结束 / isLoading=false → 自动切 Markdown 预览
```
### 7.8 时序总图(同轮二次写入)
```text
T1 write_file#1 → previewKey=msg:tc1 → 打开沙箱 A
T2 #1 结束(可能短暂切预览)
T3 write_file#2(同 path,新 description)→ previewKey=msg:tc2
→ key 变 → 组件重挂清空 → 跟 #2 重新流式
```
---
## 8. 关闭沙箱的完整步骤
### 8.1 用户手动关闭
`closeSandbox()` 应做:
1. `closedSandboxKeyRef = sandboxCloseKey(current)` —— 抑制**这一次**自动再开;
2. 关闭 `ArtifactsContext.open`(若开着);
3. 清节流定时器、pending 快照;
4. `sandboxSnapshotAppliedAtRef = 0`;
5. `sandboxArtifactRef = null` + `setSandboxArtifact(null)`;
6. `sandboxThreadStore.publish(null)`。
抑制与 path upgrade 的关系:
- 关掉临时名面板后,同一次 tool call 升级真实 path **仍被抑制**(同一 previewKey)——符合「用户不要看这次」;
- 下一次新的 `write_file`(新 previewKey)**可以**再自动开。
### 8.2 场景切换时强制关闭
以下操作应先调用 `closeSandbox()`,避免串台:
- 切岗位;
- 切节点;
- 切收口阶段;
- 新建会话;
- 切换历史会话。
是否写入 `closedSandboxKeyRef` 可按产品决定;至少必须清面板和 store。
### 8.3 错误的抑制粒度(历史坑)
若做成「关过一次就整个 thread 不再自动开」:
- 第一次实时开正常;
- 用户关掉;
- 再问一次 → 同 thread 被永久抑制 → 看起来像「第二次不实时 / 要等生成完」。
正确粒度:**单次交付的 `sandboxCloseKey`(含 previewKey)**。
---
## 9. 步骤条与沙箱的关系
### 9.1 步骤条从哪来
步骤条由 `MessageList` → `message-group.tsx` 渲染 tool call:
- 标题:优先 `args.description`;没有则 i18n 兜底「写入文件」;
- 子行:有 `args.path` 才显示路径;
- 普通对话页还会在「有 path + autoOpen」时自己 `select/setOpen`。
岗位会商里,步骤条**仍然只负责展示**;打开沙箱走 `onPreviewArtifact`,不要让两套逻辑抢。
### 9.2 对照表
| 你看到的步骤条 | 含义 | 沙箱应处于 |
| --- | --- | --- |
| 仅「写入文件」,无路径 | tool call 已开始;path/description 可能还没流到 | **应已打开**(临时名),源码在滚 |
| 「写入文件」+ 路径 | path 已可用 | 已打开;若刚从临时名升级则只改名 |
| 带自定义 description 的标题 + 路径 | 模型给了 description | 同上 |
| 第二条「重新生成…」+ 同路径 | 新的 write_file(新 toolCallId) | **应重挂**并重新流式 |
| 顶部「正在生成,完成后自动预览」 | 仍在 code 视图 | 正常,等 isLoading 结束切预览 |
| 生成结束,出现文件卡片 / present_files | 工具结果已落 | 通常已是预览模式;可手动再点开 |
### 9.3 常见误解
**误解 1:**「步骤条出现文件名 = 打开沙箱的正确时机」
→ 错。那是 path 到达的时机。content-first 时正确打开时机更早:content 首字节 / 工具调用已开始。
**误解 2:**「步骤条还在写『写入文件』,沙箱却开了,是 bug」
→ 通常不是。两边数据源相同,但沙箱允许无 path 打开,步骤条标题可能还没 description。
**误解 3:**「等生成完从编辑切预览 = 沙箱打开晚了」
→ 错。那是 `ArtifactFileDetail` 的 viewMode 策略。
---
## 10. 流式内容如何进入沙箱(性能关键)
### 10.1 为什么不能用页面 `useState` 存线程快照
错误写法:
```ts
setSandboxThreadSnapshot(snapshot) // 页面级 useState
```
后果:
- 消息 chunk 约每 30ms 一次,节流后仍约 6 次/秒;
- 每次都重渲染整页:任务卡、意图结果、流程图、节点对话……;
- 主线程占满 → 消息列表停绘、沙箱冻住;
- 纯尾随 `setTimeout(160)` 会被饿死,十几秒不 flush。
这同时解释了两个历史现象:
1. 「沙箱打开了但内容不更新」;
2. 「修完节流后整页更卡、消息也不实时」——因为节流终于开始真正 setState 了。
### 10.2 正确做法:外部 store + 子树订阅
```ts
createSandboxThreadStore()
subscribe / getSnapshot / publish
SandboxThreadProvider
useSyncExternalStore(store.subscribe, store.getSnapshot)
→ ThreadContext.Provider value={{ thread, isMock:false }}
→ ArtifactFileDetail
```
页面壳本身**不**因 snapshot 变化而重渲染;只有 Provider 及其子树重渲染。
### 10.3 节流必须是前沿(leading-edge)
`SANDBOX_SNAPSHOT_MIN_INTERVAL_MS = 160`:
```text
queue(snapshot):
pending = snapshot
if 距上次 publish >= 160ms:
立刻 flush(同步 publish)
else:
若没有在途 timer,则 setTimeout(剩余时间) 做补尾
flush:
清 timer
校验 pending.threadId === sandboxArtifactRef.threadId
publish(pending)
```
**不要**改回:
```ts
if (timer != null) return;
timer = setTimeout(flush, 160);
```
那是纯尾随;忙主线程下会假死。
### 10.4 signature 去重
`sandboxThreadSignature` 用最近 write_file 的 path、content 长度、content 尾 32 字等拼签名。
store.publish 时若 threadId+signature 未变,则不通知订阅者,减少无效渲染。
### 10.5 打开瞬间的首帧
`handlePreviewArtifact` 里往往会立刻 `queueSandboxThreadSnapshot(latestSnapshot)`。
此时 React 的 `setSandboxArtifact` 可能还没提交,若 flush 只读旧的 `sandboxArtifactRef`,会因 threadId 不匹配把首帧丢掉。
所以打开新预览时必须:
```ts
sandboxArtifactRef.current = artifact; // 同步
sandboxSnapshotAppliedAtRef.current = 0;
```
---
## 11. 与普通对话页的对照
| 点 | 普通对话页 | 岗位会商 |
| --- | --- | --- |
| 谁触发打开 | `message-group` 内 `artifacts.select` | 子组件 `onPreviewArtifact` → 页面壳 |
| 是否要求 path | 是(有 path 才自动开) | 否(write_file + content 可临时名开) |
| thread 从哪来 | 同树 ThreadContext | `onThreadSnapshot` + 外部 store |
| 关闭抑制 | 主要靠 ArtifactsContext / 用户操作 | `closedSandboxKeyRef` 按 previewKey |
| 同 path 重写 | 依赖新的 tool call / 选择逻辑 | **必须**新 previewKey 以重挂 |
| 结束后切预览 | ArtifactFileDetail 同一套 | 同一套 |
对齐目标是**用户感知一致**,不是代码路径完全相同。
普通对话页自动开的核心条件(对照用):
```ts
artifacts && isLoading && isLast && autoOpen && autoSelect && path && !result
```
它也要求 path,所以 content-first 时普通页同样会偏晚——只是很多主聊天示例 agent 先吐 path,观感更好。岗位会商报告 agent 更常 content-first,所以必须做临时名提前开。
---
## 12. 重做页面时的必守规则
按优先级:
1. **流式 thread 快照禁止进页面级 `useState`** → 用 store + `useSyncExternalStore`。
2. **节流用前沿 + 补尾**,不要纯尾随 timer。
3. **不要等完整 path 才开**;`write_file` + content 即可临时名打开。
4. **扩展名完整前不要把 path 当最终 path**。
5. **previewKey 按 tool call,不按 path**。
6. **打开时同步写 `sandboxArtifactRef`,并重置节流时间戳**。
7. **主路径扫描 `thread.messages`,不要只靠 `onToolStart`**。
8. **path upgrade 保持 previewKey,不要当第二次交付**。
9. **关闭抑制按 sandboxCloseKey,不要按整 thread**。
10. **沙箱单例在页面壳;子组件只上报**。
11. **本节点 threadId 回写不要 disarm**。
12. **「结束后才切预览」不要当打开 bug 去「修」掉共享组件**,除非产品明确要求边生成边渲染 Markdown(需单独评估性能)。
---
## 13. 历史问题与根因(务必读)
下面每个都在真实联调里出现过。重做时若踩中,优先回来对照。
### 13.1 沙箱要等文件名出来才开(晚几十秒)
**现象:** 步骤条早就「写入文件」,沙箱很晚才开;普通对话页对比显得「实时」。
**根因:** 探测逻辑硬等完整 `path`;而该 agent 先流 `content`、最后才流 `path`。
**修复:** content 首批字符即可用临时名打开;path 到了再 upgrade。
### 13.2 沙箱打开了,内容冻住,生成完才灌满
**现象:** 面板开了,但里面一直是空/旧内容;日志里 queue 很多,flush 很少。
**根因:** 纯尾随 160ms 定时器在忙主线程下被饿死。
**修复:** 前沿节流——到期就在流回调里同步 flush。
### 13.3 修完「内容更新」后,整页卡顿、消息也不实时
**现象:** 沙箱开始更新了,但页面更卡,消息列表也「攒到最后刷」。
**根因:** flush 走的是页面 `useState`,每 160ms 整页重渲染。以前 timer 饿死时反而「不卡」。
**修复:** 快照改外部 store,只让沙箱子树订阅。
### 13.4 第二次「重新生成」步骤有了,沙箱不变
**现象:** 同轮第二条二条 write 步骤,沙箱仍显示第一次完整结果。
**根因:** 用「path 相同」复用了第一次 previewKey,React key 不变,组件不重挂。
**修复:** previewKey 只按 tool call;同 path 新 call 必须新 key。
### 13.5 第一次实时,关掉后再问就不实时
**现象:** 关过沙箱后,下一轮要等生成完才开,或不开。
**根因:** 抑制绑在整个 threadId,或把 path upgrade / 新 call 误判成同一次。
**修复:** 抑制键 = `sandboxCloseKey(previewKey)`;仅抑制那一次交付。
### 13.6 首轮永远不开
**现象:** 新建节点第一次提问,armed 后很快又不满足条件。
**根因:** `node.threadId` 从 null 回写真实 id 时,绑定 effect 误 disarm。
**修复:** `isOwnThreadBinding` 时不清 armed。
### 13.7 预览变成纯文本
**现象:** 明明是 md,却按 TEXT 打开。
**根因:** 在 `.m` 阶段就当完整 path;或临时名没有 `.md` / 没传 language、mimeType;或 path 带空格。
**修复:** `hasCompleteArtifactExtension`;临时名带扩展名;URL 加 `language=markdown`;path trim。
### 13.8 依赖 onToolStart,线上偶发不开
**现象:** 本地偶发正常,联调经常不开。
**根因:** 后端 StreamBridge / worker 可能过滤 tools/events 类 stream mode。
**修复:** 主路径必须是 messages 里渐进出现的 `tool_calls`;onToolStart 只能当补充。
---
## 14. 排障手册(按症状)
排障时建议先看 Chrome Performance / React 重渲染是否整页抖,再看消息里 tool_calls 的 args 是 path-first 还是 content-first。
### 14.1 沙箱开得很晚
检查顺序:
1. `latestStreamingWriteFile` 是否仍要求完整 path?
2. armed 是否被 threadId 回写清掉?
3. 是否命中 `closedSandboxKey`?
4. 新 call 是否被 baseline 当成历史?
5. `previewThreadId` 是否为空(线程还没绑上)?
### 14.2 打开了但内容空白 / 冻住
1. 快照是否进了页面 useState?
2. 节流是否纯尾随?
3. `SandboxThreadProvider` 是否拿到带 messages 的 thread?
4. 虚拟 URL 的 message_id / tool_call_id 是否对得上?
5. 打开时 `sandboxArtifactRef` 是否同步?(首帧是否被 drop)
6. signature 是否因实现错误一直不变,导致 publish 被去重?
### 14.3 整页卡、消息列表也不实时
1. 搜页面壳是否还有 `setSandboxThreadSnapshot` / 类似大对象 state。
2. 是否在每 chunk `console.debug` 打大对象(DevTools 打开时更卡)。
3. 是否错误地让页面壳订阅了 store(页面壳不应 `useSyncExternalStore` 这份 store;只有 Provider 订)。
### 14.4 重新生成不刷新
1. 第二次 write 的 toolCallId 是否变了?
2. previewKey 是否仍用 path 复用?
3. `ArtifactFileDetail` 的 `key=` 是否基于 sandboxCloseKey/previewKey?
### 14.5 关后再问异常
1. 打印 `closedSandboxKeyRef` 与新 artifact 的 sandboxCloseKey。
2. 确认新一轮 send 时 armed/baseline 已重置。
3. 确认抑制不是整 thread。
### 14.6 语言 / 预览模式不对
1. 看打开时的 path / mimeType / language 查询参数。
2. 确认不是在扩展名不完整时打开。
3. 确认「源码→预览」发生在 isLoading false 之后(属正常)。
---
## 15. 对接自测清单
重做页面后至少跑完:
### 功能
- [ ] 首轮:步骤条「写入文件」出现时,沙箱是否已开并开始出字?
- [ ] content-first agent:无文件名阶段是否也能开?
- [ ] path 到达后:是否只改名、不整页闪、不重挂?
- [ ] 同轮第二次同路径 write:是否清空并重新流式?
- [ ] 结束后是否自动切 Markdown 预览?
- [ ] 手动点步骤条路径 / 产物卡片:能否打开正确文件?
### 关闭与抑制
- [ ] 流式中手动关闭:本次是否不再自动弹?
- [ ] 关闭后再发一轮新问题:是否仍可自动开?
- [ ] path upgrade 是否不会绕过「用户刚关闭」的抑制?
### 场景切换
- [ ] 切节点:沙箱关闭,旧内容不残留。
- [ ] 切岗位:同上。
- [ ] 新建会话 / 切历史:同上。
### 性能
- [ ] 流式中消息列表是否实时出字?
- [ ] 页面是否明显掉帧 / 卡死?
- [ ] React DevTools 中,大页面壳是否在每 160ms 整页 update?(不应)
---
## 16. 最小接线示例
### 16.1 页面壳(示意)
```tsx
const [sandboxArtifact, setSandboxArtifact] = useState<PositionArtifactPreview | null>(null);
const sandboxArtifactRef = useRef<PositionArtifactPreview | null>(null);
const closedSandboxKeyRef = useRef<string | null>(null);
const latestNodeThreadSnapshotRef = useRef<SandboxThreadSnapshot | null>(null);
const store = useMemo(createSandboxThreadStore, []);
// pending + timer + appliedAt 用于前沿节流(见 PositionRoundtablePage)
function handlePreviewArtifact(artifact: PositionArtifactPreview) {
if (!artifact.threadId || !artifact.path) return;
const key = sandboxCloseKey(artifact);
if (artifact.auto && closedSandboxKeyRef.current === key) return;
closedSandboxKeyRef.current = null;
artifactsCtx?.select(artifact.path, true);
artifactsCtx?.setOpen(true);
const prev = sandboxArtifactRef.current;
const isSame =
prev?.threadId === artifact.threadId &&
prev.path === artifact.path &&
prev.previewKey === artifact.previewKey;
const isPathUpgrade =
!isSame &&
Boolean(artifact.previewKey) &&
prev?.threadId === artifact.threadId &&
prev.previewKey === artifact.previewKey;
if (!isSame) {
sandboxArtifactRef.current = artifact; // 必须同步
setSandboxArtifact(artifact);
sandboxSnapshotAppliedAtRef.current = 0;
}
if (store.getSnapshot()?.threadId !== artifact.threadId) {
store.publish(null);
}
const latest = latestNodeThreadSnapshotRef.current;
if (latest?.threadId === artifact.threadId) {
queueSandboxThreadSnapshot(latest);
}
if (!isPathUpgrade) setRightPanelOpen(false);
}
function handleNodeThreadSnapshot(snapshot: { threadId: string; thread: BaseStream<AgentThreadState> }) {
const next = { ...snapshot, signature: sandboxThreadSignature(snapshot.thread) };
latestNodeThreadSnapshotRef.current = next;
if (sandboxArtifactRef.current?.threadId !== snapshot.threadId) return;
queueSandboxThreadSnapshot(next);
}
function closeSandbox() {
if (sandboxArtifactRef.current) {
closedSandboxKeyRef.current = sandboxCloseKey(sandboxArtifactRef.current);
}
// clear timer / pending / appliedAt
sandboxArtifactRef.current = null;
setSandboxArtifact(null);
store.publish(null);
artifactsCtx?.setOpen(false);
}
// 渲染
{sandboxArtifact && (
<SandboxThreadProvider
store={store}
threadId={sandboxArtifact.threadId}
fallbackThread={stub}
>
<ArtifactFileDetail
key={sandboxCloseKey(sandboxArtifact)}
filepath={sandboxArtifact.path}
threadId={sandboxArtifact.threadId}
mimeType={sandboxArtifact.mimeType}
onClose={closeSandbox}
allowVirtualMarkdownEdit
/>
</SandboxThreadProvider>
)}
```
### 16.2 对话子组件(示意)
```tsx
// send 前
activeWriteFilePreviewRef.current = null;
autoPreviewBaselineCallKeysRef.current = writeFileCallKeys(thread.messages);
autoPreviewRunArmedRef.current = true;
await sendMessage(...);
// 探测
const streaming = thread.isLoading ? latestStreamingWriteFile(thread.messages) : null;
const next =
streaming && !autoPreviewBaselineCallKeysRef.current.has(streaming.key)
? streaming
: null;
useEffect(() => {
if (!thread.isLoading || !next || !previewThreadId || !autoPreviewRunArmedRef.current) return;
// previewKey:同 tool call 复用,否则用 next.key
// artifactKey = threadId:previewKey:sourcePath 去重
onPreviewArtifact?.({
threadId: previewThreadId,
path: next.path,
name: next.name,
mimeType: next.mimeType,
previewKey,
auto: true,
});
}, [next, previewThreadId, thread.isLoading, onPreviewArtifact]);
useEffect(() => {
onThreadSnapshot?.({ threadId: activeThreadId, thread });
}, [activeThreadId, thread, onThreadSnapshot]);
```
**强烈建议:** 探测 / armed / baseline / 临时名逻辑直接复用或抽取自 `PositionNodeChat`,不要从零重写。
---
## 17. 关键代码索引
| 主题 | 位置 |
| --- | --- |
| 临时名 / 完整扩展名 / latestStreamingWriteFile | `PositionNodeChat.tsx` 中 `provisionalWriteFilePath`、`hasCompleteArtifactExtension`、`latestStreamingWriteFile` |
| armed / baseline / 上报 effect | `PositionNodeChat.tsx` `handleSubmit` + streaming preview `useEffect` |
| 同 tool call 判断 / 二次写入重挂 | 同上,`isSameToolCall` / `previewKey` |
| 线程绑定保护 | `PositionNodeChat.tsx` node binding `useEffect` 中 `isOwnThreadBinding` |
| sandboxCloseKey / store / 前沿节流 | `PositionRoundtablePage.tsx` `sandboxCloseKey`、`createSandboxThreadStore`、`queueSandboxThreadSnapshot` |
| 打开 / path upgrade / 抑制 | `PositionRoundtablePage.tsx` `handlePreviewArtifact` |
| 关闭 | `PositionRoundtablePage.tsx` `closeSandbox` |
| 虚拟 URL 读 content | `core/artifacts/loader.ts` `loadArtifactContentFromToolCall` |
| 源码/预览切换 | `artifact-file-detail.tsx` 中 `viewMode` + `thread.isLoading` |
| 普通页步骤条自动开 | `message-group.tsx` `write_file` 分支 |
相关提交(背景):
- `fix(frontend): 岗位会商沙箱在 write_file 流式阶段实时打开并刷新`
— 临时名打开、外部 store、前沿节流
- `fix(frontend): 同路径二次 write_file 时重挂岗位会商沙箱`
— previewKey 按 tool call,禁止按 path 复用
---
## 18. 术语表
| 术语 | 含义 |
| --- | --- |
| armed | 本轮用户发送后,允许自动打开沙箱的开关 |
| baseline | send 前已有的 write tool call 集合,用于忽略历史产物 |
| previewKey | 一次交付的稳定身份,推荐 `messageId:toolCallId` |
| sandboxCloseKey | 关闭抑制键,同时用作 `ArtifactFileDetail` 的 React key |
| provisional path / 临时名 | 尚无真实 path 时的 `未命名文件.md` / `.html` |
| path upgrade | 同 previewKey 下临时名升级为真实 path |
| sandboxThreadStore | 流式线程外部 store,避免整页重渲染 |
| write-file: URL | 用 message_id + tool_call_id 定位流式 content 的虚拟路径 |
| leading-edge throttle / 前沿节流 | 到期立即在回调里 publish,而不是只挂尾随 timer |
| content-first / path-first | 模型流式 JSON 参数时 content 与 path 哪个先到 |
| isOwnThreadBinding | 本节点把自己的新 threadId 写回 props,不是切节点 |
---
## 附录 A:给对接同学的一页纸摘要
1. 页面壳只挂一个沙箱;子组件只调用 `onPreviewArtifact` / `onThreadSnapshot`。
2. 自动打开时机 ≈ 步骤条出现「写入文件」时,而不是出现文件名时。
3. `write_file` 可以没有 path:临时名打开,path 到了再改名。
4. 流式 thread 进外部 store,进页面 state 会卡死。
5. 节流要前沿;previewKey 看 tool call;关闭抑制看 sandboxCloseKey。
6. 同路径重新生成 = 新 previewKey = 沙箱重挂。
7. 出问题先对照第 13、14 节,再看代码索引第 17 节。
@@ -1,7 +0,0 @@
# 技能知识归纳与“知识梳理”助手知识库
管理员在「技能管理 → 技能知识归纳」中选择一个或多个技能、一个或多个目标,系统按“技能 × 目标”创建后台任务。界面提供总体进度、单项失败重试、实体/关系审核、绑定重归纳、自动同步和两种解绑动作。技能列表通过一次 bindings 查询展示归纳目标,避免逐技能请求。
扫描仅处理知识资料。代码、脚本、锁文件、密钥文件以及 Markdown 代码块不会进入上传、摘要、提示词或知识指纹;ZIP 只读取逐项验证通过的知识成员。自动监听只比较该知识指纹,所以纯代码改动不会产生 stale 状态。
知识库页面新增「普通知识库 / 助手知识库」并行入口。管理员可将系统默认入口设为 v1(普通 WeKnora)或 v2(全局“知识梳理”)。助手库无需 WeKnora 即可初始化,所有用户可只读查看和搜索 Wiki;管理员可上传本地文件、从普通库导入、重新导入或删除来源、查看版本并回滚。来源删除只移除对应贡献,共享实体与关系继续保留。
File diff suppressed because it is too large. Load diff
@@ -1,822 +0,0 @@
# 沙箱统一写作管线:可实现开发方案
> 状态:设计稿;本文件只定义实施方案,不包含本轮业务代码改动。
> 覆盖范围:普通沙箱 Markdown、深度研究 `report.md`、现有 Markdown 编辑器的选区/段落改写。
## 1. 目标与结论
目标不是再增加一个“AI 写作页面”,而是将现有的四类能力统一为一个安全、可流式、可追溯的**文档改写管线**:
1. Markdown 编辑器选区改写;
2. Markdown 编辑器段落改写;
3. 深度研究报告的局部候选改写;
4. 沙箱中 Markdown 文件的全文改写。
该管线负责固定原文版本、构造上下文、逐 token 输出、校验 Markdown、生成可核验 diff、按策略提交,以及在全文覆盖时保存可撤销版本。
结论:需求可行,现有工程已有足够的复用基础:
- `frontend-web/src/open-canvas/components/artifact/MarkdownAiEditor.tsx` 已具备局部改写弹窗与人工“替换/插入/重试/追问”交互。
- `frontend-web/src/open-canvas/hooks/useWritingRewrite.ts` 与 `frontend-web/src/open-canvas/api/rewrite.ts` 已具备 SSE 文本流消费。
- `offline-backend-20260512/backend/app/gateway/routers/writing.py` 已具备模型流式读取实现。
- `offline-backend-20260512/backend/app/gateway/routers/deep_research.py` 已具备报告哈希、候选内容和用户确认应用机制。
- `frontend-web/src/components/workspace/messages/message-list.tsx`、`MessageGroup.tsx` 已可承载普通对话的工具步骤条、流式消息和文件卡片。
- `frontend-web/src/pages/deep-research/DeepResearchWorkbench.tsx` 已经通过虚拟消息把研究进度接入普通 `MessageList`。
因此应该复用这些基础,建设一个执行内核;不能为全文改写另建独立聊天列表或独立写作流。
## 2. 产品边界与交互策略
### 2.1 支持范围
第一版仅对 `.md`、`.markdown` 文件显示“AI 全文改写”按钮。
不支持 PDF、DOCX、HTML、图片和二进制文件;不在改写过程中发起新的联网搜索;超大文件不静默截断后覆盖,而是提示用户选择章节改写。
### 2.2 范围、模式和提交策略
| 入口 | 文本范围 | 管线模式 | 提交策略 | 展示位置 |
| --- | --- | --- | --- | --- |
| 编辑器气泡菜单 | 当前选区 | `selection` | `preview_only` | 现有改写预览弹窗 |
| 编辑器段落菜单 | 当前段落 | `paragraph` | `preview_only` | 现有改写预览弹窗 |
| 深度研究“改写第一段/章节” | 被解析出的报告片段 | `report_section` | `manual_apply` | 普通消息列表候选稿 + 确认卡 |
| 文件右上角“AI 全文改写” | 当前完整 Markdown | `document` | `auto_commit_after_validation` | 普通消息列表步骤条 + 右侧沙箱 |
统一内核中的枚举:
~~~python
class RewriteMode(str, Enum):
SELECTION = "selection"
PARAGRAPH = "paragraph"
REPORT_SECTION = "report_section"
DOCUMENT = "document"
class CommitPolicy(str, Enum):
PREVIEW_ONLY = "preview_only"
MANUAL_APPLY = "manual_apply"
AUTO_COMMIT_AFTER_VALIDATION = "auto_commit_after_validation"
~~~
这三类策略必须严格区分:
- `preview_only`:只生成候选,前端编辑器确认后才改本地 TipTap 文档;不写真实沙箱文件。
- `manual_apply`:后端保留基准哈希和候选片段,用户点确认后才将该片段应用进研究报告。
- `auto_commit_after_validation`:全文生成完成并校验通过后,后端进行一次带哈希校验的原子覆盖;同时保存可撤销版本。
### 2.3 局部编辑器:保持当前体验
现有文件:
- `frontend-web/src/open-canvas/components/artifact/MarkdownAiEditor.tsx`
- `frontend-web/src/open-canvas/hooks/useWritingRewrite.ts`
- `frontend-web/src/open-canvas/api/rewrite.ts`
- `offline-backend-20260512/backend/app/gateway/routers/writing.py`
局部改写仍然是:
1. 选中文字或打开段落菜单;
2. 选择润色、扩写、缩写、改写等动作;
3. 在现有弹窗中流式出现候选;
4. 用户手动选择替换、插入、重试或继续追问。
不要让局部改写每次都往普通消息列表插完整步骤条,否则频繁编辑会淹没聊天历史。它只共享底层管线,不共享全文改写的消息展示方式。
需要补充本地版本保护:发起请求时保存当前完整编辑器文本哈希、选区 `from/to` 和选区文本;用户点击“替换原文”前再次检查该范围仍匹配。若用户已修改原文,提示“原文已变化,请重新生成候选稿”,禁止将过期候选替换到错误位置。
### 2.4 右上角“AI 全文改写”
宿主文件:
- `frontend-web/src/components/workspace/artifacts/artifact-file-detail.tsx`
新增独立图标按钮,位置在右上角文件操作区,靠近保存、复制、下载一类操作。它**不能**替代页面中间当前 Sparkles 编辑模式:
| 控件 | 职责 |
| --- | --- |
| 中部 Sparkles/编辑模式 | 打开 `MarkdownAiEditor`,处理选区和段落 |
| 新增右上角 AI 全文改写 | 对整个 Markdown 发起后台全文重写任务 |
建议显示条件:
~~~ts
const canUseFullDocumentRewrite =
isMarkdownFile &&
canEditArtifact &&
!isSkillFile &&
!isMock &&
!useWriteFileStreaming &&
!hasLocalEdits;
~~~
若 `hasLocalEdits` 为真,按钮置灰并提示“请先保存当前修改后再进行全文改写”。后端全文任务从真实文件读取快照,不能在用户本地还有未保存修改时读取旧版本并最终覆盖新修改。
用户体验:
1. 点击按钮,打开简洁配置弹窗。
2. 弹窗显示文件名、原文字数;用户填写改写要求、选择模型、选择风格。
3. 点击开始,左侧普通消息列表创建一组步骤条。
4. 右侧沙箱自动切到源码视图,先显示“正在准备临时草稿,原文件尚未修改”。
5. 新 Markdown 从空临时草稿开始逐 token 写入右侧代码区域。
6. 校验通过后,后端原子替换真实内容;前端再同步真实 Artifact 缓存。
7. 左侧保留最终对比总结、查看 diff 按钮和撤销按钮。
任务进行中,同一个文件的保存、直接编辑、局部编辑和再次全文改写必须禁用;其他文件不受影响。
### 2.5 深度研究报告的约束
普通 Markdown 和深度研究报告使用同一管线,但不能使用同一上下文策略:
| 能力 | 普通沙箱 Markdown | 深度研究 report.md |
| --- | --- | --- |
| 输入上下文 | 原文 + 用户指令 | 原文 + 当前会话已选资料 |
| 联网 | 不联网 | 不联网 |
| 事实约束 | 不新增无依据事实 | 只能引用已选资料,禁止编造 |
| 引用校验 | 可选 | 必须校验来源 ID 白名单 |
| 最终存储 | Artifact 文件 | 研究 session 的 `report_markdown` |
| 局部改写 | 编辑器确认 | 现有确认卡片 |
深度研究右侧的 `report.md` 是由 `ResearchSandboxPanel.tsx` 以虚拟 `write_file` 方式展示的;它不能当作普通磁盘 Artifact 直接写入。全文任务必须通过研究 session 更新 `report_markdown`,并使 `report_html` 缓存失效。
## 3. 总体架构
~~~mermaid
flowchart LR
A["MarkdownAiEditor<br/>选区 / 段落"] --> P
B["ArtifactFileDetail<br/>AI 全文改写"] --> P
C["DeepResearch<br/>局部 / 全文"] --> P
P["Document Rewrite Pipeline<br/>冻结版本 → 构造上下文 → 流式生成<br/>校验 → 差异总结 → 按策略提交"]
P --> I["InlineDocumentSource"]
P --> F["ArtifactDocumentSource"]
P --> R["DeepResearchReportSource"]
P --> E["可恢复 SSE 事件 / Job"]
E --> L["普通 MessageList"]
E --> S["右侧沙箱临时草稿"]
P --> V["内容哈希、版本快照、原子提交"]
~~~
设计原则:
1. 纯执行内核不依赖 FastAPI、路由、用户身份或操作系统路径。
2. 鉴权、线程路径解析、研究 session 获取只在 `app` 层的来源适配器中完成。
3. 完整文档任务使用持久化后台 Job;局部弹窗可维持单次 SSE,避免过度持久化。
4. 全文流式过程中只写临时草稿;真实内容只在最终 compare-and-swap 成功时改变。
不要直接把现有完整“AI 写作 Agent”塞进改写按钮。那个流程适合从主题写新文章,可能包含大纲、资料和章节生命周期;本需求是严格以当前文档为基准改写。第一版复用它的流式视觉表达和消息列表能力,但使用专门的文档改写执行内核。
## 4. 后端模块设计
### 4.1 目录与职责
建议新增:
~~~text
offline-backend-20260512/backend/
├─ packages/harness/deerflow/
│ ├─ document_rewrite/
│ │ ├─ __init__.py
│ │ ├─ models.py # 请求、事件、校验、差异领域模型
│ │ ├─ ports.py # Source / Model / Store 协议
│ │ ├─ pipeline.py # 统一编排,不导入 app.*
│ │ ├─ prompt_builder.py # 普通与深度研究提示词
│ │ ├─ validation.py # Markdown / 引用 / 截断检查
│ │ └─ diff_summary.py # 字数、标题、块、引用差异
│ └─ persistence/
│ └─ document_rewrites/
│ ├─ base.py
│ ├─ model.py
│ └─ sql.py
├─ app/gateway/
│ ├─ routers/document_rewrites.py
│ ├─ document_rewrite_sources.py
│ └─ document_rewrite_executor.py
└─ packages/harness/deerflow/persistence/migrations/versions/
└─ <next_revision>_document_rewrites.py
~~~
`packages/harness/deerflow/document_rewrite` 不能导入 `app.*`,以符合项目 harness→app import firewall。`app/gateway/document_rewrite_sources.py` 负责把已鉴权的 Artifact/研究会话包装成内核端口。
### 4.2 来源端口
~~~python
class DocumentSource(Protocol):
async def read_snapshot(self) -> DocumentSnapshot: ...
async def read_current_hash(self) -> str: ...
async def commit_if_unchanged(
self,
*,
expected_hash: str,
content: str,
metadata: CommitMetadata,
) -> CommitResult: ...
async def restore_if_unchanged(
self,
*,
expected_hash: str,
content: str,
) -> CommitResult: ...
~~~
三种实现:
| 适配器 | 使用场景 | 读取方式 | 提交方式 |
| --- | --- | --- | --- |
| `InlineDocumentSource` | 选区/段落候选 | 前端编辑器快照 | 不提交 |
| `ArtifactDocumentSource` | 普通 Markdown | 复用 Artifact 权限与虚拟路径解析 | 同目录临时文件 + `os.replace` |
| `DeepResearchReportSource` | 研究报告 | session `report_markdown` + 已选来源 | 数据库哈希条件更新 |
`ArtifactDocumentSource` 必须复用 `app/gateway/routers/artifacts.py` 中已有的线程访问校验、虚拟路径解析逻辑,绝不允许请求体传入任意本机绝对路径。
### 4.3 持久化 Job、事件和版本
全文改写使用持久化 Job,参考 `app/gateway/deep_research_job_executor.py` 的后台任务、租约、取消监听和事件重放模式。
#### document_rewrite_jobs
| 字段 | 作用 |
| --- | --- |
| `id` | `drw_xxx` Job ID |
| `user_id` | 发起人 |
| `source_kind` | `artifact` / `deep_research_report` |
| `thread_id`、`artifact_path` | 普通文件来源 |
| `research_session_id` | 研究报告来源 |
| `presentation_thread_id` | 普通消息列表归属 |
| `mode`、`commit_policy` | 范围和提交语义 |
| `instruction`、`style`、`model_name` | 用户配置 |
| `base_sha256` | 原文冻结哈希 |
| `draft_content`、`draft_sha256` | 临时流式草稿 |
| `status`、`stage` | 生命周期 |
| `validation_json`、`diff_summary_json` | 可展示结果 |
| `committed_sha256` | 成功提交后的哈希 |
| `error_message`、时间字段 | 错误、审计、取消 |
#### document_rewrite_events
至少包含 `job_id`、`seq`、`event_type`、`stage`、`payload_json`、`created_at`。`seq` 用于断线重连时通过 `after_seq` 重放。
不必将每个 token 单独入库:每 250ms 或每积累 4KB 持久化一次 `draft_content`;状态转换、警告、完成、冲突、取消必须立即写事件。重连时先发送最新草稿快照,再发送快照序号后的增量事件。
#### document_rewrite_versions
保存真实全文覆盖前的原文版本,字段包含 `job_id`、`source_identity`、`version_no`、`content`、`sha256`、`reason`、`created_at`。初版每个文档保留最近 20 个版本即可。
索引要求:
- `(user_id, presentation_thread_id, created_at DESC)`:恢复历史消息。
- 真实来源标识 + 活跃状态:防止同一文档并行两个全文改写。
### 4.4 Job 状态机
~~~mermaid
stateDiagram-v2
[*] --> queued
queued --> snapshotting
snapshotting --> generating
generating --> validating
validating --> comparing
comparing --> committing
committing --> completed
completed --> reverted
queued --> cancelled
generating --> cancelled
snapshotting --> failed
generating --> failed
validating --> failed
committing --> conflict
committing --> failed
~~~
状态约束:
- 同一真实文档只允许一个活跃 Job。
- 生成期间取消、异常、断线,真实文档绝不能变化。
- 提交前重新读取当前哈希;与 `base_sha256` 不一致时进入 `conflict`,草稿保留但不覆盖。
### 4.5 API 与 SSE 契约
创建全文任务:
~~~http
POST /api/document-rewrites
Content-Type: application/json
~~~
普通 Artifact 请求:
~~~json
{
"source": {
"kind": "artifact",
"thread_id": "thread_xxx",
"path": "/mnt/user-data/outputs/report.md"
},
"presentation_thread_id": "thread_xxx",
"mode": "document",
"instruction": "统一为正式行业分析语气,减少重复,不新增外部事实",
"style": "formal_analysis",
"model_name": "system_default"
}
~~~
深度研究请求:
~~~json
{
"source": {
"kind": "deep_research_report",
"session_id": "drs_xxx"
},
"presentation_thread_id": "collector_thread_xxx",
"mode": "document",
"instruction": "重新组织全文逻辑,保留全部可用引用",
"style": "formal_analysis",
"model_name": "system_default"
}
~~~
其他接口:
~~~text
GET /api/document-rewrites/{job_id}
GET /api/document-rewrites/{job_id}/stream?after_seq=42
POST /api/document-rewrites/{job_id}/cancel
POST /api/document-rewrites/{job_id}/undo
GET /api/document-rewrites?presentation_thread_id={thread_id}
~~~
SSE 事件:
| 事件 | 关键数据 | 前端动作 |
| --- | --- | --- |
| `job_started` | 文件名、模式 | 建立步骤条 |
| `snapshot_fixed` | 原文字数、哈希 | 完成“固定原文版本” |
| `requirements_resolved` | 模型、风格、要求 | 完成“理解改写要求” |
| `rewrite_delta` | `delta`、累计字符数 | 追加右侧临时草稿 |
| `validation_started` | 校验项 | 进入校验步骤 |
| `validation_completed` | passed、warnings | 显示校验结果 |
| `comparison_ready` | `DiffSummary` | 渲染总结数据 |
| `commit_started` | 无 | 显示安全替换中 |
| `committed` | 最终哈希、版本 ID | 刷新真实文件缓存 |
| `completed` | 完整结果 | 固化历史步骤条 |
| `conflict` / `error` / `cancelled` | 原因 | 恢复原文显示,不保存草稿 |
局部改写兼容方案:
- `POST /api/writing/rewrite` 的请求和 SSE 格式先不变。
- `writing.py` 内部逐步把 prompt、模型流、基础 Markdown 校验下沉给统一管线的 `preview_only` 分支。
- 深度研究 `/sessions/{id}/rewrite/stream` 和确认候选接口也先保持 URL、前端行为不变,再内部复用 `manual_apply` 分支。
这样可以先交付全文改写,不会一次性破坏已有编辑器和深度研究流程。
### 4.6 模型、提示词与校验
管线只依赖一个流式模型端口:
~~~python
class StreamingRewriteModel(Protocol):
async def stream_text(
self,
*,
messages: list[BaseMessage],
model_name: str | None,
) -> AsyncIterator[TextChunk]: ...
~~~
第一版可以有两个 adapter:
- 普通文档复用 `writing.py` 的 chat model `astream`;
- 深度研究复用 `deep_research.py` 使用的 `DeerFlowCompletionBackend.stream_complete`。
先统一编排,不强制立即统一所有模型配置实现。
普通 Markdown 系统约束:
~~~text
仅根据原文与用户要求改写,不联网,不补充未给出的事实。
保留有效链接、代码块、表格、标题语义和用户明确要求保留的内容。
只输出完整 Markdown 正文;不得输出解释、前缀或“改写如下”。
~~~
深度研究额外约束:
~~~text
不得联网。事实、数字、结论和引用只能来自当前 session 已选资料。
只允许使用给出的 source_id;资料不足时保持谨慎表述,禁止自行补全。
~~~
校验规则:
| 类别 | 硬失败 | 告警但允许完成 |
| --- | --- | --- |
| 正文 | 空文档、仅空白、无可见内容 | 改写后与原文完全一致 |
| Markdown | 未闭合围栏、明确截断 | 标题层级跳级、章节数明显减少 |
| 深度研究来源 | 未选来源 ID、非法引用 | 引用数量下降、可能需核验的数字断言 |
## 5. 安全提交、对比与撤销
### 5.1 临时草稿不等于真实文件
用户视觉上看到“先清空再逐 token 写入”,但真实文件的处理必须是:
1. 读取原文并保存内容哈希、版本快照。
2. 右侧只展示内存/Job 中的 `draft_content`。
3. 生成完成后做校验和 diff。
4. 提交前再次读取真实来源,并比较 `SHA-256`。
5. 哈希一致才原子替换;否则进入冲突,不覆盖。
普通 Artifact 使用同目录临时文件、刷盘和 `os.replace`;深度研究通过数据库事务内的“旧哈希条件更新”提交。任何失败、取消或断流都保留真实原文。
### 5.2 撤销
撤销流程:
1. 读取该 Job 的 `before_full_rewrite` 快照。
2. 确认当前真实内容哈希仍等于该 Job 的 `committed_sha256`。
3. 若用户在改写后又手工编辑,返回冲突,不盲目覆盖。
4. 先保存当前内容为 `before_undo` 版本。
5. 原子恢复旧版本,Job 状态改为 `reverted`,消息列表卡片同步显示“已撤销”。
### 5.3 结构化 DiffSummary
后端产出结构化差异,前端仅渲染,避免生成空泛结论:
~~~ts
type DiffSummary = {
sourceDisplayName: string;
instruction: string;
modelName: string;
originalCharCount: number;
rewrittenCharCount: number;
charChangeRatio: number;
changedBlockCount: number;
headings: {
added: string[];
removed: string[];
reordered: string[];
levelWarnings: string[];
};
citations?: {
beforeCount: number;
afterCount: number;
retainedCount: number;
removedIds: string[];
invalidIds: string[];
};
requestedOptimizations: string[];
validationWarnings: string[];
};
~~~
推荐总结展示:
~~~text
已完成《新能源汽车市场分析报告》的整体改写。
- 改写范围:全文;要求为“统一正式分析语气、减少重复”;模型:默认模型。
- 数量变化:原文 8,260 字,改写后 8,110 字,减少 1.8%;调整 14 个内容块。
- 结构变化:标题层级保持不变;未新增或删除一级标题。
- 已执行的优化:按要求合并重复表述、统一语气、调整段落衔接。
- 保留情况:保留 35 条已选来源引用,未新增外部来源。
- 风险提示:无。
[查看前后对比] [撤销到改写前版本]
~~~
“已执行的优化”仅来自用户要求和可计算的结构差异;不能无依据宣称“文章更专业、更严谨”。
## 6. 前端实现设计
### 6.1 新增模块
~~~text
frontend-web/src/core/document-rewrite/
├─ types.ts
├─ api.ts
├─ sse.ts
├─ use-document-rewrite-job.ts
├─ document-rewrite-provider.tsx
└─ document-rewrite-presentation.ts
frontend-web/src/components/workspace/document-rewrite/
├─ DocumentRewriteDialog.tsx
├─ DocumentRewriteProgressStep.tsx
├─ DocumentRewriteSummaryCard.tsx
└─ DocumentDiffDialog.tsx
~~~
职责:
| 模块 | 职责 |
| --- | --- |
| `api.ts` | 创建、查询、取消、撤销 Job |
| `sse.ts` | SSE 解析、`after_seq` 重连 |
| `use-document-rewrite-job.ts` | Job 状态、草稿、rAF 合并 token |
| Provider | 同时向文件面板与消息列表提供同一任务状态 |
| `DocumentRewriteDialog` | 改写要求、模型、风格配置 |
| ProgressStep | 普通消息列表内的五步步骤条 |
| SummaryCard | 结构化总结、diff、撤销动作 |
| DiffDialog | 原文与改写后双栏/行级对比 |
模型选择使用项目已有的 `tdesign-react` 选择组件,放在全文改写配置弹窗中;局部编辑器保留当前模型传递方式,后续再统一选择器。
### 6.2 流式平滑:每帧合并 delta
不能因为 SSE 是 token 流就每 token 调一次 `setState`。应当网络层完整读取、渲染层按动画帧合并:
~~~ts
const pendingDeltaRef = useRef("");
const frameRef = useRef<number | null>(null);
function onRewriteDelta(delta: string) {
pendingDeltaRef.current += delta;
if (frameRef.current !== null) return;
frameRef.current = requestAnimationFrame(() => {
const pending = pendingDeltaRef.current;
pendingDeltaRef.current = "";
frameRef.current = null;
setDraftContent((previous) => previous + pending);
});
}
~~~
完成、失败、取消前必须 flush 最后一段缓存。右侧代码编辑器只消费 `draftContent`;真实 Artifact 查询缓存直到 `committed` 事件才更新。
### 6.3 ArtifactFileDetail 改造
在 `artifact-file-detail.tsx` 增加:
~~~ts
type DocumentRewriteTarget =
| {
kind: "artifact";
threadId: string;
path: string;
presentationThreadId: string;
}
| {
kind: "deep_research_report";
sessionId: string;
presentationThreadId: string;
};
~~~
改造步骤:
1. 加入右上角全文改写图标按钮和 `DocumentRewriteDialog`。
2. 有活跃任务时强制 `viewMode = "code"`。
3. 内容优先级为:`activeRewrite.draftContent ?? draftContent ?? artifactContent`。
4. 活跃任务中代码只读,禁用保存、局部编辑和重复全文改写。
5. 收到 `committed` 后用现有 `useUpdateArtifactContent` 或等价 Query cache 更新,使真实文件立即同步。
6. 收到 `conflict/error/cancelled` 时废弃临时草稿显示,回到真实文件内容。
### 6.4 ResearchSandboxPanel 接入
相关文件:
- `frontend-web/src/pages/deep-research/ResearchSandboxPanel.tsx`
- `frontend-web/src/pages/deep-research/useReportSandbox.ts`
- `frontend-web/src/pages/deep-research/DeepResearchWorkbench.tsx`
改造:
1. `ResearchSandboxPanel` 为虚拟 `report.md` 传入 `kind: "deep_research_report"` target。
2. `useReportSandbox` 接受 `externalDraftOverride`:
~~~ts
const visibleReport = activeDocumentRewrite?.isActive
? activeDocumentRewrite.draftContent
: reportMarkdown;
~~~
3. 流式期间只显示临时草稿,不提前写 session 报告。
4. `committed` 后刷新/替换 session 的 `report_markdown`;失败后恢复旧报告。
5. 当前“改写第一段 → 候选消息 → 确认应用”逻辑继续保留,不因全文改写而改变。
### 6.5 普通消息列表接入
复用:
- `frontend-web/src/components/workspace/messages/message-list.tsx`
- `frontend-web/src/components/workspace/messages/MessageGroup.tsx`
- `DeepResearchWorkbench.tsx` 中的虚拟消息注入模式。
`DocumentRewritePresentationProvider` 按 `presentation_thread_id` 读取 Job 历史并投影为:
1. 用户消息:“AI 全文改写《xxx.md》”;
2. AI 工具调用:`document_rewrite_progress`;
3. AI 富消息:`document_rewrite_summary`。
`MessageGroup.tsx` 增加 `document_rewrite_progress` 分支,渲染 `DocumentRewriteProgressStep`。最终摘要渲染 `DocumentRewriteSummaryCard`,其内含“查看前后对比”和“撤销”。
全文步骤固定为:
| 步骤 | 展示内容 |
| --- | --- |
| 固定原文版本 | 文件名、原文字数、快照已保存 |
| 理解改写要求 | 改写目标、模型、风格 |
| 流式重写 Markdown | 正在写入右侧 xxx.md、累计字数 |
| 校验文档 | 非空、标题、围栏、截断;报告还含来源检查 |
| 对比原文并生成说明 | 差异、风险、撤销入口 |
步骤条必须在完成后保留,不能因为流结束被隐藏。
## 7. 核心执行伪代码
~~~python
async def run_document_rewrite(job_id: str) -> None:
job = await jobs.acquire_lease(job_id)
source = source_factory.create(job) # 已完成鉴权的来源适配器
await emit("snapshotting")
snapshot = await source.read_snapshot()
base_hash = sha256(snapshot.content)
await jobs.freeze_snapshot(job_id, snapshot, base_hash)
await emit("snapshot_fixed", char_count=count_chars(snapshot.content))
messages = prompt_builder.build(
mode=job.mode,
source_kind=job.source_kind,
original=snapshot.content,
instruction=job.instruction,
style=job.style,
research_sources=snapshot.allowed_sources,
)
await emit("requirements_resolved", ...)
draft = ""
async for chunk in model.stream_text(messages=messages, model_name=job.model_name):
if await jobs.cancel_requested(job_id):
await jobs.mark_cancelled(job_id)
await emit("cancelled")
return
draft += chunk.text
await jobs.append_draft_periodically(job_id, draft)
await emit("rewrite_delta", delta=chunk.text)
await emit("validation_started")
validation = validate_markdown(
draft,
source_kind=job.source_kind,
allowed_citations=snapshot.allowed_citation_ids,
)
if validation.has_fatal_error:
await jobs.mark_failed(job_id, validation.message)
await emit("error", ...)
return
await emit("validation_completed", ...)
diff = build_diff_summary(snapshot.content, draft, validation)
await jobs.save_diff(job_id, diff)
await emit("comparison_ready", diff)
if job.commit_policy != AUTO_COMMIT_AFTER_VALIDATION:
await jobs.mark_candidate_ready(job_id)
return
await emit("commit_started")
await versions.save_before_rewrite(job, snapshot)
result = await source.commit_if_unchanged(
expected_hash=base_hash,
content=draft,
metadata=CommitMetadata(job_id=job_id),
)
if not result.ok:
await jobs.mark_conflict(job_id)
await emit("conflict", ...)
return
await jobs.mark_completed(job_id, result.sha256)
await emit("committed", ...)
await emit("completed", diff)
~~~
## 8. 实施顺序
### 阶段 A:后端内核与安全基础
1. 新增领域模型、来源端口、校验、确定性 diff。
2. 新增 Job、事件、版本数据表与 migration。
3. 参考深度研究 executor 完成后台任务、取消、SSE 重放。
4. 实现普通 Artifact 读取、哈希比较、原子提交和撤销 API。
5. 编写接口测试。
验收:可以通过 API 对普通 Markdown 创建全文任务;取消、失败、冲突均不改原文件;成功后可撤销。
### 阶段 B:普通沙箱全文 UI
1. 新增 `core/document-rewrite` 前端状态、SSE、rAF hook。
2. 改 `ArtifactFileDetail`:右上角按钮、配置弹窗、临时草稿、禁用态。
3. 接入普通 `MessageList` 的步骤条、总结卡、diff 和撤销。
4. 支持刷新后恢复 Job 状态与已完成历史。
验收:右侧可平滑逐 token 写入;完成后替换真实 Markdown;左侧步骤和总结保留;撤销成功恢复。
### 阶段 C:深度研究接入
1. 实现 `DeepResearchReportSource`。
2. 由 `ResearchSandboxPanel` 传入报告 target。
3. `useReportSandbox` 支持外部临时草稿。
4. 对深度研究添加引用白名单校验。
5. 保持现有报告局部候选确认卡不变,再逐步下沉公共 prompt/校验逻辑。
验收:报告全文改写不触发联网搜索,不允许新来源;局部报告改写依然先确认再应用。
### 阶段 D:局部改写内核迁移
1. 保持 `/api/writing/rewrite` 契约不变。
2. 将 `writing.py` 转为 `InlineDocumentSource + preview_only` 的兼容 facade。
3. 给 `useWritingRewrite` 增加原文快照失效检查。
4. 回归替换、插入、重试、继续追问。
## 9. 测试与验收
建议新增后端测试:
~~~text
offline-backend-20260512/backend/tests/
├─ test_document_rewrite_pipeline.py
├─ test_document_rewrite_api.py
├─ test_document_rewrite_versions.py
└─ test_document_rewrite_deep_research.py
~~~
必须覆盖:
- Job 状态、SSE 顺序和断线恢复;
- 空输出、围栏不闭合、截断、非法深度研究引用;
- 同一文件并发任务;
- 提交前手工修改导致的冲突;
- 取消/异常不改真实文件;
- 正常撤销、撤销前手工编辑导致的冲突;
- 旧 `/api/writing/rewrite`、深度研究 `/rewrite/stream` 兼容回归。
前端必须覆盖:
- 多个 delta 在一帧合并,最终内容不丢失;
- `committed` 前 Artifact 缓存不被临时草稿污染;
- 失败/取消/冲突后右侧恢复原文;
- 活跃任务禁用同文件编辑、保存、重复改写;
- 刷新后历史步骤条与总结仍存在;
- 深度研究虚拟 `report.md` 可用全文改写;
- 局部编辑器原文变化后不能应用过期候选。
执行基线:
~~~powershell
cd offline-backend-20260512/backend
$env:PYTHONPATH = "."
uv run --no-sync pytest tests/test_document_rewrite_pipeline.py -v
uv run --no-sync pytest tests/test_document_rewrite_api.py -v
uv run --no-sync ruff check app packages/harness
cd ../../frontend-web
pnpm typecheck
pnpm build
~~~
## 10. 风险控制
| 风险 | 控制措施 |
| --- | --- |
| 用户误以为真实文件已经清空 | 明确显示“临时草稿,原文件尚未修改” |
| 流式显示仍然卡顿 | 网络完整读取 + `requestAnimationFrame` 合并渲染 |
| 改写中用户手动编辑 | `SHA-256` compare-and-swap,冲突即拒绝覆盖 |
| 输出 Markdown 不完整 | 非空、围栏、截断和标题检查 |
| 深度研究幻觉 | 来源白名单、禁止联网、引用 ID 校验 |
| 文档过大 | 第一版拒绝并提示按章节改写,不隐式截断 |
| 局部编辑污染聊天历史 | 局部只在编辑器弹窗展示,不创建完整步骤条 |
| 历史记录只存在浏览器内存 | 全文 Job/Event/Diff 持久化,按展示线程恢复 |
## 11. 复用点清单
| 现有实现 | 在新方案中的用途 |
| --- | --- |
| `MarkdownAiEditor.tsx` | 保留局部编辑菜单、预览弹窗、确认动作 |
| `useWritingRewrite.ts` | 保留局部流控制,增加快照失效保护 |
| `open-canvas/api/rewrite.ts` | 保持兼容,逐步接入统一内核 |
| `routers/writing.py` | 复用当前模型流式读取,抽取 prompt/流逻辑 |
| `routers/deep_research.py` | 复用报告来源、哈希候选、来源约束 |
| `deep_research_job_executor.py` | 复用后台 Job、取消、事件重放模式 |
| `artifact-file-detail.tsx` | 复用沙箱文件操作、代码/预览、缓存同步 |
| `useUpdateArtifactContent` | 完成后更新普通 Artifact 缓存 |
| `ResearchSandboxPanel.tsx` | 复用研究报告的右侧沙箱宿主 |
| `useReportSandbox.ts` | 加入临时草稿覆盖显示 |
| `MessageList.tsx / MessageGroup.tsx` | 复用普通消息步骤条、总结消息、文件卡片能力 |
| `DeepResearchWorkbench.tsx` | 复用向普通消息列表投影过程事件的模式 |
## 12. 完成定义
完成后应满足:
1. 局部编辑依旧是编辑器弹窗中的人工确认操作。
2. 全文改写在普通消息列表展示完整且不隐藏的步骤条。
3. 右侧沙箱可平滑地逐 token 展示临时 Markdown 草稿。
4. 任何中断、取消、校验失败和冲突都不损坏真实文件。
5. 完成后用户可以看到量化差异、结构变化、来源保留和风险提示。
6. 普通 Markdown 与深度研究报告都可全文改写,但研究报告绝不绕过已选来源约束。
7. 每一次真实全文覆盖都有版本快照,并且能够安全撤销。
+6 -2
View File
@@ -11,7 +11,7 @@
"build:network": "node --max-old-space-size=8192 ./node_modules/vite/bin/vite.js build --mode network", "build:network": "node --max-old-space-size=8192 ./node_modules/vite/bin/vite.js build --mode network",
"preview": "vite preview", "preview": "vite preview",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test:report-collaboration": "npx esbuild src/report-collaboration/tests/event-reducer.test.ts --bundle --platform=node --format=esm --outfile=.runtime/unit-tests/event-reducer.test.mjs && npx esbuild src/report-collaboration/tests/message-adapter.test.ts --bundle --platform=node --format=esm --outfile=.runtime/unit-tests/message-adapter.test.mjs && node --test .runtime/unit-tests/event-reducer.test.mjs .runtime/unit-tests/message-adapter.test.mjs", "test:maf": "vitest run --config vitest.maf.config.ts",
"check:chrome109-css": "node scripts/check-chrome109-css.mjs", "check:chrome109-css": "node scripts/check-chrome109-css.mjs",
"check:legacy-chrome-css": "node scripts/check-chrome109-css.mjs" "check:legacy-chrome-css": "node scripts/check-chrome109-css.mjs"
}, },
@@ -107,19 +107,23 @@
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.0.15", "@tailwindcss/postcss": "^4.0.15",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/file-saver": "^2.0.7", "@types/file-saver": "^2.0.7",
"@types/gsap": "^3.0.0", "@types/gsap": "^3.0.0",
"@types/node": "^20.14.10", "@types/node": "^20.14.10",
"@types/react": "^19.0.0", "@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0", "@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^5.0.4", "@vitejs/plugin-react": "^5.0.4",
"jsdom": "^30.0.1",
"lightningcss": "^1.30.2", "lightningcss": "^1.30.2",
"postcss": "^8.5.3", "postcss": "^8.5.3",
"tailwindcss": "^4.0.15", "tailwindcss": "^4.0.15",
"tw-animate-css": "^1.4.0", "tw-animate-css": "^1.4.0",
"typescript": "^5.8.2", "typescript": "^5.8.2",
"vite": "^6.0.0", "vite": "^6.0.0",
"vite-plugin-source-identifier": "^1.1.2" "vite-plugin-source-identifier": "^1.1.2",
"vitest": "^4.1.10"
}, },
"packageManager": "pnpm@10.26.2" "packageManager": "pnpm@10.26.2"
} }
+3 -35
View File
@@ -32,10 +32,10 @@ window.__CM_RUNTIME_CONFIG__ = {
VITE_BRAND_WELCOME_DARK_URL: "", VITE_BRAND_WELCOME_DARK_URL: "",
// DeerFlow Gateway 地址:前端自有后端接口,例如 /api/agents、/api/auth、/api/threads 等。 // DeerFlow Gateway 地址:前端自有后端接口,例如 /api/agents、/api/auth、/api/threads 等。
// VITE_BACKEND_BASE_URL: "https://ch1.b.uat.4.cn/deerflow", // VITE_BACKEND_BASE_URL: "http://10.19.200.5:2026",
// LangGraph 流式对话接口地址:普通问答、智能体对话等流式能力使用。 // LangGraph 流式对话接口地址:普通问答、智能体对话等流式能力使用。
// VITE_LANGGRAPH_BASE_URL: "https://ch1.b.uat.4.cn/deerflow/api", // VITE_LANGGRAPH_BASE_URL: "http://10.19.200.5:2026/api",
// Canvas/AI 写作独立 LangGraph 地址:为空时前端会回退使用 VITE_LANGGRAPH_BASE_URL。 // Canvas/AI 写作独立 LangGraph 地址:为空时前端会回退使用 VITE_LANGGRAPH_BASE_URL。
VITE_CANVAS_LANGGRAPH_BASE_URL: "", VITE_CANVAS_LANGGRAPH_BASE_URL: "",
@@ -50,19 +50,6 @@ window.__CM_RUNTIME_CONFIG__ = {
// CMZS 后端接口:任务管理、任务分析、三情分析、行动分析等业务接口。 // CMZS 后端接口:任务管理、任务分析、三情分析、行动分析等业务接口。
VITE_API_BASE_URL: "https://ch1.b.uat.4.cn/zncm", VITE_API_BASE_URL: "https://ch1.b.uat.4.cn/zncm",
// 8BF 嵌入页专用任务系统接口。部署到其他系统时只需修改这一项,
// 不影响原多智能体会商使用的任务详情接口。
VITE_8BF_TASK_API_BASE_URL: "https://ch1.b.uat.4.cn/zl_consumer",
// 8BF 会商页右上角「返回」按钮的跳转地址(当前窗口 window.location.href)。
// 部署后直接改 dist/runtime-config.js 即可,无需重新打包。留空则点击时提示未配置。
VITE_8BF_ROUNDTABLE_BACK_URL: "",
// 任务深链「宿主路由」按钮的 postMessage targetOrigin(HOST_NAVIGATE)。
// 填宿主系统 origin,例如 https://localhost:4912;生产改成他们线上地址。
// 留空时尝试用 iframe 的 ancestorOrigins / referrer 自动探测,探测失败则不发送。
VITE_HOST_NAVIGATE_ORIGIN: "",
// 佳来模型对话接口。 // 佳来模型对话接口。
VITE_AIPI_CHAT_URL: "https://ch1.b.uat.4.cn/gpt", VITE_AIPI_CHAT_URL: "https://ch1.b.uat.4.cn/gpt",
@@ -103,7 +90,7 @@ window.__CM_RUNTIME_CONFIG__ = {
VITE_AIPI_FRONTEND_URL: "http://47.88.25.99:3000", VITE_AIPI_FRONTEND_URL: "http://47.88.25.99:3000",
// Consumer 接口:深链任务详情 cop-task-detail、研判情报报告 selectSqReport 等使用。 // Consumer 接口:深链任务详情 cop-task-detail、研判情报报告 selectSqReport 等使用。
VITE_AIPI_CONSUMER_URL: "https://ch1.b.uat.4.cn/consumer", VITE_AIPI_CONSUMER_URL: "http://10.19.200.5:8002/consumer",
// A 系统跳转地址:人物、组织、事件等列表项打开链接使用。 // A 系统跳转地址:人物、组织、事件等列表项打开链接使用。
VITE_AIPI_PRESENT_URL: "http://present.a.uat.4.cn/present/domain", VITE_AIPI_PRESENT_URL: "http://present.a.uat.4.cn/present/domain",
@@ -143,25 +130,6 @@ window.__CM_RUNTIME_CONFIG__ = {
// 隐藏系统 Logo、换肤按钮以及“全量/简洁模式”切换。修改后刷新页面即可生效。 // 隐藏系统 Logo、换肤按钮以及“全量/简洁模式”切换。修改后刷新页面即可生效。
VITE_FORCE_COLLAPSED_SIDEBAR: "false", VITE_FORCE_COLLAPSED_SIDEBAR: "false",
// 简介模式左侧菜单类型:与菜单管理页「简介模式」里的类型 A / B 对应。
// 两套网页部署时分别填 "A" 或 "B"。不填、留空、或旧配置没有这一项,都按类型 A,
// 继续读取原来的简介菜单数据,无需改旧页面。
VITE_COMPACT_MENU_TYPE: "A",
// GitHub OAuth Token;不使用 GitHub 相关能力时留空。 // GitHub OAuth Token;不使用 GitHub 相关能力时留空。
VITE_GITHUB_OAUTH_TOKEN: "", VITE_GITHUB_OAUTH_TOKEN: "",
// 是否在智能体管理页显示「舆情分析」类型:"true" 显示,"false" 隐藏。
// 关闭后,该智能体的专用对话地址也会自动跳回智能体管理页。
VITE_SENTIMENT_AGENT_VISIBLE: "true",
// 舆情分析智能体:外部流式问答接口地址(POST,SSE 流式返回)。
// 前端会把该地址随请求传给后台转发。留空时该智能体对话页会提示未配置。
VITE_SENTIMENT_AGENT_API_URL: "http://alg.gw.y.uat.cn/a6_report_agent/alg/stream/report-agent",
// 舆情分析智能体:请求头 Authorization Basic Auth 用户名。
VITE_SENTIMENT_AGENT_AUTH_USERNAME: "1054841959975223296",
// 舆情分析智能体:请求头 Authorization Basic Auth 密码。
VITE_SENTIMENT_AGENT_AUTH_PASSWORD: "LzqqMTUxMTIwMjQxNjQ2MjY5MDUduC",
}; };
@@ -31,16 +31,6 @@ const requiredLegacyFallbacks = [
pattern: /<InputGroup className="h-auto min-h-16">/, pattern: /<InputGroup className="h-auto min-h-16">/,
description: "Prompt textarea must not rely on :has() for its parent height", description: "Prompt textarea must not rely on :has() for its parent height",
}, },
{
file: "src/core/utils/mermaid.ts",
pattern: /htmlLabels:\s*false[\s\S]*secure:\s*\[[\s\S]*"htmlLabels"/,
description: "Sandbox flowcharts must use native SVG labels in legacy browsers",
},
{
file: "src/core/utils/legacy-html-preview.ts",
pattern: /export function downlevelModernColors[\s\S]*function injectLegacyChartShim/,
description: "Generated HTML charts must downlevel modern CSS colors for Chrome 109",
},
]; ];
for (const file of cssFiles) { for (const file of cssFiles) {
+2 -15
View File
@@ -38,21 +38,14 @@ import EmbedChatPage from "./pages/EmbedChatPage";
import EmbedRoundtablePage from "./pages/EmbedRoundtablePage"; import EmbedRoundtablePage from "./pages/EmbedRoundtablePage";
import DashboardStandalonePage from "@/roundtable-planning/pages/DashboardStandalonePage"; import DashboardStandalonePage from "@/roundtable-planning/pages/DashboardStandalonePage";
import PositionRoundtablePage from "@/position-roundtable/pages/PositionRoundtablePage"; import PositionRoundtablePage from "@/position-roundtable/pages/PositionRoundtablePage";
import WeKnoraWikiPageView from "@/strategy-components/components/resource-management/llmwiki/WeKnoraWikiPageView";
import { import {
isPositionRoundtableStandaloneMode, isPositionRoundtableStandaloneMode,
POSITION_ROUNDTABLE_ROUTE, POSITION_ROUNDTABLE_ROUTE,
} from "@/position-roundtable/demo/position-roundtable-demo-config"; } from "@/position-roundtable/demo/position-roundtable-demo-config";
import { ChatRuntime } from "./pages/WorkspaceRoutes"; import { ChatRuntime } from "./pages/WorkspaceRoutes";
import { NotFoundPage } from "./pages/NotFoundPage"; import { NotFoundPage } from "./pages/NotFoundPage";
import OfficialDeerFlowEntry from "./pages/OfficialDeerFlowEntry";
const PUBLIC_EMBED_PREFIXES = [ const PUBLIC_EMBED_PREFIXES = ["/share/", "/public/", "/roundtable-share/"];
"/share/",
"/public/",
"/roundtable-share/",
"/embed/knowledge/",
];
function AppProviders({ children }: { children: React.ReactNode }) { function AppProviders({ children }: { children: React.ReactNode }) {
const locale = useMemo(() => detectLocale(), []); const locale = useMemo(() => detectLocale(), []);
@@ -109,17 +102,16 @@ function AppProviders({ children }: { children: React.ReactNode }) {
forcedTheme={forcedTheme} forcedTheme={forcedTheme}
> >
<QueryClientProvider> <QueryClientProvider>
<AuthSyncWatcher disabled={positionStandaloneMode}>
<I18nProvider initialLocale={locale}> <I18nProvider initialLocale={locale}>
<ThemeProvider> <ThemeProvider>
<ChatProvider> <ChatProvider>
{!positionStandaloneMode && <AuthSyncWatcher />}
{!positionStandaloneMode && <DesensitizeWordsLoader />} {!positionStandaloneMode && <DesensitizeWordsLoader />}
<FontScaleApplier /> <FontScaleApplier />
{children} {children}
</ChatProvider> </ChatProvider>
</ThemeProvider> </ThemeProvider>
</I18nProvider> </I18nProvider>
</AuthSyncWatcher>
</QueryClientProvider> </QueryClientProvider>
</NextThemesProvider> </NextThemesProvider>
); );
@@ -196,15 +188,10 @@ export function App() {
} }
/> />
<Route path="/embed/roundtable" element={<EmbedRoundtablePage />} /> <Route path="/embed/roundtable" element={<EmbedRoundtablePage />} />
<Route
path="/embed/knowledge/:noteId"
element={<WeKnoraWikiPageView publicEmbed />}
/>
<Route <Route
path="/roundtable-dashboard" path="/roundtable-dashboard"
element={<DashboardStandalonePage />} element={<DashboardStandalonePage />}
/> />
<Route path="/official/*" element={<OfficialDeerFlowEntry />} />
<Route path="/page/*" element={pageElement} /> <Route path="/page/*" element={pageElement} />
<Route path="*" element={<NotFoundPage />} /> <Route path="*" element={<NotFoundPage />} />
</Routes> </Routes>
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="2064"
height="2591" viewBox="0 0 2064 2591">
<path fill-rule="nonzero"
d="M 68.582031 0 C 66.890625 0 65.300781 1 64.617188 2.640625 C 49.46875 38.800781 33.71875 76.199219 33.628906 106.539062 C 33.550781 134.230469 46.445312 155.730469 59.949219 175.71875 L 59.949219 175.730469 C 52.414062 175.671875 44.992188 175.371094 37.472656 174.171875 C 27.210938 172.53125 16.585938 169.199219 5.585938 165.738281 C 5.15625 165.609375 4.722656 165.539062 4.296875 165.539062 C 2.824219 165.539062 1.417969 166.300781 0.625 167.609375 C -0.402344 169.300781 -0.140625 171.46875 1.257812 172.871094 L 1.261719 172.878906 C 11.230469 182.871094 21.8125 193.53125 36.980469 200.050781 C 51.5625 206.320312 70.167969 208.628906 88.085938 210.78125 L 88.027344 210.78125 C 127.152344 253.410156 166.617188 296.300781 215.761719 334.941406 C 230.558594 346.578125 246.292969 357.878906 261.785156 369 C 277.171875 380.050781 292.441406 391.011719 306.660156 402.191406 C 326.132812 417.511719 343.5625 433.179688 356.773438 450.019531 C 377.808594 476.828125 388.449219 506.960938 395.4375 538.628906 L 395.4375 538.640625 C 372.683594 510.710938 349.328125 483.929688 324.855469 469.339844 C 295.957031 452.121094 265.800781 452 236.960938 451.808594 L 236.933594 451.820312 C 235.792969 451.808594 234.707031 452.261719 233.898438 453.070312 C 233.085938 453.871094 232.632812 454.96875 232.636719 456.121094 C 232.722656 494.011719 232.699219 533.539062 256.304688 567.480469 C 279.351562 600.621094 324.738281 628.019531 369.191406 654.679688 L 369.132812 654.691406 C 371.476562 683.539062 373.40625 710.691406 367.109375 728.03125 C 365.828125 731.558594 364.191406 734.71875 362.058594 738.820312 C 358.910156 744.871094 354.964844 752.441406 350.417969 764.960938 C 342.890625 785.699219 333.769531 819.839844 323.648438 883.109375 C 303.347656 1010.019531 278.722656 1255.949219 308.882812 1409.269531 C 326.265625 1497.660156 361.828125 1555.210938 393.511719 1606.519531 C 417.042969 1644.632812 438.207031 1678.960938 448.835938 1720.09375 C 466.921875 1790.089844 454.648438 1880.246094 444.5 1954.386719 C 440.613281 1982.78125 437.042969 2008.839844 435.726562 2030.261719 C 433.410156 2067.929688 438.066406 2091.179688 442.304688 2112.347656 L 442.304688 2112.355469 C 445.910156 2130.347656 449.152344 2146.589844 447.757812 2169.28125 C 447.429688 2174.613281 446.835938 2180.359375 445.933594 2186.535156 L 445.933594 2186.542969 C 436.582031 2250.328125 393.613281 2362.808594 362.105469 2416.636719 C 339.761719 2454.804688 323.546875 2462.851562 309.597656 2469.925781 C 303.980469 2472.777344 298.261719 2475.660156 292.691406 2480.238281 C 273.378906 2496.113281 256.457031 2532.078125 240.183594 2566.417969 C 239.578125 2567.703125 239.640625 2569.203125 240.363281 2570.429688 C 241.082031 2571.65625 242.359375 2572.449219 243.777344 2572.542969 L 243.789062 2572.542969 L 243.882812 2572.550781 L 243.882812 2572.554688 C 261.582031 2573.746094 279.460938 2574.957031 296.386719 2574.957031 C 323.671875 2574.957031 349.332031 2571.84375 368.355469 2559.785156 C 392.640625 2544.394531 405.109375 2514.960938 414.488281 2493.074219 C 417.011719 2487.183594 419.289062 2481.871094 421.546875 2477.308594 C 432.054688 2456.039062 441.753906 2451.664062 451.855469 2446.960938 C 453.054688 2446.402344 453.929688 2445.320312 454.226562 2444.042969 L 454.238281 2443.996094 L 454.238281 2443.988281 C 476.210938 2348.800781 498.035156 2254.347656 524.300781 2196.363281 L 524.300781 2196.367188 C 536.363281 2169.730469 549.363281 2150.796875 562.695312 2131.402344 C 576.28125 2111.625 590.1875 2091.402344 603.300781 2062.445312 L 603.304688 2062.453125 C 605.183594 2058.292969 607.054688 2053.949219 608.894531 2049.421875 C 625.066406 2009.675781 639.746094 1954.289062 653.585938 1902.101562 C 663.0625 1866.367188 672.15625 1832.09375 681.085938 1805.085938 C 699.308594 1749.992188 716.863281 1725.09375 734.371094 1705.144531 L 734.421875 1705.148438 C 727.285156 1740.746094 721.597656 1776.628906 729.320312 1807.472656 C 733.351562 1823.570312 740.996094 1838.160156 749.066406 1853.613281 C 758.828125 1872.296875 769.433594 1892.636719 776.359375 1919.675781 C 783.289062 1946.71875 786.574219 1980.605469 789.527344 2011.140625 L 789.527344 2011.148438 C 791.875 2035.402344 794.023438 2057.78125 797.746094 2072.316406 L 797.746094 2072.320312 C 797.929688 2073.023438 798.128906 2073.769531 798.316406 2074.441406 L 798.320312 2074.441406 C 802.132812 2087.941406 807.617188 2093.914062 813.515625 2100.324219 C 821.132812 2108.597656 830.351562 2118.441406 839.742188 2151.671875 L 839.738281 2151.675781 C 840.105469 2152.96875 840.402344 2154.039062 840.765625 2155.398438 C 857.484375 2217.601562 874.097656 2354.589844 872.078125 2423.390625 C 870.472656 2478.15625 857.140625 2488.390625 845.339844 2498.136719 C 842.320312 2500.632812 839.085938 2503.296875 836.09375 2506.566406 C 820.847656 2523.230469 812.652344 2554.886719 804.800781 2584.753906 C 804.457031 2586.0625 804.75 2587.453125 805.589844 2588.515625 C 806.40625 Line truncated
</svg>

Before

Width:  |  Height:  |  Size: 19 KiB

@@ -1,3 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" viewBox="0 0 14 12" fill="none" aria-hidden="true">
<path d="M13 6H1.5M1.5 6L6.2 1.4M1.5 6L6.2 10.6" stroke="#A2E1F9" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 258 B

@@ -60,6 +60,7 @@ import {
createContext, createContext,
type FormEvent, type FormEvent,
type FormEventHandler, type FormEventHandler,
Fragment,
type HTMLAttributes, type HTMLAttributes,
type KeyboardEventHandler, type KeyboardEventHandler,
type PropsWithChildren, type PropsWithChildren,
@@ -123,10 +124,8 @@ export const usePromptInputController = () => {
return ctx; return ctx;
}; };
// Optional variants (do NOT throw). Useful for dual-mode components and for // Optional variants (do NOT throw). Useful for dual-mode components.
// Fast Refresh transitions where a page can briefly retain the previous const useOptionalPromptInputController = () =>
// provider context instance.
export const useOptionalPromptInputController = () =>
useContext(PromptInputController); useContext(PromptInputController);
export const useProviderAttachments = () => { export const useProviderAttachments = () => {
@@ -407,9 +406,9 @@ export function PromptInputAttachments({
{...props} {...props}
> >
{attachments.files.map((file) => ( {attachments.files.map((file) => (
<div key={file.id} className="max-w-60"> <Fragment key={file.id}>
{children(file)} <div className="max-w-60">{children(file)}</div>
</div> </Fragment>
))} ))}
</div> </div>
); );
@@ -165,7 +165,7 @@ export const ReasoningTrigger = memo(
export type ReasoningContentProps = ComponentProps< export type ReasoningContentProps = ComponentProps<
typeof CollapsibleContent typeof CollapsibleContent
> & { > & {
children: ReactNode; children: string;
}; };
export const ReasoningContent = memo( export const ReasoningContent = memo(
@@ -178,11 +178,7 @@ export const ReasoningContent = memo(
)} )}
{...props} {...props}
> >
{typeof children === "string" ? (
<Streamdown {...reasoningPlugins}>{children}</Streamdown> <Streamdown {...reasoningPlugins}>{children}</Streamdown>
) : (
children
)}
</CollapsibleContent> </CollapsibleContent>
), ),
); );
@@ -1,104 +0,0 @@
import { FileOutput } from "lucide-react";
import { toast } from "sonner";
import responsibilityIcon from "@/assets/position-roundtable/责任岗位.svg";
import resultTimeIcon from "@/assets/position-roundtable/时间.svg";
import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils";
import "./analysis-results.css";
import type { AnalysisResultCardItem } from "./types";
function formatResultTime(value: string | undefined, fallback: string): string {
if (!value) return fallback;
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).format(date);
}
export function AnalysisResultCardList({
items,
emptyTitle = "暂无交付产物",
emptyDescription = "第二步研讨与第三步总结生成 Markdown 后,产物会显示在这里。",
padded = true,
onOpen,
}: {
items: AnalysisResultCardItem[];
emptyTitle?: string;
emptyDescription?: string;
padded?: boolean;
onOpen: (item: AnalysisResultCardItem) => void;
}) {
if (items.length === 0) {
return (
<div className="position-roundtable-analysis-results-empty flex h-full min-h-[260px] flex-col items-center justify-center p-6 text-center">
<FileOutput className="mb-3 size-8 text-muted-foreground/50" />
<p className="text-sm font-semibold">{emptyTitle}</p>
<p className="mt-1 max-w-[240px] text-xs leading-5 text-muted-foreground">
{emptyDescription}
</p>
</div>
);
}
return (
<div className={cn("analysis-result-card-list", padded && "p-[15px]")}>
{items.map((item, index) => {
const displayedTime = formatResultTime(
item.updatedAt,
item.fallbackTime || "刚刚",
);
const displayedProductName = item.delivered ? item.productName : "未交付";
return (
<button
key={item.id}
type="button"
className="position-roundtable-analysis-result-card"
onClick={() => {
if (!item.delivered) {
toast.info(
item.unavailableMessage ||
`「${desensitize(item.agentName)}」尚未交付可预览的 Markdown 文件。`,
);
return;
}
onOpen(item);
}}
>
<div className="position-roundtable-analysis-result-card-body">
<div
className={cn(
"position-roundtable-analysis-result-tag",
`position-roundtable-analysis-result-tag--${(index % 6) + 1}`,
)}
aria-label={desensitize(item.agentName)}
>
<span>{desensitize(item.agentName)}</span>
</div>
<p className="position-roundtable-analysis-result-product">
{desensitize(displayedProductName)}
</p>
<footer className="position-roundtable-analysis-result-meta">
<span>
<img src={responsibilityIcon} alt="" aria-hidden="true" />
{desensitize(item.positionName)}
</span>
<i aria-hidden="true" />
<span>
<img src={resultTimeIcon} alt="" aria-hidden="true" />
{displayedTime}
</span>
</footer>
</div>
</button>
);
})}
</div>
);
}
@@ -1,141 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { FileOutput, Loader2 } from "lucide-react";
import type { ReactNode } from "react";
import { ArtifactFilePreview } from "@/components/workspace/artifacts";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { loadArtifactContent } from "@/core/artifacts/loader";
import { desensitize } from "@/lib/desensitize";
import { Button as TButton } from "tdesign-react";
import type { AnalysisResultCardItem } from "./types";
function isArtifactErrorContent(content: string | null | undefined): boolean {
const trimmed = content?.trim();
if (!trimmed || !trimmed.startsWith("{") || !trimmed.endsWith("}")) {
return false;
}
try {
const parsed = JSON.parse(trimmed) as Record<string, unknown>;
const detail = parsed.detail ?? parsed.message ?? parsed.error;
return typeof detail === "string" && detail.trim().length > 0;
} catch {
return false;
}
}
function fallbackContent(item: AnalysisResultCardItem | null): string {
return (
item?.artifactContent?.trim() ||
item?.summary?.trim() ||
"暂无产物正文"
);
}
export function AnalysisResultDetailDialog({
item,
onOpenChange,
extraBody,
footerStart,
}: {
item: AnalysisResultCardItem | null;
onOpenChange: (open: boolean) => void;
extraBody?: ReactNode;
footerStart?: ReactNode;
}) {
const artifactThreadId = item?.artifactThreadId || null;
const artifactPathValue = item?.artifactPath || "";
const artifactContentQuery = useQuery({
queryKey: [
"analysis-results",
"deliverable-artifact-content",
artifactThreadId,
artifactPathValue,
],
queryFn: async () => {
if (!artifactThreadId || !artifactPathValue) return "";
const result = await loadArtifactContent({
filepath: artifactPathValue,
threadId: artifactThreadId,
isMock: false,
});
return result.content;
},
enabled: Boolean(item && artifactThreadId && artifactPathValue),
staleTime: 30_000,
});
const loadedArtifactContent =
typeof artifactContentQuery.data === "string" ? artifactContentQuery.data : "";
const loadedArtifactIsError = isArtifactErrorContent(loadedArtifactContent);
const artifactContent =
loadedArtifactContent.trim() && !loadedArtifactIsError ? loadedArtifactContent : null;
const displayedContent = artifactContent || fallbackContent(item);
const artifactLoadFailed =
(artifactContentQuery.isError || loadedArtifactIsError) &&
!item?.artifactContent?.trim();
return (
<Dialog open={Boolean(item)} onOpenChange={onOpenChange}>
<DialogContent
overlayClassName="!z-[6000]"
className="!z-[6001] flex max-h-[86vh] w-[900px] !max-w-[calc(100vw-2rem)] flex-col gap-0 overflow-hidden p-0"
>
<DialogHeader className="shrink-0 border-b px-5 py-4 dark:border-[#2b8ffe]/25">
<DialogTitle className="flex items-center gap-2 text-base">
<FileOutput className="size-4 text-primary" />
交付产物详情
</DialogTitle>
</DialogHeader>
{!item ? null : (
<div className="custom-scrollbar min-h-0 flex-1 overflow-y-auto px-5 py-4">
<div className="min-w-0">
<p className="text-sm font-extrabold text-slate-900 dark:text-[#e8edf5]">
{desensitize(item.productName)}
</p>
<p className="mt-1 truncate text-xs text-muted-foreground">
{desensitize(item.agentName)} · {desensitize(item.positionName)}
</p>
</div>
{extraBody}
<div className="mt-4 rounded-xl border border-slate-200 bg-white p-3 dark:border-[#2b8ffe]/30 dark:bg-[#042b59]/65">
<div className="mb-2 flex items-center justify-between gap-2">
<p className="text-xs font-bold text-slate-700 dark:text-[#e8edf5]">产物内容</p>
</div>
<div className="h-[52vh] min-h-[320px] overflow-hidden rounded-lg border border-slate-100 bg-slate-50/60 dark:border-[#2b8ffe]/20 dark:bg-[#021d3d]/70">
{artifactContentQuery.isLoading ? (
<div className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground dark:text-[#8aa0c4]">
<Loader2 className="size-4 animate-spin" />
正在加载 Markdown 文件内容…
</div>
) : (
<ArtifactFilePreview
content={displayedContent}
language="markdown"
threadId={artifactThreadId ?? ""}
/>
)}
</div>
{artifactLoadFailed && (
<p className="mt-2 text-[11px] text-amber-600 dark:text-amber-300">
Markdown 文件内容加载失败,当前展示的是已保存正文。
</p>
)}
</div>
</div>
)}
<DialogFooter className="shrink-0 border-t px-5 py-3 dark:border-[#2b8ffe]/25">
{footerStart}
<TButton variant="outline" onClick={() => onOpenChange(false)}>
关闭
</TButton>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -1,130 +0,0 @@
.analysis-result-card-list {
display: grid;
gap: 10px;
min-width: 0;
max-width: 100%;
}
.position-roundtable-analysis-result-card {
position: relative;
display: block;
width: 100%;
max-width: 100%;
min-width: 0;
min-height: 102px;
box-sizing: border-box;
padding: 40px 12px 12px;
border: 1px solid rgba(85, 166, 254, 0.1);
border-radius: 4px;
background: rgba(0, 98, 217, 0.1);
color: #ffffff;
text-align: left;
cursor: pointer;
transition: background 160ms ease, border-color 160ms ease, box-shadow 160ms ease;
}
.position-roundtable-analysis-result-card:hover,
.position-roundtable-analysis-result-card:focus-visible {
border-color: #0062d9;
background: rgba(0, 98, 217, 0.3);
box-shadow: 0 4px 14px rgba(0, 44, 110, 0.18);
outline: none;
}
.position-roundtable-analysis-result-card-body {
position: relative;
min-width: 0;
max-width: 100%;
}
.position-roundtable-analysis-result-tag {
position: absolute;
top: -40px;
left: -12px;
display: inline-flex;
width: fit-content;
max-width: calc(100% + 12px);
height: 26px;
align-items: center;
box-sizing: border-box;
padding: 0 22px 0 12px;
overflow: hidden;
border-radius: 4px 0 0 0;
background: rgba(212, 120, 0, 0.5);
color: #ffffff;
font-family: "Noto Sans S Chinese", "Noto Sans SC", sans-serif;
font-size: 16px;
line-height: normal;
white-space: nowrap;
clip-path: polygon(0 0, 100% 0, calc(100% - 14px) 100%, 0 100%);
}
.position-roundtable-analysis-result-tag--1 { background: rgba(212, 120, 0, 0.5); }
.position-roundtable-analysis-result-tag--2 { background: rgba(207, 19, 34, 0.5); }
.position-roundtable-analysis-result-tag--3 { background: rgba(29, 171, 123, 0.5); }
.position-roundtable-analysis-result-tag--4 { background: rgba(132, 85, 230, 0.5); }
.position-roundtable-analysis-result-tag--5 { background: rgba(201, 181, 0, 0.5); }
.position-roundtable-analysis-result-tag--6 { background: rgba(69, 195, 243, 0.5); }
.position-roundtable-analysis-result-tag span {
position: relative;
z-index: 1;
box-sizing: border-box;
min-width: 0;
max-width: 100%;
overflow: hidden;
padding: 0;
text-overflow: ellipsis;
}
.position-roundtable-analysis-result-product {
margin: 0;
overflow: hidden;
color: #ffffff;
font-family: "Noto Sans S Chinese", "Noto Sans SC", sans-serif;
font-size: 18px;
font-weight: 500;
line-height: 24px;
text-overflow: ellipsis;
white-space: nowrap;
}
.position-roundtable-analysis-result-meta {
display: flex;
min-width: 0;
align-items: center;
gap: 10px;
margin-top: 6px;
color: #80b7ff;
font-family: "Noto Sans S Chinese", "Noto Sans SC", sans-serif;
font-size: 16px;
font-weight: 300;
line-height: 24px;
}
.position-roundtable-analysis-result-meta span {
display: inline-flex;
min-width: 0;
align-items: center;
gap: 5px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.position-roundtable-analysis-result-meta img {
width: 16px;
height: 16px;
flex: 0 0 auto;
}
.position-roundtable-analysis-result-meta i {
width: 1px;
height: 14px;
flex: 0 0 auto;
background: rgba(128, 183, 255, 0.45);
}
.position-roundtable-analysis-results-empty {
color: #80b7ff;
}
@@ -1,3 +0,0 @@
export { AnalysisResultCardList } from "./AnalysisResultCardList";
export { AnalysisResultDetailDialog } from "./AnalysisResultDetailDialog";
export type { AnalysisResultCardItem } from "./types";
@@ -1,17 +0,0 @@
export interface AnalysisResultCardItem {
id: string;
agentName: string;
productName: string;
positionName: string;
updatedAt?: string;
/** Shown when `updatedAt` is missing. */
fallbackTime?: string;
/** Clickable preview is available. */
delivered: boolean;
artifactPath?: string;
artifactMimeType?: string | null;
artifactThreadId?: string | null;
artifactContent?: string | null;
summary?: string;
unavailableMessage?: string;
}
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { prepareGeneratedHtml } from "@/core/utils/legacy-html-preview"; import { injectInPageAnchorHandler } from "@/core/utils/markdown";
/** /**
* Sandboxed preview of a generated HTML document. * Sandboxed preview of a generated HTML document.
@@ -26,7 +26,7 @@ export function HtmlPreviewFrame({
const [url, setUrl] = useState<string>(); const [url, setUrl] = useState<string>();
useEffect(() => { useEffect(() => {
const blob = new Blob([prepareGeneratedHtml(html ?? "")], { const blob = new Blob([injectInPageAnchorHandler(html ?? "")], {
type: "text/html;charset=utf-8", type: "text/html;charset=utf-8",
}); });
const objectUrl = URL.createObjectURL(blob); const objectUrl = URL.createObjectURL(blob);
+1 -6
View File
@@ -3,7 +3,6 @@
import { ChevronRightIcon } from "lucide-react"; import { ChevronRightIcon } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import deerMaskUrl from "@/assets/deer.svg";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { FlickeringGrid } from "@/components/ui/flickering-grid"; import { FlickeringGrid } from "@/components/ui/flickering-grid";
import Galaxy from "@/components/ui/galaxy"; import Galaxy from "@/components/ui/galaxy";
@@ -30,11 +29,7 @@ export function Hero({ className }: { className?: string }) {
/> />
</div> </div>
<FlickeringGrid <FlickeringGrid
className="absolute inset-0 z-0 translate-y-8 mask-size-[100vw] mask-center mask-no-repeat md:mask-size-[72vh]" className="absolute inset-0 z-0 translate-y-8 mask-[url(/images/deer.svg)] mask-size-[100vw] mask-center mask-no-repeat md:mask-size-[72vh]"
style={{
WebkitMaskImage: `url("${deerMaskUrl}")`,
maskImage: `url("${deerMaskUrl}")`,
}}
squareSize={4} squareSize={4}
gridGap={4} gridGap={4}
color={"white"} color={"white"}
+1 -43
View File
@@ -2,7 +2,6 @@ import { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom"; import { useNavigate, useLocation } from "react-router-dom";
import { import {
Bell, Bell,
Cpu,
ChevronLeft, ChevronLeft,
ChevronRight, ChevronRight,
ChevronsUpDown, ChevronsUpDown,
@@ -10,7 +9,6 @@ import {
FolderOpen, FolderOpen,
Gauge, Gauge,
ListTree, ListTree,
MessageSquareText,
MousePointerClick, MousePointerClick,
BriefcaseBusiness, BriefcaseBusiness,
Settings, Settings,
@@ -56,7 +54,7 @@ type PageSidebarProps = {
headerHidden?: boolean; headerHidden?: boolean;
}; };
type SettingsSection = "account" | "appearance" | "memory" | "tools" | "encoder" | "about"; type SettingsSection = "account" | "appearance" | "memory" | "tools" | "about";
const hasActiveChild = (item: MenuItem, pathname: string): boolean => const hasActiveChild = (item: MenuItem, pathname: string): boolean =>
menuItemContainsPath(item, pathname); menuItemContainsPath(item, pathname);
@@ -238,14 +236,6 @@ function SecondaryNavSidebar({ headerHidden }: { headerHidden: boolean }) {
按钮管理 按钮管理
</DropdownMenuItem> </DropdownMenuItem>
)} )}
{isAdmin && (
<DropdownMenuItem
onClick={() => navigate("/page/strategy/admin/fixed-questions")}
>
<MessageSquareText className="size-4" />
问题配置
</DropdownMenuItem>
)}
{isAdmin && ( {isAdmin && (
<DropdownMenuItem <DropdownMenuItem
onClick={() => navigate("/page/strategy/admin/position-roles")} onClick={() => navigate("/page/strategy/admin/position-roles")}
@@ -262,20 +252,6 @@ function SecondaryNavSidebar({ headerHidden }: { headerHidden: boolean }) {
白名单管理 白名单管理
</DropdownMenuItem> </DropdownMenuItem>
)} )}
{isAdmin && (
<DropdownMenuItem
onClick={() => navigate("/page/workspace/admin/models")}
>
<Cpu className="size-4" />
模型配置
</DropdownMenuItem>
)}
{isAdmin && (
<DropdownMenuItem onClick={() => openSettings("encoder")}>
<Cpu className="size-4" />
本地编码器
</DropdownMenuItem>
)}
{isAdmin && ( {isAdmin && (
<DropdownMenuItem <DropdownMenuItem
onClick={() => navigate("/page/strategy/settings/model-concurrency")} onClick={() => navigate("/page/strategy/settings/model-concurrency")}
@@ -573,30 +549,12 @@ function LegacyAccordionSidebar({
按钮管理 按钮管理
</DropdownMenuItem> </DropdownMenuItem>
)} )}
{isAdmin && (
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/fixed-questions")}>
<MessageSquareText className="size-4" />
问题配置
</DropdownMenuItem>
)}
{isAdmin && ( {isAdmin && (
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/position-roles")}> <DropdownMenuItem onClick={() => navigate("/page/strategy/admin/position-roles")}>
<BriefcaseBusiness className="size-4" /> <BriefcaseBusiness className="size-4" />
岗位角色配置 岗位角色配置
</DropdownMenuItem> </DropdownMenuItem>
)} )}
{isAdmin && (
<DropdownMenuItem onClick={() => navigate("/page/workspace/admin/models")}>
<Cpu className="size-4" />
模型配置
</DropdownMenuItem>
)}
{isAdmin && (
<DropdownMenuItem onClick={() => openSettings("encoder")}>
<Cpu className="size-4" />
本地编码器
</DropdownMenuItem>
)}
{isAdmin && ( {isAdmin && (
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/login-whitelist")}> <DropdownMenuItem onClick={() => navigate("/page/strategy/admin/login-whitelist")}>
<ShieldCheck className="size-4" /> <ShieldCheck className="size-4" />
@@ -1,71 +0,0 @@
"use client";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { languages } from "@codemirror/language-data";
import { basicLightInit } from "@uiw/codemirror-theme-basic";
import { monokaiInit } from "@uiw/codemirror-theme-monokai";
import CodeMirror from "@uiw/react-codemirror";
import { useTheme } from "next-themes";
import { useMemo } from "react";
import { cn } from "@/lib/utils";
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
import { reasoningPlugins } from "@/core/streamdown";
const lightTheme = basicLightInit({ settings: { background: "transparent", fontSize: "14px" } });
const darkTheme = monokaiInit({
settings: { background: "transparent", gutterBackground: "transparent", fontSize: "14px" },
});
/** Markdown-aware source editor shared by Wiki create/edit dialogs. */
export function MarkdownCodeEditor({
value,
onChange,
className,
}: {
value: string;
onChange: (value: string) => void;
className?: string;
}) {
const { resolvedTheme } = useTheme();
const extensions = useMemo(
() => [markdown({ base: markdownLanguage, codeLanguages: languages })],
[],
);
return (
<div className={cn("grid min-h-[46vh] overflow-hidden rounded-lg border bg-background lg:grid-cols-2", className)}>
<section className="flex min-h-0 flex-col border-b lg:border-r lg:border-b-0">
<div className="flex h-9 shrink-0 items-center border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground">
Markdown 编辑
</div>
<CodeMirror
value={value}
onChange={onChange}
theme={resolvedTheme === "dark" ? darkTheme : lightTheme}
extensions={extensions}
basicSetup={{
foldGutter: true,
highlightActiveLine: true,
highlightActiveLineGutter: false,
lineNumbers: true,
}}
className="min-h-[42vh] flex-1 overflow-auto font-mono text-sm [&_.cm-editor]:min-h-[42vh] [&_.cm-focused]:outline-none!"
/>
</section>
<section className="flex min-h-0 flex-col bg-muted/10">
<div className="flex h-9 shrink-0 items-center border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground">
实时渲染
</div>
<div className="min-h-[42vh] flex-1 overflow-auto p-4">
<MarkdownContent
content={value || "*暂无正文*"}
isLoading={false}
remarkPlugins={reasoningPlugins.remarkPlugins}
rehypePlugins={reasoningPlugins.rehypePlugins}
/>
</div>
</section>
</div>
);
}
@@ -8,7 +8,6 @@ import {
SlidersHorizontal, SlidersHorizontal,
Upload, Upload,
} from "lucide-react"; } from "lucide-react";
import type { ReactNode } from "react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -19,7 +18,7 @@ function HeaderButton({
variant = "outline", variant = "outline",
className, className,
}: { }: {
icon: ReactNode; icon: React.ReactNode;
label: string; label: string;
onClick: () => void; onClick: () => void;
variant?: "outline" | "primary"; variant?: "outline" | "primary";
@@ -53,7 +52,6 @@ export function WikiHeader({
onCreate, onCreate,
onManageFolders, onManageFolders,
onManageTemplates, onManageTemplates,
extraActions,
}: { }: {
onToggleSidebar: () => void; onToggleSidebar: () => void;
onImportFile: () => void; onImportFile: () => void;
@@ -63,7 +61,6 @@ export function WikiHeader({
onCreate: () => void; onCreate: () => void;
onManageFolders: () => void; onManageFolders: () => void;
onManageTemplates: () => void; onManageTemplates: () => void;
extraActions?: ReactNode;
}) { }) {
return ( return (
<header className="flex h-14 shrink-0 items-center justify-between border-b border-slate-100 bg-white px-4 sm:px-6 dark:border-slate-800 dark:bg-slate-900"> <header className="flex h-14 shrink-0 items-center justify-between border-b border-slate-100 bg-white px-4 sm:px-6 dark:border-slate-800 dark:bg-slate-900">
@@ -77,12 +74,11 @@ export function WikiHeader({
<Menu className="size-5" /> <Menu className="size-5" />
</button> </button>
<div className="text-base font-semibold tracking-tight text-slate-900 dark:text-slate-100"> <div className="text-base font-semibold tracking-tight text-slate-900 dark:text-slate-100">
知识库管理 问答梳理
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{extraActions}
<HeaderButton <HeaderButton
icon={<Upload className="size-4" />} icon={<Upload className="size-4" />}
label="导入文件" label="导入文件"
@@ -204,7 +204,7 @@ export function noteFolderSegments(note: KnowledgeNote): string[] {
/** Breadcrumb segments for a note (folders only; the title is appended by the caller). */ /** Breadcrumb segments for a note (folders only; the title is appended by the caller). */
export function noteBreadcrumbSegments(note: KnowledgeNote): string[] { export function noteBreadcrumbSegments(note: KnowledgeNote): string[] {
return ["知识库管理", ...noteFolderSegments(note).map(localizeFolderName)]; return ["问答梳理", ...noteFolderSegments(note).map(localizeFolderName)];
} }
function sortTree(nodes: TreeNode[]): void { function sortTree(nodes: TreeNode[]): void {
@@ -835,10 +835,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
); );
const cardLayout = ( const cardLayout = (
<Card <Card className="group flex min-w-0 flex-col transition-shadow hover:shadow-md">
className="group flex min-w-0 flex-col transition-shadow hover:shadow-md"
data-agent-guide="agent-card"
>
<CardHeader className="min-w-0 pb-2"> <CardHeader className="min-w-0 pb-2">
<div className="flex min-w-0 items-start justify-between gap-2"> <div className="flex min-w-0 items-start justify-between gap-2">
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden"> <div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
@@ -896,10 +893,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
); );
const listLayout = ( const listLayout = (
<div <div className="group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]">
className="group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]"
data-agent-guide="agent-card"
>
<div className="agent-avatar bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg"> <div className="agent-avatar bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
<BotIcon className="h-5 w-5" /> <BotIcon className="h-5 w-5" />
</div> </div>
@@ -72,7 +72,6 @@ import type { AgentThread, AgentThreadState } from "@/core/threads/types";
import { import {
bootstrapResumePath, bootstrapResumePath,
isBootstrapThread, isBootstrapThread,
isHiddenFromRecentChats,
isThreadFavorite, isThreadFavorite,
isThreadPinned, isThreadPinned,
sortThreadsPinnedFirst, sortThreadsPinnedFirst,
@@ -373,10 +372,17 @@ function RecentChatsPane({ activeAgentId }: { activeAgentId?: string }) {
const [renameValue, setRenameValue] = useState(""); const [renameValue, setRenameValue] = useState("");
const [shareThreadId, setShareThreadId] = useState<string | null>(null); const [shareThreadId, setShareThreadId] = useState<string | null>(null);
// 排除调度/会商/报告结构&写作配置向导等系统会话,与首页一致; // 排除调度/会商类系统会话,与首页一致;智能体创建(bootstrap)会话保留展示
// 智能体创建(bootstrap)会话保留展示(带机器人图标、点击回创建页);置顶优先。 // (带机器人图标、点击回创建页);置顶优先。
const visibleThreads = useMemo( const visibleThreads = useMemo(
() => sortThreadsPinnedFirst(threads.filter((thread) => !isHiddenFromRecentChats(thread))), () =>
sortThreadsPinnedFirst(
threads.filter(
(thread) =>
thread.metadata?.thread_type !== "scheduler" &&
thread.metadata?.thread_type !== "roundtable",
),
),
[threads], [threads],
); );
@@ -2,9 +2,7 @@
import { import {
BotIcon, BotIcon,
BriefcaseBusinessIcon,
CheckIcon, CheckIcon,
DatabaseIcon,
GlobeIcon, GlobeIcon,
InfoIcon, InfoIcon,
Loader2Icon, Loader2Icon,
@@ -45,7 +43,6 @@ import {
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor"; import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor";
import { LlmWikiKnowledgeSelector } from "@/components/workspace/llmwiki-knowledge-selector";
import { AgentRecentChats } from "@/components/workspace/agents/agent-recent-chats"; import { AgentRecentChats } from "@/components/workspace/agents/agent-recent-chats";
import { useArtifactsOptional } from "@/components/workspace/artifacts"; import { useArtifactsOptional } from "@/components/workspace/artifacts";
import { EnabledSkillList } from "@/components/workspace/agents/enabled-skill-list"; import { EnabledSkillList } from "@/components/workspace/agents/enabled-skill-list";
@@ -83,7 +80,6 @@ interface AgentDraft {
templateName: string; templateName: string;
/** 会商席位「技能识别强化」开关。 */ /** 会商席位「技能识别强化」开关。 */
seatSkillDirective: boolean; seatSkillDirective: boolean;
knowledgeBaseIds: string[];
} }
function draftFromAgent(agent: Agent): AgentDraft { function draftFromAgent(agent: Agent): AgentDraft {
@@ -97,7 +93,6 @@ function draftFromAgent(agent: Agent): AgentDraft {
featured: agent.featured_order != null, featured: agent.featured_order != null,
templateName: agent.template_name ?? "", templateName: agent.template_name ?? "",
seatSkillDirective: agent.seat_skill_directive ?? false, seatSkillDirective: agent.seat_skill_directive ?? false,
knowledgeBaseIds: agent.llmwiki_knowledge_base_ids ?? [],
}; };
} }
@@ -144,8 +139,6 @@ export function AgentDetailPanel({
onAskQuestion, onAskQuestion,
disabled, disabled,
defaultCollapsed, defaultCollapsed,
collapsed: collapsedProp,
onCollapsedChange,
showRecentChats, showRecentChats,
compactAppearanceActions, compactAppearanceActions,
avatarSrc, avatarSrc,
@@ -153,7 +146,6 @@ export function AgentDetailPanel({
skillsIcon, skillsIcon,
skillsTitle, skillsTitle,
showCommonQuestions = false, showCommonQuestions = false,
jobResponsibilities,
panelTitle, panelTitle,
embedded, embedded,
hideStatusBadges = false, hideStatusBadges = false,
@@ -165,14 +157,6 @@ export function AgentDetailPanel({
disabled?: boolean; disabled?: boolean;
/** 初始收起(任务工作区进入时默认收起智能体信息面板)。 */ /** 初始收起(任务工作区进入时默认收起智能体信息面板)。 */
defaultCollapsed?: boolean; defaultCollapsed?: boolean;
/**
* 受控折叠态:传入时由父级持有状态(智能体问答页把展开/收起按钮放在顶部
* 「新对话」右侧)。此时收起 = 整列宽度动画归零(不保留细条),面板内置的
* 收起按钮不再渲染。不传则沿用面板内置状态 + 细条收起交互(会商等工作区)。
*/
collapsed?: boolean;
/** 受控折叠态变化回调(配合 `collapsed` 使用)。 */
onCollapsedChange?: (collapsed: boolean) => void;
/** 在面板底部展示「有关此智能体的最近对话」(仅智能体问答页开启,任务工作区不展示)。 */ /** 在面板底部展示「有关此智能体的最近对话」(仅智能体问答页开启,任务工作区不展示)。 */
showRecentChats?: boolean; showRecentChats?: boolean;
/** 简洁模式下挂在右上角收起/展开按钮左侧的外观控件。 */ /** 简洁模式下挂在右上角收起/展开按钮左侧的外观控件。 */
@@ -182,11 +166,6 @@ export function AgentDetailPanel({
skillsIcon?: ReactNode; skillsIcon?: ReactNode;
skillsTitle?: string; skillsTitle?: string;
showCommonQuestions?: boolean; showCommonQuestions?: boolean;
/**
* 业务链席位上配置的岗位职责。传入(含空字符串)时在常用问题上方展示;
* 不传则隐藏该区块。此字段来自业务链,不随智能体本身编辑。
*/
jobResponsibilities?: string | null;
/** Overrides the standard panel heading for an embedded consumer. */ /** Overrides the standard panel heading for an embedded consumer. */
panelTitle?: string; panelTitle?: string;
/** Renders one fixed panel instead of the responsive collapsible rail. */ /** Renders one fixed panel instead of the responsive collapsible rail. */
@@ -197,15 +176,7 @@ export function AgentDetailPanel({
editIcon?: ReactNode; editIcon?: ReactNode;
}) { }) {
const router = useRouter(); const router = useRouter();
// 折叠态:受控(collapsedProp 传入,智能体问答页)优先;否则面板内置(会商等工作区)。 const [collapsed, setCollapsed] = useState(defaultCollapsed ?? false);
const [internalCollapsed, setInternalCollapsed] = useState(
defaultCollapsed ?? false,
);
const collapsed = collapsedProp ?? internalCollapsed;
const setCollapsed = (next: boolean) => {
if (collapsedProp === undefined) setInternalCollapsed(next);
onCollapsedChange?.(next);
};
const [mobileOpen, setMobileOpen] = useState(false); const [mobileOpen, setMobileOpen] = useState(false);
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState<AgentDraft | null>(null); const [draft, setDraft] = useState<AgentDraft | null>(null);
@@ -255,10 +226,9 @@ export function AgentDetailPanel({
const isSaving = updateAgent.isPending || setFeatured.isPending; const isSaving = updateAgent.isPending || setFeatured.isPending;
// 对话生成文件(md/txt 等 artifact)并首次展开预览时,自动收起智能体 // 对话生成文件(md/txt 等 artifact)并在右侧展开预览时,自动收起智能体
// 信息面板给预览让位。目录内切换文件不能再次改写用户的手动选择:否则用户 // 信息面板给预览让位;切换到新文件时同样收起。编辑中不打断用户,用户随时
// 刚展开智能体信息,点另一个文件时面板又会突然收起,看起来就像收起按钮被 // 可手动重新展开。
// 移除了。编辑中也不打断用户。
// //
// 关键:判定用 open + selectedArtifact,而非 artifacts.length。流式写文件时 // 关键:判定用 open + selectedArtifact,而非 artifacts.length。流式写文件时
// message-group 一开始就调用 select()+setOpen(true) 打开预览并选中该文件,但 // message-group 一开始就调用 select()+setOpen(true) 打开预览并选中该文件,但
@@ -267,19 +237,20 @@ export function AgentDetailPanel({
const artifactsCtx = useArtifactsOptional(); const artifactsCtx = useArtifactsOptional();
const artifactCount = artifactsCtx?.artifacts.length ?? 0; const artifactCount = artifactsCtx?.artifacts.length ?? 0;
const selectedArtifact = artifactsCtx?.selectedArtifact ?? null; const selectedArtifact = artifactsCtx?.selectedArtifact ?? null;
// preOpen:流式自动开沙箱的两阶段标记 —— 沙箱真正展开(open 翻转)前就
// 先收起本面板,让收起布局先落地,避免与沙箱展开同帧叠加造成卡顿。
const artifactPanelVisible = const artifactPanelVisible =
(!!artifactsCtx?.open || !!artifactsCtx?.preOpen) && !!artifactsCtx?.open && (!!selectedArtifact || artifactCount > 0);
(!!selectedArtifact || artifactCount > 0);
const prevArtifactPanelVisible = useRef(false); const prevArtifactPanelVisible = useRef(false);
const prevSelectedArtifact = useRef<string | null>(null);
useEffect(() => { useEffect(() => {
const opened = artifactPanelVisible && !prevArtifactPanelVisible.current; const opened = artifactPanelVisible && !prevArtifactPanelVisible.current;
const switched =
artifactPanelVisible && selectedArtifact !== prevSelectedArtifact.current;
prevArtifactPanelVisible.current = artifactPanelVisible; prevArtifactPanelVisible.current = artifactPanelVisible;
if (opened && !editing) { prevSelectedArtifact.current = selectedArtifact;
if ((opened || switched) && !editing) {
setCollapsed(true); setCollapsed(true);
} }
}, [artifactPanelVisible, editing]); }, [artifactPanelVisible, selectedArtifact, editing]);
const displayName = desensitize(agent?.name ?? agentName); const displayName = desensitize(agent?.name ?? agentName);
const questions = useMemo( const questions = useMemo(
@@ -363,11 +334,6 @@ export function AgentDetailPanel({
request.template_name = draft.templateName.trim(); request.template_name = draft.templateName.trim();
if (draft.seatSkillDirective !== (agent.seat_skill_directive ?? false)) if (draft.seatSkillDirective !== (agent.seat_skill_directive ?? false))
request.seat_skill_directive = draft.seatSkillDirective; request.seat_skill_directive = draft.seatSkillDirective;
if (
JSON.stringify(draft.knowledgeBaseIds) !==
JSON.stringify(agent.llmwiki_knowledge_base_ids ?? [])
)
request.llmwiki_knowledge_base_ids = draft.knowledgeBaseIds;
if (nextPublished !== agent.published) request.published = nextPublished; if (nextPublished !== agent.published) request.published = nextPublished;
if (JSON.stringify(draft.skills) !== JSON.stringify(agent.skills ?? [])) if (JSON.stringify(draft.skills) !== JSON.stringify(agent.skills ?? []))
request.skills = draft.skills; request.skills = draft.skills;
@@ -664,13 +630,6 @@ export function AgentDetailPanel({
</div> </div>
)} )}
{!editing && (agent.llmwiki_knowledge_base_ids?.length ?? 0) > 0 && (
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
<DatabaseIcon className="size-3 shrink-0" />
LLMWiki 知识库:{agent.llmwiki_knowledge_base_ids?.length ?? 0} 个
</div>
)}
{/* Publish / featured toggles — only meaningful in edit mode. */} {/* Publish / featured toggles — only meaningful in edit mode. */}
{editing && draft && ( {editing && draft && (
<div className="mt-3 space-y-2"> <div className="mt-3 space-y-2">
@@ -688,14 +647,6 @@ export function AgentDetailPanel({
配置后,对话生成的 Markdown 文件可一键发布到知识入库接口。 配置后,对话生成的 Markdown 文件可一键发布到知识入库接口。
</p> </p>
</div> </div>
<LlmWikiKnowledgeSelector
source="all"
value={draft.knowledgeBaseIds}
onChange={(knowledgeBaseIds) =>
setDraft({ ...draft, knowledgeBaseIds })
}
variant="panel"
/>
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2"> <div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
<div className="pr-3"> <div className="pr-3">
<p className="text-sm font-medium">会商技能识别强化</p> <p className="text-sm font-medium">会商技能识别强化</p>
@@ -745,23 +696,6 @@ export function AgentDetailPanel({
</section> </section>
{/* ── 岗位职责(业务链席位配置,只读)────────────────────────────── */}
{jobResponsibilities !== undefined && (
<Section
icon={<BriefcaseBusinessIcon className="size-3.5" />}
title="岗位职责"
>
{jobResponsibilities?.trim() ? (
<p className="text-muted-foreground text-sm leading-relaxed whitespace-pre-wrap">
{desensitize(jobResponsibilities)}
</p>
) : (
<p className="text-muted-foreground/60 text-sm">暂无岗位职责</p>
)}
</Section>
)}
{/* ── 常用问题 ───────────────────────────────────────────────────── */} {/* ── 常用问题 ───────────────────────────────────────────────────── */}
{(showCommonQuestions || editing || questions.length > 0 || canEdit) && ( {(showCommonQuestions || editing || questions.length > 0 || canEdit) && (
<Section <Section
@@ -947,18 +881,14 @@ export function AgentDetailPanel({
const panelChrome = (collapseButton: ReactNode) => ( const panelChrome = (collapseButton: ReactNode) => (
<> <>
<div className="flex h-12 shrink-0 items-center gap-2 border-b px-4"> <div className="flex h-12 shrink-0 items-center justify-between border-b px-4">
{/* 标题不参与压缩(此前被简洁模式外观控件挤成单字);空间不足时只 <span className="shrink-0 whitespace-nowrap text-sm font-semibold">
裁剪 compactAppearanceActions,编辑等主操作与标题始终完整。 */}
<span className="shrink-0 text-sm font-semibold whitespace-nowrap">
{panelTitle ?? "智能体信息"} {panelTitle ?? "智能体信息"}
</span> </span>
<div className="flex min-w-0 flex-1 items-center justify-end gap-1"> <div className="flex min-w-0 items-center gap-1">
<div className="flex shrink-0 items-center gap-1">{headerActions}</div> {headerActions}
<div className="flex min-w-0 items-center justify-end gap-1 overflow-hidden">
{compactAppearanceActions} {compactAppearanceActions}
</div> {collapseButton}
{collapseButton && <div className="shrink-0">{collapseButton}</div>}
</div> </div>
</div> </div>
<div className="min-h-0 flex-1 overflow-y-auto">{body}</div> <div className="min-h-0 flex-1 overflow-y-auto">{body}</div>
@@ -967,48 +897,21 @@ export function AgentDetailPanel({
return ( return (
<> <>
{/* ── Desktop (lg+) ────────────────────────────────────────────────── */} {/* ── Desktop (lg+): inline aside, collapsible to a rail ───────────── */}
{embedded ? ( {embedded ? (
<aside className="bg-card/40 flex h-full w-full min-w-0 shrink-0 flex-col border-l"> <aside className="bg-card/40 flex h-full w-full min-w-0 shrink-0 flex-col border-l">
{panelChrome(null)} {panelChrome(null)}
</aside> </aside>
) : collapsedProp !== undefined ? (
/* 受控模式(智能体问答页):收起时整列宽度动画归零(含左边框),不再保留细条;
展开态的「收起」按钮在面板右上角,收起态的「展开」按钮在页面
header「新对话」按钮右侧。 */
<div
className={cn(
"hidden h-full shrink-0 overflow-hidden transition-[width] duration-300 ease-in-out lg:block",
collapsed ? "w-0" : "w-[360px]",
)}
>
<aside className="bg-card/40 flex h-full w-[360px] flex-col border-l">
{panelChrome(
<Tooltip content="收起">
<Button
variant="ghost"
size="icon-sm"
onClick={() => setCollapsed(true)}
aria-label="收起智能体信息"
aria-expanded={true}
>
<PanelRightCloseIcon className="size-4" />
</Button>
</Tooltip>,
)}
</aside>
</div>
) : collapsed ? ( ) : collapsed ? (
<div className="hidden shrink-0 items-start border-l px-2 pt-3 lg:flex"> <div className="hidden shrink-0 items-start border-l px-2 pt-3 lg:flex">
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
{compactAppearanceActions} {compactAppearanceActions}
<Tooltip content="展开智能体信息"> <Tooltip content="智能体信息">
<Button <Button
variant="ghost" variant="ghost"
size="icon-sm" size="icon-sm"
onClick={() => setCollapsed(false)} onClick={() => setCollapsed(false)}
aria-label="展开智能体信息" aria-label="展开智能体信息"
aria-expanded={false}
> >
<PanelRightOpenIcon className="size-4" /> <PanelRightOpenIcon className="size-4" />
</Button> </Button>
@@ -1024,7 +927,6 @@ export function AgentDetailPanel({
size="icon-sm" size="icon-sm"
onClick={() => setCollapsed(true)} onClick={() => setCollapsed(true)}
aria-label="收起智能体信息" aria-label="收起智能体信息"
aria-expanded={true}
> >
<PanelRightCloseIcon className="size-4" /> <PanelRightCloseIcon className="size-4" />
</Button> </Button>
@@ -1,6 +1,6 @@
"use client"; "use client";
import { ArrowDownUpIcon, BotIcon, Compass, Loader2, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react"; import { ArrowDownUpIcon, BotIcon, Loader2, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -16,16 +16,9 @@ import { getStoredAuth } from "@/core/auth";
import { useAgentsPaginated, usePrivateAgentsPaginated } from "@/core/agents"; import { useAgentsPaginated, usePrivateAgentsPaginated } from "@/core/agents";
import type { Agent, AgentSort } from "@/core/agents"; import type { Agent, AgentSort } from "@/core/agents";
import { useI18n } from "@/core/i18n/hooks"; import { useI18n } from "@/core/i18n/hooks";
import { isSentimentAgentVisible } from "@/core/sentiment-agent/config";
import { usePrivateSquareStatus, usePublishSquares, useViewMode } from "@/core/system-settings/hooks"; import { usePrivateSquareStatus, usePublishSquares, useViewMode } from "@/core/system-settings/hooks";
import { AgentCard } from "./agent-card"; import { AgentCard } from "./agent-card";
import { SentimentAgentCard } from "./sentiment-agent-card";
import {
AgentGuide,
isAgentGuideEnvironment,
startAgentGuide,
} from "./agent-guide";
const PAGE_SIZE = 12; const PAGE_SIZE = 12;
@@ -37,7 +30,6 @@ const PRIVATE_SQUARE_PASSWORD_KEY = "deer-flow.private-square-password";
export function AgentGallery() { export function AgentGallery() {
const { t } = useI18n(); const { t } = useI18n();
const router = useRouter(); const router = useRouter();
const sentimentAgentVisible = isSentimentAgentVisible();
// 「内置智能体」筛选仅管理员可见(后端 scope=builtin 也做了 admin 闸门兜底)。 // 「内置智能体」筛选仅管理员可见(后端 scope=builtin 也做了 admin 闸门兜底)。
const isAdmin = getStoredAuth()?.system_role === "admin"; const isAdmin = getStoredAuth()?.system_role === "admin";
const [viewMode, setViewMode] = useViewMode("agent"); const [viewMode, setViewMode] = useViewMode("agent");
@@ -49,9 +41,6 @@ export function AgentGallery() {
// Each configured publish square (发布广场) becomes its own browse tab; the // Each configured publish square (发布广场) becomes its own browse tab; the
// backend always returns at least one (the built-in default). // backend always returns at least one (the built-in default).
const squareTabs = publishSquares?.squares ?? []; const squareTabs = publishSquares?.squares ?? [];
// 默认广场固定排在「我的」之后;舆情分析是依附在默认广场后的前端虚拟类型,
// 其余自定义广场继续保持后端给出的顺序。
const [defaultSquare, ...additionalSquares] = squareTabs;
// Publisher filter: click a card's 发布者 to keep only that user's agents. // Publisher filter: click a card's 发布者 to keep only that user's agents.
// {id} is the owner user_id (server filter), {label} the desensitized name. // {id} is the owner user_id (server filter), {label} the desensitized name.
const [publisher, setPublisher] = useState<{ id: string; label: string } | null>( const [publisher, setPublisher] = useState<{ id: string; label: string } | null>(
@@ -81,7 +70,6 @@ export function AgentGallery() {
activeTab !== "mine" && activeTab !== "mine" &&
activeTab !== "private" && activeTab !== "private" &&
activeTab !== "builtin" && activeTab !== "builtin" &&
activeTab !== "sentiment" &&
squareTabs.length > 0 && squareTabs.length > 0 &&
!squareTabs.some((sq) => sq.id === activeTab) !squareTabs.some((sq) => sq.id === activeTab)
) { ) {
@@ -102,13 +90,9 @@ export function AgentGallery() {
// Only the active tab fetches. "广场" maps to the server "square" scope // Only the active tab fetches. "广场" maps to the server "square" scope
// (built-in/published, never private), "我的" to "mine" (owned + favorited), // (built-in/published, never private), "我的" to "mine" (owned + favorited),
// "内置" to "builtin" (admin-only, user_id IS NULL). 「舆情分析」是前端虚拟 // "内置" to "builtin" (admin-only, user_id IS NULL).
// 类型,不查后端列表。
const isSquareTab = const isSquareTab =
activeTab !== "mine" && activeTab !== "mine" && activeTab !== "private" && activeTab !== "builtin";
activeTab !== "private" &&
activeTab !== "builtin" &&
activeTab !== "sentiment";
const mainScope = const mainScope =
activeTab === "mine" activeTab === "mine"
? "mine" ? "mine"
@@ -128,7 +112,7 @@ export function AgentGallery() {
sort, sort,
page: mainPage, page: mainPage,
pageSize: PAGE_SIZE, pageSize: PAGE_SIZE,
enabled: activeTab !== "private" && activeTab !== "sentiment", enabled: activeTab !== "private",
owner: publisher?.id, owner: publisher?.id,
// Each square tab fetches only that square's agents. // Each square tab fetches only that square's agents.
square: isSquareTab ? activeTab : undefined, square: isSquareTab ? activeTab : undefined,
@@ -164,16 +148,9 @@ export function AgentGallery() {
// password has been verified. Until then we show the gate (or the lock // password has been verified. Until then we show the gate (or the lock
// prompt) and hide the keyword/tag search bar — there is no list to filter. // prompt) and hide the keyword/tag search bar — there is no list to filter.
const privateUnlocked = privateFeatureUsable && !!privatePassword; const privateUnlocked = privateFeatureUsable && !!privatePassword;
const showSearchBar = const showSearchBar = activeTab !== "private" || privateUnlocked;
activeTab !== "sentiment" &&
(activeTab !== "private" || privateUnlocked);
const activeTotal = const activeTotal = activeTab === "private" ? privateTotal : mainTotal;
activeTab === "sentiment"
? 1
: activeTab === "private"
? privateTotal
: mainTotal;
const setTabPage = (tab: string, page: number) => const setTabPage = (tab: string, page: number) =>
setPages((prev) => ({ ...prev, [tab]: page })); setPages((prev) => ({ ...prev, [tab]: page }));
@@ -351,22 +328,15 @@ export function AgentGallery() {
请输入访问密码,验证通过后才能查看其中的智能体。 请输入访问密码,验证通过后才能查看其中的智能体。
</p> </p>
</div> </div>
<form <div className="flex flex-col gap-2">
className="flex flex-col gap-2"
onSubmit={(event) => {
event.preventDefault();
handleSubmitPassword();
}}
>
<label className="sr-only" htmlFor="private-square-access-code">
访问密码
</label>
<Input <Input
id="private-square-access-code"
type="password" type="password"
placeholder="访问密码" placeholder="访问密码"
value={passwordInput} value={passwordInput}
onChange={(e) => setPasswordInput(e.target.value)} onChange={(e) => setPasswordInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleSubmitPassword();
}}
// This is a one-off access code, not a login credential. Tell // This is a one-off access code, not a login credential. Tell
// browsers / password managers not to save or autofill it (which // browsers / password managers not to save or autofill it (which
// would also stop them from spilling a saved account into the // would also stop them from spilling a saved account into the
@@ -377,8 +347,8 @@ export function AgentGallery() {
data-lpignore="true" data-lpignore="true"
data-form-type="other" data-form-type="other"
/> />
<Button type="submit">进入私密广场</Button> <Button onClick={handleSubmitPassword}>进入私密广场</Button>
</form> </div>
</div> </div>
); );
} }
@@ -403,23 +373,11 @@ export function AgentGallery() {
{t.agents.description} {t.agents.description}
</p> </p>
</div> </div>
<div className="flex items-center gap-2"> <Button onClick={handleNewAgent}>
<Button
variant="ghost"
size="sm"
className="text-muted-foreground hover:text-foreground"
title="重新播放智能体使用引导"
onClick={() => startAgentGuide("list")}
>
<Compass className="mr-1.5 h-4 w-4" />
使用引导
</Button>
<Button onClick={handleNewAgent} data-agent-guide="new-agent-btn">
<PlusIcon className="mr-1.5 h-4 w-4" /> <PlusIcon className="mr-1.5 h-4 w-4" />
{t.agents.newAgent} {t.agents.newAgent}
</Button> </Button>
</div> </div>
</div>
{/* Tabs */} {/* Tabs */}
<Tabs <Tabs
@@ -438,27 +396,9 @@ export function AgentGallery() {
> >
<div className="mx-6 mt-4 flex flex-col gap-3"> <div className="mx-6 mt-4 flex flex-col gap-3">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
<TabsList <TabsList className="w-auto max-w-full flex-wrap justify-start self-start">
className="w-auto max-w-full flex-wrap justify-start self-start"
data-agent-guide="tabs"
>
<TabsTrigger value="mine">我的</TabsTrigger> <TabsTrigger value="mine">我的</TabsTrigger>
{defaultSquare && ( {squareTabs.map((sq) => (
<TabsTrigger
key={defaultSquare.id}
value={defaultSquare.id}
title={defaultSquare.description || defaultSquare.name}
>
{defaultSquare.name}
</TabsTrigger>
)}
{sentimentAgentVisible && (
/* 舆情分析:前端虚拟类型,直连外部舆情问答接口。 */
<TabsTrigger value="sentiment" title="舆情分析智能体(外部接口对接)">
舆情分析
</TabsTrigger>
)}
{additionalSquares.map((sq) => (
<TabsTrigger key={sq.id} value={sq.id} title={sq.description || sq.name}> <TabsTrigger key={sq.id} value={sq.id} title={sq.description || sq.name}>
{sq.name} {sq.name}
</TabsTrigger> </TabsTrigger>
@@ -495,7 +435,6 @@ export function AgentGallery() {
</div> </div>
</div> </div>
{showSearchBar && ( {showSearchBar && (
<div data-agent-guide="search">
<TagSearchBar <TagSearchBar
// Remount per tab so the internal keyword input / 展开 state also // Remount per tab so the internal keyword input / 展开 state also
// resets when the parent-owned filters are cleared on tab switch. // resets when the parent-owned filters are cleared on tab switch.
@@ -527,7 +466,6 @@ export function AgentGallery() {
</Select> </Select>
} }
/> />
</div>
)} )}
{publisher && ( {publisher && (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -574,25 +512,6 @@ export function AgentGallery() {
})} })}
</TabsContent> </TabsContent>
{/* 舆情分析类型:固定一张虚拟智能体卡片(名称/简介可编辑),
接口地址与鉴权在 runtime-config.js 配置。 */}
{sentimentAgentVisible && (
<TabsContent
value="sentiment"
className="flex-1 overflow-y-auto p-6 mt-0"
>
{viewMode === "list" ? (
<div className="flex flex-col gap-2">
<SentimentAgentCard layout="list" />
</div>
) : (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<SentimentAgentCard />
</div>
)}
</TabsContent>
)}
{isAdmin && ( {isAdmin && (
<TabsContent value="builtin" className="flex-1 overflow-y-auto p-6 mt-0"> <TabsContent value="builtin" className="flex-1 overflow-y-auto p-6 mt-0">
{renderListBody({ {renderListBody({
@@ -615,11 +534,6 @@ export function AgentGallery() {
</TabsContent> </TabsContent>
)} )}
</Tabs> </Tabs>
<AgentGuide
stage="list"
eligible={isAgentGuideEnvironment()}
autoStart={false}
/>
</div> </div>
); );
} }
@@ -1,331 +0,0 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { Guide, type GuideStep } from "tdesign-react";
import { env } from "@/env";
import { isEmbedActive, isHideChromeActive } from "@/core/embed/embed-session";
import { isWujieEnv } from "@/core/embed/wujie";
/**
* 智能体使用引导(三段式,基于 TDesign React 的 Guide 组件),完整覆盖
* 「浏览管理 → 创建与配置 → 发起问答」流程:
*
* - list :智能体列表页(/page/workspace/agents)——分区、搜索排序、卡片操作、
* 创建入口;完成 / 跳过就地结束,不跳转创建页(创建页有自己的一段
* 引导,点「创建智能体」进入时自动演示)。
* - create :创建页(/page/workspace/agents/new)——对话式创建、基本信息、模型、
* 知识空间、SOUL.md、技能、保存。
* - chat :智能体对话页(/page/workspace/agents/:id/chats/...)——侧栏切换与
* 历史、常用问题、输入框、右侧详情面板。
*
* 记忆语义与简洁模式引导(compact-mode-guide.tsx)一致:每个阶段各自记一个
* localStorage 标记,**只有用户显式点「完成」或「跳过」才写入**;中途刷新/离开
* 不记忆,下次进入该页面还会自动演示。各页头部的「使用引导」按钮可随时强制重放。
*
* 自动演示范围:只有 create 段(进入新建页)与 chat 段自动弹;list 段挂在
* 智能体列表页但不自动演示(`autoStart={false}`,避免一进列表页就弹引导),
* 仅由头部「使用引导」按钮手动触发。
*
* 高亮目标通过 `data-agent-guide` 标记在各组件上;启动时按目标是否存在过滤步骤
* (如新用户无智能体卡片、无预设常用问题时自动剔除该步)——Guide 对找不到的
* 目标元素会抛错,不能盲传。
*/
export type AgentGuideStage = "list" | "create" | "chat";
const finishedKey = (stage: AgentGuideStage) =>
`deerflow.agent-guide.${stage}.finished`;
const startEventName = (stage: AgentGuideStage) =>
`agent-guide:start:${stage}`;
/** 手动触发某阶段的引导(各页面头部「使用引导」按钮调用,忽略已看过记忆)。 */
export function startAgentGuide(stage: AgentGuideStage) {
if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent(startEventName(stage)));
}
}
/** 环境闸门:iframe 嵌入 / 去 chrome / 强制收起侧栏(无界)等环境不弹引导。 */
export function isAgentGuideEnvironment(): boolean {
return (
!env.FORCE_COLLAPSED_SIDEBAR &&
!isEmbedActive() &&
!isHideChromeActive() &&
!isWujieEnv()
);
}
/** 引导步骤高亮目标选择器;各目标元素由所在组件打上同名 data 标记。 */
const TARGET = {
// list 阶段(智能体列表页)
tabs: '[data-agent-guide="tabs"]',
search: '[data-agent-guide="search"]',
agentCard: '[data-agent-guide="agent-card"]',
newAgentBtn: '[data-agent-guide="new-agent-btn"]',
// create 阶段(创建页)
createChatInput: '[data-agent-guide="create-chat-input"]',
createBasic: '[data-agent-guide="create-basic"]',
createModel: '[data-agent-guide="create-model"]',
createKnowledge: '[data-agent-guide="create-knowledge"]',
createSoul: '[data-agent-guide="create-soul"]',
createSkills: '[data-agent-guide="create-skills"]',
createSaveBtn: '[data-agent-guide="create-save-btn"]',
// chat 阶段(智能体对话页)
chatSidebar: '[data-agent-guide="chat-sidebar"]',
chatQuestions: '[data-agent-guide="chat-questions"]',
chatInput: '[data-agent-guide="chat-input"]',
chatDetail: '[data-agent-guide="chat-detail"]',
} as const;
// 等布局稳定后再启动:Guide 只在步骤切换时测量目标位置,起步太早会把高亮框
// 定位到过渡中的坐标且不会自行纠正。
const START_DELAY_MS = 800;
interface StepSpec {
/** 高亮目标选择器;缺省(dialog 步骤)以 body 兜底。 */
selector?: string;
mode: "popup" | "dialog";
placement: NonNullable<GuideStep["placement"]>;
title: string;
body: string;
}
const LIST_STEPS: StepSpec[] = [
{
mode: "dialog",
placement: "center",
title: "欢迎使用智能体",
body: "这里是你的智能体中心。接下来花几分钟走完整个流程:浏览与管理智能体 → 创建与配置 → 发起问答。",
},
{
selector: TARGET.tabs,
mode: "popup",
placement: "bottom",
title: "分区浏览",
body: "「我的」放着你创建和收藏的智能体;各「广场」是他人发布共享的,可直接使用或收藏;「私密广场」需要密码访问(管理员还可以查看「内置智能体」)。",
},
{
selector: TARGET.search,
mode: "popup",
placement: "bottom",
title: "搜索与排序",
body: "支持关键词、标签搜索,可按最新创建、最近更新、名称排序;右侧按钮可在卡片 / 列表两种视图间切换。",
},
{
selector: TARGET.agentCard,
mode: "popup",
placement: "top",
title: "智能体卡片",
body: "卡片展示名称、简介、模型与技能徽章;底部操作栏支持收藏、置顶、打标签、发布到广场、复制、编辑、删除;点「对话」直接进入该智能体的问答。",
},
{
selector: TARGET.newAgentBtn,
mode: "popup",
placement: "bottom-left",
title: "创建智能体",
body: "准备好了就点这里,开始创建你的专属智能体;进入创建页后还会有一段配置引导。",
},
];
const CREATE_STEPS: StepSpec[] = [
{
mode: "dialog",
placement: "center",
title: "创建智能体",
body: "页面分两栏:左侧直接与模型对话,让它帮你配置;右侧表单手动填写。两边内容实时联动,选顺手的方式即可。",
},
{
selector: TARGET.createChatInput,
mode: "popup",
placement: "top",
title: "对话式创建",
body: "在这里描述你想要的智能体,例如「帮我做一个周报助手,语气正式、要点条目化」。模型会追问细节并给出配置方案,你确认后方案自动填入右侧表单,可继续微调。",
},
{
selector: TARGET.createBasic,
mode: "popup",
placement: "left",
title: "基本信息",
body: "「名称」显示在卡片和对话页;「描述」用一句话说明它擅长什么,方便日后挑选。",
},
{
selector: TARGET.createModel,
mode: "popup",
placement: "left",
title: "运行模型与入库",
body: "「模型」选择该智能体被使用时调用的模型;「入库模板名」配置后,对话生成的文档可一键发布入库(不需要可留空)。",
},
{
selector: TARGET.createKnowledge,
mode: "popup",
placement: "left",
title: "知识空间",
body: "为智能体挂载知识库,回答时会优先检索其中的资料,让结果更贴合你的业务数据。",
},
{
selector: TARGET.createSoul,
mode: "popup",
placement: "left",
title: "SOUL.md · 人设",
body: "智能体的「灵魂文件」——写清角色定位、能力边界、工作步骤和输出格式。这份提示词直接决定回答质量,是最值得花时间打磨的配置。",
},
{
selector: TARGET.createSkills,
mode: "popup",
placement: "left",
title: "技能挂载",
body: "从可用技能中勾选要赋予的能力,已选技能会作为工具在对话中被调用;全部不选则是纯对话型智能体。",
},
{
selector: TARGET.createSaveBtn,
mode: "popup",
placement: "top",
title: "创建并保存",
body: "配置完成后点这里保存(左侧对话只是试用场,内容不会自动保存)。保存成功会回到智能体列表。",
},
{
mode: "dialog",
placement: "center",
title: "开始问答",
body: "回到列表页后,点智能体卡片上的「对话」按钮即可开始问答;进入对话页还会有最后一段引导。",
},
];
const CHAT_STEPS: StepSpec[] = [
{
mode: "dialog",
placement: "center",
title: "智能体问答",
body: "一切就绪!这里就是与智能体对话的工作区,快速认识一下。",
},
{
selector: TARGET.chatSidebar,
mode: "popup",
placement: "right",
title: "切换与历史",
body: "左栏顶部可在「我的 / 广场」智能体之间切换;下方是当前智能体的历史会话,点击任意一条继续上次的对话。",
},
{
selector: TARGET.chatQuestions,
mode: "popup",
placement: "bottom",
title: "常用问题",
body: "智能体预设的开场问题,点击即可直接提问,快速体验它的能力。",
},
{
selector: TARGET.chatInput,
mode: "popup",
placement: "top",
title: "输入框",
body: "输入问题后发送即可开始问答;新对话里还可以挂载知识空间,让回答优先检索知识库。",
},
{
selector: TARGET.chatDetail,
mode: "popup",
placement: "left",
title: "智能体详情",
body: "右侧面板展示当前智能体的配置(人设、技能、常用问题),可以直接修改并即时生效;里面的快捷提问也能一键发送。",
},
];
const STAGE_STEPS: Record<AgentGuideStage, StepSpec[]> = {
list: LIST_STEPS,
create: CREATE_STEPS,
chat: CHAT_STEPS,
};
function isBrowser(): boolean {
return typeof window !== "undefined";
}
function isStageFinished(stage: AgentGuideStage): boolean {
return (
isBrowser() && localStorage.getItem(finishedKey(stage)) === "1"
);
}
function markStageFinished(stage: AgentGuideStage) {
if (isBrowser()) localStorage.setItem(finishedKey(stage), "1");
}
function buildSteps(stage: AgentGuideStage): GuideStep[] {
if (!isBrowser()) return [];
return STAGE_STEPS[stage]
.filter((spec) => !spec.selector || document.querySelector(spec.selector))
.map((spec) => ({
element: spec.selector ?? (() => document.body),
mode: spec.mode,
placement: spec.placement,
title: spec.title,
body: spec.body,
}));
}
/**
* 智能体三段引导的运行组件:`stage` 决定步骤内容,`eligible` 为 false 时完全
* 静默(不监听、不自动弹)。挂在三个页面各自的作用域内;`autoStart` 为 false
* 时仅响应手动触发(列表页不自动弹,进新建页才自动演示)。
*/
export function AgentGuide({
stage,
eligible,
autoStart = true,
}: {
stage: AgentGuideStage;
eligible: boolean;
autoStart?: boolean;
}) {
const [current, setCurrent] = useState(-1);
const stepsRef = useRef<GuideStep[]>([]);
const start = useCallback(() => {
const steps = buildSteps(stage);
if (steps.length === 0) return;
stepsRef.current = steps;
setCurrent(0);
}, [stage]);
// 自动演示:没显式结束过(没点过完成/跳过)时,每次进入该页都演示;是否
// 「已看过」只由 finish 回调(完成/跳过)写入。
const autoTriedRef = useRef(false);
useEffect(() => {
if (!eligible || !autoStart || autoTriedRef.current) return;
autoTriedRef.current = true;
if (isStageFinished(stage)) return;
const timer = setTimeout(start, START_DELAY_MS);
return () => {
clearTimeout(timer);
// 组件在计时窗口内卸载(用户迅速离开页面)则下次进入再演示。
autoTriedRef.current = false;
};
}, [eligible, autoStart, stage, start]);
// 手动触发:页面头部「使用引导」按钮广播事件,忽略已看过记忆强制重放。
useEffect(() => {
if (!eligible) return;
const handler = () => start();
window.addEventListener(startEventName(stage), handler);
return () =>
window.removeEventListener(startEventName(stage), handler);
}, [eligible, stage, start]);
// 完成 / 跳过都是用户显式结束引导,就地关闭并记忆「已看过」,不跳转任何页面。
const finish = useCallback(() => {
markStageFinished(stage);
setCurrent(-1);
}, [stage]);
if (!eligible) return null;
return (
<Guide
current={current}
steps={stepsRef.current}
onChange={setCurrent}
onFinish={finish}
onSkip={finish}
/>
);
}
@@ -5,7 +5,7 @@ import Link from "next/link";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { useThreadsPage } from "@/core/threads/hooks"; import { useThreadsPage } from "@/core/threads/hooks";
import { pathOfThread, titleOfThread, isHiddenFromRecentChats, isBootstrapThread } from "@/core/threads/utils"; import { pathOfThread, titleOfThread } from "@/core/threads/utils";
import { desensitize } from "@/lib/desensitize"; import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -22,9 +22,12 @@ export function AgentRecentChats({ agentId }: { agentId: string }) {
pageSize: RECENT_LIMIT, pageSize: RECENT_LIMIT,
metadata: { agent_id: agentId }, metadata: { agent_id: agentId },
}); });
// 该智能体的会话里同样排除引导 / 系统 / 配置向导会话。 // 该智能体的会话里同样排除调度 / 引导 / 会商类系统会话。
const threads = (data?.threads ?? []).filter( const threads = (data?.threads ?? []).filter(
(th) => !isBootstrapThread(th) && !isHiddenFromRecentChats(th), (th) =>
th.metadata?.thread_type !== "bootstrap" &&
th.metadata?.thread_type !== "scheduler" &&
th.metadata?.thread_type !== "roundtable",
); );
return ( return (
@@ -1,160 +0,0 @@
"use client";
import { BotIcon, MessageSquareIcon, Radio, SquarePenIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { SENTIMENT_AGENT_ID } from "@/core/sentiment-agent/config";
import { readSentimentAgentProfile } from "@/core/sentiment-agent/profile";
import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils";
import { SentimentAgentProfileDialog } from "./sentiment-agent-profile-dialog";
/**
* 「舆情分析」类型下的虚拟智能体卡片:只存在于前端(不落库 /api/agents),
* 对话经 Gateway 转发外部 AG-UI 网关。名称 / 简介可编辑(localStorage),
* 视觉与普通智能体卡片保持一致(网格 / 列表两种布局)。
*/
export function SentimentAgentCard({
layout = "grid",
className,
}: {
layout?: "grid" | "list";
className?: string;
}) {
const router = useRouter();
const [profile, setProfile] = useState(() => readSentimentAgentProfile());
const [editOpen, setEditOpen] = useState(false);
// 编辑弹窗也可能挂在对话页,保存后广播事件,这里即时刷新卡片。
useEffect(() => {
const onChange = () => setProfile(readSentimentAgentProfile());
window.addEventListener("sentiment-agent-profile-changed", onChange);
return () =>
window.removeEventListener("sentiment-agent-profile-changed", onChange);
}, []);
const handleChat = () => {
router.push(`/page/workspace/agents/${SENTIMENT_AGENT_ID}/chats/new`);
};
const editButton = (
<Button
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
onClick={() => setEditOpen(true)}
title="编辑名称与简介"
aria-label="编辑名称与简介"
>
<SquarePenIcon className="h-3.5 w-3.5" />
</Button>
);
const chatButton = (
<Button
size="sm"
className={cn(layout === "list" ? "shrink-0" : "w-full")}
onClick={handleChat}
>
<MessageSquareIcon className="mr-1.5 h-3.5 w-3.5" />
对话
</Button>
);
const badge = (
<Badge variant="secondary" className="gap-1 text-xs">
<Radio className="size-3" />
舆情分析
</Badge>
);
const dialog = (
<SentimentAgentProfileDialog
open={editOpen}
onOpenChange={setEditOpen}
/>
);
if (layout === "list") {
return (
<div
className={cn(
"group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]",
className,
)}
>
<div className="agent-avatar bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
<BotIcon className="h-5 w-5" />
</div>
<div className="min-w-0 flex-1 overflow-hidden">
<div className="flex min-w-0 items-center gap-2">
<span
className="min-w-0 truncate text-sm font-medium"
title={desensitize(profile.name)}
>
{desensitize(profile.name)}
</span>
{badge}
</div>
<p className="text-muted-foreground mt-0.5 truncate text-xs">
{desensitize(profile.description)}
</p>
</div>
<div className="flex shrink-0 items-center gap-1">
{editButton}
{chatButton}
</div>
{dialog}
</div>
);
}
return (
<Card
className={cn(
"group flex min-w-0 flex-col transition-shadow hover:shadow-md",
className,
)}
>
<CardHeader className="min-w-0 pb-2">
<div className="flex min-w-0 items-start justify-between gap-2">
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
<div className="agent-avatar bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
<BotIcon className="h-5 w-5" />
</div>
<div className="min-w-0 flex-1 overflow-hidden">
<CardTitle
className="block w-full min-w-0 overflow-hidden text-base text-ellipsis whitespace-nowrap"
title={desensitize(profile.name)}
>
{desensitize(profile.name)}
</CardTitle>
<div className="mt-0.5">{badge}</div>
</div>
</div>
<div className="flex shrink-0 items-center justify-end gap-1">
{editButton}
</div>
</div>
<CardDescription className="mt-2 line-clamp-2 text-sm">
{desensitize(profile.description)}
</CardDescription>
</CardHeader>
<CardFooter className="mt-auto flex flex-col items-stretch gap-2 pt-2">
{chatButton}
</CardFooter>
{dialog}
</Card>
);
}
@@ -1,104 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
DEFAULT_SENTIMENT_AGENT_PROFILE,
type SentimentAgentProfile,
readSentimentAgentProfile,
saveSentimentAgentProfile,
} from "@/core/sentiment-agent/profile";
/**
* 舆情分析智能体的「编辑信息」弹窗:修改名称 / 简介并保存到 localStorage。
* 智能体管理页的卡片和对话页顶栏共用。
*/
export function SentimentAgentProfileDialog({
open,
onOpenChange,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
useEffect(() => {
if (!open) return;
const profile = readSentimentAgentProfile();
setName(profile.name);
setDescription(profile.description);
}, [open]);
const handleSave = () => {
const next: SentimentAgentProfile = {
name: name.trim() || DEFAULT_SENTIMENT_AGENT_PROFILE.name,
description:
description.trim() || DEFAULT_SENTIMENT_AGENT_PROFILE.description,
};
saveSentimentAgentProfile(next);
toast.success("舆情分析智能体信息已更新");
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[480px]">
<DialogHeader>
<DialogTitle>编辑舆情分析智能体</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4 py-2">
<div className="flex flex-col gap-2">
<label htmlFor="sentiment-agent-name" className="text-sm font-medium">
名称
</label>
<Input
id="sentiment-agent-name"
value={name}
maxLength={50}
onChange={(e) => setName(e.target.value)}
placeholder="智能体名称"
/>
</div>
<div className="flex flex-col gap-2">
<label
htmlFor="sentiment-agent-description"
className="text-sm font-medium"
>
简介
</label>
<Textarea
id="sentiment-agent-description"
value={description}
maxLength={300}
onChange={(e) => setDescription(e.target.value)}
placeholder="智能体简介(展示在卡片与对话页)"
className="min-h-[96px] resize-none"
/>
</div>
<p className="text-muted-foreground text-xs">
仅修改本浏览器展示的名称与简介;接口地址与鉴权请在部署目录的
runtime-config.js 中配置。
</p>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
取消
</Button>
<Button onClick={handleSave}>保存</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -165,26 +165,10 @@ export function SkillPickerSheet({
return; return;
} }
try { try {
const validation = await validateUpload.mutateAsync({ const validation = await validateUpload.mutateAsync(file);
file,
targetCategory: "custom",
});
if (validation.conflict) { if (validation.conflict) {
const owner = validation.owner_username ?? validation.owner_user_id;
if (validation.owned_by_other && owner) {
toast.error(
`技能「${validation.skill_name}」已由用户「${owner}」上传,不能覆盖。`,
);
return;
}
if (validation.owned_by_me && validation.can_overwrite) {
toast.warning( toast.warning(
`您已上传过同名技能「${validation.skill_name}」,可到「技能」设置页重复上传并覆盖原版本。`, `已存在同名技能「${validation.skill_name}」,请到「技能」设置页上传以选择是否覆盖。`,
);
return;
}
toast.warning(
`已存在同名技能「${validation.skill_name}」,当前不可覆盖。`,
); );
return; return;
} }
@@ -14,12 +14,11 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { useTheme, type ThemeType } from "@/contexts/ThemeContext"; import { useTheme, type ThemeType } from "@/contexts/ThemeContext";
import type { CompactShortcutRouteParam } from "@/core/system-settings/api";
import { useAppearanceSettings, useLayoutMode } from "@/core/system-settings/hooks"; import { useAppearanceSettings, useLayoutMode } from "@/core/system-settings/hooks";
import { isHideChromeActive } from "@/core/embed/embed-session"; import { isHideChromeActive } from "@/core/embed/embed-session";
import { env } from "@/env"; import { env } from "@/env";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { buildLightAppUrl, resolveRouteParamValue } from "@/strategy-components/lib/light-app"; import { buildLightAppUrl } from "@/strategy-components/lib/light-app";
/** /**
* 换肤 / 界面模式 顶栏控件。深色顶栏(Header)与简洁模式页面级顶栏(ChatPage 等)共用, * 换肤 / 界面模式 顶栏控件。深色顶栏(Header)与简洁模式页面级顶栏(ChatPage 等)共用,
@@ -48,34 +47,6 @@ const triggerToneClass = (tone: AppearanceControlTone) =>
? "text-[var(--navigation-foreground)] hover:bg-white/20 hover:text-[var(--navigation-foreground)] active:bg-white/30" ? "text-[var(--navigation-foreground)] hover:bg-white/20 hover:text-[var(--navigation-foreground)] active:bg-white/30"
: "text-muted-foreground hover:bg-muted hover:text-foreground"; : "text-muted-foreground hover:bg-muted hover:text-foreground";
function appendShortcutPathParams(url: string, params: CompactShortcutRouteParam[]) {
const pathSegments = params
.filter((param) => param.paramType === "path")
.map((param) =>
resolveRouteParamValue({ ...param, paramType: "login" }).trim(),
)
.filter(Boolean)
.map((value) => encodeURIComponent(value));
if (pathSegments.length === 0) return url;
const hashIndex = url.indexOf("#");
if (hashIndex < 0) {
const [path, query = ""] = url.split("?", 2);
return `${path.replace(/\/+$/, "")}/${pathSegments.join("/")}${query ? `?${query}` : ""}`;
}
const beforeHash = url.slice(0, hashIndex);
const fragment = url.slice(hashIndex + 1);
const [routePath, query = ""] = fragment.split("?", 2);
return `${beforeHash}#${routePath.replace(/\/+$/, "")}/${pathSegments.join("/")}${query ? `?${query}` : ""}`;
}
function isQueryShortcutParam(
param: CompactShortcutRouteParam,
): param is CompactShortcutRouteParam & { paramType: "login" | "theme" } {
return param.paramType === "login" || param.paramType === "theme";
}
export function CompactShortcutButtons({ tone }: { tone: AppearanceControlTone }) { export function CompactShortcutButtons({ tone }: { tone: AppearanceControlTone }) {
const { data: appearance } = useAppearanceSettings(); const { data: appearance } = useAppearanceSettings();
const buttons = (appearance?.compact_shortcut_buttons ?? []) const buttons = (appearance?.compact_shortcut_buttons ?? [])
@@ -98,10 +69,9 @@ export function CompactShortcutButtons({ tone }: { tone: AppearanceControlTone }
)} )}
title={button.label} title={button.label}
onClick={() => { onClick={() => {
const routeParams = (button.route_params ?? []).map((param) => ({ ...param }));
const url = buildLightAppUrl({ const url = buildLightAppUrl({
url: appendShortcutPathParams(button.url, routeParams), url: button.url,
routeParams: routeParams.filter(isQueryShortcutParam), routeParams: button.route_params.map((param) => ({ ...param })),
}); });
window.open(url, "_blank", "noopener,noreferrer"); window.open(url, "_blank", "noopener,noreferrer");
}} }}
@@ -152,7 +122,6 @@ export function ThemeSwitcher({ tone }: { tone: AppearanceControlTone }) {
return ( return (
<div <div
className="relative" className="relative"
data-compact-guide="theme-switcher"
onMouseEnter={() => { onMouseEnter={() => {
cancelClose(); cancelClose();
setOpen(true); setOpen(true);
@@ -223,19 +192,22 @@ const LAYOUT_OPTIONS = [
* 界面模式(全量 / 简洁)下拉切换。换肤旁并排,图标 + 下拉: * 界面模式(全量 / 简洁)下拉切换。换肤旁并排,图标 + 下拉:
* - 简洁模式 ChatPage 顶栏(全局顶栏被隐藏)。 * - 简洁模式 ChatPage 顶栏(全局顶栏被隐藏)。
* - 全量模式 Header 右上角。 * - 全量模式 Header 右上角。
* 当前态为有效界面模式(用户自选 > 管理员系统默认 > 内置简洁默认)—— * 用户未显式设置过界面模式时(mode === undefined),当前态按调用方所在的实际界面
* useLayoutMode 总会返回具体值,不再有 undefined 兜底。 * 兜底——`fallback` 指明这一回退值(Header 传 "full",ChatPage 传 "compact")。
*/ */
export function LayoutModeSwitcher({ export function LayoutModeSwitcher({
tone, tone,
fallback = "compact",
navigateTo = "/page/workspace/chats/new", navigateTo = "/page/workspace/chats/new",
}: { }: {
tone: AppearanceControlTone; tone: AppearanceControlTone;
fallback?: "full" | "compact";
navigateTo?: string | null; navigateTo?: string | null;
}) { }) {
const [mode, setLayoutMode] = useLayoutMode(); const [mode, setLayoutMode] = useLayoutMode();
const navigate = useNavigate(); const navigate = useNavigate();
const TriggerIcon = mode === "full" ? PanelLeftIcon : LayoutIcon; const current = mode ?? fallback;
const TriggerIcon = current === "full" ? PanelLeftIcon : LayoutIcon;
if (env.FORCE_COLLAPSED_SIDEBAR || isHideChromeActive()) return null; if (env.FORCE_COLLAPSED_SIDEBAR || isHideChromeActive()) return null;
@@ -249,7 +221,6 @@ export function LayoutModeSwitcher({
className={cn("size-8 shrink-0 rounded-sm", triggerToneClass(tone))} className={cn("size-8 shrink-0 rounded-sm", triggerToneClass(tone))}
title="界面模式" title="界面模式"
aria-label="界面模式" aria-label="界面模式"
data-compact-guide="layout-mode"
> >
<TriggerIcon className="size-4" /> <TriggerIcon className="size-4" />
</Button> </Button>
@@ -259,7 +230,7 @@ export function LayoutModeSwitcher({
<DropdownMenuSeparator /> <DropdownMenuSeparator />
{LAYOUT_OPTIONS.map((option) => { {LAYOUT_OPTIONS.map((option) => {
const Icon = option.icon; const Icon = option.icon;
const active = mode === option.id; const active = current === option.id;
return ( return (
<DropdownMenuItem <DropdownMenuItem
key={option.id} key={option.id}
@@ -1,226 +0,0 @@
import {
ChevronDownIcon,
ChevronRightIcon,
FolderIcon,
FolderOpenIcon,
RefreshCwIcon,
} from "lucide-react";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { artifactPathname, artifactRelativePath } from "@/core/artifacts/listing";
import { getFileIcon, getFileName } from "@/core/utils/files";
import { cn } from "@/lib/utils";
type DirectoryNode = {
name: string;
path: string;
directories: DirectoryNode[];
files: Array<{ artifact: string; name: string; relativePath: string }>;
};
function buildDirectoryTree(artifacts: string[]): DirectoryNode {
const root: DirectoryNode = {
name: "生成文件",
path: "",
directories: [],
files: [],
};
for (const artifact of artifacts) {
const relativePath = artifactRelativePath(artifact);
const parts = relativePath.split("/").filter(Boolean);
if (parts.length === 0) continue;
let current = root;
for (const directoryName of parts.slice(0, -1)) {
let child = current.directories.find((node) => node.name === directoryName);
if (!child) {
child = {
name: directoryName,
path: current.path ? `${current.path}/${directoryName}` : directoryName,
directories: [],
files: [],
};
current.directories.push(child);
}
current = child;
}
current.files.push({
artifact,
name: parts.at(-1) ?? getFileName(artifact),
relativePath,
});
}
const sort = (node: DirectoryNode) => {
node.directories.sort((left, right) =>
left.name.localeCompare(right.name, "zh-CN"),
);
node.files.sort((left, right) =>
left.name.localeCompare(right.name, "zh-CN"),
);
node.directories.forEach(sort);
};
sort(root);
return root;
}
function DirectoryBranch({
node,
depth,
collapsedDirectories,
onToggleDirectory,
selectedArtifact,
onSelect,
}: {
node: DirectoryNode;
depth: number;
collapsedDirectories: Set<string>;
onToggleDirectory: (path: string) => void;
selectedArtifact: string | null;
onSelect: (artifact: string) => void;
}) {
return (
<>
{node.directories.map((directory) => {
const collapsed = collapsedDirectories.has(directory.path);
return (
<div key={directory.path}>
<button
type="button"
className="text-muted-foreground hover:bg-muted/70 hover:text-foreground flex h-8 w-full items-center gap-1.5 rounded-md pr-2 text-left text-xs"
style={{ paddingLeft: `${8 + depth * 14}px` }}
onClick={() => onToggleDirectory(directory.path)}
title={directory.path}
>
{collapsed ? (
<ChevronRightIcon className="size-3.5 shrink-0" />
) : (
<ChevronDownIcon className="size-3.5 shrink-0" />
)}
{collapsed ? (
<FolderIcon className="size-4 shrink-0 text-amber-500" />
) : (
<FolderOpenIcon className="size-4 shrink-0 text-amber-500" />
)}
<span className="truncate">{directory.name}</span>
</button>
{!collapsed && (
<DirectoryBranch
node={directory}
depth={depth + 1}
collapsedDirectories={collapsedDirectories}
onToggleDirectory={onToggleDirectory}
selectedArtifact={selectedArtifact}
onSelect={onSelect}
/>
)}
</div>
);
})}
{node.files.map((file) => {
const selected =
!!selectedArtifact &&
artifactPathname(selectedArtifact) === artifactPathname(file.artifact);
return (
<button
key={file.relativePath}
type="button"
className={cn(
"hover:bg-muted/70 flex min-h-8 w-full items-center gap-2 rounded-md py-1 pr-2 text-left text-xs",
selected
? "bg-primary/10 text-primary font-medium"
: "text-foreground/85",
)}
style={{ paddingLeft: `${27 + depth * 14}px` }}
onClick={() => onSelect(file.artifact)}
title={file.relativePath}
aria-current={selected ? "page" : undefined}
>
<span className="shrink-0">{getFileIcon(file.artifact, "size-4")}</span>
<span className="truncate">{file.name}</span>
</button>
);
})}
</>
);
}
export function ArtifactDirectory({
className,
artifacts,
selectedArtifact,
onSelect,
onRefresh,
refreshing = false,
}: {
className?: string;
artifacts: string[];
selectedArtifact: string | null;
onSelect: (artifact: string) => void;
onRefresh?: () => void;
refreshing?: boolean;
}) {
const tree = useMemo(() => buildDirectoryTree(artifacts), [artifacts]);
const [collapsedDirectories, setCollapsedDirectories] = useState<Set<string>>(
() => new Set(),
);
const toggleDirectory = (path: string) => {
setCollapsedDirectories((current) => {
const next = new Set(current);
if (next.has(path)) next.delete(path);
else next.add(path);
return next;
});
};
return (
<aside
className={cn(
"bg-muted/20 flex min-h-0 w-48 shrink-0 flex-col border-r xl:w-56",
className,
)}
aria-label="生成文件目录"
>
<div className="flex h-12 shrink-0 items-center justify-between gap-2 border-b px-3">
<div className="min-w-0">
<div className="truncate text-sm font-semibold">生成文件</div>
<div className="text-muted-foreground text-[11px]">{artifacts.length} 个文件</div>
</div>
{onRefresh && (
<Button
type="button"
size="icon-sm"
variant="ghost"
className="size-7 shrink-0"
onClick={onRefresh}
disabled={refreshing}
title="刷新文件目录"
aria-label="刷新文件目录"
>
<RefreshCwIcon className={cn("size-3.5", refreshing && "animate-spin")} />
</Button>
)}
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-2">
{artifacts.length > 0 ? (
<DirectoryBranch
node={tree}
depth={0}
collapsedDirectories={collapsedDirectories}
onToggleDirectory={toggleDirectory}
selectedArtifact={selectedArtifact}
onSelect={onSelect}
/>
) : (
<div className="text-muted-foreground px-2 py-8 text-center text-xs leading-5">
生成的文件会显示在这里
</div>
)}
</div>
</aside>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,5 @@
import { DownloadIcon, LoaderIcon, PackageIcon } from "lucide-react"; import { DownloadIcon, LoaderIcon, PackageIcon } from "lucide-react";
import { useCallback, useState, type ReactNode } from "react"; import { useCallback, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -28,17 +28,11 @@ export function ArtifactFileList({
files, files,
threadId, threadId,
onOpenArtifact, onOpenArtifact,
onDownloadArtifact,
fileDescriptions,
}: { }: {
className?: string; className?: string;
files: string[]; files: string[];
threadId: string; threadId: string;
onOpenArtifact?: (filepath: string) => void; onOpenArtifact?: (filepath: string) => void;
/** Optional host download action for virtual/session-owned artifacts. */
onDownloadArtifact?: (filepath: string) => void | Promise<void>;
/** Optional per-file secondary text, such as the report structure used. */
fileDescriptions?: Record<string, ReactNode>;
}) { }) {
const { t } = useI18n(); const { t } = useI18n();
const { isMock, publicShareCode } = useThread(); const { isMock, publicShareCode } = useThread();
@@ -74,11 +68,7 @@ export function ArtifactFileList({
if (downloadingFile) return; if (downloadingFile) return;
setDownloadingFile(filepath); setDownloadingFile(filepath);
try { try {
if (onDownloadArtifact) {
await onDownloadArtifact(filepath);
} else {
await downloadArtifactFile({ filepath, threadId, isMock, publicShareCode }); await downloadArtifactFile({ filepath, threadId, isMock, publicShareCode });
}
} catch (error) { } catch (error) {
console.error(error); console.error(error);
toast.error( toast.error(
@@ -88,7 +78,7 @@ export function ArtifactFileList({
setDownloadingFile(null); setDownloadingFile(null);
} }
}, },
[threadId, isMock, publicShareCode, downloadingFile, onDownloadArtifact], [threadId, isMock, publicShareCode, downloadingFile],
); );
return ( return (
@@ -107,7 +97,7 @@ export function ArtifactFileList({
</div> </div>
</CardTitle> </CardTitle>
<CardDescription className="min-w-0 pl-8 text-xs"> <CardDescription className="min-w-0 pl-8 text-xs">
{fileDescriptions?.[file] ?? `${getFileExtensionDisplayName(file)} file`} {getFileExtensionDisplayName(file)} file
</CardDescription> </CardDescription>
<CardAction className="row-span-1 self-center"> <CardAction className="row-span-1 self-center">
{file.endsWith(".skill") && ( {file.endsWith(".skill") && (
@@ -2,8 +2,6 @@ import {
createContext, createContext,
useCallback, useCallback,
useContext, useContext,
useEffect,
useRef,
useState, useState,
type ReactNode, type ReactNode,
} from "react"; } from "react";
@@ -11,44 +9,18 @@ import {
import { useSidebarSafe } from "@/components/ui/sidebar"; import { useSidebarSafe } from "@/components/ui/sidebar";
import { env } from "@/env"; import { env } from "@/env";
export function artifactPreviewKey(artifact: string): string {
if (!artifact.startsWith("write-file:")) {
return artifact.trim();
}
try {
const url = new URL(artifact);
const messageId = url.searchParams.get("message_id");
const toolCallId = url.searchParams.get("tool_call_id");
if (messageId && toolCallId) {
return `${messageId}:${toolCallId}`;
}
} catch {
// Fall back to the complete value for malformed legacy virtual URLs.
}
return artifact;
}
export interface ArtifactsContextType { export interface ArtifactsContextType {
artifacts: string[]; artifacts: string[];
setArtifacts: (artifacts: string[]) => void; setArtifacts: (artifacts: string[]) => void;
selectedArtifact: string | null; selectedArtifact: string | null;
selectedArtifactKey: string | null;
autoSelect: boolean; autoSelect: boolean;
select: (artifact: string, autoSelect?: boolean) => void; select: (artifact: string, autoSelect?: boolean) => void;
/** Open/update a streamed write without overriding a manual close of that call. */
openStreamedArtifact: (artifact: string, previewKey: string) => boolean;
deselect: () => void; deselect: () => void;
open: boolean; open: boolean;
autoOpen: boolean; autoOpen: boolean;
setOpen: (open: boolean) => void; setOpen: (open: boolean) => void;
/**
* 流式写文件自动开沙箱的两阶段标记:openStreamedArtifact 先收起两侧侧栏
* (阶段一),等收起布局落定后再真正翻转 open(阶段二)。两阶段之间为
* true —— 右侧智能体信息面板据此提前收起,避免与沙箱展开同帧叠加造成卡顿。
*/
preOpen: boolean;
} }
const ArtifactsContext = createContext<ArtifactsContextType | undefined>( const ArtifactsContext = createContext<ArtifactsContextType | undefined>(
@@ -59,171 +31,55 @@ interface ArtifactsProviderProps {
children: ReactNode; children: ReactNode;
} }
// 流式写文件自动开沙箱的分步延迟:t=0 收起左侧聊天记录侧栏,延迟
// STREAMED_PREOPEN_DELAY_MS 后再收右侧智能体信息面板(两次收起错开、
// 不做「左边收完再收右边」的判断,只给固定延迟,避免收起瞬间同帧叠加
// 卡顿),到 STREAMED_OPEN_DELAY_MS(右侧 300ms 收起动画结束)才展开沙箱。
const STREAMED_PREOPEN_DELAY_MS = 200;
const STREAMED_OPEN_DELAY_MS = 500;
export function ArtifactsProvider({ children }: ArtifactsProviderProps) { export function ArtifactsProvider({ children }: ArtifactsProviderProps) {
const [artifacts, setArtifactsState] = useState<string[]>([]); const [artifacts, setArtifactsState] = useState<string[]>([]);
const setArtifacts = useCallback((next: string[]) => { const setArtifacts = useCallback((next: string[]) => {
const normalized = Array.isArray(next) ? next : []; setArtifactsState(Array.isArray(next) ? next : []);
setArtifactsState((previous) =>
previous.length === normalized.length &&
previous.every((artifact, index) => artifact === normalized[index])
? previous
: normalized,
);
}, []); }, []);
const [selectedArtifact, setSelectedArtifact] = useState<string | null>(null); const [selectedArtifact, setSelectedArtifact] = useState<string | null>(null);
const [selectedArtifactKey, setSelectedArtifactKey] = useState<string | null>(null);
const [autoSelect, setAutoSelect] = useState(true); const [autoSelect, setAutoSelect] = useState(true);
const [open, setOpenState] = useState( const [open, setOpen] = useState(
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true", env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true",
); );
const [preOpen, setPreOpen] = useState(false);
const [autoOpen, setAutoOpen] = useState(true); const [autoOpen, setAutoOpen] = useState(true);
const suppressedAutoOpenKeyRef = useRef<string | null>(null);
// 供稳定的 setOpen 回调同步读取。写文件流会高频调用 select/setOpen,避免每次
// Context 状态变化都重建 setter 并触发依赖它的布局 effect。
const selectedArtifactKeyRef = useRef<string | null>(selectedArtifactKey);
const autoOpenRef = useRef(autoOpen);
const openStateRef = useRef(open);
const preOpenTimerRef = useRef<number | null>(null);
const openTimerRef = useRef<number | null>(null);
const sidebar = useSidebarSafe(); const sidebar = useSidebarSafe();
const applyOpen = useCallback((next: boolean) => {
openStateRef.current = next;
setOpenState((previous) => (previous === next ? previous : next));
}, []);
// 取消尚未触发的分步自动开沙箱(用户手动关闭 / 切换会话时)。
const cancelPendingStreamedOpen = useCallback(() => {
if (preOpenTimerRef.current !== null) {
window.clearTimeout(preOpenTimerRef.current);
preOpenTimerRef.current = null;
}
if (openTimerRef.current !== null) {
window.clearTimeout(openTimerRef.current);
openTimerRef.current = null;
}
setPreOpen(false);
}, []);
useEffect(
() => () => {
if (preOpenTimerRef.current !== null) {
window.clearTimeout(preOpenTimerRef.current);
preOpenTimerRef.current = null;
}
if (openTimerRef.current !== null) {
window.clearTimeout(openTimerRef.current);
openTimerRef.current = null;
}
},
[],
);
const select = useCallback( const select = useCallback(
(artifact: string, autoSelect = false) => { (artifact: string, autoSelect = false) => {
const previewKey = artifactPreviewKey(artifact); setSelectedArtifact(artifact);
selectedArtifactKeyRef.current = previewKey;
setSelectedArtifact((previous) => (previous === artifact ? previous : artifact));
setSelectedArtifactKey((previous) => (previous === previewKey ? previous : previewKey));
if (env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true") { if (env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true") {
sidebar?.setOpen(false); sidebar?.setOpen(false);
} }
if (!autoSelect) { if (!autoSelect) {
setAutoSelect((previous) => (previous ? false : previous)); setAutoSelect(false);
} }
}, },
[sidebar], [sidebar, setSelectedArtifact, setAutoSelect],
);
const openStreamedArtifact = useCallback(
(artifact: string, previewKey: string) => {
if (suppressedAutoOpenKeyRef.current === previewKey) {
return false;
}
selectedArtifactKeyRef.current = previewKey;
autoOpenRef.current = true;
setSelectedArtifact((previous) => (previous === artifact ? previous : artifact));
setSelectedArtifactKey((previous) => (previous === previewKey ? previous : previewKey));
setAutoSelect((previous) => (previous ? previous : true));
setAutoOpen((previous) => (previous ? previous : true));
// 阶段一(t=0):立即收起左侧聊天记录侧栏。
if (env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true") {
sidebar?.setOpen(false);
}
if (openStateRef.current) {
// 沙箱已展开(如连续写多个文件):只需切换选中文件,无需分步。
cancelPendingStreamedOpen();
return true;
}
if (openTimerRef.current === null) {
// 阶段二(t=+200ms):延迟固定时长再置 preOpen,右侧智能体信息
// 面板此时才开始收起 —— 与左侧错开,避免两次收起同帧叠加卡顿。
preOpenTimerRef.current = window.setTimeout(() => {
preOpenTimerRef.current = null;
setPreOpen(true);
}, STREAMED_PREOPEN_DELAY_MS);
// 阶段三(t=+500ms,右侧 300ms 收起动画结束):翻转 open 展开
// 沙箱,把「聊天列变窄 + 沙箱内容挂载」与侧栏收起彻底分帧。
openTimerRef.current = window.setTimeout(() => {
openTimerRef.current = null;
applyOpen(true);
setPreOpen(false);
}, STREAMED_OPEN_DELAY_MS);
}
return true;
},
[applyOpen, cancelPendingStreamedOpen, sidebar],
); );
const deselect = useCallback(() => { const deselect = useCallback(() => {
selectedArtifactKeyRef.current = null; setSelectedArtifact(null);
setSelectedArtifact((previous) => (previous === null ? previous : null)); setAutoSelect(true);
setSelectedArtifactKey((previous) => (previous === null ? previous : null)); setOpen(false);
setAutoSelect((previous) => (previous ? previous : true)); }, []);
cancelPendingStreamedOpen();
applyOpen(false);
suppressedAutoOpenKeyRef.current = null;
}, [applyOpen, cancelPendingStreamedOpen]);
const setOpen = useCallback(
(isOpen: boolean) => {
if (!isOpen) {
// 两阶段等待期间用户手动关闭:取消尚未触发的自动展开。
cancelPendingStreamedOpen();
if (autoOpenRef.current) {
autoOpenRef.current = false;
setAutoOpen((previous) => (previous ? false : previous));
setAutoSelect((previous) => (previous ? false : previous));
}
suppressedAutoOpenKeyRef.current = selectedArtifactKeyRef.current;
}
applyOpen(isOpen);
},
[applyOpen, cancelPendingStreamedOpen],
);
const value: ArtifactsContextType = { const value: ArtifactsContextType = {
artifacts, artifacts,
setArtifacts, setArtifacts,
open, open,
preOpen,
autoOpen, autoOpen,
autoSelect, autoSelect,
setOpen, setOpen: (isOpen: boolean) => {
if (!isOpen && autoOpen) {
setAutoOpen(false);
setAutoSelect(false);
}
setOpen(isOpen);
},
selectedArtifact, selectedArtifact,
selectedArtifactKey,
select, select,
openStreamedArtifact,
deselect, deselect,
}; };
@@ -1,344 +0,0 @@
"use client";
import { FilePenLineIcon, ImagePlusIcon, SparklesIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { ModelNameSelect } from "@/components/workspace/model-name-select";
import type { DocumentRewriteStyle } from "@/open-canvas/api/rewrite";
import { useReportStructures, REPORT_STRUCTURE_MODE_OPTIONS, normalizeReportStructureMode, type ReportStructureMode } from "@/strategy-components/api/report-structures";
const KEEP_CURRENT_REPORT_STRUCTURE = "__keep_current_report_structure__";
const DEFAULT_REWRITE_INSTRUCTION = "统一表达风格,减少重复内容,改善段落衔接;不新增原文没有依据的事实。";
const DEFAULT_GENERATE_INSTRUCTION = "基于已选资料按所选报告结构生成一篇新的完整报告;保持事实可核验,不补充没有依据的信息。";
export interface DocumentRewriteDialogInput {
instruction: string;
style: DocumentRewriteStyle;
modelName: string | null;
reportOutline: string;
structureMode: "fixed" | "adaptive";
generateImages: boolean;
maxGeneratedImages: number;
}
const STYLE_OPTIONS: { value: DocumentRewriteStyle; label: string; description: string }[] = [
{
value: "formal_analysis",
label: "正式分析",
description: "客观、严谨,适合报告与研究材料。",
},
{
value: "professional",
label: "专业正式",
description: "适合业务文档和说明材料。",
},
{
value: "concise",
label: "精炼简洁",
description: "减少重复,保留核心信息。",
},
{
value: "readable",
label: "清晰易读",
description: "优化段落衔接和阅读节奏。",
},
];
export function DocumentRewriteDialog({
open,
onOpenChange,
fileName,
charCount,
imageGenerationAvailable = false,
maxGeneratedImages = 4,
initialReportOutline,
operationLabel,
operationDescription,
submitLabel,
operation,
onStart,
onRewriteOriginal,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
fileName: string;
charCount: number;
imageGenerationAvailable?: boolean;
maxGeneratedImages?: number;
/** A saved report structure selected before the dialog was opened. */
initialReportOutline?: string;
/** Optional copy for flows that create a new document instead of replacing one. */
operationLabel?: string;
operationDescription?: string;
submitLabel?: string;
/** ``generate`` creates an independent report; ``rewrite`` edits this report in place. */
operation?: "rewrite" | "generate";
onStart: (input: DocumentRewriteDialogInput) => void;
/** Optional secondary action for generation flows that rewrites the source report in place. */
onRewriteOriginal?: (input: DocumentRewriteDialogInput) => void;
}) {
const isNewReportGeneration = operation === "generate";
const [instruction, setInstruction] = useState(DEFAULT_REWRITE_INSTRUCTION);
const [style, setStyle] = useState<DocumentRewriteStyle>("formal_analysis");
const [modelName, setModelName] = useState<string | null>(null);
const [reportStructureId, setReportStructureId] = useState(KEEP_CURRENT_REPORT_STRUCTURE);
const [structureMode, setStructureMode] = useState<ReportStructureMode>("adaptive");
const [generateImages, setGenerateImages] = useState(false);
const [imageCount, setImageCount] = useState("2");
const reportStructuresQuery = useReportStructures({ status: "enabled" });
const reportStructures = reportStructuresQuery.data ?? [];
const selectedReportStructure = reportStructures.find((item) => item.id === reportStructureId);
const initialReportStructureId = useMemo(() => {
const outline = initialReportOutline?.trim();
if (!outline) return null;
return reportStructures.find((item) => item.content.trim() === outline)?.id ?? null;
}, [initialReportOutline, reportStructures]);
useEffect(() => {
if (!open) return;
setInstruction(isNewReportGeneration ? DEFAULT_GENERATE_INSTRUCTION : DEFAULT_REWRITE_INSTRUCTION);
setStyle("formal_analysis");
setModelName(null);
setReportStructureId(KEEP_CURRENT_REPORT_STRUCTURE);
setStructureMode("adaptive");
setGenerateImages(false);
setImageCount("2");
}, [isNewReportGeneration, open]);
// The structures query may resolve after the dialog opens. Only seed the
// value while the user still has the default selection, so a manual choice
// is never overwritten by a query refresh.
useEffect(() => {
if (!open || !initialReportStructureId) return;
setReportStructureId((current) => (
current === KEEP_CURRENT_REPORT_STRUCTURE ? initialReportStructureId : current
));
}, [initialReportStructureId, open]);
useEffect(() => {
if (!selectedReportStructure) return;
setStructureMode(selectedReportStructure.structureMode);
}, [selectedReportStructure?.id, selectedReportStructure?.structureMode]);
const selectedStyle = STYLE_OPTIONS.find((item) => item.value === style);
const canStart = instruction.trim().length > 0;
const startWith = (handler: (input: DocumentRewriteDialogInput) => void) => {
if (!canStart) return;
handler({
instruction: instruction.trim(),
style,
modelName,
reportOutline: selectedReportStructure?.content ?? "",
structureMode,
generateImages,
maxGeneratedImages: Math.min(
Math.max(Number(imageCount) || 1, 1),
Math.max(Math.min(maxGeneratedImages, 4), 1),
),
});
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<SparklesIcon className="size-5 text-primary" />
{operationLabel ?? "AI 全文改写"}
</DialogTitle>
<DialogDescription>
{operationDescription ?? "将以当前文件快照生成临时草稿。校验通过前不会覆盖原 Markdown。"}
</DialogDescription>
</DialogHeader>
<div className="rounded-lg border bg-muted/35 px-3 py-2.5 text-sm">
<div className="font-medium">{fileName}</div>
<div className="text-muted-foreground mt-1">
{isNewReportGeneration ? "来源报告" : "原文"}约 {charCount.toLocaleString()} 字
</div>
</div>
<label className="grid gap-2 text-sm font-medium">
{isNewReportGeneration ? "生成要求" : "改写要求"}
<Textarea
value={instruction}
onChange={(event) => setInstruction(event.target.value)}
placeholder={isNewReportGeneration
? "例如:突出政策影响,并按所选结构组织章节;仅使用已选资料。"
: "例如:统一为正式行业分析语气,减少重复,不新增外部事实。"}
rows={4}
/>
</label>
<div className="grid gap-4 sm:grid-cols-2">
<label className="grid gap-2 text-sm font-medium">
{isNewReportGeneration ? "报告风格" : "改写风格"}
<Select value={style} onValueChange={(value) => setStyle(value as DocumentRewriteStyle)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{STYLE_OPTIONS.map((item) => (
<SelectItem key={item.value} value={item.value}>
{item.label}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-muted-foreground text-xs">{selectedStyle?.description}</span>
</label>
<label className="grid gap-2 text-sm font-medium">
报告结构
<Select value={reportStructureId} onValueChange={setReportStructureId}>
<SelectTrigger aria-label="报告结构">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={KEEP_CURRENT_REPORT_STRUCTURE}>沿用当前结构</SelectItem>
{reportStructuresQuery.isLoading && (
<SelectItem value="__report_structures_loading__" disabled>
正在加载结构…
</SelectItem>
)}
{reportStructuresQuery.isError && (
<SelectItem value="__report_structures_error__" disabled>
报告结构库加载失败
</SelectItem>
)}
{reportStructures.map((structure) => (
<SelectItem key={structure.id} value={structure.id}>
{structure.title}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-muted-foreground text-xs">
{selectedReportStructure?.name || "默认保留原文的章节安排。"}
</span>
</label>
<label className="grid gap-2 text-sm font-medium">
结构约束
<Select
value={structureMode}
onValueChange={(value) => setStructureMode(normalizeReportStructureMode(value))}
>
<SelectTrigger aria-label="结构约束">
<SelectValue />
</SelectTrigger>
<SelectContent>
{REPORT_STRUCTURE_MODE_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-muted-foreground text-xs">
{REPORT_STRUCTURE_MODE_OPTIONS.find((option) => option.value === structureMode)?.description}
</span>
</label>
<label className="grid gap-2 text-sm font-medium">
模型
<ModelNameSelect
value={modelName}
onChange={setModelName}
triggerClassName="h-10 text-sm"
defaultLabel="系统默认模型"
/>
<span className="text-muted-foreground text-xs">
仅影响本次{isNewReportGeneration ? "新报告生成" : "全文改写"}。
</span>
</label>
</div>
{imageGenerationAvailable && (
<div className="rounded-lg border bg-muted/20 p-3">
<div className="flex items-start justify-between gap-4">
<label className="flex min-w-0 cursor-pointer items-start gap-3" htmlFor="document-rewrite-images">
<span className="bg-primary/10 text-primary mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full">
<ImagePlusIcon className="size-4" />
</span>
<span className="grid gap-0.5">
<span className="text-sm font-medium">
{isNewReportGeneration ? "为新报告补充配图" : "改写后补充配图"}
</span>
<span className="text-muted-foreground text-xs leading-5">
根据章节生成并保存为当前沙箱的本地图片,不使用外部图片链接。
</span>
</span>
</label>
<Switch
aria-label={isNewReportGeneration ? "为新报告补充配图" : "改写后补充配图"}
checked={generateImages}
id="document-rewrite-images"
onCheckedChange={setGenerateImages}
/>
</div>
{generateImages && (
<div className="mt-3 flex items-center justify-between gap-3 border-t pt-3">
<span className="text-muted-foreground text-xs">每次会额外消耗图片模型额度</span>
<label className="flex items-center gap-2 text-sm">
配图数量
<Select value={imageCount} onValueChange={setImageCount}>
<SelectTrigger className="h-8 w-20 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
{Array.from({ length: Math.min(Math.max(maxGeneratedImages, 1), 4) }, (_, index) => index + 1).map((count) => (
<SelectItem key={count} value={String(count)}>{count} 张</SelectItem>
))}
</SelectContent>
</Select>
</label>
</div>
)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
取消
</Button>
{isNewReportGeneration && onRewriteOriginal && (
<Button
variant="outline"
disabled={!canStart}
onClick={() => startWith(onRewriteOriginal)}
>
<FilePenLineIcon />
改写原文
</Button>
)}
<Button
disabled={!canStart}
onClick={() => startWith(onStart)}
>
<SparklesIcon />
{submitLabel ?? "开始改写"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -1,5 +1,4 @@
export * from "./artifact-file-detail"; export * from "./artifact-file-detail";
export * from "./artifact-directory";
export * from "./artifact-file-list"; export * from "./artifact-file-list";
export * from "./artifact-trigger"; export * from "./artifact-trigger";
export * from "./context"; export * from "./context";
@@ -117,7 +117,7 @@ export function SpreadsheetPreview({
{Array.from({ length: columnCount }, (_, columnIndex) => ( {Array.from({ length: columnCount }, (_, columnIndex) => (
<th <th
key={columnIndex} key={columnIndex}
className="border-border bg-muted/60 text-foreground border px-3 py-1.5 text-left font-semibold whitespace-pre-wrap" className="border-border bg-muted/60 text-foreground sticky top-0 border px-3 py-1.5 text-left font-medium whitespace-pre-wrap"
> >
{desensitize(headerRow?.[columnIndex] ?? "")} {desensitize(headerRow?.[columnIndex] ?? "")}
</th> </th>
@@ -1,7 +1,6 @@
import type { Message } from "@langchain/langgraph-sdk"; import type { Message } from "@langchain/langgraph-sdk";
import { useQuery } from "@tanstack/react-query";
import { FilesIcon, XIcon } from "lucide-react"; import { FilesIcon, XIcon } from "lucide-react";
import { usePathname, useSearchParams } from "next/navigation"; import { usePathname } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import type { GroupImperativeHandle } from "react-resizable-panels"; import type { GroupImperativeHandle } from "react-resizable-panels";
@@ -14,17 +13,8 @@ import {
} from "@/components/ui/resizable"; } from "@/components/ui/resizable";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { apiFetch } from "@/core/api"; import { apiFetch } from "@/core/api";
import {
artifactPathname,
listThreadArtifacts,
mergeArtifactPaths,
} from "@/core/artifacts/listing";
import { latestInFlightWriteFilePreview } from "@/core/artifacts/write-file-in-flight";
import { shouldAutoOpenWritingArtifact } from "@/core/threads/writing-mode";
import { getBackendBaseURL } from "@/core/config"; import { getBackendBaseURL } from "@/core/config";
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings"; import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
import { isSingleRoundRagMessage } from "@/core/threads/use-single-round-rag";
import { useSkills } from "@/core/skills/hooks"; import { useSkills } from "@/core/skills/hooks";
import type { SkillDisplayConfig } from "@/core/skills/type"; import type { SkillDisplayConfig } from "@/core/skills/type";
import { import {
@@ -40,7 +30,6 @@ import { cn } from "@/lib/utils";
import { import {
ArtifactFileDetail, ArtifactFileDetail,
ArtifactDirectory,
ArtifactFileList, ArtifactFileList,
useArtifacts, useArtifacts,
} from "../artifacts"; } from "../artifacts";
@@ -49,7 +38,6 @@ import { SkillDisplaySources } from "../skill-display-sources";
const CLOSE_MODE = { chat: 100, artifacts: 0 }; const CLOSE_MODE = { chat: 100, artifacts: 0 };
const OPEN_MODE = { chat: 60, artifacts: 40 }; const OPEN_MODE = { chat: 60, artifacts: 40 };
const DIRECTORY_OPEN_MODE = { chat: 48, artifacts: 52 };
const SHOW_REFERENCE_EVENT = "workspace:show-reference"; const SHOW_REFERENCE_EVENT = "workspace:show-reference";
type BackendReferenceSource = Parameters<typeof SkillDisplaySources>[0]["sources"][number]; type BackendReferenceSource = Parameters<typeof SkillDisplaySources>[0]["sources"][number];
@@ -88,19 +76,9 @@ const ChatBox: React.FC<{
threadId, threadId,
disableArtifacts = false, disableArtifacts = false,
}) => { }) => {
const { const { thread } = useThread();
isMock,
thread,
knowledgeReferencesEnabled = false,
} = useThread();
const pathname = usePathname(); const pathname = usePathname();
const searchParams = useSearchParams();
const requestedArtifact = useMemo(() => {
const value = searchParams.get("artifact")?.trim();
return value ? artifactPathname(value) : null;
}, [searchParams]);
const threadIdRef = useRef(threadId); const threadIdRef = useRef(threadId);
const openedRequestedArtifactRef = useRef<string | null>(null);
const artifactsCountRef = useRef(0); const artifactsCountRef = useRef(0);
const layoutRef = useRef<GroupImperativeHandle>(null); const layoutRef = useRef<GroupImperativeHandle>(null);
const latestReferenceBatchIdRef = useRef<string | null>(null); const latestReferenceBatchIdRef = useRef<string | null>(null);
@@ -112,83 +90,10 @@ const ChatBox: React.FC<{
const [pinnedReferenceId, setPinnedReferenceId] = useState<string | null>(null); const [pinnedReferenceId, setPinnedReferenceId] = useState<string | null>(null);
const [backendReferenceBatches, setBackendReferenceBatches] = useState<BackendReferenceBatch[]>([]); const [backendReferenceBatches, setBackendReferenceBatches] = useState<BackendReferenceBatch[]>([]);
const [settings] = useLocalSettings(); const [settings] = useLocalSettings();
// 写作模式专属的产物拦截 / 沙箱打开策略只在开关开启时生效,普通模式保持
// 原有行为(新产物自动打开 + in-flight 预览不过滤)。
const writingModeEnabled = !!settings.context.writing_mode;
const artifactDirectoryModeEnabled =
settings.display.artifactDirectoryModeEnabled ?? false;
const { data: citationDisplay } = useCitationDisplaySettings();
const referenceModeEntryEnabled =
citationDisplay?.reference_mode_enabled ?? false;
const ragModeEnabled = const ragModeEnabled =
(referenceModeEntryEnabled && settings.display.ragModeEnabled) || settings.display.ragModeEnabled || isThreadRagModeLocked(threadId);
isThreadRagModeLocked(threadId) ||
knowledgeReferencesEnabled;
// Frontend RAG modes write their own hidden source tool messages. They use
// the existing reference panel, but must not request or write reference
// batches through DeerFlow's backend APIs.
const hasFrontendRag = useMemo(
() =>
(thread.values.messages ?? []).some((message) =>
isSingleRoundRagMessage(message),
),
[thread.values.messages],
);
const referencesEnabled = ragModeEnabled || hasFrontendRag;
const shouldFetchBackendReferenceBatches =
referencesEnabled && !hasFrontendRag && !!threadId && threadId !== "new";
const { skills } = useSkills(); const { skills } = useSkills();
const canScanArtifactDirectory =
(artifactDirectoryModeEnabled || !!requestedArtifact) &&
!disableArtifacts &&
!isMock &&
!!threadId &&
threadId !== "new";
const artifactListingQuery = useQuery({
queryKey: ["artifact-directory", threadId],
queryFn: ({ signal }) => listThreadArtifacts(threadId, signal),
enabled: canScanArtifactDirectory,
refetchInterval: thread.isLoading ? 1_500 : false,
retry: false,
});
const checkpointArtifacts = useMemo(
() => (disableArtifacts ? [] : (thread.values.artifacts ?? [])),
[disableArtifacts, thread.values.artifacts],
);
const checkpointArtifactSignature = checkpointArtifacts.join("\n");
const availableArtifacts = useMemo(
() => {
if (!artifactDirectoryModeEnabled && !requestedArtifact) {
return checkpointArtifacts;
}
const discoveredArtifacts = (artifactListingQuery.data?.files ?? []).map(
(file) => file.path,
);
if (requestedArtifact) discoveredArtifacts.push(requestedArtifact);
return mergeArtifactPaths(checkpointArtifacts, discoveredArtifacts);
},
[
artifactDirectoryModeEnabled,
artifactListingQuery.data?.files,
checkpointArtifacts,
requestedArtifact,
],
);
useEffect(() => {
if (!canScanArtifactDirectory || thread.isLoading) return;
// Run once after streaming settles as well as when checkpoint artifacts
// change, so files written without present_files are not missed by the
// last polling tick.
void artifactListingQuery.refetch();
}, [
artifactListingQuery.refetch,
canScanArtifactDirectory,
checkpointArtifactSignature,
thread.isLoading,
]);
const { const {
artifacts, artifacts,
open: artifactsOpen, open: artifactsOpen,
@@ -197,17 +102,15 @@ const ChatBox: React.FC<{
select: selectArtifact, select: selectArtifact,
deselect, deselect,
selectedArtifact, selectedArtifact,
selectedArtifactKey,
openStreamedArtifact,
} = useArtifacts(); } = useArtifacts();
const [autoSelectFirstArtifact, setAutoSelectFirstArtifact] = useState(true); const [autoSelectFirstArtifact, setAutoSelectFirstArtifact] = useState(true);
const skillDisplayMap = useMemo( const skillDisplayMap = useMemo(
() => (referencesEnabled ? buildSkillDisplayMap(skills) : new Map()), () => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
[referencesEnabled, skills], [ragModeEnabled, skills],
); );
const fallbackReferenceBatches = useMemo(() => { const fallbackReferenceBatches = useMemo(() => {
if (!referencesEnabled) { if (!ragModeEnabled) {
return []; return [];
} }
return buildTurnReferenceBatches( return buildTurnReferenceBatches(
@@ -215,32 +118,9 @@ const ChatBox: React.FC<{
skillDisplayMap, skillDisplayMap,
thread.isLoading, thread.isLoading,
); );
}, [referencesEnabled, skillDisplayMap, thread.isLoading, thread.values.messages]); }, [ragModeEnabled, skillDisplayMap, thread.isLoading, thread.values.messages]);
useEffect(() => { useEffect(() => {
if ( if (!ragModeEnabled) {
disableArtifacts ||
!requestedArtifact ||
!threadId ||
threadId === "new"
) {
return;
}
const requestKey = `${threadId}:${artifactPathname(requestedArtifact)}`;
if (openedRequestedArtifactRef.current === requestKey) return;
openedRequestedArtifactRef.current = requestKey;
selectArtifact(requestedArtifact);
setArtifactsOpen(true);
setSideTab("document");
}, [
disableArtifacts,
requestedArtifact,
selectArtifact,
setArtifactsOpen,
threadId,
]);
useEffect(() => {
if (!shouldFetchBackendReferenceBatches) {
setBackendReferenceBatches([]); setBackendReferenceBatches([]);
return; return;
} }
@@ -276,12 +156,7 @@ const ChatBox: React.FC<{
} }
}); });
return () => controller.abort(); return () => controller.abort();
}, [ }, [ragModeEnabled, thread.isLoading, threadId, thread.values.messages]);
shouldFetchBackendReferenceBatches,
thread.isLoading,
threadId,
thread.values.messages,
]);
const adaptedBackendReferenceBatches = useMemo( const adaptedBackendReferenceBatches = useMemo(
() => () =>
adaptBackendReferenceBatches( adaptBackendReferenceBatches(
@@ -292,22 +167,15 @@ const ChatBox: React.FC<{
); );
const referenceBatches = useMemo( const referenceBatches = useMemo(
() => { () => {
if ( if (adaptedBackendReferenceBatches.length > 0) {
shouldFetchBackendReferenceBatches &&
adaptedBackendReferenceBatches.length > 0
) {
return adaptedBackendReferenceBatches; return adaptedBackendReferenceBatches;
} }
return fallbackReferenceBatches; return fallbackReferenceBatches;
}, },
[ [adaptedBackendReferenceBatches, fallbackReferenceBatches],
adaptedBackendReferenceBatches,
fallbackReferenceBatches,
shouldFetchBackendReferenceBatches,
],
); );
useEffect(() => { useEffect(() => {
if (!shouldFetchBackendReferenceBatches) { if (!ragModeEnabled) {
return; return;
} }
const signature = JSON.stringify({ const signature = JSON.stringify({
@@ -334,14 +202,7 @@ const ChatBox: React.FC<{
fallbackBatches: debugReferenceBatches(fallbackReferenceBatches), fallbackBatches: debugReferenceBatches(fallbackReferenceBatches),
finalBatches: debugReferenceBatches(referenceBatches), finalBatches: debugReferenceBatches(referenceBatches),
}); });
}, [ }, [adaptedBackendReferenceBatches, backendReferenceBatches, fallbackReferenceBatches, ragModeEnabled, referenceBatches, threadId]);
adaptedBackendReferenceBatches,
backendReferenceBatches,
fallbackReferenceBatches,
referenceBatches,
shouldFetchBackendReferenceBatches,
threadId,
]);
const latestReferenceBatch = const latestReferenceBatch =
referenceBatches.length > 0 referenceBatches.length > 0
? referenceBatches[referenceBatches.length - 1]! ? referenceBatches[referenceBatches.length - 1]!
@@ -352,7 +213,7 @@ const ChatBox: React.FC<{
const referenceSources = activeReferenceBatch?.sources ?? []; const referenceSources = activeReferenceBatch?.sources ?? [];
const hasCitationReferences = referenceSources.length > 0; const hasCitationReferences = referenceSources.length > 0;
useEffect(() => { useEffect(() => {
if (!shouldFetchBackendReferenceBatches || !activeReferenceBatch) { if (!ragModeEnabled || !activeReferenceBatch) {
return; return;
} }
logReferenceDebug("frontend-active-reference-batch-payload", threadId, { logReferenceDebug("frontend-active-reference-batch-payload", threadId, {
@@ -361,7 +222,7 @@ const ChatBox: React.FC<{
sourceCount: activeReferenceBatch.sources.length, sourceCount: activeReferenceBatch.sources.length,
sources: activeReferenceBatch.sources.map(debugReferenceSource), sources: activeReferenceBatch.sources.map(debugReferenceSource),
}); });
}, [activeReferenceBatch, shouldFetchBackendReferenceBatches, threadId]); }, [activeReferenceBatch, ragModeEnabled, threadId]);
useEffect(() => { useEffect(() => {
if (hasCitationReferences) { if (hasCitationReferences) {
setReferencesOpen(true); setReferencesOpen(true);
@@ -405,8 +266,7 @@ const ChatBox: React.FC<{
}; };
}, []); }, []);
useEffect(() => { useEffect(() => {
const threadChanged = threadIdRef.current !== threadId; if (threadIdRef.current !== threadId) {
if (threadChanged) {
threadIdRef.current = threadId; threadIdRef.current = threadId;
artifactsCountRef.current = 0; artifactsCountRef.current = 0;
deselect(); deselect();
@@ -420,29 +280,20 @@ const ChatBox: React.FC<{
} }
// Update artifacts from the current thread // Update artifacts from the current thread
const nextArtifacts = availableArtifacts; const nextArtifacts = disableArtifacts ? [] : (thread.values.artifacts ?? []);
const hadArtifacts = artifactsCountRef.current > 0; const hadArtifacts = artifactsCountRef.current > 0;
const hasNewArtifact = nextArtifacts.length > artifactsCountRef.current; const hasNewArtifact = nextArtifacts.length > artifactsCountRef.current;
artifactsCountRef.current = nextArtifacts.length; artifactsCountRef.current = nextArtifacts.length;
const artifactsChanged =
artifacts.length !== nextArtifacts.length ||
artifacts.some((artifact, index) => artifact !== nextArtifacts[index]);
if (artifactsChanged) {
setArtifacts(nextArtifacts); setArtifacts(nextArtifacts);
}
if ( if (
!disableArtifacts && !disableArtifacts &&
nextArtifacts.length > 0 && (hasNewArtifact || (!hadArtifacts && nextArtifacts.length > 0)) &&
((artifactDirectoryModeEnabled && threadChanged) || !selectedArtifact
((hasNewArtifact || !hadArtifacts) && !selectedArtifact))
) { ) {
const newest = nextArtifacts[nextArtifacts.length - 1]!; selectArtifact(nextArtifacts[nextArtifacts.length - 1]!);
if (shouldAutoOpenWritingArtifact(newest, thread.messages, writingModeEnabled)) {
selectArtifact(newest);
setArtifactsOpen(true); setArtifactsOpen(true);
setSideTab("document"); setSideTab("document");
} }
}
// DO NOT automatically deselect the artifact when switching threads, because the artifacts auto discovering is not work now. // DO NOT automatically deselect the artifact when switching threads, because the artifacts auto discovering is not work now.
// if ( // if (
@@ -464,61 +315,13 @@ const ChatBox: React.FC<{
} }
}, [ }, [
threadId, threadId,
artifactDirectoryModeEnabled,
autoSelectFirstArtifact, autoSelectFirstArtifact,
deselect, deselect,
selectArtifact, selectArtifact,
selectedArtifact, selectedArtifact,
artifacts,
setArtifacts, setArtifacts,
availableArtifacts, thread.values.artifacts,
disableArtifacts, disableArtifacts,
thread.messages,
writingModeEnabled,
]);
// Live sandbox: open as soon as any in-flight write_file has a path or
// the first content bytes — not only when that tool is the last CoT step.
// Agentfx (and other agents) often emit write_file + present_files/bash in
// the same turn; the collapsed earlier write would otherwise never auto-open.
const streamingWritePreview = useMemo(
() =>
disableArtifacts || !thread.isLoading
? null
: latestInFlightWriteFilePreview(thread.messages ?? [], writingModeEnabled),
[disableArtifacts, thread.isLoading, thread.messages, writingModeEnabled],
);
useEffect(() => {
if (!streamingWritePreview) return;
openStreamedArtifact(
streamingWritePreview.artifactPath,
streamingWritePreview.previewKey,
);
setSideTab("document");
}, [openStreamedArtifact, streamingWritePreview]);
const directoryModeWasEnabledRef = useRef(artifactDirectoryModeEnabled);
useEffect(() => {
const wasEnabled = directoryModeWasEnabledRef.current;
directoryModeWasEnabledRef.current = artifactDirectoryModeEnabled;
if (
wasEnabled ||
!artifactDirectoryModeEnabled ||
availableArtifacts.length === 0
) {
return;
}
if (!selectedArtifact) {
selectArtifact(availableArtifacts[availableArtifacts.length - 1]!);
}
setArtifactsOpen(true);
setSideTab("document");
}, [
artifactDirectoryModeEnabled,
availableArtifacts,
selectArtifact,
selectedArtifact,
setArtifactsOpen,
]); ]);
const artifactPanelOpen = useMemo(() => { const artifactPanelOpen = useMemo(() => {
@@ -531,10 +334,7 @@ const ChatBox: React.FC<{
return artifactsOpen; return artifactsOpen;
}, [artifactsOpen, artifacts, disableArtifacts]); }, [artifactsOpen, artifacts, disableArtifacts]);
const sidePanelOpen = artifactPanelOpen || (hasCitationReferences && referencesOpen); const sidePanelOpen = artifactPanelOpen || (hasCitationReferences && referencesOpen);
const showTabs = const showTabs = !!selectedArtifact && hasCitationReferences;
hasCitationReferences &&
(!!selectedArtifact ||
(artifactDirectoryModeEnabled && artifacts.length > 0));
useEffect(() => { useEffect(() => {
if (selectedArtifact) { if (selectedArtifact) {
@@ -554,103 +354,12 @@ const ChatBox: React.FC<{
useEffect(() => { useEffect(() => {
if (layoutRef.current) { if (layoutRef.current) {
if (sidePanelOpen) { if (sidePanelOpen) {
layoutRef.current.setLayout( layoutRef.current.setLayout(OPEN_MODE);
artifactDirectoryModeEnabled && artifactPanelOpen
? DIRECTORY_OPEN_MODE
: OPEN_MODE,
);
} else { } else {
layoutRef.current.setLayout(CLOSE_MODE); layoutRef.current.setLayout(CLOSE_MODE);
} }
} }
}, [artifactDirectoryModeEnabled, artifactPanelOpen, sidePanelOpen]); }, [sidePanelOpen]);
const artifactDocumentPanel = artifactDirectoryModeEnabled ? (
<div className="flex size-full min-w-0 overflow-hidden rounded-lg border">
<ArtifactDirectory
artifacts={artifacts}
selectedArtifact={selectedArtifact}
onSelect={(artifact) => {
selectArtifact(artifact);
setArtifactsOpen(true);
}}
onRefresh={
canScanArtifactDirectory
? () => void artifactListingQuery.refetch()
: undefined
}
refreshing={artifactListingQuery.isFetching}
/>
<div className="relative min-w-0 flex-1 overflow-hidden">
{selectedArtifact ? (
<ArtifactFileDetail
key={selectedArtifactKey ?? selectedArtifact}
className="size-full"
filepath={selectedArtifact}
threadId={threadId}
allowVirtualMarkdownEdit
/>
) : (
<>
<div className="absolute top-1 right-1 z-30">
<Button
size="icon-sm"
variant="ghost"
onClick={() => setArtifactsOpen(false)}
>
<XIcon />
</Button>
</div>
<ConversationEmptyState
icon={<FilesIcon />}
title="请选择文件"
description="从左侧目录中选择一个文件进行查看"
/>
</>
)}
</div>
</div>
) : selectedArtifact ? (
<ArtifactFileDetail
key={selectedArtifactKey ?? selectedArtifact}
className="size-full"
filepath={selectedArtifact}
threadId={threadId}
allowVirtualMarkdownEdit
/>
) : (
<div className="relative flex size-full justify-center">
<div className="absolute top-1 right-1 z-30">
<Button
size="icon-sm"
variant="ghost"
onClick={() => setArtifactsOpen(false)}
>
<XIcon />
</Button>
</div>
{artifacts.length === 0 ? (
<ConversationEmptyState
icon={<FilesIcon />}
title="No artifact selected"
description="Select an artifact to view its details"
/>
) : (
<div className="flex size-full max-w-(--container-width-sm) flex-col justify-center p-4 pt-8">
<header className="shrink-0">
<h2 className="text-lg font-medium">Artifacts</h2>
</header>
<main className="min-h-0 grow">
<ArtifactFileList
className="max-w-(--container-width-sm) p-4 pt-12"
files={artifacts}
threadId={threadId}
/>
</main>
</div>
)}
</div>
);
if (disableArtifacts) { if (disableArtifacts) {
return ( return (
@@ -710,7 +419,12 @@ const ChatBox: React.FC<{
</Button> </Button>
</div> </div>
<TabsContent value="document" className="min-h-0 flex-1 overflow-hidden p-0"> <TabsContent value="document" className="min-h-0 flex-1 overflow-hidden p-0">
{artifactDocumentPanel} <ArtifactFileDetail
className="size-full"
filepath={selectedArtifact}
threadId={threadId}
allowVirtualMarkdownEdit
/>
</TabsContent> </TabsContent>
<TabsContent value="references" className="min-h-0 flex-1 overflow-y-auto p-0"> <TabsContent value="references" className="min-h-0 flex-1 overflow-y-auto p-0">
<ReferencePanel <ReferencePanel
@@ -719,8 +433,13 @@ const ChatBox: React.FC<{
/> />
</TabsContent> </TabsContent>
</Tabs> </Tabs>
) : artifactPanelOpen ? ( ) : selectedArtifact ? (
artifactDocumentPanel <ArtifactFileDetail
className="size-full"
filepath={selectedArtifact}
threadId={threadId}
allowVirtualMarkdownEdit
/>
) : hasCitationReferences ? ( ) : hasCitationReferences ? (
<div className="relative size-full overflow-hidden"> <div className="relative size-full overflow-hidden">
<div className="absolute top-1 right-1 z-30"> <div className="absolute top-1 right-1 z-30">
@@ -740,7 +459,41 @@ const ChatBox: React.FC<{
sources={referenceSources} sources={referenceSources}
/> />
</div> </div>
) : null} ) : (
<div className="relative flex size-full justify-center">
<div className="absolute top-1 right-1 z-30">
<Button
size="icon-sm"
variant="ghost"
onClick={() => {
setArtifactsOpen(false);
}}
>
<XIcon />
</Button>
</div>
{thread.values.artifacts?.length === 0 ? (
<ConversationEmptyState
icon={<FilesIcon />}
title="No artifact selected"
description="Select an artifact to view its details"
/>
) : (
<div className="flex size-full max-w-(--container-width-sm) flex-col justify-center p-4 pt-8">
<header className="shrink-0">
<h2 className="text-lg font-medium">Artifacts</h2>
</header>
<main className="min-h-0 grow">
<ArtifactFileList
className="max-w-(--container-width-sm) p-4 pt-12"
files={thread.values.artifacts ?? []}
threadId={threadId}
/>
</main>
</div>
)}
</div>
)}
</div> </div>
</ResizablePanel> </ResizablePanel>
</ResizablePanelGroup> </ResizablePanelGroup>
@@ -989,10 +742,11 @@ function buildTurnReferenceBatches(
continue; continue;
} }
const nextHumanIndex = findNextHumanIndex(messages, index + 1); const nextHumanIndex = findNextHumanIndex(messages, index + 1);
if (nextHumanIndex === -1 && isLoading) {
continue;
}
const endIndex = nextHumanIndex === -1 ? messages.length : nextHumanIndex; const endIndex = nextHumanIndex === -1 ? messages.length : nextHumanIndex;
const assistant = const assistant = findLastAssistantAnswer(messages, index + 1, endIndex);
findLastAssistantAnswer(messages, index + 1, endIndex) ??
findFrontendRagAssistant(messages, index + 1, endIndex);
if (!assistant?.id) { if (!assistant?.id) {
continue; continue;
} }
@@ -1002,13 +756,6 @@ function buildTurnReferenceBatches(
nextHumanIndex === -1 ? undefined : messages[nextHumanIndex]?.id, nextHumanIndex === -1 ? undefined : messages[nextHumanIndex]?.id,
includeBeforeMessage: false, includeBeforeMessage: false,
}).filter((source) => source.mode !== "none"); }).filter((source) => source.mode !== "none");
// GeneralQA's single-RAG stream sends `docs` before the answer. Make
// those cards available immediately, while keeping normal streaming turns
// on their existing "wait for an answer" behavior.
const isFrontendRagTurn = isSingleRoundRagMessage(assistant);
if (nextHumanIndex === -1 && isLoading && !isFrontendRagTurn) {
continue;
}
if (sources.length > 0) { if (sources.length > 0) {
batches.push({ batches.push({
id: assistant.id, id: assistant.id,
@@ -1047,23 +794,6 @@ function findLastAssistantAnswer(
return null; return null;
} }
function findFrontendRagAssistant(
messages: Message[],
start: number,
end: number,
): Message | null {
for (let index = end - 1; index >= start; index -= 1) {
const message = messages[index];
if (
message?.type === "ai" &&
isSingleRoundRagMessage(message)
) {
return message;
}
}
return null;
}
function hasAssistantAnswerContent(message: Message): boolean { function hasAssistantAnswerContent(message: Message): boolean {
const content = message.content; const content = message.content;
if (typeof content === "string") { if (typeof content === "string") {
@@ -1,7 +1,7 @@
import { useParams, useSearchParams } from "next/navigation"; import { useParams, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useRef } from "react"; import { useEffect, useMemo, useRef } from "react";
import { useOptionalPromptInputController } from "@/components/ai-elements/prompt-input"; import { usePromptInputController } from "@/components/ai-elements/prompt-input";
import { useI18n } from "@/core/i18n/hooks"; import { useI18n } from "@/core/i18n/hooks";
/** /**
@@ -11,11 +11,7 @@ export function useSpecificChatMode() {
const { t } = useI18n(); const { t } = useI18n();
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>(); const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
// A regular history item can navigate here while Vite Fast Refresh is const promptInputController = usePromptInputController();
// reconciling the previous page tree. In that short window the page may see
// a stale provider context. This hook only pre-fills the skill-mode draft,
// so it must not make an ordinary chat page fail to render.
const promptInputController = useOptionalPromptInputController();
const inputInitialValue = useMemo(() => { const inputInitialValue = useMemo(() => {
if (threadIdFromPath !== "new" || searchParams.get("mode") !== "skill") { if (threadIdFromPath !== "new" || searchParams.get("mode") !== "skill") {
return undefined; return undefined;
@@ -23,10 +19,8 @@ export function useSpecificChatMode() {
return t.inputBox.createSkillPrompt; return t.inputBox.createSkillPrompt;
}, [threadIdFromPath, searchParams, t.inputBox.createSkillPrompt]); }, [threadIdFromPath, searchParams, t.inputBox.createSkillPrompt]);
const lastInitialValueRef = useRef<string | undefined>(undefined); const lastInitialValueRef = useRef<string | undefined>(undefined);
const setInputRef = useRef<((value: string) => void) | undefined>( const setInputRef = useRef(promptInputController.textInput.setInput);
promptInputController?.textInput.setInput, setInputRef.current = promptInputController.textInput.setInput;
);
setInputRef.current = promptInputController?.textInput.setInput;
useEffect(() => { useEffect(() => {
if ( if (
inputInitialValue && inputInitialValue &&
@@ -34,10 +28,7 @@ export function useSpecificChatMode() {
) { ) {
lastInitialValueRef.current = inputInitialValue; lastInitialValueRef.current = inputInitialValue;
setTimeout(() => { setTimeout(() => {
const setInput = setInputRef.current; setInputRef.current(inputInitialValue);
if (!setInput) return;
setInput(inputInitialValue);
const textarea = document.querySelector("textarea"); const textarea = document.querySelector("textarea");
if (textarea) { if (textarea) {
textarea.focus(); textarea.focus();
@@ -8,13 +8,8 @@ export function CitationLink({
href, href,
children, children,
className, className,
onReferenceClick,
onClick,
...props ...props
}: ComponentProps<"a"> & { }: ComponentProps<"a">) {
/** Lets a message renderer show an in-place source preview instead of scrolling. */
onReferenceClick?: (referenceId: string) => void;
}) {
const childrenText = normalizeCitationText(children); const childrenText = normalizeCitationText(children);
const displayText = childrenText ?? ""; const displayText = childrenText ?? "";
const referenceId = href?.startsWith("#reference-") const referenceId = href?.startsWith("#reference-")
@@ -33,11 +28,6 @@ export function CitationLink({
)} )}
onClick={(event) => { onClick={(event) => {
event.preventDefault(); event.preventDefault();
if (onReferenceClick) {
onReferenceClick(referenceId);
onClick?.(event);
return;
}
const batchId = const batchId =
event.currentTarget.closest<HTMLElement>("[data-reference-batch-id]") event.currentTarget.closest<HTMLElement>("[data-reference-batch-id]")
?.dataset.referenceBatchId; ?.dataset.referenceBatchId;
@@ -51,7 +41,6 @@ export function CitationLink({
target?.scrollIntoView({ behavior: "smooth", block: "center" }); target?.scrollIntoView({ behavior: "smooth", block: "center" });
}; };
window.setTimeout(scroll, 240); window.setTimeout(scroll, 240);
onClick?.(event);
}} }}
{...props} {...props}
> >
@@ -69,7 +58,6 @@ export function CitationLink({
"text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors", "text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors",
className, className,
)} )}
onClick={onClick}
{...props} {...props}
> >
{displayText || children} {displayText || children}
@@ -11,11 +11,12 @@ import { basicLightInit } from "@uiw/codemirror-theme-basic";
import { monokaiInit } from "@uiw/codemirror-theme-monokai"; import { monokaiInit } from "@uiw/codemirror-theme-monokai";
import CodeMirror from "@uiw/react-codemirror"; import CodeMirror from "@uiw/react-codemirror";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
import { memo, useMemo } from "react"; import { useMemo } from "react";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useThread } from "./messages/context";
const customDarkTheme = monokaiInit({ const customDarkTheme = monokaiInit({
settings: { settings: {
background: "transparent", background: "transparent",
@@ -33,7 +34,7 @@ const customLightTheme = basicLightInit({
}, },
}); });
export const CodeEditor = memo(function CodeEditor({ export function CodeEditor({
className, className,
placeholder, placeholder,
value, value,
@@ -42,7 +43,6 @@ export const CodeEditor = memo(function CodeEditor({
disabled, disabled,
autoFocus, autoFocus,
settings, settings,
isStreaming = false,
streamingReadonlyFallback = true, streamingReadonlyFallback = true,
}: { }: {
className?: string; className?: string;
@@ -53,10 +53,11 @@ export const CodeEditor = memo(function CodeEditor({
disabled?: boolean; disabled?: boolean;
autoFocus?: boolean; autoFocus?: boolean;
settings?: unknown; settings?: unknown;
/** Parent-owned streaming flag so this editor does not subscribe to `thread`. */
isStreaming?: boolean;
streamingReadonlyFallback?: boolean; streamingReadonlyFallback?: boolean;
}) { }) {
const {
thread: { isLoading },
} = useThread();
const { resolvedTheme } = useTheme(); const { resolvedTheme } = useTheme();
const extensions = useMemo(() => { const extensions = useMemo(() => {
@@ -80,7 +81,7 @@ export const CodeEditor = memo(function CodeEditor({
className, className,
)} )}
> >
{isStreaming && streamingReadonlyFallback ? ( {isLoading && streamingReadonlyFallback ? (
<Textarea <Textarea
className={cn( className={cn(
"h-full overflow-auto font-mono [&_.cm-editor]:h-full [&_.cm-focused]:outline-none!", "h-full overflow-auto font-mono [&_.cm-editor]:h-full [&_.cm-focused]:outline-none!",
@@ -115,4 +116,4 @@ export const CodeEditor = memo(function CodeEditor({
)} )}
</div> </div>
); );
}); }
@@ -1,318 +0,0 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { Guide, type GuideStep } from "tdesign-react";
import { PROMPT_DIALOG_GUIDE_EVENT } from "@/components/workspace/custom-prompt-menu";
/**
* 简洁模式(隐藏全局导航栏 + 页面侧边栏的布局)新手引导,基于 TDesign React 的
* Guide 组件(https://tdesign.tencent.com/react/components/guide)。
*
* 触发方式:
* - 自动:简洁模式问答落地页自动演示,直到用户显式点「完成」或「跳过」才写
* localStorage 记忆;中途刷新/离开不记忆,下次进入还会再演示。
* - 手动:左侧「设置和更多」下拉的「界面使用引导」。问答页内通过
* COMPACT_GUIDE_START_EVENT 直接启动;其它页面先落 sessionStorage 再导航到
* /chats/new,由本组件在挂载后消费。
*
* 高亮目标通过 `data-compact-guide` 标记在各组件上(见 TARGET 选择器)。启动时逐个
* 检查目标是否存在(新用户无聊天记录、侧栏被收起等场景对应区块不渲染),缺失的
* 步骤直接剔除 —— Guide 对找不到的目标元素会抛错,不能盲传。唯一例外是提示词
* 管理弹窗步骤:弹窗由引导在切到该步时才打开(PROMPT_DIALOG_GUIDE_EVENT 事件),
* 存在性检查落在它的入口(提示词栏)上,且必须等弹窗锚点真正挂载后才切步。
*/
const COMPACT_GUIDE_DONE_KEY = "deerflow.compact-guide-finished";
const COMPACT_GUIDE_PENDING_KEY = "deerflow.compact-guide-pending";
/** 同页手动触发引导的窗口事件名(「设置和更多」→「界面使用引导」)。 */
export const COMPACT_GUIDE_START_EVENT = "compact-guide:start";
/** 引导步骤高亮目标选择器;各目标元素由所在组件打上同名 data 标记。 */
const TARGET = {
nav: '[data-compact-guide="sidebar-nav"]',
recentChats: '[data-compact-guide="recent-chats"]',
settingsMenu: '[data-compact-guide="settings-menu"]',
themeSwitcher: '[data-compact-guide="theme-switcher"]',
layoutMode: '[data-compact-guide="layout-mode"]',
promptBar: '[data-compact-guide="prompt-bar"]',
promptDialog: '[data-compact-guide="prompt-dialog"]',
promptInput: '[data-compact-guide="prompt-input"]',
} as const;
// 等侧栏宽度过渡 / 落地态布局稳定后再启动:Guide 只在步骤切换时测量目标位置,
// 起步太早会把高亮框定位到过渡中的坐标且不会自行纠正。
const START_DELAY_MS = 800;
// 引导打开提示词管理弹窗后等待其锚点挂载的最长时间,超时视为弹窗打不开,
// 跳过该步避免引导卡死。
const PROMPT_DIALOG_TIMEOUT_MS = 4000;
function isBrowser(): boolean {
return typeof window !== "undefined";
}
export function isCompactGuideDone(): boolean {
return isBrowser() && localStorage.getItem(COMPACT_GUIDE_DONE_KEY) === "1";
}
function markCompactGuideDone() {
if (isBrowser()) localStorage.setItem(COMPACT_GUIDE_DONE_KEY, "1");
}
/** 跨页触发:非问答页点击「界面使用引导」时先记录请求,导航到 /chats/new 后消费。 */
export function requestCompactGuideStart() {
if (isBrowser()) sessionStorage.setItem(COMPACT_GUIDE_PENDING_KEY, "1");
}
function hasCompactGuideRequest(): boolean {
return (
isBrowser() &&
sessionStorage.getItem(COMPACT_GUIDE_PENDING_KEY) === "1"
);
}
function consumeCompactGuideRequest() {
if (isBrowser()) sessionStorage.removeItem(COMPACT_GUIDE_PENDING_KEY);
}
interface StepSpec {
/** 高亮目标选择器;缺省(欢迎步骤 dialog 模式)以 body 兜底。 */
selector?: string;
/**
* 目标元素在引导过程中才渲染时(提示词管理弹窗由引导动态打开),存在性检查
* 改查这个已存在的「入口」元素 —— Guide 只在切到某步时才解析其元素,所以
* 该步可以留在步骤列表里,等锚点真正挂载后再切过去。
*/
dependsOn?: string;
mode: "popup" | "dialog";
placement: NonNullable<GuideStep["placement"]>;
title: string;
body: string;
}
const STEP_SPECS: StepSpec[] = [
{
mode: "dialog",
placement: "center",
title: "欢迎使用简洁模式",
body: "当前已隐藏顶部导航栏与全局侧边栏,为您留出更大的工作区。接下来花一分钟认识一下界面布局。",
},
{
selector: TARGET.nav,
mode: "popup",
placement: "right",
title: "功能导航",
body: "新对话、智能体、技能、AI 写作、深度研究等主要入口都在左侧这里,点击即可切换(菜单项由管理员统一配置)。",
},
{
selector: TARGET.recentChats,
mode: "popup",
placement: "right",
title: "聊天记录",
body: "最近的对话会保留在这里,点击任意一条即可继续上次的问答。",
},
{
selector: TARGET.settingsMenu,
mode: "popup",
placement: "right-top",
title: "设置和更多",
body: "通知、设置、用户排行榜,以及菜单管理、技能管理等管理入口都收纳在这个菜单里。",
},
{
selector: TARGET.themeSwitcher,
mode: "popup",
placement: "bottom-left",
title: "主题换肤",
body: "在这里一键切换红色、蓝色、深蓝等多套界面主题。",
},
{
selector: TARGET.layoutMode,
mode: "popup",
placement: "bottom-left",
title: "切回全量模式",
body: "需要顶部导航栏和全局侧边栏时,从这里随时切换回「全量模式」。",
},
{
selector: TARGET.promptBar,
mode: "popup",
placement: "top",
title: "常用提示词",
body: "输入框上方是常用提示词栏:点击任意提示词即可一键填入输入框,省去重复输入。最右侧的齿轮按钮用来管理这些提示词,点击「下一步」带你看一看。",
},
{
selector: TARGET.promptDialog,
dependsOn: TARGET.promptBar,
mode: "popup",
placement: "top",
title: "管理常用提示词",
body: "这就是齿轮按钮打开的管理弹窗:填写名称与提示词内容、选择关联的智能体后保存,即可添加自己的常用提示词(与账号绑定、跨设备可用);下方列表中已保存的提示词可随时编辑、删除;顶部开关可让本账号只用自己保存的提示词。",
},
{
selector: TARGET.promptInput,
mode: "popup",
placement: "top",
title: "开始提问",
body: "在输入框中输入问题,可先选择智能体与知识空间,发送后即可开始问答。",
},
];
/**
* 简洁模式引导。挂在 ChatPage:`eligible` 表示当前处于简洁模式(无全局
* chrome)且非嵌入/强制收起等特殊环境;`autoStart` 表示处于新对话落地态,
* 满足「首次进入」条件时自动演示一遍。
*/
export function CompactModeGuide({
eligible,
autoStart = false,
}: {
eligible: boolean;
autoStart?: boolean;
}) {
const [current, setCurrent] = useState(-1);
const specsRef = useRef<StepSpec[]>([]);
const stepsRef = useRef<GuideStep[]>([]);
const pollTimerRef = useRef<number | null>(null);
// 引导是否处于「已要求打开并接管提示词管理弹窗」状态(事件已发出 owner:true)。
const promptDialogTakenRef = useRef(false);
const clearPollTimer = useCallback(() => {
if (pollTimerRef.current !== null) {
window.clearInterval(pollTimerRef.current);
pollTimerRef.current = null;
}
}, []);
const setPromptDialog = useCallback(
(open: boolean, takeOver: boolean) => {
promptDialogTakenRef.current = takeOver;
window.dispatchEvent(
new CustomEvent(PROMPT_DIALOG_GUIDE_EVENT, {
detail: { open, owner: takeOver },
}),
);
},
[],
);
const releasePromptDialog = useCallback(() => {
if (!promptDialogTakenRef.current) return;
setPromptDialog(false, false);
}, [setPromptDialog]);
const start = useCallback(() => {
clearPollTimer();
releasePromptDialog();
const specs = STEP_SPECS.filter(
(spec) =>
!spec.selector || document.querySelector(spec.dependsOn ?? spec.selector),
);
if (specs.length === 0) return;
specsRef.current = specs;
stepsRef.current = specs.map((spec) => ({
element: spec.selector ?? (() => document.body),
mode: spec.mode,
placement: spec.placement,
title: spec.title,
body: spec.body,
}));
setCurrent(0);
}, [clearPollTimer, releasePromptDialog]);
// 自动引导:没显式结束过(没点过完成/跳过)时,每次落地页都演示。是否「已看过」
// 只由下方 finish 回调(完成/跳过)写入 —— 这里启动时绝不能提前写,否则中途刷新
// 又会被当成已看过。
const autoTriedRef = useRef(false);
useEffect(() => {
if (!eligible || !autoStart || autoTriedRef.current) return;
autoTriedRef.current = true;
if (isCompactGuideDone()) return;
const timer = setTimeout(start, START_DELAY_MS);
return () => {
clearTimeout(timer);
// 组件在计时窗口内卸载(用户迅速离开页面)则下次落地再演示。
autoTriedRef.current = false;
};
}, [eligible, autoStart, start]);
// 跨页手动触发:非问答页点「界面使用引导」→ 记录请求 → 导航到 /chats/new → 此处启动。
// 请求只在定时器真正启动引导时才消费 —— StrictMode 下 effect 会 mount→cleanup→mount
// 双跑,若在检查时就删除,第二次跑就拿不到请求了。
useEffect(() => {
if (!eligible) return;
if (!hasCompactGuideRequest()) return;
const timer = setTimeout(() => {
consumeCompactGuideRequest();
start();
}, START_DELAY_MS);
return () => clearTimeout(timer);
}, [eligible, start]);
// 同页手动触发:已在问答页时「界面使用引导」直接广播事件启动。
useEffect(() => {
if (!eligible) return;
const handler = () => start();
window.addEventListener(COMPACT_GUIDE_START_EVENT, handler);
return () => window.removeEventListener(COMPACT_GUIDE_START_EVENT, handler);
}, [eligible, start]);
// 中途卸载(用户离开页面)也要归还弹窗控制权并停止等待。
useEffect(() => {
return () => {
clearPollTimer();
releasePromptDialog();
};
}, [clearPollTimer, releasePromptDialog]);
// 受控切步:进入提示词弹窗步骤前先打开弹窗并等锚点挂载(Guide 切步时才解析
// 元素,元素必须已存在);离开该步 / 跳过 / 完成时收回弹窗。跳过和完成时
// onChange 也会收到 -1,与 finish 回调各自幂等。
const goTo = (next: number) => {
const specs = specsRef.current;
clearPollTimer();
if (next < 0 || next >= specs.length) {
releasePromptDialog();
setCurrent(-1);
return;
}
if (specs[next].selector === TARGET.promptDialog) {
setPromptDialog(true, true);
const startedAt = Date.now();
pollTimerRef.current = window.setInterval(() => {
if (document.querySelector(TARGET.promptDialog)) {
clearPollTimer();
setCurrent(next);
} else if (Date.now() - startedAt > PROMPT_DIALOG_TIMEOUT_MS) {
clearPollTimer();
releasePromptDialog();
goTo(next + 1 >= specs.length ? -1 : next + 1);
}
}, 50);
return;
}
releasePromptDialog();
setCurrent(next);
};
// 完成 / 跳过是用户显式结束引导 —— 只有这两种情况才记忆「已看过」;中途刷新或
// 离开不记忆,下次进入简洁模式问答页还会再演示。
const finish = useCallback(() => {
clearPollTimer();
releasePromptDialog();
markCompactGuideDone();
setCurrent(-1);
}, [clearPollTimer, releasePromptDialog]);
if (!eligible) return null;
return (
<Guide
current={current}
steps={stepsRef.current}
onChange={goTo}
onFinish={finish}
onSkip={finish}
/>
);
}
@@ -1,142 +0,0 @@
"use client";
import { Wrench, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { cn } from "@/lib/utils";
import { useWorkspaceCompactNavItems } from "./workspace-nav-chat-list";
const TOOLBOX_ICON_TONES = [
"bg-blue-500/12 text-blue-600 dark:text-blue-400",
"bg-violet-500/12 text-violet-600 dark:text-violet-400",
"bg-emerald-500/12 text-emerald-600 dark:text-emerald-400",
"bg-amber-500/14 text-amber-600 dark:text-amber-400",
] as const;
/**
* 简洁模式右侧工具箱。
*
* 菜单来源与左侧简洁菜单、设置和更多完全一致,由管理员在菜单管理中把项目
* 放到 ``toolbox`` 泳道。默认展开常显(不再藏进右侧按钮后面);点 X 或 Esc
* 收起后右侧出现竖排按钮,可再次展开。
*/
export function CompactToolbox() {
const { toolboxItems } = useWorkspaceCompactNavItems();
const { pathname } = useLocation();
const navigate = useNavigate();
const [open, setOpen] = useState(true);
const triggerRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!open) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setOpen(false);
triggerRef.current?.focus();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [open]);
if (toolboxItems.length === 0) return null;
const closeDrawer = () => {
setOpen(false);
requestAnimationFrame(() => triggerRef.current?.focus());
};
return (
<>
<button
ref={triggerRef}
type="button"
aria-label="打开工具箱"
aria-controls="compact-toolbox-panel"
aria-expanded={open}
title="打开工具箱"
onClick={() => setOpen(true)}
className={cn(
"fixed right-0 top-1/2 z-[80] flex size-16 -translate-y-1/2 flex-col items-center justify-center gap-1 rounded-l-2xl border border-r-0 border-primary/25 bg-primary text-primary-foreground shadow-xl transition-[transform,opacity,background-color] duration-200 hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
open && "pointer-events-none translate-x-full opacity-0",
)}
>
<Wrench className="size-6 shrink-0" />
<span className="text-xs font-semibold leading-4">工具箱</span>
</button>
<aside
id="compact-toolbox-panel"
aria-label="工具箱"
aria-hidden={!open}
inert={!open}
className={cn(
"fixed right-0 top-1/2 z-[100] flex max-h-[calc(100vh-32px)] w-32 max-w-[calc(100vw-48px)] -translate-y-1/2 flex-col overflow-hidden rounded-l-2xl bg-background text-foreground shadow-2xl transition-transform duration-300 ease-out",
open
? "pointer-events-auto translate-x-0"
: "pointer-events-none translate-x-full",
)}
>
<header className="relative flex h-12 shrink-0 items-center justify-center px-2">
<h2 className="text-sm font-semibold">工具箱</h2>
<button
type="button"
aria-label="收起工具箱"
title="收起"
onClick={closeDrawer}
className="absolute right-2 flex size-7 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-4" />
</button>
</header>
<nav
aria-label="工具箱菜单"
className="flex min-h-0 flex-col items-center gap-2.5 overflow-y-auto bg-muted/20 p-2"
>
{toolboxItems.map((item, index) => {
const Icon = item.icon;
const active = item.match(pathname);
return (
<button
key={item.id}
type="button"
aria-current={active ? "page" : undefined}
className={cn(
"group flex h-24 w-24 aspect-square shrink-0 flex-col items-center justify-center gap-1.5 rounded-xl p-2 text-center transition-[color,background-color,transform] hover:-translate-y-0.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
active
? "bg-primary/12 text-primary ring-1 ring-inset ring-primary/25"
: "bg-muted/55 text-card-foreground hover:bg-primary/8 hover:text-primary",
)}
onClick={() => navigate(item.path ?? "/page/workspace/chats/new")}
>
<span
className={cn(
"flex size-10 shrink-0 items-center justify-center rounded-xl transition-transform group-hover:scale-105",
active
? "bg-primary text-primary-foreground"
: TOOLBOX_ICON_TONES[index % TOOLBOX_ICON_TONES.length],
)}
>
<Icon className="size-6" strokeWidth={1.8} />
</span>
<span
className="line-clamp-2 w-full text-center text-xs font-medium leading-4"
title={item.label}
>
{item.label}
</span>
</button>
);
})}
</nav>
</aside>
</>
);
}
@@ -42,13 +42,6 @@ import {
import { desensitize } from "@/lib/desensitize"; import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
/**
* 简洁模式引导控制提示词管理弹窗的窗口事件。detail 为
* `{ open: boolean; owner?: boolean }`:`owner` 表示弹窗由引导接管,期间 ESC /
* 点击遮罩等关闭请求一律忽略,直到引导以 `owner: false` 收回控制权。
*/
export const PROMPT_DIALOG_GUIDE_EVENT = "compact-guide:prompt-dialog";
export function CustomPromptBar({ export function CustomPromptBar({
onInsert, onInsert,
className, className,
@@ -63,23 +56,10 @@ export function CustomPromptBar({
(prompt) => !prompt.agent_id || prompt.agent_id === currentAgentId, (prompt) => !prompt.agent_id || prompt.agent_id === currentAgentId,
); );
const [manageOpen, setManageOpen] = useState(false); const [manageOpen, setManageOpen] = useState(false);
const guideOwnsDialogRef = useRef(false);
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
const [canLeft, setCanLeft] = useState(false); const [canLeft, setCanLeft] = useState(false);
const [canRight, setCanRight] = useState(false); const [canRight, setCanRight] = useState(false);
useEffect(() => {
const handler = (event: Event) => {
const detail = (
event as CustomEvent<{ open?: boolean; owner?: boolean }>
).detail;
guideOwnsDialogRef.current = Boolean(detail?.owner);
setManageOpen(Boolean(detail?.open));
};
window.addEventListener(PROMPT_DIALOG_GUIDE_EVENT, handler);
return () => window.removeEventListener(PROMPT_DIALOG_GUIDE_EVENT, handler);
}, []);
const updateArrows = useCallback(() => { const updateArrows = useCallback(() => {
const el = scrollRef.current; const el = scrollRef.current;
if (!el) return; if (!el) return;
@@ -101,10 +81,7 @@ export function CustomPromptBar({
return ( return (
<> <>
<div <div className={cn("flex min-w-0 items-center gap-1", className)}>
className={cn("flex min-w-0 items-center gap-1", className)}
data-compact-guide="prompt-bar"
>
{prompts.length > 0 && ( {prompts.length > 0 && (
<> <>
{overflowing && ( {overflowing && (
@@ -171,14 +148,7 @@ export function CustomPromptBar({
</Button> </Button>
</div> </div>
<ManagePromptsDialog <ManagePromptsDialog open={manageOpen} onOpenChange={setManageOpen} />
open={manageOpen}
onOpenChange={(next) => {
// 引导演示期间接管弹窗:ESC / 点击遮罩不关闭,避免高亮目标消失导致引导报错。
if (!next && guideOwnsDialogRef.current) return;
setManageOpen(next);
}}
/>
</> </>
); );
} }
@@ -287,10 +257,7 @@ function ManagePromptsDialog({
onOpenChange(next); onOpenChange(next);
}} }}
> >
<DialogContent <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-xl">
className="max-h-[85vh] overflow-y-auto sm:max-w-xl"
data-compact-guide="prompt-dialog"
>
<DialogHeader> <DialogHeader>
<DialogTitle>管理常用提示词</DialogTitle> <DialogTitle>管理常用提示词</DialogTitle>
<DialogDescription> <DialogDescription>
@@ -12,11 +12,10 @@ export function FlipDisplay({
className?: string; className?: string;
}) { }) {
return ( return (
<div className={cn("relative min-w-0 overflow-hidden", className)}> <div className={cn("relative overflow-hidden", className)}>
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
<motion.div <motion.div
key={uniqueKey} key={uniqueKey}
className="min-w-0 max-w-full"
initial={{ y: 8, opacity: 0 }} initial={{ y: 8, opacity: 0 }}
animate={{ y: 2, opacity: 1 }} animate={{ y: 2, opacity: 1 }}
exit={{ y: -8, opacity: 0 }} exit={{ y: -8, opacity: 0 }}
@@ -7,8 +7,7 @@
* 共享的 WorkspaceNavChatList / FrequentAgentsList / RecentChatList 里塞会越来越难 * 共享的 WorkspaceNavChatList / FrequentAgentsList / RecentChatList 里塞会越来越难
* 维护,故单独成一个组件,只在 `/page/workspace/chats*` 的全量布局下挂载,互不影响。 * 维护,故单独成一个组件,只在 `/page/workspace/chats*` 的全量布局下挂载,互不影响。
* *
* 可挂在 workspace / strategy 两个普通问答路由下;导航目标由 RouteBaseProvider * 三块结构(自上而下):
* 决定。三块结构(自上而下):
* 1. 「新对话」胶囊按钮 + 收起整列的圆形按钮; * 1. 「新对话」胶囊按钮 + 收起整列的圆形按钮;
* 2. 「常用智能体」—— 彩色图标卡(名称 + 两行简介,命中为选中态:主色描边 + 右侧主色条); * 2. 「常用智能体」—— 彩色图标卡(名称 + 两行简介,命中为选中态:主色描边 + 右侧主色条);
* 3. 「最近的对话」—— 计数徽标 + 折叠、历史搜索框、会话列表(悬浮「更多」菜单: * 3. 「最近的对话」—— 计数徽标 + 折叠、历史搜索框、会话列表(悬浮「更多」菜单:
@@ -77,7 +76,6 @@ import {
import type { AgentThread, AgentThreadState } from "@/core/threads/types"; import type { AgentThread, AgentThreadState } from "@/core/threads/types";
import { import {
isBootstrapThread, isBootstrapThread,
isHiddenFromRecentChats,
isThreadFavorite, isThreadFavorite,
isThreadPinned, isThreadPinned,
listPathOfThread, listPathOfThread,
@@ -86,7 +84,6 @@ import {
titleOfThread, titleOfThread,
} from "@/core/threads/utils"; } from "@/core/threads/utils";
import { buildFullChatNavigationPath } from "@/core/page-layout/chats-iframe-route"; import { buildFullChatNavigationPath } from "@/core/page-layout/chats-iframe-route";
import { useRouteBase } from "@/core/route-base";
import { env } from "@/env"; import { env } from "@/env";
import { desensitize } from "@/lib/desensitize"; import { desensitize } from "@/lib/desensitize";
import { isIMEComposing } from "@/lib/ime"; import { isIMEComposing } from "@/lib/ime";
@@ -95,6 +92,11 @@ import { cn } from "@/lib/utils";
import { agentColor } from "./agent-icon-color"; import { agentColor } from "./agent-icon-color";
import { SidebarCollapseButton } from "./workspace-header"; import { SidebarCollapseButton } from "./workspace-header";
const NEW_CHAT_PATH = "/page/workspace/chats/new";
/** 「更多」常用智能体跳转目标:智能体管理页。 */
const MORE_AGENTS_HREF = "/page/workspace/agents";
/** 「更多最近对话」跳转目标。 */
const MORE_CHATS_HREF = "/page/workspace/chats";
/** 常用智能体最多展示个数。 */ /** 常用智能体最多展示个数。 */
const MAX_FREQUENT = 4; const MAX_FREQUENT = 4;
@@ -139,7 +141,6 @@ function SectionLabel({
export function GeneralQaSidebar() { export function GeneralQaSidebar() {
const { t } = useI18n(); const { t } = useI18n();
const routeBase = useRouteBase();
// 智能体图标配色分主题:深蓝主题用规范蓝-青系,其它(浅色)保持原高彩度色,互不影响。 // 智能体图标配色分主题:深蓝主题用规范蓝-青系,其它(浅色)保持原高彩度色,互不影响。
const { theme } = useTheme(); const { theme } = useTheme();
const isDark = theme === "dark"; const isDark = theme === "dark";
@@ -186,14 +187,9 @@ export function GeneralQaSidebar() {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const activeAgentId = searchParams.get("agent"); const activeAgentId = searchParams.get("agent");
const currentSearch = searchParams.toString(); const currentSearch = searchParams.toString();
const chatsBasePath = `${routeBase}/chats`; const newChatHref = buildFullChatNavigationPath(NEW_CHAT_PATH, currentSearch);
const newChatPath = `${chatsBasePath}/new`; const moreAgentsHref = buildFullChatNavigationPath(MORE_AGENTS_HREF, currentSearch);
const newChatHref = buildFullChatNavigationPath(newChatPath, currentSearch); const moreChatsHref = buildFullChatNavigationPath(MORE_CHATS_HREF, currentSearch);
const moreAgentsHref = buildFullChatNavigationPath(
`${routeBase}/agents`,
currentSearch,
);
const moreChatsHref = buildFullChatNavigationPath(chatsBasePath, currentSearch);
// 点击常用智能体 = 在通用问答右侧**原地嵌入**该智能体的对话页:停留在 /chats/new, // 点击常用智能体 = 在通用问答右侧**原地嵌入**该智能体的对话页:停留在 /chats/new,
// 仅给 URL 加 ?agent=<id>,由 NewChatContent 把右侧问答区换成 AgentChatPage。 // 仅给 URL 加 ?agent=<id>,由 NewChatContent 把右侧问答区换成 AgentChatPage。
@@ -202,18 +198,19 @@ export function GeneralQaSidebar() {
(agentId: string) => { (agentId: string) => {
navigate( navigate(
buildFullChatNavigationPath( buildFullChatNavigationPath(
routeBase === "/page/workspace" `${NEW_CHAT_PATH}?agent=${encodeURIComponent(agentId)}`,
? `${newChatPath}?agent=${encodeURIComponent(agentId)}`
: `${routeBase}/agents/${encodeURIComponent(agentId)}/chats/new`,
currentSearch, currentSearch,
), ),
); );
}, },
[currentSearch, navigate, newChatPath, routeBase], [currentSearch, navigate],
); );
// ── 最近的对话取数 + 搜索 ── // ── 最近的对话取数 + 搜索 ──
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>(); const { thread_id: threadIdFromPath, agent_id: agentIdFromPath } = useParams<{
thread_id: string;
agent_id?: string;
}>();
const { data: threads = [] } = useThreads(); const { data: threads = [] } = useThreads();
const { mutate: deleteThread } = useDeleteThread(); const { mutate: deleteThread } = useDeleteThread();
const { mutate: renameThread } = useRenameThread(); const { mutate: renameThread } = useRenameThread();
@@ -226,19 +223,17 @@ export function GeneralQaSidebar() {
const [renameValue, setRenameValue] = useState(""); const [renameValue, setRenameValue] = useState("");
const [shareThreadId, setShareThreadId] = useState<string | null>(null); const [shareThreadId, setShareThreadId] = useState<string | null>(null);
const pathForThread = useCallback(
(thread: AgentThread) =>
isBootstrapThread(thread)
? listPathOfThread(thread)
: pathOfThread(thread, undefined, routeBase),
[routeBase],
);
const visibleThreads = useMemo( const visibleThreads = useMemo(
() => () =>
// 智能体创建(bootstrap)会话也展示(带机器人图标、点击回创建页); // 智能体创建(bootstrap)会话也展示(带机器人图标、点击回创建页);
// 排除调度 / 会商 / 报告结构&写作配置向导等系统会话。 // 仅排除调度 / 会商类系统会话。
sortThreadsPinnedFirst(threads.filter((thread) => !isHiddenFromRecentChats(thread))), sortThreadsPinnedFirst(
threads.filter(
(thread) =>
thread.metadata?.thread_type !== "scheduler" &&
thread.metadata?.thread_type !== "roundtable",
),
),
[threads], [threads],
); );
@@ -264,22 +259,21 @@ export function GeneralQaSidebar() {
deleteThread({ threadId }); deleteThread({ threadId });
if (threadId === threadIdFromPath) { if (threadId === threadIdFromPath) {
const threadIndex = threads.findIndex((th) => th.thread_id === threadId); const threadIndex = threads.findIndex((th) => th.thread_id === threadId);
let nextThreadPath = newChatPath; let nextThreadPath = pathOfThread("new", { agent_id: agentIdFromPath });
if (threadIndex > -1) { if (threadIndex > -1) {
if (threads[threadIndex + 1]) { if (threads[threadIndex + 1]) {
nextThreadPath = pathForThread(threads[threadIndex + 1]!); nextThreadPath = listPathOfThread(threads[threadIndex + 1]!);
} else if (threads[threadIndex - 1]) { } else if (threads[threadIndex - 1]) {
nextThreadPath = pathForThread(threads[threadIndex - 1]!); nextThreadPath = listPathOfThread(threads[threadIndex - 1]!);
} }
} }
void router.push(buildFullChatNavigationPath(nextThreadPath, currentSearch)); void router.push(buildFullChatNavigationPath(nextThreadPath, currentSearch));
} }
}, },
[ [
agentIdFromPath,
currentSearch, currentSearch,
deleteThread, deleteThread,
newChatPath,
pathForThread,
router, router,
threadIdFromPath, threadIdFromPath,
threads, threads,
@@ -478,7 +472,7 @@ export function GeneralQaSidebar() {
) : ( ) : (
filteredThreads.map((thread) => { filteredThreads.map((thread) => {
const href = buildFullChatNavigationPath( const href = buildFullChatNavigationPath(
pathForThread(thread), listPathOfThread(thread),
currentSearch, currentSearch,
); );
const isActive = href === pathname; const isActive = href === pathname;
@@ -6,7 +6,6 @@ import {
BookMarkedIcon, BookMarkedIcon,
CheckIcon, CheckIcon,
FileTextIcon, FileTextIcon,
FolderTreeIcon,
GraduationCapIcon, GraduationCapIcon,
LightbulbIcon, LightbulbIcon,
PaperclipIcon, PaperclipIcon,
@@ -25,7 +24,6 @@ import {
useRef, useRef,
useState, useState,
type ComponentProps, type ComponentProps,
type ReactNode,
} from "react"; } from "react";
import { import {
@@ -66,7 +64,6 @@ import { getBackendBaseURL } from "@/core/config";
import { useI18n } from "@/core/i18n/hooks"; import { useI18n } from "@/core/i18n/hooks";
import { isHiddenFromUIMessage } from "@/core/messages/utils"; import { isHiddenFromUIMessage } from "@/core/messages/utils";
import { useModels } from "@/core/models/hooks"; import { useModels } from "@/core/models/hooks";
import type { Model } from "@/core/models/types";
import type { AgentThreadContext } from "@/core/threads"; import type { AgentThreadContext } from "@/core/threads";
import { textOfMessage } from "@/core/threads/utils"; import { textOfMessage } from "@/core/threads/utils";
import { desensitize } from "@/lib/desensitize"; import { desensitize } from "@/lib/desensitize";
@@ -98,7 +95,7 @@ import {
lockThreadRagMode, lockThreadRagMode,
useLocalSettings, useLocalSettings,
} from "@/core/settings"; } from "@/core/settings";
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
import { CustomPromptBar } from "./custom-prompt-menu"; import { CustomPromptBar } from "./custom-prompt-menu";
import { useThread } from "./messages/context"; import { useThread } from "./messages/context";
@@ -137,13 +134,9 @@ export function InputBox({
onStop, onStop,
promptPrefix, promptPrefix,
agentSelector, agentSelector,
knowledgeSelector,
extraModels = [],
assistantId, assistantId,
hideAdminRecommendedQuestions, hideAdminRecommendedQuestions,
compact, compact,
hideContextTools,
hideMemoryTool = true,
...props ...props
}: Omit<ComponentProps<typeof PromptInput>, "onSubmit"> & { }: Omit<ComponentProps<typeof PromptInput>, "onSubmit"> & {
assistantId?: string | null; assistantId?: string | null;
@@ -151,14 +144,6 @@ export function InputBox({
/** 紧凑模式(正常 App)新对话落地态:去掉旋转彩边、用 CM 参考图的白卡输入框, /** 紧凑模式(正常 App)新对话落地态:去掉旋转彩边、用 CM 参考图的白卡输入框,
* 并在推荐问题上方加「试试这些高频业务场景」标题。仅落地态生效,默认 false。 */ * 并在推荐问题上方加「试试这些高频业务场景」标题。仅落地态生效,默认 false。 */
compact?: boolean; compact?: boolean;
/** 隐藏输入框工具条上的「写作 / 记忆 / 参考文献」上下文开关按钮(任务深链工作区等
* 受控场景用;文件/模型等其他按钮不受影响)。 */
hideContextTools?: boolean;
/**
* 仅控制「记忆」开关的可见性。产品当前全局隐藏,传入 false 即可无损恢复。
* 写作和参考文献开关不受影响。
*/
hideMemoryTool?: boolean;
disabled?: boolean; disabled?: boolean;
context: Omit< context: Omit<
AgentThreadContext, AgentThreadContext,
@@ -209,30 +194,15 @@ export function InputBox({
selectedAgentId: string | null; selectedAgentId: string | null;
onAgentChange: (agentId: string | null) => void; onAgentChange: (agentId: string | null) => void;
}; };
/** WeKnora-style knowledge-space picker rendered inside the composer toolbar. */
knowledgeSelector?: ReactNode;
/** Page-scoped model choices implemented outside the DeerFlow model API. */
extraModels?: Model[];
}) { }) {
const { t } = useI18n(); const { t } = useI18n();
const [localSettings, setLocalSettings] = useLocalSettings(); const [localSettings, setLocalSettings] = useLocalSettings();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const [modelDialogOpen, setModelDialogOpen] = useState(false); const [modelDialogOpen, setModelDialogOpen] = useState(false);
const { models } = useModels(); const { models } = useModels();
const singleRoundRagActive =
context.execution_profile === "single_round_rag";
const multiRoundRagActive =
context.execution_profile === "multi_round_rag";
const frontendRagActive = singleRoundRagActive || multiRoundRagActive;
const modelOptions = useMemo(() => {
return singleRoundRagActive ? extraModels : models;
}, [extraModels, models, singleRoundRagActive]);
const { thread, isMock } = useThread(); const { thread, isMock } = useThread();
const { textInput } = usePromptInputController(); const { textInput } = usePromptInputController();
const promptRootRef = useRef<HTMLDivElement | null>(null); const promptRootRef = useRef<HTMLDivElement | null>(null);
const { data: citationDisplay } = useCitationDisplaySettings();
const referenceModeEntryEnabled =
citationDisplay?.reference_mode_enabled ?? false;
const [followups, setFollowups] = useState<string[]>([]); const [followups, setFollowups] = useState<string[]>([]);
const [followupsHidden, setFollowupsHidden] = useState(false); const [followupsHidden, setFollowupsHidden] = useState(false);
@@ -253,25 +223,16 @@ export function InputBox({
recommendedQuestions.length > 0; recommendedQuestions.length > 0;
useEffect(() => { useEffect(() => {
// Multi-round RAG is a frontend execution profile, not a model option. if (models.length === 0) {
// Do not let the normal model fallback clear it on every render.
if (multiRoundRagActive) {
return; return;
} }
if (modelOptions.length === 0) { const currentModel = models.find((m) => m.name === context.model_name);
return; const fallbackModel = currentModel ?? models[0]!;
}
const currentModel = modelOptions.find((m) => m.name === context.model_name);
const fallbackModel = currentModel ?? modelOptions[0]!;
const supportsThinking = fallbackModel.supports_thinking ?? false; const supportsThinking = fallbackModel.supports_thinking ?? false;
const nextModelName = fallbackModel.name; const nextModelName = fallbackModel.name;
const nextMode = getResolvedMode(context.mode, supportsThinking); const nextMode = getResolvedMode(context.mode, supportsThinking);
if ( if (context.model_name === nextModelName && context.mode === nextMode) {
context.model_name === nextModelName &&
context.mode === nextMode &&
context.execution_profile === fallbackModel.execution_profile
) {
return; return;
} }
@@ -279,19 +240,17 @@ export function InputBox({
...context, ...context,
model_name: nextModelName, model_name: nextModelName,
mode: nextMode, mode: nextMode,
execution_profile: fallbackModel.execution_profile,
}); });
}, [context, modelOptions, multiRoundRagActive, onContextChange]); }, [context, models, onContextChange]);
const selectedModel = useMemo(() => { const selectedModel = useMemo(() => {
if (modelOptions.length === 0) { if (models.length === 0) {
return undefined; return undefined;
} }
return modelOptions.find((m) => m.name === context.model_name) ?? modelOptions[0]; return models.find((m) => m.name === context.model_name) ?? models[0];
}, [context.model_name, modelOptions]); }, [context.model_name, models]);
const resolvedModelName = selectedModel?.name; const resolvedModelName = selectedModel?.name;
const selectedSingleRoundRag = singleRoundRagActive;
const supportThinking = useMemo( const supportThinking = useMemo(
() => selectedModel?.supports_thinking ?? false, () => selectedModel?.supports_thinking ?? false,
@@ -305,7 +264,7 @@ export function InputBox({
const handleModelSelect = useCallback( const handleModelSelect = useCallback(
(model_name: string) => { (model_name: string) => {
const model = modelOptions.find((m) => m.name === model_name); const model = models.find((m) => m.name === model_name);
if (!model) { if (!model) {
return; return;
} }
@@ -314,24 +273,17 @@ export function InputBox({
model_name, model_name,
mode: getResolvedMode(context.mode, model.supports_thinking ?? false), mode: getResolvedMode(context.mode, model.supports_thinking ?? false),
reasoning_effort: context.reasoning_effort, reasoning_effort: context.reasoning_effort,
execution_profile: model.execution_profile,
}); });
setModelDialogOpen(false); setModelDialogOpen(false);
}, },
[onContextChange, context, modelOptions], [onContextChange, context, models],
); );
const handleModeSelect = useCallback( const handleModeSelect = useCallback(
(mode: InputMode) => { (mode: InputMode) => {
const ordinaryModel =
models.find((model) => model.name === context.model_name) ?? models[0];
onContextChange?.({ onContextChange?.({
...context, ...context,
model_name: ordinaryModel?.name ?? context.model_name, mode: getResolvedMode(mode, supportThinking),
mode: getResolvedMode(
mode,
ordinaryModel?.supports_thinking ?? supportThinking,
),
reasoning_effort: reasoning_effort:
mode === "ultra" mode === "ultra"
? "high" ? "high"
@@ -340,38 +292,11 @@ export function InputBox({
: mode === "thinking" : mode === "thinking"
? "low" ? "low"
: "minimal", : "minimal",
execution_profile: undefined,
}); });
}, },
[onContextChange, context, models, supportThinking], [onContextChange, context, supportThinking],
); );
const handleSingleRoundRagSelect = useCallback(() => {
const ragModel =
extraModels.find((model) => model.name === context.model_name) ??
extraModels[0];
if (!ragModel) {
return;
}
onContextChange?.({
...context,
model_name: ragModel.name,
mode: getResolvedMode(
context.mode,
ragModel.supports_thinking ?? false,
),
execution_profile: "single_round_rag",
});
}, [context, extraModels, onContextChange]);
const handleMultiRoundRagSelect = useCallback(() => {
onContextChange?.({
...context,
execution_profile: "multi_round_rag",
});
}, [context, onContextChange]);
const handleReasoningEffortSelect = useCallback( const handleReasoningEffortSelect = useCallback(
(effort: "minimal" | "low" | "medium" | "high") => { (effort: "minimal" | "low" | "medium" | "high") => {
onContextChange?.({ onContextChange?.({
@@ -389,14 +314,6 @@ export function InputBox({
}); });
}, [context, onContextChange]); }, [context, onContextChange]);
const artifactDirectoryModeEnabled =
localSettings.display.artifactDirectoryModeEnabled ?? false;
const handleArtifactDirectoryModeToggle = useCallback(() => {
setLocalSettings("display", {
artifactDirectoryModeEnabled: !artifactDirectoryModeEnabled,
});
}, [artifactDirectoryModeEnabled, setLocalSettings]);
const memoryInjectionEnabled = context.memory_injection_enabled ?? true; const memoryInjectionEnabled = context.memory_injection_enabled ?? true;
const handleMemoryInjectionToggle = useCallback(() => { const handleMemoryInjectionToggle = useCallback(() => {
onContextChange?.({ onContextChange?.({
@@ -448,7 +365,6 @@ export function InputBox({
context.mode, context.mode,
selectedModel?.supports_thinking ?? false, selectedModel?.supports_thinking ?? false,
), ),
execution_profile: selectedModel?.execution_profile,
}); });
setTimeout(() => onSubmit?.(message), 0); setTimeout(() => onSubmit?.(message), 0);
return; return;
@@ -464,7 +380,6 @@ export function InputBox({
resolvedModelName, resolvedModelName,
ragModeEnabled, ragModeEnabled,
selectedModel?.supports_thinking, selectedModel?.supports_thinking,
selectedModel?.execution_profile,
status, status,
threadId, threadId,
], ],
@@ -524,7 +439,6 @@ export function InputBox({
const showFollowups = const showFollowups =
!disabled && !disabled &&
!isNewThread && !isNewThread &&
!selectedSingleRoundRag &&
!followupsHidden && !followupsHidden &&
(followupsLoading || followups.length > 0); (followupsLoading || followups.length > 0);
@@ -550,7 +464,7 @@ export function InputBox({
return; return;
} }
if (disabled || isMock || selectedSingleRoundRag) { if (disabled || isMock) {
return; return;
} }
@@ -612,7 +526,7 @@ export function InputBox({
}); });
return () => controller.abort(); return () => controller.abort();
}, [context.model_name, disabled, isMock, selectedSingleRoundRag, status, thread.messages, threadId]); }, [context.model_name, disabled, isMock, status, thread.messages, threadId]);
return ( return (
<div ref={promptRootRef} className="relative flex flex-col gap-6"> <div ref={promptRootRef} className="relative flex flex-col gap-6">
@@ -749,7 +663,6 @@ export function InputBox({
/> />
</PromptInputActionMenuContent> </PromptInputActionMenuContent>
</PromptInputActionMenu> */} </PromptInputActionMenu> */}
{!frontendRagActive && (
<AddAttachmentsButton <AddAttachmentsButton
className={cn( className={cn(
"rounded-full border-0 bg-transparent px-2.5! shadow-none text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100", "rounded-full border-0 bg-transparent px-2.5! shadow-none text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
@@ -757,12 +670,11 @@ export function InputBox({
"gap-1.5! rounded-lg px-2.5! py-1! text-[11px] font-medium", "gap-1.5! rounded-lg px-2.5! py-1! text-[11px] font-medium",
)} )}
/> />
)} <Tooltip
{!frontendRagActive && !hideContextTools && <Tooltip
content={ content={
context.writing_mode context.writing_mode
? "写作模式已开启:报告由深度研究管线按「通用分析结构」撰写,优先使用对话中已检索的资料" ? "写作模式已开启:最终输出会强制保存为 Markdown 文件"
: "开启写作模式:对话照常进行,交付时由深度研究管线撰写报告并保存为 Markdown 进入画布" : "开启写作模式:最终输出保存为 Markdown 文件并进入画布"
} }
> >
<PromptInputButton <PromptInputButton
@@ -783,37 +695,8 @@ export function InputBox({
<FileTextIcon className="size-3" /> <FileTextIcon className="size-3" />
<span className="text-xs font-normal">写作</span> <span className="text-xs font-normal">写作</span>
</PromptInputButton> </PromptInputButton>
</Tooltip>} </Tooltip>
{!frontendRagActive && <Tooltip <Tooltip
content={
artifactDirectoryModeEnabled
? "文件模式已开启:右侧会显示当前对话生成的全部文件目录"
: "开启文件模式:在右侧目录中浏览当前对话生成的全部文件"
}
>
<PromptInputButton
type="button"
aria-pressed={artifactDirectoryModeEnabled}
disabled={disabled}
className={cn(
"gap-1.5! rounded-full px-3! shadow-none",
compact && "rounded-lg px-2.5! py-1! text-[11px] font-medium",
artifactDirectoryModeEnabled
? "border border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100 dark:border-sky-600 dark:bg-sky-950/45 dark:text-sky-200"
: compact
? "border border-transparent bg-muted/40 text-muted-foreground hover:bg-muted hover:text-foreground"
: "border-0 bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
)}
onClick={handleArtifactDirectoryModeToggle}
>
{artifactDirectoryModeEnabled && (
<CheckIcon className="size-3 text-sky-700 dark:text-sky-200" />
)}
<FolderTreeIcon className="size-3" />
<span className="text-xs font-normal">文件</span>
</PromptInputButton>
</Tooltip>}
{!frontendRagActive && !hideContextTools && !hideMemoryTool && <Tooltip
content={ content={
memoryInjectionEnabled memoryInjectionEnabled
? "记忆注入已开启:对话前会注入历史记忆" ? "记忆注入已开启:对话前会注入历史记忆"
@@ -838,8 +721,8 @@ export function InputBox({
<BrainCircuitIcon className="size-3" /> <BrainCircuitIcon className="size-3" />
<span className="text-xs font-normal">记忆</span> <span className="text-xs font-normal">记忆</span>
</PromptInputButton> </PromptInputButton>
</Tooltip>} </Tooltip>
{referenceModeEntryEnabled && !frontendRagActive && !hideContextTools && <Tooltip <Tooltip
content={ content={
ragModeEnabled ragModeEnabled
? "参考文献模式已开启:检索类结果会按编号引用展示" ? "参考文献模式已开启:检索类结果会按编号引用展示"
@@ -868,8 +751,8 @@ export function InputBox({
<BookMarkedIcon className="size-3" /> <BookMarkedIcon className="size-3" />
<span className="text-xs font-normal">参考文献</span> <span className="text-xs font-normal">参考文献</span>
</PromptInputButton> </PromptInputButton>
</Tooltip>} </Tooltip>
{!frontendRagActive && <Tooltip <Tooltip
content={ content={
contextCompressionEnabled contextCompressionEnabled
? "上下文压缩已开启:超长对话会自动压缩历史以节省 token" ? "上下文压缩已开启:超长对话会自动压缩历史以节省 token"
@@ -897,7 +780,7 @@ export function InputBox({
<ShrinkIcon className="size-3" /> <ShrinkIcon className="size-3" />
<span className="text-xs font-normal">上下文压缩</span> <span className="text-xs font-normal">上下文压缩</span>
</PromptInputButton> </PromptInputButton>
</Tooltip>} </Tooltip>
<PromptInputActionMenu> <PromptInputActionMenu>
<ModeHoverGuide <ModeHoverGuide
mode={ mode={
@@ -908,22 +791,13 @@ export function InputBox({
? context.mode ? context.mode
: "flash" : "flash"
} }
tooltipContent={
singleRoundRagActive
? "单轮 RAG 问答:基于知识库检索生成答案,并展示参考资料"
: multiRoundRagActive
? "多轮 RAG 问答:多次检索并展示检索过程与参考资料"
: undefined
}
> >
<PromptInputActionMenuTrigger <PromptInputActionMenuTrigger
className={cn( className={cn(
"gap-1.5! rounded-full border-0 bg-transparent px-3! text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100", "gap-1.5! rounded-full border-0 bg-transparent px-3! text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
compact && "rounded-lg border px-2.5! py-1! text-[11px] font-medium", compact && "rounded-lg border px-2.5! py-1! text-[11px] font-medium",
compact && compact &&
(frontendRagActive (context.mode === "thinking"
? "border-emerald-200 bg-emerald-50/60 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
: context.mode === "thinking"
? "border-indigo-200 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100 dark:border-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-200" ? "border-indigo-200 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100 dark:border-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-200"
: context.mode === "pro" : context.mode === "pro"
? "border-violet-200 bg-violet-50/60 text-violet-700 hover:bg-violet-100 dark:border-violet-700 dark:bg-violet-950/40 dark:text-violet-200" ? "border-violet-200 bg-violet-50/60 text-violet-700 hover:bg-violet-100 dark:border-violet-700 dark:bg-violet-950/40 dark:text-violet-200"
@@ -933,17 +807,16 @@ export function InputBox({
)} )}
> >
<div> <div>
{frontendRagActive ? ( {context.mode === "flash" && <ZapIcon className="size-3" />}
<BookMarkedIcon className="size-3" /> {context.mode === "thinking" && (
) : context.mode === "flash" ? (
<ZapIcon className="size-3" />
) : context.mode === "thinking" ? (
<LightbulbIcon className="size-3" /> <LightbulbIcon className="size-3" />
) : context.mode === "pro" ? ( )}
{context.mode === "pro" && (
<GraduationCapIcon className="size-3" /> <GraduationCapIcon className="size-3" />
) : context.mode === "ultra" ? ( )}
{context.mode === "ultra" && (
<RocketIcon className="size-3 text-[#dabb5e]" /> <RocketIcon className="size-3 text-[#dabb5e]" />
) : null} )}
</div> </div>
<div <div
className={cn( className={cn(
@@ -951,11 +824,7 @@ export function InputBox({
context.mode === "ultra" ? "golden-text" : "", context.mode === "ultra" ? "golden-text" : "",
)} )}
> >
{frontendRagActive {(context.mode === "flash" && t.inputBox.flashMode) ||
? multiRoundRagActive
? "多轮 RAG"
: "单轮 RAG"
: (context.mode === "flash" && t.inputBox.flashMode) ||
(context.mode === "thinking" && (context.mode === "thinking" &&
t.inputBox.reasoningMode) || t.inputBox.reasoningMode) ||
(context.mode === "pro" && t.inputBox.proMode) || (context.mode === "pro" && t.inputBox.proMode) ||
@@ -971,7 +840,7 @@ export function InputBox({
<PromptInputActionMenu> <PromptInputActionMenu>
<PromptInputActionMenuItem <PromptInputActionMenuItem
className={cn( className={cn(
!frontendRagActive && context.mode === "flash" context.mode === "flash"
? "text-accent-foreground" ? "text-accent-foreground"
: "text-muted-foreground/65", : "text-muted-foreground/65",
)} )}
@@ -982,7 +851,7 @@ export function InputBox({
<ZapIcon <ZapIcon
className={cn( className={cn(
"mr-2 size-4", "mr-2 size-4",
!frontendRagActive && context.mode === "flash" && context.mode === "flash" &&
"text-accent-foreground", "text-accent-foreground",
)} )}
/> />
@@ -992,7 +861,7 @@ export function InputBox({
{t.inputBox.flashModeDescription} {t.inputBox.flashModeDescription}
</div> </div>
</div> </div>
{!frontendRagActive && context.mode === "flash" ? ( {context.mode === "flash" ? (
<CheckIcon className="ml-auto size-4" /> <CheckIcon className="ml-auto size-4" />
) : ( ) : (
<div className="ml-auto size-4" /> <div className="ml-auto size-4" />
@@ -1001,7 +870,7 @@ export function InputBox({
{supportThinking && ( {supportThinking && (
<PromptInputActionMenuItem <PromptInputActionMenuItem
className={cn( className={cn(
!frontendRagActive && context.mode === "thinking" context.mode === "thinking"
? "text-accent-foreground" ? "text-accent-foreground"
: "text-muted-foreground/65", : "text-muted-foreground/65",
)} )}
@@ -1012,7 +881,7 @@ export function InputBox({
<LightbulbIcon <LightbulbIcon
className={cn( className={cn(
"mr-2 size-4", "mr-2 size-4",
!frontendRagActive && context.mode === "thinking" && context.mode === "thinking" &&
"text-accent-foreground", "text-accent-foreground",
)} )}
/> />
@@ -1022,7 +891,7 @@ export function InputBox({
{t.inputBox.reasoningModeDescription} {t.inputBox.reasoningModeDescription}
</div> </div>
</div> </div>
{!frontendRagActive && context.mode === "thinking" ? ( {context.mode === "thinking" ? (
<CheckIcon className="ml-auto size-4" /> <CheckIcon className="ml-auto size-4" />
) : ( ) : (
<div className="ml-auto size-4" /> <div className="ml-auto size-4" />
@@ -1031,7 +900,7 @@ export function InputBox({
)} )}
<PromptInputActionMenuItem <PromptInputActionMenuItem
className={cn( className={cn(
!frontendRagActive && context.mode === "pro" context.mode === "pro"
? "text-accent-foreground" ? "text-accent-foreground"
: "text-muted-foreground/65", : "text-muted-foreground/65",
)} )}
@@ -1042,7 +911,7 @@ export function InputBox({
<GraduationCapIcon <GraduationCapIcon
className={cn( className={cn(
"mr-2 size-4", "mr-2 size-4",
!frontendRagActive && context.mode === "pro" && context.mode === "pro" &&
"text-accent-foreground", "text-accent-foreground",
)} )}
/> />
@@ -1052,7 +921,7 @@ export function InputBox({
{t.inputBox.proModeDescription} {t.inputBox.proModeDescription}
</div> </div>
</div> </div>
{!frontendRagActive && context.mode === "pro" ? ( {context.mode === "pro" ? (
<CheckIcon className="ml-auto size-4" /> <CheckIcon className="ml-auto size-4" />
) : ( ) : (
<div className="ml-auto size-4" /> <div className="ml-auto size-4" />
@@ -1060,7 +929,7 @@ export function InputBox({
</PromptInputActionMenuItem> </PromptInputActionMenuItem>
<PromptInputActionMenuItem <PromptInputActionMenuItem
className={cn( className={cn(
!frontendRagActive && context.mode === "ultra" context.mode === "ultra"
? "text-accent-foreground" ? "text-accent-foreground"
: "text-muted-foreground/65", : "text-muted-foreground/65",
)} )}
@@ -1071,16 +940,12 @@ export function InputBox({
<RocketIcon <RocketIcon
className={cn( className={cn(
"mr-2 size-4", "mr-2 size-4",
!frontendRagActive && context.mode === "ultra" && "text-[#dabb5e]",
context.mode === "ultra" &&
"text-[#dabb5e]",
)} )}
/> />
<div <div
className={cn( className={cn(
!frontendRagActive && context.mode === "ultra" && "golden-text",
context.mode === "ultra" &&
"golden-text",
)} )}
> >
{t.inputBox.ultraMode} {t.inputBox.ultraMode}
@@ -1090,68 +955,7 @@ export function InputBox({
{t.inputBox.ultraModeDescription} {t.inputBox.ultraModeDescription}
</div> </div>
</div> </div>
{!frontendRagActive && context.mode === "ultra" ? ( {context.mode === "ultra" ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
{extraModels.length > 0 && (
<>
<DropdownMenuSeparator className="my-2" />
<PromptInputActionMenuItem
className={cn(
selectedSingleRoundRag
? "bg-emerald-50 text-emerald-800 hover:bg-emerald-100 focus:bg-emerald-100 dark:bg-emerald-950/40 dark:text-emerald-200 dark:hover:bg-emerald-950/60 dark:focus:bg-emerald-950/60"
: "text-muted-foreground/65",
)}
onSelect={handleSingleRoundRagSelect}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
<BookMarkedIcon
className={cn(
"mr-2 size-4",
selectedSingleRoundRag && "text-emerald-700 dark:text-emerald-200",
)}
/>
单轮 RAG 问答
</div>
<div className="pl-7 text-xs">
基于知识库检索生成答案,并展示思考内容与参考资料
</div>
</div>
{selectedSingleRoundRag ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
</>
)}
<PromptInputActionMenuItem
className={cn(
multiRoundRagActive
? "bg-emerald-50 text-emerald-800 hover:bg-emerald-100 focus:bg-emerald-100 dark:bg-emerald-950/40 dark:text-emerald-200 dark:hover:bg-emerald-950/60 dark:focus:bg-emerald-950/60"
: "text-muted-foreground/65",
)}
onSelect={handleMultiRoundRagSelect}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
<BookMarkedIcon
className={cn(
"mr-2 size-4",
multiRoundRagActive && "text-emerald-700 dark:text-emerald-200",
)}
/>
多轮 RAG 问答
</div>
<div className="pl-7 text-xs">
多次检索、展示过程与参考资料,适合复杂问题
</div>
</div>
{multiRoundRagActive ? (
<CheckIcon className="ml-auto size-4" /> <CheckIcon className="ml-auto size-4" />
) : ( ) : (
<div className="ml-auto size-4" /> <div className="ml-auto size-4" />
@@ -1161,7 +965,7 @@ export function InputBox({
</DropdownMenuGroup> </DropdownMenuGroup>
</PromptInputActionMenuContent> </PromptInputActionMenuContent>
</PromptInputActionMenu> </PromptInputActionMenu>
{!frontendRagActive && supportReasoningEffort && context.mode !== "flash" && ( {supportReasoningEffort && context.mode !== "flash" && (
<PromptInputActionMenu> <PromptInputActionMenu>
<PromptInputActionMenuTrigger className={cn("gap-1.5! rounded-full border-0 bg-transparent px-3! text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100", compact && "rounded-lg border border-border px-2.5! py-1! text-[13px]")}> <PromptInputActionMenuTrigger className={cn("gap-1.5! rounded-full border-0 bg-transparent px-3! text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100", compact && "rounded-lg border border-border px-2.5! py-1! text-[13px]")}>
<div className="text-xs font-normal"> <div className="text-xs font-normal">
@@ -1279,7 +1083,7 @@ export function InputBox({
)} )}
</PromptInputTools> </PromptInputTools>
<PromptInputTools className={cn("gap-1.5", compact && "gap-2")}> <PromptInputTools className={cn("gap-1.5", compact && "gap-2")}>
{!frontendRagActive && agentSelector && ( {agentSelector && (
<AgentSelector <AgentSelector
selectedAgentId={agentSelector.selectedAgentId} selectedAgentId={agentSelector.selectedAgentId}
onAgentChange={agentSelector.onAgentChange} onAgentChange={agentSelector.onAgentChange}
@@ -1287,8 +1091,7 @@ export function InputBox({
compact={compact} compact={compact}
/> />
)} )}
{!frontendRagActive && knowledgeSelector} {promptPrefix && (
{!frontendRagActive && promptPrefix && (
<Tooltip <Tooltip
content={ content={
promptPrefix.on promptPrefix.on
@@ -1316,7 +1119,7 @@ export function InputBox({
</PromptInputButton> </PromptInputButton>
</Tooltip> </Tooltip>
)} )}
{!multiRoundRagActive && <ModelSelector <ModelSelector
open={modelDialogOpen} open={modelDialogOpen}
onOpenChange={setModelDialogOpen} onOpenChange={setModelDialogOpen}
> >
@@ -1343,7 +1146,7 @@ export function InputBox({
<ModelSelectorContent> <ModelSelectorContent>
<ModelSelectorInput placeholder={t.inputBox.searchModels} /> <ModelSelectorInput placeholder={t.inputBox.searchModels} />
<ModelSelectorList> <ModelSelectorList>
{modelOptions.map((m) => ( {models.map((m) => (
<ModelSelectorItem <ModelSelectorItem
key={m.name} key={m.name}
value={m.name} value={m.name}
@@ -1352,9 +1155,7 @@ export function InputBox({
<div className="flex min-w-0 flex-1 flex-col"> <div className="flex min-w-0 flex-1 flex-col">
<ModelSelectorName>{m.display_name}</ModelSelectorName> <ModelSelectorName>{m.display_name}</ModelSelectorName>
<span className="text-muted-foreground truncate text-[10px]"> <span className="text-muted-foreground truncate text-[10px]">
{selectedSingleRoundRag {m.model}
? `单轮知识库问答 · ${m.name}`
: m.model}
</span> </span>
</div> </div>
{m.name === context.model_name ? ( {m.name === context.model_name ? (
@@ -1366,7 +1167,7 @@ export function InputBox({
))} ))}
</ModelSelectorList> </ModelSelectorList>
</ModelSelectorContent> </ModelSelectorContent>
</ModelSelector>} </ModelSelector>
<PromptInputSubmit <PromptInputSubmit
className={cn( className={cn(
"rounded-full border-border bg-background shadow-sm hover:bg-muted dark:bg-blue-500 dark:border-blue-500 dark:text-white dark:hover:bg-blue-400 dark:shadow-none", "rounded-full border-border bg-background shadow-sm hover:bg-muted dark:bg-blue-500 dark:border-blue-500 dark:text-white dark:hover:bg-blue-400 dark:shadow-none",
@@ -1,79 +0,0 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { BookOpen, Database } from "lucide-react";
import { useLocation, useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { getStoredAuth } from "@/core/auth";
import { useLlmWikiRuntime } from "@/strategy-components/api/llmwiki";
import {
loadKnowledgeBaseProductVersion,
loadOrdinaryKnowledgeLanding,
saveOrdinaryKnowledgeLanding,
type OrdinaryKnowledgeLanding,
type KnowledgeBaseProductVersion,
updateKnowledgeBaseProductVersion,
} from "@/core/system-settings/api";
export const KNOWLEDGE_PRODUCT_KEY = ["system-settings", "knowledge-base-product-version"] as const;
const LANDING_KEY = ["system-settings", "ordinary-knowledge-landing"] as const;
export function useOrdinaryKnowledgeLanding() {
return useQuery({ queryKey: LANDING_KEY, queryFn: loadOrdinaryKnowledgeLanding, staleTime: 0 });
}
export const KNOWLEDGE_NORMAL_VIEW_VALUE = "normal";
export const KNOWLEDGE_NORMAL_VIEW_SEARCH = `?view=${KNOWLEDGE_NORMAL_VIEW_VALUE}`;
export function useKnowledgeBaseProductVersion() {
return useQuery({ queryKey: KNOWLEDGE_PRODUCT_KEY, queryFn: loadKnowledgeBaseProductVersion, staleTime: 60_000 });
}
export function KnowledgeProductNav() {
const location = useLocation();
const navigate = useNavigate();
const client = useQueryClient();
const version = useKnowledgeBaseProductVersion();
const landing = useOrdinaryKnowledgeLanding();
const saveLanding = useMutation({
mutationFn: saveOrdinaryKnowledgeLanding,
onSuccess: (mode) => { client.setQueryData(LANDING_KEY, mode); toast.success("普通知识库默认页面已更新"); },
onError: (error) => toast.error(error.message),
});
const runtime = useLlmWikiRuntime();
const normalAvailable = runtime.data?.provider === "weknora" && Boolean(runtime.data.api_base_url?.trim());
const isAdmin = getStoredAuth()?.system_role === "admin";
const save = useMutation({
mutationFn: updateKnowledgeBaseProductVersion,
onSuccess: (value) => {
client.setQueryData(KNOWLEDGE_PRODUCT_KEY, value);
toast.success(`默认知识库体验已切换为 ${value}`);
},
});
const assistant = location.pathname.includes("/knowledge/assistant");
return (
<div className="flex flex-wrap items-center gap-2 border-b bg-card px-6 py-2">
<Button size="sm" disabled={!normalAvailable} title={normalAvailable ? "普通知识库" : "管理员配置知识服务地址后可用"} variant={assistant ? "ghost" : "secondary"} onClick={() => navigate(`/page/workspace/knowledge${KNOWLEDGE_NORMAL_VIEW_SEARCH}`)}>
<BookOpen />普通知识库
</Button>
<Button size="sm" variant={assistant ? "secondary" : "ghost"} onClick={() => navigate("/page/workspace/knowledge/assistant")}>
<Database />助手知识库
</Button>
{isAdmin && (
<div className="ml-auto flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
普通知识库默认页面
<Select disabled={landing.isLoading || saveLanding.isPending} value={landing.data ?? "wiki"} onValueChange={(value) => saveLanding.mutate(value as OrdinaryKnowledgeLanding)}>
<SelectTrigger className="h-8 w-40" aria-label="普通知识库默认页面"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="wiki">本系统 Wiki 索引</SelectItem><SelectItem value="weknora">知识库管理页面</SelectItem></SelectContent>
</Select>
默认产品版本
<Select value={version.data ?? "v1"} onValueChange={(value) => save.mutate(value as KnowledgeBaseProductVersion)}>
<SelectTrigger className="h-8 w-40"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="v1">v1 普通知识库</SelectItem><SelectItem value="v2">v2 助手知识库</SelectItem></SelectContent>
</Select>
</div>
)}
</div>
);
}
@@ -1,536 +0,0 @@
"use client";
import {
Check,
Database,
Folder,
Globe2,
Loader2,
Search,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import {
type AssistantKnowledgeBase,
useAssistantKnowledgeBases,
} from "@/strategy-components/api/assistant-knowledge";
import {
type LlmWikiKnowledgeBase,
useAgentLlmWikiKnowledgeBases,
useLlmWikiKnowledgeBases,
useLlmWikiRuntime,
} from "@/strategy-components/api/llmwiki";
type SelectorSource = "all" | "agent";
type SelectorVariant = "popover" | "panel";
function groupRows(rows: LlmWikiKnowledgeBase[]) {
return [
{
key: "personal",
label: "我的知识空间",
rows: rows.filter((item) => item.publication_status !== "published" || item.is_owner),
},
{
key: "public",
label: "公共知识空间",
rows: rows.filter((item) => item.publication_status === "published" && !item.is_owner),
},
].filter((group) => group.rows.length > 0);
}
function SpaceIcon({ item }: { item: LlmWikiKnowledgeBase }) {
return (
<span
className={cn(
"flex size-7 shrink-0 items-center justify-center rounded-md",
item.publication_status === "published"
? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
: "bg-primary/10 text-primary",
)}
>
{item.publication_status === "published" ? (
<Globe2 className="size-3.5" />
) : (
<Folder className="size-3.5" />
)}
</span>
);
}
function AssistantSpaceIcon({ item }: { item: AssistantKnowledgeBase }) {
return (
<span
className={cn(
"flex size-7 shrink-0 items-center justify-center rounded-md",
item.is_global ? "bg-amber-500/10 text-amber-600 dark:text-amber-400" : "bg-sky-500/10 text-sky-600 dark:text-sky-400",
)}
>
<Database className="size-3.5" />
</span>
);
}
function SelectionContent({
rows,
assistantRows,
value,
assistantValue,
onChange,
onAssistantChange,
search,
onSearchChange,
loading,
error,
source,
variant,
readOnly,
}: {
rows: LlmWikiKnowledgeBase[];
assistantRows: AssistantKnowledgeBase[];
value: string[];
assistantValue: string[];
onChange: (value: string[]) => void;
onAssistantChange: (value: string[]) => void;
search: string;
onSearchChange: (value: string) => void;
loading: boolean;
error: unknown;
source: SelectorSource;
variant: SelectorVariant;
readOnly: boolean;
}) {
const selected = useMemo(() => new Set(value), [value]);
const selectedAssistant = useMemo(() => new Set(assistantValue), [assistantValue]);
const filtered = useMemo(() => {
const query = search.trim().toLocaleLowerCase();
if (!query) return rows;
return rows.filter((item) =>
`${item.name} ${item.description}`.toLocaleLowerCase().includes(query),
);
}, [rows, search]);
const filteredAssistant = useMemo(() => {
const query = search.trim().toLocaleLowerCase();
if (!query) return assistantRows;
return assistantRows.filter((item) =>
`${item.name} ${item.description ?? ""}`.toLocaleLowerCase().includes(query),
);
}, [assistantRows, search]);
const groups = useMemo(() => groupRows(filtered), [filtered]);
const toggle = (id: string) => {
if (readOnly) return;
onChange(selected.has(id) ? value.filter((item) => item !== id) : [...value, id]);
};
const toggleAssistant = (id: string) => {
if (readOnly) return;
onAssistantChange(
selectedAssistant.has(id)
? assistantValue.filter((item) => item !== id)
: [...assistantValue, id],
);
};
const selectedCount = value.length + assistantValue.length;
const hasRows = groups.length > 0 || filteredAssistant.length > 0;
return (
<>
<div className="border-b p-2.5">
<div className="relative">
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
value={search}
onChange={(event) => onSearchChange(event.target.value)}
onKeyDown={(event) => event.stopPropagation()}
placeholder="搜索知识空间"
className="h-8 bg-muted/40 pl-8 text-xs"
/>
</div>
</div>
<div className={cn("overflow-y-auto p-1.5", variant === "popover" ? "max-h-64" : "max-h-80")}>
{loading ? (
<div className="flex h-28 items-center justify-center text-xs text-muted-foreground">
<Loader2 className="mr-2 size-4 animate-spin" />正在读取知识空间
</div>
) : error ? (
<div className="m-2 rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">
{error instanceof Error ? error.message : "知识空间读取失败"}
</div>
) : !hasRows ? (
<div className="flex h-28 items-center justify-center px-4 text-center text-xs text-muted-foreground">
{search
? "没有匹配的知识空间"
: source === "agent"
? "该智能体尚未绑定可用知识空间"
: "当前账号暂无可用知识空间"}
</div>
) : (
<>
{groups.map((group, groupIndex) => (
<div key={group.key}>
{groupIndex > 0 && (
variant === "popover"
? <DropdownMenuSeparator className="my-1.5" />
: <div className="my-1.5 border-t" />
)}
{variant === "popover" ? (
<DropdownMenuLabel className="flex items-center gap-1.5 px-2 py-1 text-[11px] font-semibold text-muted-foreground">
{group.key === "personal" ? <Folder className="size-3" /> : <Globe2 className="size-3" />}{group.label}
</DropdownMenuLabel>
) : (
<div className="flex items-center gap-1.5 px-2 py-1 text-[11px] font-semibold text-muted-foreground">
{group.key === "personal" ? <Folder className="size-3" /> : <Globe2 className="size-3" />}{group.label}
</div>
)}
{group.rows.map((item) => {
const rowContent = (
<>
<SpaceIcon item={item} />
<div className="min-w-0 flex-1">
<div className="truncate text-xs font-medium">{item.name}</div>
<div className="mt-0.5 truncate text-[10px] text-muted-foreground">
{item.type === "faq" ? "FAQ" : "文档库"} · {item.knowledge_count ?? 0} 项知识
</div>
</div>
{item.publication_status === "published" && (
<Badge variant="outline" className="h-4 px-1 text-[9px]">公共</Badge>
)}
</>
);
return variant === "popover" ? (
<DropdownMenuCheckboxItem
key={item.id}
checked={selected.has(item.id)}
disabled={readOnly}
onCheckedChange={() => toggle(item.id)}
onSelect={(event) => event.preventDefault()}
className={cn(
"my-0.5 min-h-10 rounded-md py-1.5 pr-2 pl-7",
selected.has(item.id) && "bg-primary/8 focus:bg-primary/12",
)}
>
{rowContent}
</DropdownMenuCheckboxItem>
) : (
<button
key={item.id}
type="button"
role="checkbox"
aria-checked={selected.has(item.id)}
disabled={readOnly}
onClick={() => toggle(item.id)}
className={cn(
"my-0.5 flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1.5 text-left outline-none transition-colors hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-primary",
selected.has(item.id) && "bg-primary/8",
)}
>
<span className={cn(
"flex size-4 shrink-0 items-center justify-center rounded border",
selected.has(item.id) && "border-primary bg-primary text-primary-foreground",
)}>
{selected.has(item.id) && <Check className="size-3" />}
</span>
{rowContent}
</button>
);
})}
</div>
))}
{filteredAssistant.length > 0 && (
<div>
{(groups.length > 0) && (
variant === "popover"
? <DropdownMenuSeparator className="my-1.5" />
: <div className="my-1.5 border-t" />
)}
{variant === "popover" ? (
<DropdownMenuLabel className="flex items-center gap-1.5 px-2 py-1 text-[11px] font-semibold text-muted-foreground">
<Database className="size-3" />助手知识库
</DropdownMenuLabel>
) : (
<div className="flex items-center gap-1.5 px-2 py-1 text-[11px] font-semibold text-muted-foreground">
<Database className="size-3" />助手知识库
</div>
)}
{filteredAssistant.map((item) => {
const rowContent = (
<>
<AssistantSpaceIcon item={item} />
<div className="min-w-0 flex-1">
<div className="truncate text-xs font-medium">{item.name}</div>
<div className="mt-0.5 truncate text-[10px] text-muted-foreground">
Wiki · {item.page_count ?? 0} 页 · {item.entity_count ?? 0} 实体
</div>
</div>
<Badge variant="outline" className="h-4 px-1 text-[9px]">
{item.is_global ? "总库" : "助手"}
</Badge>
</>
);
return variant === "popover" ? (
<DropdownMenuCheckboxItem
key={`assistant:${item.id}`}
checked={selectedAssistant.has(item.id)}
disabled={readOnly}
onCheckedChange={() => toggleAssistant(item.id)}
onSelect={(event) => event.preventDefault()}
className={cn(
"my-0.5 min-h-10 rounded-md py-1.5 pr-2 pl-7",
selectedAssistant.has(item.id) && "bg-primary/8 focus:bg-primary/12",
)}
>
{rowContent}
</DropdownMenuCheckboxItem>
) : (
<button
key={`assistant:${item.id}`}
type="button"
role="checkbox"
aria-checked={selectedAssistant.has(item.id)}
disabled={readOnly}
onClick={() => toggleAssistant(item.id)}
className={cn(
"my-0.5 flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1.5 text-left outline-none transition-colors hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-primary",
selectedAssistant.has(item.id) && "bg-primary/8",
)}
>
<span className={cn(
"flex size-4 shrink-0 items-center justify-center rounded border",
selectedAssistant.has(item.id) && "border-primary bg-primary text-primary-foreground",
)}>
{selectedAssistant.has(item.id) && <Check className="size-3" />}
</span>
{rowContent}
</button>
);
})}
</div>
)}
</>
)}
</div>
<div className="flex items-center justify-between gap-2 border-t bg-muted/20 px-2.5 py-2">
<span className="text-[11px] text-muted-foreground">
{readOnly ? `本对话已选 ${selectedCount} 个` : `已选择 ${selectedCount} 个`}
</span>
{readOnly ? (
<span className="text-[11px] text-muted-foreground">对话开始后不可更改</span>
) : (
<div className="flex items-center gap-1">
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 px-2 text-xs"
onClick={() => {
onChange(filtered.map((item) => item.id));
onAssistantChange(filteredAssistant.map((item) => item.id));
}}
>
全选
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 px-2 text-xs"
onClick={() => {
onChange([]);
onAssistantChange([]);
}}
>
清空
</Button>
</div>
)}
</div>
</>
);
}
export function LlmWikiKnowledgeSelector({
value,
assistantValue = [],
onChange,
onAssistantChange = () => undefined,
source = "all",
agentId,
autoSelectAll = false,
disabled = false,
readOnly = false,
className,
label = "知识空间",
variant = "popover",
}: {
value: string[];
assistantValue?: string[];
onChange: (value: string[]) => void;
onAssistantChange?: (value: string[]) => void;
source?: SelectorSource;
agentId?: string | null;
autoSelectAll?: boolean;
disabled?: boolean;
/** Keep the selected knowledge spaces visible without allowing the thread scope to change. */
readOnly?: boolean;
className?: string;
label?: string;
variant?: SelectorVariant;
}) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
const runtime = useLlmWikiRuntime();
const weknoraEnabled = runtime.data?.provider === "weknora";
const all = useLlmWikiKnowledgeBases(
"all",
weknoraEnabled,
);
const agent = useAgentLlmWikiKnowledgeBases(
agentId,
weknoraEnabled && source === "agent" && !!agentId,
);
const assistantBases = useAssistantKnowledgeBases();
const rows = weknoraEnabled ? (all.data ?? []) : [];
const assistantRows = assistantBases.data ?? [];
const defaultIds = useMemo(() => {
if (source !== "agent") {
return rows.map((item) => item.id);
}
return (agent.data ?? []).map((item) => item.id);
}, [agent.data, rows, source]);
const loading = runtime.isLoading || (weknoraEnabled && all.isLoading) || assistantBases.isLoading || (source === "agent" && !!agentId && agent.isLoading);
const error = (weknoraEnabled ? all.error ?? (source === "agent" ? agent.error : null) : null) ?? assistantBases.error;
const availableIds = useMemo(() => new Set(rows.map((item) => item.id)), [rows]);
const assistantAvailableIds = useMemo(
() => new Set(assistantRows.map((item) => item.id)),
[assistantRows],
);
const initializationKey = `${source}:${agentId ?? "all"}:${defaultIds.join(",")}`;
const initialized = useRef<string | null>(null);
useEffect(() => {
if (!runtime.isLoading && !weknoraEnabled) {
if (value.length > 0) onChange([]);
return;
}
if (!all.data || (source === "agent" && agentId && !agent.data) || initialized.current === initializationKey) return;
initialized.current = initializationKey;
const valid = value.filter((id) => availableIds.has(id));
const next = autoSelectAll && valid.length === 0 && defaultIds.length > 0
? defaultIds.filter((id) => availableIds.has(id))
: valid;
if (next.length !== value.length || next.some((id, index) => id !== value[index])) {
onChange(next);
}
}, [agent.data, agentId, all.data, autoSelectAll, availableIds, defaultIds, initializationKey, onChange, runtime.isLoading, source, value, weknoraEnabled]);
useEffect(() => {
if (!assistantBases.data) return;
const valid = assistantValue.filter((id) => assistantAvailableIds.has(id));
if (valid.length !== assistantValue.length || valid.some((id, index) => id !== assistantValue[index])) {
onAssistantChange(valid);
}
}, [assistantAvailableIds, assistantBases.data, assistantValue, onAssistantChange]);
useEffect(() => {
if (!open) setSearch("");
}, [open]);
if ((runtime.isError || !weknoraEnabled) && !assistantBases.isLoading && assistantRows.length === 0) return null;
const content = (
<SelectionContent
rows={rows}
assistantRows={assistantRows}
value={value}
assistantValue={assistantValue}
onChange={onChange}
onAssistantChange={onAssistantChange}
search={search}
onSearchChange={setSearch}
loading={loading}
error={error}
source={source}
variant={variant}
readOnly={readOnly}
/>
);
if (variant === "panel") {
return (
<div className={cn("overflow-hidden rounded-xl border bg-background shadow-sm", className)}>
<div className="flex items-start justify-between gap-4 border-b px-4 py-3">
<div>
<div className="flex items-center gap-2 text-sm font-semibold">
<Database className="size-4 text-primary" />绑定知识空间
</div>
<p className="mt-1 text-xs text-muted-foreground">
新建该智能体对话时,只能从已绑定空间中选择本次检索范围。
</p>
</div>
<Badge variant="secondary" className="shrink-0">{value.length + assistantValue.length} 个</Badge>
</div>
{content}
</div>
);
}
const selectedNames = value
.map((id) => rows.find((item) => item.id === id)?.name)
.filter((name): name is string => !!name);
const selectedAssistantNames = assistantValue
.map((id) => assistantRows.find((item) => item.id === id)?.name)
.filter((name): name is string => !!name);
const allSelectedNames = [...selectedNames, ...selectedAssistantNames];
const selectedCount = value.length + assistantValue.length;
const selectedLabel = allSelectedNames.length > 0
? allSelectedNames.join("、")
: selectedCount > 0
? `已选 ${selectedCount} 个知识空间`
: label;
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
className={cn(
"h-8 max-w-52 gap-1.5 rounded-full border-0 bg-transparent px-2.5 text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground",
selectedCount > 0 && "bg-primary/8 text-primary hover:bg-primary/12 hover:text-primary",
className,
)}
disabled={disabled || loading}
title={selectedCount > 0 ? selectedLabel : undefined}
>
{loading ? <Loader2 className="size-3.5 animate-spin" /> : <Database className="size-3.5" />}
<span className="truncate text-xs font-normal">{selectedLabel}</span>
{selectedCount > 0 && (
<span className="flex size-4 items-center justify-center rounded-full bg-primary text-[9px] font-semibold text-primary-foreground">
{selectedCount}
</span>
)}
{selectedCount > 0 && selectedCount === rows.length + assistantRows.length && <Check className="size-3" />}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" sideOffset={8} className="w-80 overflow-hidden rounded-xl p-0 shadow-xl">
{content}
</DropdownMenuContent>
</DropdownMenu>
);
}
export default LlmWikiKnowledgeSelector;
@@ -7,12 +7,6 @@ import type { AgentThreadState } from "@/core/threads";
export interface ThreadContextType { export interface ThreadContextType {
thread: BaseStream<AgentThreadState>; thread: BaseStream<AgentThreadState>;
isMock?: boolean; isMock?: boolean;
/**
* True when the active conversation has selected LLMWiki knowledge bases.
* Knowledge-base Q&A should always expose its source documents, independent
* from the admin-controlled manual reference-mode button.
*/
knowledgeReferencesEnabled?: boolean;
/** /**
* When set, the conversation is rendered from a public read-only share. * When set, the conversation is rendered from a public read-only share.
* Artifact/image URLs then resolve to the unauthenticated * Artifact/image URLs then resolve to the unauthenticated
@@ -1,125 +0,0 @@
"use client";
import { useMemo } from "react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
type DiffRow = {
left: { text: string; kind: "same" | "removed" } | null;
right: { text: string; kind: "same" | "added" } | null;
};
function buildLineDiff(before: string, after: string): DiffRow[] {
const left = before.split("\n");
const right = after.split("\n");
// A large quadratic matrix would make the dialog itself a performance risk.
// Documents above this threshold still get an honest two-column comparison,
// just without expensive alignment of every unchanged line.
if (left.length * right.length > 1_000_000) {
const rows: DiffRow[] = [];
const length = Math.max(left.length, right.length);
for (let index = 0; index < length; index += 1) {
const beforeLine = left[index];
const afterLine = right[index];
const same = beforeLine === afterLine;
rows.push({
left: beforeLine === undefined ? null : { text: beforeLine, kind: same ? "same" : "removed" },
right: afterLine === undefined ? null : { text: afterLine, kind: same ? "same" : "added" },
});
}
return rows;
}
const table = Array.from({ length: left.length + 1 }, () => new Uint16Array(right.length + 1));
for (let i = left.length - 1; i >= 0; i -= 1) {
for (let j = right.length - 1; j >= 0; j -= 1) {
table[i][j] = left[i] === right[j]
? table[i + 1][j + 1] + 1
: Math.max(table[i + 1][j], table[i][j + 1]);
}
}
const rows: DiffRow[] = [];
let i = 0;
let j = 0;
while (i < left.length || j < right.length) {
if (i < left.length && j < right.length && left[i] === right[j]) {
rows.push({ left: { text: left[i], kind: "same" }, right: { text: right[j], kind: "same" } });
i += 1;
j += 1;
} else if (j < right.length && (i === left.length || table[i][j + 1] >= table[i + 1][j])) {
rows.push({ left: null, right: { text: right[j], kind: "added" } });
j += 1;
} else {
rows.push({ left: { text: left[i], kind: "removed" }, right: null });
i += 1;
}
}
return rows;
}
function DiffCell({
value,
line,
}: {
value: DiffRow["left"] | DiffRow["right"];
line: number | null;
}) {
return (
<div
className={cn(
"grid min-w-0 grid-cols-[3rem_minmax(0,1fr)] border-b font-mono text-xs leading-5",
value?.kind === "removed" && "bg-red-50 text-red-950 dark:bg-red-950/30 dark:text-red-100",
value?.kind === "added" && "bg-emerald-50 text-emerald-950 dark:bg-emerald-950/30 dark:text-emerald-100",
!value && "bg-muted/30",
)}
>
<span className="select-none border-r px-2 text-right text-muted-foreground">{line ?? ""}</span>
<pre className="min-w-0 whitespace-pre-wrap break-words px-3">{value?.text ?? ""}</pre>
</div>
);
}
export function DocumentRewriteDiffDialog({
open,
onOpenChange,
fileName,
original,
rewritten,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
fileName: string;
original: string;
rewritten: string;
}) {
const rows = useMemo(() => buildLineDiff(original, rewritten), [original, rewritten]);
let leftLine = 0;
let rightLine = 0;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[85vh] max-w-[calc(100vw-2rem)] flex-col p-0 sm:max-w-[min(94vw,1440px)]">
<DialogHeader className="border-b px-6 py-4">
<DialogTitle>改写前后对比 · {fileName}</DialogTitle>
<DialogDescription>红色为删除或调整前内容,绿色为新增或改写后内容。</DialogDescription>
</DialogHeader>
<div className="grid min-h-0 flex-1 grid-cols-2 divide-x overflow-auto" role="region" aria-label="Markdown 改写前后对比">
<section aria-label="改写前原文">
<div className="sticky top-0 z-10 border-b bg-background px-4 py-2 text-sm font-medium">改写前</div>
{rows.map((row, index) => {
const line = row.left ? ++leftLine : null;
return <DiffCell key={`left-${index}`} value={row.left} line={line} />;
})}
</section>
<section aria-label="改写后内容">
<div className="sticky top-0 z-10 border-b bg-background px-4 py-2 text-sm font-medium">改写后</div>
{rows.map((row, index) => {
const line = row.right ? ++rightLine : null;
return <DiffCell key={`right-${index}`} value={row.right} line={line} />;
})}
</section>
</div>
</DialogContent>
</Dialog>
);
}
@@ -1,600 +0,0 @@
"use client";
import {
CheckCircle2Icon,
ChevronDownIcon,
ChevronsDownIcon,
FilePenLineIcon,
LightbulbIcon,
Loader2Icon,
Undo2Icon,
XCircleIcon,
} from "lucide-react";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { apiFetch } from "@/core/api/fetch-client";
import { updateArtifactContent } from "@/core/artifacts/api";
import { urlOfArtifact } from "@/core/artifacts/utils";
import {
DEEP_RESEARCH_REPORT_REWRITE_REQUESTED_EVENT,
DOCUMENT_REWRITE_LOCAL_UNDO_GUARD_EVENT,
DOCUMENT_REWRITE_UNDONE_EVENT,
type DocumentRewritePresentation,
useDocumentRewritePresentation,
} from "@/core/document-rewrite/context";
import {
clearArtifactRewriteFallback,
loadArtifactRewriteFallback,
sha256DocumentContent,
} from "@/core/document-rewrite/local-fallback";
import { getBackendBaseURL } from "@/core/config";
import { cn } from "@/lib/utils";
import { DocumentRewriteDiffDialog } from "./document-rewrite-diff-dialog";
const REWRITE_STEPS = [
{ key: "snapshot", label: "固定原文版本" },
{ key: "requirements", label: "理解改写要求" },
{ key: "writing", label: "流式重写 Markdown" },
{ key: "illustrations", label: "生成文档配图" },
{ key: "validation", label: "校验文档" },
{ key: "comparison", label: "对比原文并生成说明" },
] as const;
const GENERATE_STEPS = [
{ key: "snapshot", label: "固定来源报告快照" },
{ key: "requirements", label: "确认用户生成需求" },
{ key: "writing", label: "流式生成 Markdown" },
{ key: "illustrations", label: "生成文档配图" },
{ key: "validation", label: "校验新报告" },
{ key: "comparison", label: "生成报告说明" },
] as const;
function stepPosition(stage: DocumentRewritePresentation["stage"]): number {
switch (stage) {
case "snapshot":
return 0;
case "requirements":
return 1;
case "writing":
return 2;
case "illustrating":
return 3;
case "validation":
return 4;
case "committing":
case "completed":
return 6;
case "conflict":
case "error":
case "cancelled":
return 5;
default:
return -1;
}
}
function isTerminal(stage: DocumentRewritePresentation["stage"]) {
return ["completed", "conflict", "error", "cancelled"].includes(stage);
}
function RewriteThinkingTrace({ text, active }: { text: string; active: boolean }) {
const [open, setOpen] = useState(active);
const [autoScrollPaused, setAutoScrollPaused] = useState(false);
const contentRef = useRef<HTMLPreElement>(null);
const autoScrollEnabledRef = useRef(true);
const previousActiveRef = useRef(active);
const lastAutoScrollTopRef = useRef<number | null>(null);
useEffect(() => {
if (active && text) setOpen(true);
}, [active, text]);
useEffect(() => {
if (active && !previousActiveRef.current) {
autoScrollEnabledRef.current = true;
lastAutoScrollTopRef.current = null;
setAutoScrollPaused(false);
}
previousActiveRef.current = active;
}, [active]);
const scrollToLatestThinking = useCallback(() => {
if (!autoScrollEnabledRef.current) return;
const content = contentRef.current;
if (!content) return;
content.scrollTop = content.scrollHeight;
lastAutoScrollTopRef.current = content.scrollTop;
}, []);
useLayoutEffect(() => {
if (!active || !open || !text) return;
scrollToLatestThinking();
}, [active, open, scrollToLatestThinking, text]);
useEffect(() => {
if (!active || !open || !text) return;
const content = contentRef.current;
if (!content) return;
let frame: number | null = null;
const observer = new MutationObserver(() => {
if (frame !== null) cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
frame = null;
scrollToLatestThinking();
});
});
observer.observe(content, { childList: true, characterData: true, subtree: true });
return () => {
observer.disconnect();
if (frame !== null) cancelAnimationFrame(frame);
};
}, [active, open, scrollToLatestThinking, text]);
const pauseAutoScrollOnManualScroll = (event: React.UIEvent<HTMLPreElement>) => {
if (!active || !autoScrollEnabledRef.current) return;
const lastAutoScrollTop = lastAutoScrollTopRef.current;
if (
lastAutoScrollTop === null ||
Math.abs(event.currentTarget.scrollTop - lastAutoScrollTop) > 1
) {
autoScrollEnabledRef.current = false;
setAutoScrollPaused(true);
}
};
const resumeAutoScroll = () => {
autoScrollEnabledRef.current = true;
setAutoScrollPaused(false);
requestAnimationFrame(scrollToLatestThinking);
};
if (!text.trim()) return null;
return (
<Collapsible className="mt-2 max-w-3xl" onOpenChange={setOpen} open={open}>
<CollapsibleTrigger asChild>
<Button
aria-label={open ? "收起模型思考" : "展开模型思考"}
className="h-7 gap-1.5 px-2 text-xs"
size="sm"
type="button"
variant="ghost"
>
<LightbulbIcon className="size-3.5 text-amber-600 dark:text-amber-300" />
<span>模型思考</span>
<span className="text-muted-foreground">{active ? "思考中" : "已完成"}</span>
<ChevronDownIcon className={cn("size-3.5 transition-transform", open && "rotate-180")} />
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<p aria-live={active ? "polite" : undefined} className="sr-only" role={active ? "status" : undefined}>
{active ? "模型思考内容正在更新" : "模型思考内容已完成"}
</p>
<div className="relative mt-1">
<pre
className="bg-muted/45 text-muted-foreground max-h-56 overflow-auto rounded-lg border px-3 py-2 text-xs leading-5 whitespace-pre-wrap break-words"
onScroll={pauseAutoScrollOnManualScroll}
ref={contentRef}
>
{text}
</pre>
{active && autoScrollPaused && (
<Button
aria-label="恢复思考内容自动下滑"
className="absolute top-1/2 left-1/2 h-9 -translate-x-1/2 -translate-y-1/2 gap-1.5 bg-background/95 px-3 text-xs shadow-md backdrop-blur-sm hover:bg-background"
onClick={resumeAutoScroll}
size="sm"
title="恢复自动下滑"
type="button"
variant="outline"
>
<ChevronsDownIcon className="size-3.5" />
自动下滑
</Button>
)}
</div>
</CollapsibleContent>
</Collapsible>
);
}
export function DocumentRewriteTimeline({
item,
}: {
item: DocumentRewritePresentation;
}) {
const isNewReportGeneration = item.operation === "generate";
const steps = isNewReportGeneration ? GENERATE_STEPS : REWRITE_STEPS;
const current = stepPosition(item.stage);
const failed = ["conflict", "error", "cancelled"].includes(item.stage);
const completed = item.stage === "completed";
const thinkingStep = ["snapshot", "requirements"].includes(item.stage)
? "requirements"
: "writing";
const presentation = useDocumentRewritePresentation();
const [undoing, setUndoing] = useState(false);
const [diffOpen, setDiffOpen] = useState(false);
const reapplying = Boolean(item.revertedAt);
const activeVersionId = reapplying ? item.redoVersionId : item.versionId;
const canUseLocalFallback =
!reapplying &&
!activeVersionId &&
item.source.kind === "artifact" &&
typeof item.source.path === "string" &&
item.localFallbackAvailable &&
typeof item.committedHash === "string";
const handleUndo = async () => {
if ((!activeVersionId && !canUseLocalFallback) || undoing) return;
if (canUseLocalFallback && item.source.kind === "artifact" && item.source.path && item.committedHash) {
setUndoing(true);
try {
const fallback = loadArtifactRewriteFallback({
threadId: item.source.id,
path: item.source.path,
committedHash: item.committedHash,
});
if (!fallback) {
console.error("本地 AI 全文改写撤销备份不可用,未修改当前文件。");
return;
}
const currentResponse = await apiFetch(
urlOfArtifact({ filepath: item.source.path, threadId: item.source.id }),
);
if (!currentResponse.ok) {
throw new Error(`读取当前文件失败(${currentResponse.status})。`);
}
const currentHash = await sha256DocumentContent(await currentResponse.text());
if (!currentHash || currentHash !== fallback.committedHash) {
console.error("当前文件已在改写后发生变化,已跳过本地 AI 全文改写撤销。");
return;
}
const guard = new CustomEvent<{
source: DocumentRewritePresentation["source"];
rewrittenContent: string | null;
unchanged: boolean;
}>(DOCUMENT_REWRITE_LOCAL_UNDO_GUARD_EVENT, {
detail: {
source: item.source,
rewrittenContent: item.rewrittenContent,
unchanged: false,
},
});
window.dispatchEvent(guard);
if (!guard.detail.unchanged) {
console.error("沙箱中存在改写后的未保存编辑,已跳过本地 AI 全文改写撤销。");
return;
}
await updateArtifactContent({
filepath: item.source.path,
threadId: item.source.id,
content: fallback.originalContent,
});
clearArtifactRewriteFallback(item.source.id, item.source.path);
presentation?.update(item.id, {
localFallbackAvailable: false,
revertedAt: new Date().toISOString(),
});
window.dispatchEvent(
new CustomEvent(DOCUMENT_REWRITE_UNDONE_EVENT, {
detail: { source: item.source, content: fallback.originalContent },
}),
);
} catch (error) {
console.error("本地 AI 全文改写撤销失败:", error);
} finally {
setUndoing(false);
}
return;
}
if (!activeVersionId) return;
const baseUrl = getBackendBaseURL();
const endpoint =
item.source.kind === "artifact"
? `${baseUrl}/api/writing/document-rewrite/versions/${encodeURIComponent(activeVersionId)}/undo`
: `${baseUrl}/api/deep-research/sessions/${encodeURIComponent(item.source.id)}/document-rewrite/versions/${encodeURIComponent(activeVersionId)}/undo`;
const payload =
item.source.kind === "artifact"
? { threadId: item.source.id, path: item.source.path }
: undefined;
setUndoing(true);
try {
const response = await apiFetch(endpoint, {
method: "POST",
headers: payload ? { "Content-Type": "application/json" } : undefined,
body: payload ? JSON.stringify(payload) : undefined,
});
const result = (await response.json().catch(() => ({}))) as Record<string, unknown>;
if (!response.ok) {
throw new Error(
typeof result.detail === "string" ? result.detail : "撤销改写失败,请稍后重试。",
);
}
const content = typeof result.content === "string" ? result.content : "";
const nextInverseVersionId =
typeof result.redoVersionId === "string" ? result.redoVersionId : null;
presentation?.update(
item.id,
reapplying
? { versionId: nextInverseVersionId, redoVersionId: null, revertedAt: null }
: { redoVersionId: nextInverseVersionId, revertedAt: new Date().toISOString() },
);
window.dispatchEvent(
new CustomEvent(DOCUMENT_REWRITE_UNDONE_EVENT, {
detail: { source: item.source, content },
}),
);
toast.success(
isNewReportGeneration
? reapplying
? "已重新应用本次生成的新报告版本。"
: "已恢复本次生成前的新报告快照。"
: reapplying
? "已重新应用本次 AI 全文改写版本。"
: "已恢复到本次 AI 全文改写前的版本。",
);
} catch (error) {
toast.error(error instanceof Error ? error.message : "撤销改写失败,请稍后重试。");
} finally {
setUndoing(false);
}
};
return (
<article className="w-full rounded-2xl border bg-card shadow-sm">
<header className="flex items-start gap-3 border-b px-5 py-4">
<div className="bg-primary/10 text-primary flex size-8 shrink-0 items-center justify-center rounded-full">
<FilePenLineIcon className="size-4" />
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<h3 className="font-semibold">
{isNewReportGeneration ? "生成新报告" : "AI 全文改写"} · {item.fileName}
</h3>
<span
className={cn(
"rounded-full px-2 py-0.5 text-xs",
completed
? "bg-emerald-50 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-300"
: failed
? "bg-destructive/10 text-destructive"
: "bg-primary/10 text-primary",
)}
>
{completed ? "已完成" : failed ? (isNewReportGeneration ? "未生成新报告" : "未覆盖原文件") : "进行中"}
</span>
</div>
<p className="text-muted-foreground mt-1 text-sm">
{item.instruction}
</p>
</div>
</header>
<div className="space-y-3 px-5 py-4">
{steps.map((step, index) => {
const active = !isTerminal(item.stage) && index === current;
const illustrationSkipped = step.key === "illustrations" && !item.generateImages;
const illustrationFailed =
step.key === "illustrations" &&
item.generateImages &&
completed &&
item.generatedImageCount === 0;
const done = !illustrationSkipped && !illustrationFailed && (completed || index < current);
return (
<div className="flex items-start gap-3" key={step.key}>
<div
className={cn(
"mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-full border",
done
? "border-emerald-200 bg-emerald-50 text-emerald-600 dark:border-emerald-400/30 dark:bg-emerald-400/10"
: active
? "border-primary/30 bg-primary/10 text-primary"
: "border-border text-muted-foreground",
)}
>
{done ? (
<CheckCircle2Icon className="size-4" />
) : active ? (
<Loader2Icon className="size-4 animate-spin" />
) : (
<span className="text-xs">{index + 1}</span>
)}
</div>
<div className="min-w-0 pt-0.5">
<div className="text-sm font-medium">{step.label}</div>
{step.key === "snapshot" && item.originalCharCount > 0 && (
<p className="text-muted-foreground mt-0.5 text-xs">
已冻结 {item.originalCharCount.toLocaleString()} 字{isNewReportGeneration ? "来源报告" : "原文"}快照。
</p>
)}
{step.key === "requirements" && (
item.requirementsPlan ? (
<div
aria-live={active ? "polite" : undefined}
className="bg-muted/45 text-muted-foreground mt-2 max-w-3xl rounded-lg border px-3 py-2 text-xs leading-5 whitespace-pre-wrap"
role={active ? "status" : undefined}
>
{item.requirementsPlan}
</div>
) : active ? (
<p className="text-muted-foreground mt-0.5 text-xs">
{isNewReportGeneration
? "正在确认新报告的结构、资料范围与生成要求…"
: "正在识别改写目标、保留约束与执行方式…"}
</p>
) : (
<p className="text-muted-foreground mt-0.5 text-xs">
{isNewReportGeneration ? "已根据所选结构确定生成计划。" : "已根据改写要求确定执行计划。"}
</p>
)
)}
{step.key === "writing" && (
item.writtenCharCount > 0 ? (
<p className="text-muted-foreground mt-0.5 text-xs">
正在写入右侧沙箱,已{isNewReportGeneration ? "生成" : "改写"} {item.writtenCharCount.toLocaleString()} 字。
</p>
) : active ? (
<p aria-live="polite" className="text-muted-foreground mt-0.5 text-xs" role="status">
{isNewReportGeneration
? "正在等待模型开始输出;右侧将在首个字符到达后显示新报告。"
: "正在等待模型开始输出;右侧将在首个字符到达后显示草稿。"}
</p>
) : null
)}
{step.key === "illustrations" && (
illustrationSkipped ? (
<p className="text-muted-foreground mt-0.5 text-xs">
本次未启用配图,保留原文已有图片与链接。
</p>
) : active ? (
<p aria-live="polite" className="text-muted-foreground mt-0.5 text-xs" role="status">
{item.illustrationTarget
? `正在为「${item.illustrationTarget}」生成配图,已完成 ${item.generatedImageCount}/${item.maxGeneratedImages} 张。`
: `正在准备 ${item.maxGeneratedImages} 张文档配图…`}
</p>
) : item.generatedImageCount > 0 ? (
<p className="text-muted-foreground mt-0.5 text-xs">
已生成并保存 {item.generatedImageCount} 张本地配图。
</p>
) : (
<p className="text-muted-foreground mt-0.5 text-xs">
未成功生成配图,文字改写结果仍已保留。
</p>
)
)}
{step.key === thinkingStep && (
<RewriteThinkingTrace active={active} text={item.thinkingText} />
)}
{step.key === "validation" && item.warnings.length > 0 && (
<p className="mt-0.5 text-xs text-amber-700 dark:text-amber-300">
{item.warnings.join(";")}
</p>
)}
</div>
</div>
);
})}
</div>
{item.summary && (
<div className="border-t px-5 py-4 text-sm leading-6">
<div className="mb-2 font-semibold">{isNewReportGeneration ? "生成说明" : "改写说明"}</div>
<p>
{isNewReportGeneration ? "来源报告" : "原文"} {item.summary.originalCharCount.toLocaleString()} 字,
{isNewReportGeneration ? "新报告" : "改写后"}{" "}
{item.summary.rewrittenCharCount.toLocaleString()} 字;调整了约{" "}
{item.summary.changedBlockCount} 个内容块。
</p>
<p className="text-muted-foreground">
标题数量 {item.summary.headingCountBefore} → {item.summary.headingCountAfter},
使用模型:{item.summary.modelName}。
</p>
{item.summary.requestedOptimizations?.length ? (
<p className="text-muted-foreground">
本次优化:{item.summary.requestedOptimizations.join("、")}。
</p>
) : null}
{item.summary.requestedImageCount ? (
<p className="text-muted-foreground">
文档配图:请求 {item.summary.requestedImageCount} 张,已保存 {item.summary.generatedImageCount ?? 0} 张本地图片。
</p>
) : null}
{item.summary.headingChanges && (
item.summary.headingChanges.reordered ||
item.summary.headingChanges.added.length > 0 ||
item.summary.headingChanges.removed.length > 0 ||
item.summary.headingChanges.levelWarnings.length > 0
) && (
<p className="text-muted-foreground">
{item.summary.headingChanges.reordered ? "已调整章节顺序;" : ""}
{item.summary.headingChanges.added.length
? `新增标题:${item.summary.headingChanges.added.join("、")};`
: ""}
{item.summary.headingChanges.removed.length
? `移除标题:${item.summary.headingChanges.removed.join("、")};`
: ""}
{item.summary.headingChanges.levelWarnings.join(";")}
</p>
)}
{item.originalContent && item.rewrittenContent && (
<Button
className="mt-3 mr-2"
onClick={() => setDiffOpen(true)}
size="sm"
type="button"
variant="outline"
>
查看前后对比
</Button>
)}
{isNewReportGeneration && completed && item.source.kind === "deep_research_report" && (
<Button
className="mt-3 mr-2"
onClick={() => {
window.dispatchEvent(
new CustomEvent(DEEP_RESEARCH_REPORT_REWRITE_REQUESTED_EVENT, {
detail: { sessionId: item.source.id },
}),
);
}}
size="sm"
type="button"
variant="outline"
>
<FilePenLineIcon className="mr-1.5 size-3.5" />
改写新报告
</Button>
)}
{completed && (activeVersionId || canUseLocalFallback) && (
<Button
className="mt-3"
disabled={undoing}
onClick={() => void handleUndo()}
size="sm"
type="button"
variant="outline"
>
{undoing ? <Loader2Icon className="mr-1.5 size-3.5 animate-spin" /> : <Undo2Icon className="mr-1.5 size-3.5" />}
{isNewReportGeneration
? reapplying
? "重新应用本次生成"
: "撤销本次生成"
: reapplying
? "重新应用此次改写"
: "撤销此次改写"}
</Button>
)}
{item.revertedAt && (
<p className="mt-2 text-xs text-emerald-700 dark:text-emerald-300">
已恢复为{isNewReportGeneration ? "生成前" : "改写前"}版本。
{item.redoVersionId ? `可重新应用本次${isNewReportGeneration ? "生成" : "改写"}。` : ""}
</p>
)}
</div>
)}
{item.error && (
<div className="flex items-center gap-2 border-t px-5 py-3 text-sm text-destructive">
<XCircleIcon className="size-4 shrink-0" />
{item.error}
</div>
)}
<DocumentRewriteDiffDialog
fileName={item.fileName}
onOpenChange={setDiffOpen}
open={diffOpen}
original={item.originalContent}
rewritten={item.rewrittenContent ?? ""}
/>
</article>
);
}
@@ -1,14 +1,8 @@
import { FileText, Loader2, MessagesSquare } from "lucide-react"; import { FileText, Loader2 } from "lucide-react";
import { useState, type ComponentProps } from "react"; import { useState, type ComponentProps } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx"; import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx";
import { Tooltip } from "../tooltip"; import { Tooltip } from "../tooltip";
@@ -17,95 +11,44 @@ export function DownloadWordButton({
markdown, markdown,
fileName, fileName,
title, title,
questionMarkdown,
...props ...props
}: ComponentProps<typeof Button> & { }: ComponentProps<typeof Button> & {
markdown: string; markdown: string;
fileName?: string; fileName?: string;
title?: string; title?: string;
/** When present, the button offers both answer-only and current Q&A export. */
questionMarkdown?: string;
}) { }) {
const [busyScope, setBusyScope] = useState<"answer" | "qa" | null>(null); const [busy, setBusy] = useState(false);
const handleDownload = async (scope: "answer" | "qa" = "answer") => { const handleDownload = async () => {
const source = markdown?.trim(); const source = markdown?.trim();
if (!source) { if (!source) {
toast.error("无可下载的 Markdown 内容"); toast.error("无可下载的 Markdown 内容");
return; return;
} }
const question = questionMarkdown?.trim(); setBusy(true);
setBusyScope(scope);
try { try {
if (scope === "qa" && question) { await downloadMarkdownAsDocx(source, fileName || "message", title);
const qaMarkdown = `## 问题\n\n${question}\n\n## 回答\n\n${source}`;
await downloadMarkdownAsDocx(
qaMarkdown,
`${fileName || "message"}-问答`,
"问答记录",
);
} else {
await downloadMarkdownAsDocx(
source,
fileName || "message",
title || (question ? "问答回答" : undefined),
);
}
toast.success("Word 文件已生成"); toast.success("Word 文件已生成");
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : "生成 Word 失败"); toast.error(error instanceof Error ? error.message : "生成 Word 失败");
} finally { } finally {
setBusyScope(null); setBusy(false);
} }
}; };
return (
const busy = busyScope !== null; <Tooltip content="下载为 Word">
const icon = busy ? ( <Button
size="icon-sm"
type="button"
variant="ghost"
disabled={busy}
onClick={handleDownload}
{...props}
>
{busy ? (
<Loader2 size={12} className="animate-spin" /> <Loader2 size={12} className="animate-spin" />
) : ( ) : (
<FileText size={12} /> <FileText size={12} />
); )}
if (questionMarkdown?.trim()) {
return (
<DropdownMenu>
<Tooltip content="下载为 Word">
<DropdownMenuTrigger asChild>
<Button
size="icon-sm"
type="button"
variant="ghost"
disabled={busy}
{...props}
>
{icon}
</Button>
</DropdownMenuTrigger>
</Tooltip>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => void handleDownload("answer")}>
<FileText className="text-muted-foreground" />
仅下载当前回答
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => void handleDownload("qa")}>
<MessagesSquare className="text-muted-foreground" />
下载当前问题和回答
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
return (
<Tooltip content="下载为 Word">
<Button
size="icon-sm"
type="button"
variant="ghost"
disabled={busy}
onClick={() => void handleDownload("answer")}
{...props}
>
{icon}
</Button> </Button>
</Tooltip> </Tooltip>
); );
@@ -1,18 +1,13 @@
"use client"; "use client";
import { useMemo, useRef } from "react"; import { useMemo } from "react";
import type { import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } from "react";
AnchorHTMLAttributes,
HTMLAttributes,
MouseEvent as ReactMouseEvent,
ReactNode,
} from "react";
import { import {
MessageResponse, MessageResponse,
type MessageResponseProps, type MessageResponseProps,
} from "@/components/ai-elements/message"; } from "@/components/ai-elements/message";
import { streamdownPlugins, useStreamdownMermaidPngDownload } from "@/core/streamdown"; import { streamdownPlugins } from "@/core/streamdown";
import { import {
createMarkdownAnchorResolver, createMarkdownAnchorResolver,
isInPageAnchor, isInPageAnchor,
@@ -39,12 +34,6 @@ export type MarkdownContentProps = {
className?: string; className?: string;
remarkPlugins?: MessageResponseProps["remarkPlugins"]; remarkPlugins?: MessageResponseProps["remarkPlugins"];
components?: MessageResponseProps["components"]; components?: MessageResponseProps["components"];
linkClassName?: (href: string, label: string) => string | undefined;
onLinkClick?: (
event: ReactMouseEvent<HTMLAnchorElement>,
href: string,
label: string,
) => void;
}; };
/** Renders markdown content. */ /** Renders markdown content. */
@@ -54,12 +43,8 @@ export function MarkdownContent({
className, className,
remarkPlugins = streamdownPlugins.remarkPlugins, remarkPlugins = streamdownPlugins.remarkPlugins,
components: componentsFromProps, components: componentsFromProps,
linkClassName,
onLinkClick,
}: MarkdownContentProps) { }: MarkdownContentProps) {
const rootRef = useRef<HTMLDivElement>(null);
const anchorResolver = useMemo(() => createMarkdownAnchorResolver(content), [content]); const anchorResolver = useMemo(() => createMarkdownAnchorResolver(content), [content]);
useStreamdownMermaidPngDownload(rootRef);
const components = useMemo(() => { const components = useMemo(() => {
const heading = (level: 1 | 2 | 3 | 4 | 5 | 6) => { const heading = (level: 1 | 2 | 3 | 4 | 5 | 6) => {
const Tag = `h${level}` as const; const Tag = `h${level}` as const;
@@ -108,7 +93,6 @@ export function MarkdownContent({
); );
} }
const finalHref = resolvedHref ?? props.href; const finalHref = resolvedHref ?? props.href;
const label = extractTextFromChildren(props.children);
return ( return (
<a <a
{...rest} {...rest}
@@ -116,7 +100,6 @@ export function MarkdownContent({
className={cn( className={cn(
"text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors", "text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors",
className, className,
linkClassName?.(finalHref || "", label),
)} )}
target={target ?? (external ? "_blank" : undefined)} target={target ?? (external ? "_blank" : undefined)}
rel={rel ?? (external ? "noopener noreferrer" : undefined)} rel={rel ?? (external ? "noopener noreferrer" : undefined)}
@@ -127,7 +110,6 @@ export function MarkdownContent({
event.preventDefault(); event.preventDefault();
scrollToInPageAnchor(event.currentTarget, finalHref); scrollToInPageAnchor(event.currentTarget, finalHref);
} }
onLinkClick?.(event, finalHref || "", label);
rest.onClick?.(event); rest.onClick?.(event);
}} }}
/> />
@@ -135,17 +117,16 @@ export function MarkdownContent({
}, },
...componentsFromProps, ...componentsFromProps,
}; };
}, [anchorResolver, componentsFromProps, linkClassName, onLinkClick]); }, [anchorResolver, componentsFromProps]);
if (!content) return null; if (!content) return null;
return ( return (
<div ref={rootRef} data-markdown-anchor-root className="contents"> <div data-markdown-anchor-root className="contents">
<MessageResponse <MessageResponse
className={className} className={className}
remarkPlugins={remarkPlugins} remarkPlugins={remarkPlugins}
rehypePlugins={rehypePlugins} rehypePlugins={rehypePlugins}
mermaidConfig={streamdownPlugins.mermaidConfig}
components={components} components={components}
> >
{content} {content}
@@ -1,22 +1,19 @@
import type { Message } from "@langchain/langgraph-sdk"; import type { Message } from "@langchain/langgraph-sdk";
import { import {
BookOpenTextIcon, BookOpenTextIcon,
CheckCircle2Icon,
ChevronDownIcon, ChevronDownIcon,
ChevronsDownIcon,
ChevronUp, ChevronUp,
FolderOpenIcon, FolderOpenIcon,
GlobeIcon, GlobeIcon,
LightbulbIcon, LightbulbIcon,
ListTodoIcon, ListTodoIcon,
Loader2Icon,
MessageCircleQuestionMarkIcon, MessageCircleQuestionMarkIcon,
NotebookPenIcon, NotebookPenIcon,
SearchIcon, SearchIcon,
SquareTerminalIcon, SquareTerminalIcon,
WrenchIcon, WrenchIcon,
} from "lucide-react"; } from "lucide-react";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type AnchorHTMLAttributes } from "react"; import { useMemo, useState } from "react";
import { import {
ChainOfThought, ChainOfThought,
@@ -39,14 +36,6 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import {
buildWriteFileVirtualUrl,
hasCompleteArtifactExtension,
isAutoPreviewableArtifactPath,
languageOfStreamingArtifact,
normalizeStreamingArtifactPath,
provisionalWriteFilePath,
} from "@/core/artifacts/streaming-write-preview";
import { useI18n } from "@/core/i18n/hooks"; import { useI18n } from "@/core/i18n/hooks";
import { import {
normalizeSearchResults, normalizeSearchResults,
@@ -61,7 +50,6 @@ import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { useLocalSettings } from "@/core/settings"; import { useLocalSettings } from "@/core/settings";
import { useSkills } from "@/core/skills/hooks"; import { useSkills } from "@/core/skills/hooks";
import { import {
applyInlineCitations,
buildSkillDisplayMap, buildSkillDisplayMap,
findDisplayConfigForTool, findDisplayConfigForTool,
isDisplaySamplePayload, isDisplaySamplePayload,
@@ -70,32 +58,25 @@ import {
type RuntimeDisplaySource, type RuntimeDisplaySource,
} from "@/core/skill-display/runtime"; } from "@/core/skill-display/runtime";
import { normalizeDisplaySources } from "@/core/skill-display/display-adapter"; import { normalizeDisplaySources } from "@/core/skill-display/display-adapter";
import { isInterceptedWritingReportWrite } from "@/core/threads/writing-mode";
import { extractTitleFromMarkdown } from "@/core/utils/markdown"; import { extractTitleFromMarkdown } from "@/core/utils/markdown";
import { env } from "@/env"; import { env } from "@/env";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useArtifactsOptional } from "../artifacts"; import { useArtifactsOptional } from "../artifacts";
import { CitationLink } from "../citations/citation-link";
import { FlipDisplay } from "../flip-display"; import { FlipDisplay } from "../flip-display";
import { Tooltip } from "../tooltip"; import { Tooltip } from "../tooltip";
import { SourceCard } from "../skill-display-sources"; import { SourceCard } from "../skill-display-sources";
import { MarkdownContent } from "./markdown-content"; import { MarkdownContent } from "./markdown-content";
import { SingleRoundRagCitationDialog } from "./message-list-item";
export function MessageGroup({ export function MessageGroup({
className, className,
messages, messages,
isLoading = false, isLoading = false,
displaySources = [],
ragModeEnabled = false,
}: { }: {
className?: string; className?: string;
messages: Message[]; messages: Message[];
isLoading?: boolean; isLoading?: boolean;
displaySources?: RuntimeDisplaySource[];
ragModeEnabled?: boolean;
}) { }) {
const { t } = useI18n(); const { t } = useI18n();
const [showAbove, setShowAbove] = useState( const [showAbove, setShowAbove] = useState(
@@ -104,18 +85,12 @@ export function MessageGroup({
const [showLastThinking, setShowLastThinking] = useState( const [showLastThinking, setShowLastThinking] = useState(
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true", env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true",
); );
const steps = useMemo(() => convertToSteps(messages), [messages]);
const [settings] = useLocalSettings(); const [settings] = useLocalSettings();
// 写作模式的「拦截 outputs/*.md 手写」只在写作模式生效;普通模式的
// write_file / read_file 步骤条必须照旧显示。
const writingModeEnabled = !!settings.context.writing_mode;
const steps = useMemo(
() => convertToSteps(messages, writingModeEnabled),
[messages, writingModeEnabled],
);
const { skills } = useSkills(); const { skills } = useSkills();
const skillDisplayMap = useMemo( const skillDisplayMap = useMemo(
() => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()), () => (settings.display.ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
[ragModeEnabled, skills], [settings.display.ragModeEnabled, skills],
); );
const lastToolCallStep = useMemo(() => { const lastToolCallStep = useMemo(() => {
const filteredSteps = steps.filter((step) => step.type === "toolCall"); const filteredSteps = steps.filter((step) => step.type === "toolCall");
@@ -138,27 +113,9 @@ export function MessageGroup({
} }
}, [lastToolCallStep, steps]); }, [lastToolCallStep, steps]);
const rehypePlugins = useRehypeSplitWordsIntoSpans(isLoading); const rehypePlugins = useRehypeSplitWordsIntoSpans(isLoading);
const [selectedCitation, setSelectedCitation] =
useState<RuntimeDisplaySource | null>(null);
const handleCitationClick = useCallback(
(referenceId: string) => {
const referenceIndex = Number(referenceId);
if (!Number.isInteger(referenceIndex) || referenceIndex < 1) return;
const source =
displaySources.find((item) => item.index === referenceIndex) ??
displaySources[referenceIndex - 1];
if (source) setSelectedCitation(source);
},
[displaySources],
);
const reasoningId =
lastReasoningStep?.id ??
messages.find((message) => message.type === "ai")?.id;
return ( return (
<>
<ChainOfThought <ChainOfThought
className={cn("w-full gap-2 rounded-lg border p-0.5", className)} className={cn("w-full gap-2 rounded-lg border p-0.5", className)}
data-reference-batch-id={reasoningId}
open={true} open={true}
> >
{aboveLastToolCallSteps.length > 0 && ( {aboveLastToolCallSteps.length > 0 && (
@@ -195,12 +152,10 @@ export function MessageGroup({
<ChainOfThoughtStep <ChainOfThoughtStep
key={step.id} key={step.id}
label={ label={
<StepReasoningMarkdown <MarkdownContent
content={step.reasoning ?? ""} content={step.reasoning ?? ""}
displaySources={displaySources}
isLoading={isLoading} isLoading={isLoading}
rehypePlugins={rehypePlugins} rehypePlugins={rehypePlugins}
onCitationClick={handleCitationClick}
/> />
} }
></ChainOfThoughtStep> ></ChainOfThoughtStep>
@@ -210,7 +165,7 @@ export function MessageGroup({
{...step} {...step}
isLoading={isLoading} isLoading={isLoading}
skillDisplayMap={skillDisplayMap} skillDisplayMap={skillDisplayMap}
ragModeEnabled={ragModeEnabled} ragModeEnabled={settings.display.ragModeEnabled}
/> />
), ),
)} )}
@@ -222,7 +177,7 @@ export function MessageGroup({
isLast={true} isLast={true}
isLoading={isLoading} isLoading={isLoading}
skillDisplayMap={skillDisplayMap} skillDisplayMap={skillDisplayMap}
ragModeEnabled={ragModeEnabled} ragModeEnabled={settings.display.ragModeEnabled}
/> />
</FlipDisplay> </FlipDisplay>
)} )}
@@ -257,12 +212,10 @@ export function MessageGroup({
<ChainOfThoughtStep <ChainOfThoughtStep
key={lastReasoningStep.id} key={lastReasoningStep.id}
label={ label={
<StepReasoningMarkdown <MarkdownContent
content={lastReasoningStep.reasoning ?? ""} content={lastReasoningStep.reasoning ?? ""}
displaySources={displaySources}
isLoading={isLoading} isLoading={isLoading}
rehypePlugins={rehypePlugins} rehypePlugins={rehypePlugins}
onCitationClick={handleCitationClick}
/> />
} }
></ChainOfThoughtStep> ></ChainOfThoughtStep>
@@ -271,59 +224,6 @@ export function MessageGroup({
</> </>
)} )}
</ChainOfThought> </ChainOfThought>
<SingleRoundRagCitationDialog
source={selectedCitation}
onOpenChange={(open) => {
if (!open) setSelectedCitation(null);
}}
/>
</>
);
}
function StepReasoningMarkdown({
content,
displaySources,
isLoading,
rehypePlugins,
onCitationClick,
}: {
content: string;
displaySources: RuntimeDisplaySource[];
isLoading: boolean;
rehypePlugins: ReturnType<typeof useRehypeSplitWordsIntoSpans>;
onCitationClick: (referenceId: string) => void;
}) {
const markdown = useMemo(
() =>
applyInlineCitations(content, displaySources, { appendSummary: false }),
[content, displaySources],
);
const components = useMemo(() => {
if (displaySources.length === 0) return undefined;
return {
a: ({ href, ...props }: AnchorHTMLAttributes<HTMLAnchorElement>) => {
if (href?.startsWith("#reference-")) {
return (
<CitationLink
href={href}
{...props}
onReferenceClick={onCitationClick}
/>
);
}
return <a href={href} {...props} />;
},
};
}, [displaySources.length, onCitationClick]);
return (
<MarkdownContent
content={markdown}
isLoading={isLoading}
rehypePlugins={rehypePlugins}
components={components}
/>
); );
} }
@@ -349,6 +249,8 @@ function ToolCall({
ragModeEnabled?: boolean; ragModeEnabled?: boolean;
}) { }) {
const { t } = useI18n(); const { t } = useI18n();
const artifacts = useArtifactsOptional();
const displayMatch = const displayMatch =
result !== undefined && isDisplaySamplePayload(result) result !== undefined && isDisplaySamplePayload(result)
? null ? null
@@ -363,20 +265,14 @@ function ToolCall({
mode: item.displayMode ?? displayMatch.display.mode, mode: item.displayMode ?? displayMatch.display.mode,
})) }))
: []; : [];
const wikiQuery = name === "llmwiki_search" ? resolveSearchQuery(args, result) : "";
const wikiSearchLabel = name === "llmwiki_search"
? wikiQuery
? `Wiki 文档检索 "${wikiQuery}"`
: "Wiki 文档检索"
: null;
if (displayItems.length > 0) { if (displayItems.length > 0) {
return ( return (
<ChainOfThoughtStep <ChainOfThoughtStep
key={id} key={id}
label={ label={
wikiSearchLabel || (displayMatch?.display.mode === "citation" || !displayMatch displayMatch?.display.mode === "citation" || !displayMatch
? "检索参考来源" ? "检索参考来源"
: `获取 ${displayItems.length} 条结果`) : `获取 ${displayItems.length} 条结果`
} }
icon={SearchIcon} icon={SearchIcon}
> >
@@ -385,13 +281,6 @@ function ToolCall({
); );
} }
// Deep Research uses a virtual tool call for each durable writing phase.
// Rendering it here keeps its lifecycle in the very same ChainOfThought
// component as ordinary Q&A retrieval and sandbox tool calls.
if (name === "deep_research_progress") {
return <DeepResearchProgressStep id={id} args={args} />;
}
const searchItems = normalizeSearchResults(result); const searchItems = normalizeSearchResults(result);
if (ragModeEnabled && shouldUseDefaultCitationMode(name, result, args) && searchItems.length > 0) { if (ragModeEnabled && shouldUseDefaultCitationMode(name, result, args) && searchItems.length > 0) {
const defaultItems = normalizeDefaultDisplaySources(result).map((item, index) => ({ const defaultItems = normalizeDefaultDisplaySources(result).map((item, index) => ({
@@ -401,7 +290,7 @@ function ToolCall({
mode: "citation" as const, mode: "citation" as const,
})); }));
return ( return (
<ChainOfThoughtStep key={id} label={wikiSearchLabel || "检索参考来源"} icon={SearchIcon}> <ChainOfThoughtStep key={id} label="检索参考来源" icon={SearchIcon}>
<DisplayResultsList results={defaultItems} /> <DisplayResultsList results={defaultItems} />
</ChainOfThoughtStep> </ChainOfThoughtStep>
); );
@@ -412,10 +301,8 @@ function ToolCall({
if (query) { if (query) {
label = label =
name === "web_search" name === "web_search"
? `知识库检索 "${query}"` ? t.toolCalls.searchOnWebFor(query)
: t.toolCalls.searchFor(query); : t.toolCalls.searchFor(query);
} else if (name === "web_search") {
label = "知识库检索";
} }
return ( return (
<ChainOfThoughtStep key={id} label={label} icon={SearchIcon}> <ChainOfThoughtStep key={id} label={label} icon={SearchIcon}>
@@ -535,17 +422,43 @@ function ToolCall({
if (!description) { if (!description) {
description = t.toolCalls.writeFile; description = t.toolCalls.writeFile;
} }
const path: string | undefined = (args as { path: string })?.path;
const artifactPath =
name === "write_file" && path
? new URL(
`write-file:${path}?message_id=${messageId}&tool_call_id=${id}`,
).toString()
: path;
if (artifacts && isLoading && isLast && artifacts.autoOpen && artifacts.autoSelect && path && !result) {
setTimeout(() => {
if (!artifactPath || artifacts.selectedArtifact === artifactPath) {
return;
}
artifacts.select(artifactPath, true);
artifacts.setOpen(true);
}, 100);
}
return ( return (
<ArtifactWriteToolCall <ChainOfThoughtStep
id={id} key={id}
messageId={messageId} className="cursor-pointer"
name={name} label={description}
args={args} icon={NotebookPenIcon}
result={result} onClick={() => {
description={description} if (!artifactPath || !artifacts) {
isLast={isLast} return;
isLoading={isLoading} }
/> artifacts.select(artifactPath);
artifacts.setOpen(true);
}}
>
{path && (
<ChainOfThoughtSearchResult className="cursor-pointer">
{path}
</ChainOfThoughtSearchResult>
)}
</ChainOfThoughtStep>
); );
} else if (name === "bash") { } else if (name === "bash") {
const description: string | undefined = (args as { description: string }) const description: string | undefined = (args as { description: string })
@@ -610,237 +523,6 @@ function ToolCall({
} }
} }
function DeepResearchProgressStep({
id,
args,
}: {
id?: string;
args: Record<string, unknown>;
}) {
const label = typeof args.label === "string" && args.label.trim()
? args.label
: "正在撰写研究报告";
const detail = typeof args.detail === "string" ? args.detail.trim() : "";
const thinking = typeof args.thinking === "string" ? args.thinking.trim() : "";
const active = args.status !== "complete";
const [thinkingOpen, setThinkingOpen] = useState(false);
const [autoScrollPaused, setAutoScrollPaused] = useState(false);
const thinkingContentRef = useRef<HTMLPreElement>(null);
const autoScrollEnabledRef = useRef(true);
const programmaticScrollRef = useRef(false);
const previousActiveRef = useRef(active);
useEffect(() => {
if (active && thinking) setThinkingOpen(true);
}, [active, thinking]);
useEffect(() => {
if (active && !previousActiveRef.current) {
autoScrollEnabledRef.current = true;
setAutoScrollPaused(false);
}
previousActiveRef.current = active;
}, [active]);
const scrollToLatestThinking = useCallback(() => {
if (!autoScrollEnabledRef.current) return;
const content = thinkingContentRef.current;
if (!content) return;
// Scroll events do not identify their initiator reliably across browsers.
// Mark this assignment so it never disables following as if it were a
// user drag; a user-originated scroll away from the bottom still pauses it.
programmaticScrollRef.current = true;
content.scrollTop = content.scrollHeight;
requestAnimationFrame(() => {
programmaticScrollRef.current = false;
});
}, []);
useLayoutEffect(() => {
if (!active || !thinkingOpen || !thinking) return;
scrollToLatestThinking();
// A second frame covers the browser's delayed reflow of a growing <pre>.
const frame = requestAnimationFrame(scrollToLatestThinking);
return () => cancelAnimationFrame(frame);
}, [active, thinking, thinkingOpen, scrollToLatestThinking]);
const pauseAutoScrollOnManualScroll = (event: React.UIEvent<HTMLPreElement>) => {
if (!active || !autoScrollEnabledRef.current || programmaticScrollRef.current) return;
const { clientHeight, scrollHeight, scrollTop } = event.currentTarget;
// Being at the bottom is still the follow state. Only an actual move away
// from it (wheel, touch, keyboard or scrollbar drag) pauses auto-follow.
if (scrollTop + clientHeight >= scrollHeight - 4) return;
autoScrollEnabledRef.current = false;
setAutoScrollPaused(true);
};
const resumeAutoScroll = () => {
autoScrollEnabledRef.current = true;
setAutoScrollPaused(false);
requestAnimationFrame(scrollToLatestThinking);
};
return (
<ChainOfThoughtStep
key={id}
status={active ? "active" : "complete"}
icon={active
? <Loader2Icon className="text-primary size-4 animate-spin" />
: <CheckCircle2Icon className="size-4 text-emerald-600 dark:text-emerald-400" />}
label={
<span className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
<span>{label}</span>
<span className={active ? "text-primary text-xs" : "text-muted-foreground text-xs"}>
{active ? "进行中" : "已完成"}
</span>
</span>
}
>
{detail && (
<div className="text-muted-foreground text-xs leading-5">
{detail}
</div>
)}
{thinking && (
<Collapsible className="mt-2" onOpenChange={setThinkingOpen} open={thinkingOpen}>
<CollapsibleTrigger asChild>
<Button
aria-label={thinkingOpen ? "收起模型思考" : "展开模型思考"}
className="h-7 gap-1.5 px-2 text-xs"
size="sm"
type="button"
variant="ghost"
>
<LightbulbIcon className="size-3.5 text-amber-600 dark:text-amber-300" />
<span>模型思考</span>
<span className="text-muted-foreground">{active ? "思考中" : "已完成"}</span>
<ChevronDownIcon className={cn("size-3.5 transition-transform", thinkingOpen && "rotate-180")} />
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<p aria-live={active ? "polite" : undefined} className="sr-only" role={active ? "status" : undefined}>
{active ? "模型思考内容正在更新" : "模型思考内容已完成"}
</p>
<div className="relative mt-1">
<pre
className="bg-muted/45 text-muted-foreground max-h-56 overflow-auto rounded-lg border px-3 py-2 text-xs leading-5 whitespace-pre-wrap break-words"
onScroll={pauseAutoScrollOnManualScroll}
ref={thinkingContentRef}
>
{thinking}
</pre>
{active && autoScrollPaused && (
<Button
aria-label="恢复思考内容自动下滑"
className="absolute top-1/2 left-1/2 h-9 -translate-x-1/2 -translate-y-1/2 gap-1.5 bg-background/95 px-3 text-xs shadow-md backdrop-blur-sm hover:bg-background"
onClick={resumeAutoScroll}
size="sm"
title="恢复自动下滑"
type="button"
variant="outline"
>
<ChevronsDownIcon className="size-3.5" />
自动下滑
</Button>
)}
</div>
</CollapsibleContent>
</Collapsible>
)}
</ChainOfThoughtStep>
);
}
/** 文件卡片只显示文件名:宿主泄漏路径(F:\...\outputs\report.md)与虚拟路径
* (/mnt/user-data/outputs/report.md)统一收敛到最后一段,避免把服务端磁盘结构暴露给用户。 */
function artifactDisplayName(path: string): string {
const filename = path.replace(/\\/g, "/").split("/").filter(Boolean).at(-1);
return filename || path;
}
function ArtifactWriteToolCall({
id,
messageId,
name,
args,
result,
description,
isLoading,
}: {
id?: string;
messageId?: string;
name: "write_file" | "str_replace";
args: Record<string, unknown>;
result?: string | Record<string, unknown>;
description: string;
isLast: boolean;
isLoading: boolean;
}) {
const artifacts = useArtifactsOptional();
const openStreamedArtifact = artifacts?.openStreamedArtifact;
const rawPath = typeof args.path === "string" ? args.path : "";
const content = typeof args.content === "string" ? args.content : "";
const normalizedPath = normalizeStreamingArtifactPath(rawPath);
const hasUsablePath =
Boolean(normalizedPath) && hasCompleteArtifactExtension(normalizedPath);
const sourcePath = hasUsablePath
? normalizedPath
: name === "write_file" && content.trim()
? provisionalWriteFilePath(content)
: null;
const previewKey = messageId && id ? `${messageId}:${id}` : null;
// Never select a bare provisional name like `未命名文件.md` — the artifacts
// API only serves `/mnt/user-data/...` paths and would 400. Wait until the
// tool call has ids so we can open a write-file: memory preview instead.
const artifactPath =
sourcePath && name === "write_file" && messageId && id
? buildWriteFileVirtualUrl({ path: sourcePath, messageId, toolCallId: id })
: null;
useEffect(() => {
if (
!openStreamedArtifact ||
!artifactPath ||
!previewKey ||
!isLoading ||
result !== undefined ||
!sourcePath ||
!languageOfStreamingArtifact(sourcePath) ||
!isAutoPreviewableArtifactPath(sourcePath)
) {
return;
}
openStreamedArtifact(artifactPath, previewKey);
}, [
artifactPath,
isLoading,
openStreamedArtifact,
previewKey,
result,
sourcePath,
]);
return (
<ChainOfThoughtStep
key={id}
className={cn(artifactPath && "cursor-pointer")}
label={description}
icon={NotebookPenIcon}
onClick={() => {
if (!artifactPath || !artifacts) return;
artifacts.select(artifactPath);
artifacts.setOpen(true);
}}
>
{(normalizedPath || sourcePath) && (
<ChainOfThoughtSearchResult className="cursor-pointer">
{artifactDisplayName(normalizedPath || (sourcePath ?? ""))}
</ChainOfThoughtSearchResult>
)}
</ChainOfThoughtStep>
);
}
interface GenericCoTStep<T extends string = string> { interface GenericCoTStep<T extends string = string> {
id?: string; id?: string;
messageId?: string; messageId?: string;
@@ -859,7 +541,7 @@ interface CoTToolCallStep extends GenericCoTStep<"toolCall"> {
type CoTStep = CoTReasoningStep | CoTToolCallStep; type CoTStep = CoTReasoningStep | CoTToolCallStep;
function convertToSteps(messages: Message[], writingMode: boolean): CoTStep[] { function convertToSteps(messages: Message[]): CoTStep[] {
const steps: CoTStep[] = []; const steps: CoTStep[] = [];
for (const message of messages) { for (const message of messages) {
if (message.type === "ai") { if (message.type === "ai") {
@@ -877,22 +559,6 @@ function convertToSteps(messages: Message[], writingMode: boolean): CoTStep[] {
if (tool_call.name === "task") { if (tool_call.name === "task") {
continue; continue;
} }
const writePath =
typeof (tool_call.args as { path?: unknown } | undefined)?.path === "string"
? (tool_call.args as { path: string }).path
: "";
if (
(
tool_call.name === "write_file" ||
tool_call.name === "str_replace" ||
tool_call.name === "read_file" ||
tool_call.name === "read_multiple_files" ||
tool_call.name === "present_files"
) &&
isInterceptedWritingReportWrite(writePath, message.id, messages, writingMode)
) {
continue;
}
const step: CoTToolCallStep = { const step: CoTToolCallStep = {
id: tool_call.id, id: tool_call.id,
messageId: message.id, messageId: message.id,
@@ -1,13 +1,5 @@
import type { Message } from '@langchain/langgraph-sdk'; import type { Message } from '@langchain/langgraph-sdk';
import { import { ClockIcon, FileIcon, Loader2Icon, PencilIcon } from 'lucide-react';
BookMarkedIcon,
ChevronDownIcon,
ClockIcon,
ExternalLinkIcon,
FileIcon,
Loader2Icon,
PencilIcon,
} from 'lucide-react';
import { import {
memo, memo,
useCallback, useCallback,
@@ -17,7 +9,6 @@ import {
useState, useState,
type AnchorHTMLAttributes, type AnchorHTMLAttributes,
type ImgHTMLAttributes, type ImgHTMLAttributes,
type ReactNode,
} from 'react'; } from 'react';
import rehypeKatex from 'rehype-katex'; import rehypeKatex from 'rehype-katex';
@@ -36,18 +27,6 @@ import {
import { Task, TaskTrigger } from '@/components/ai-elements/task'; import { Task, TaskTrigger } from '@/components/ai-elements/task';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from '@/components/ui/textarea';
import { import {
UploadedFilePreviewDialog, UploadedFilePreviewDialog,
@@ -56,7 +35,6 @@ import {
import { resolveArtifactURL } from '@/core/artifacts/utils'; import { resolveArtifactURL } from '@/core/artifacts/utils';
import { useChatAskTimes } from '@/core/chat-timestamps'; import { useChatAskTimes } from '@/core/chat-timestamps';
import { getBackendBaseURL } from '@/core/config'; import { getBackendBaseURL } from '@/core/config';
import { readRuntimeEnv } from '@/env';
import { useI18n } from '@/core/i18n/hooks'; import { useI18n } from '@/core/i18n/hooks';
import { import {
extractContentFromMessage, extractContentFromMessage,
@@ -72,10 +50,6 @@ import {
type RuntimeDisplaySource, type RuntimeDisplaySource,
} from '@/core/skill-display/runtime'; } from '@/core/skill-display/runtime';
import { humanMessagePlugins } from '@/core/streamdown'; import { humanMessagePlugins } from '@/core/streamdown';
import {
getMultiRoundRagTrace,
isMultiRoundRagMessage,
} from '@/core/threads/use-multi-round-rag';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { CitationLink } from '../citations/citation-link'; import { CitationLink } from '../citations/citation-link';
@@ -87,7 +61,6 @@ import { DeleteMessageButton } from './delete-message-button';
import { DownloadWordButton } from './download-word-button'; import { DownloadWordButton } from './download-word-button';
import { MarkdownContent, type MarkdownContentProps } from './markdown-content'; import { MarkdownContent, type MarkdownContentProps } from './markdown-content';
import { MessageTokenUsage } from './message-token-usage'; import { MessageTokenUsage } from './message-token-usage';
import { MultiRoundRagAssistantBody } from './multi-round-rag-message-list';
type EmbeddedPageContext = { type EmbeddedPageContext = {
title?: string; title?: string;
@@ -158,7 +131,6 @@ export function MessageListItem({
fitRowToContent = false, fitRowToContent = false,
anchorId, anchorId,
message, message,
questionMarkdown,
isLoading, isLoading,
threadId, threadId,
tokenUsageEnabled = false, tokenUsageEnabled = false,
@@ -177,8 +149,6 @@ export function MessageListItem({
*/ */
anchorId?: string; anchorId?: string;
message: Message; message: Message;
/** Nearest preceding user question, used by the current-Q&A Word export. */
questionMarkdown?: string;
isLoading?: boolean; isLoading?: boolean;
threadId: string; threadId: string;
tokenUsageEnabled?: boolean; tokenUsageEnabled?: boolean;
@@ -331,8 +301,6 @@ export function MessageListItem({
<DownloadWordButton <DownloadWordButton
markdown={messageMarkdown} markdown={messageMarkdown}
fileName="message" fileName="message"
title="问答回答"
questionMarkdown={questionMarkdown}
/> />
)} )}
{canSaveAssistantEdit && ( {canSaveAssistantEdit && (
@@ -378,12 +346,12 @@ function HumanMessageBlock({
messageId?: string; messageId?: string;
text: string; text: string;
pageContext?: EmbeddedPageContext | null; pageContext?: EmbeddedPageContext | null;
filesList: ReactNode; filesList: React.ReactNode;
messageTime: { label: string; full: string } | null; messageTime: { label: string; full: string } | null;
components: MarkdownContentProps["components"]; components: MarkdownContentProps["components"];
onEditResubmit?: (text: string) => void; onEditResubmit?: (text: string) => void;
onEditSave?: (messageId: string, text: string) => void | Promise<void>; onEditSave?: (messageId: string, text: string) => void | Promise<void>;
deleteButton?: ReactNode; deleteButton?: React.ReactNode;
}) { }) {
const { t } = useI18n(); const { t } = useI18n();
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
@@ -595,26 +563,7 @@ function MessageContent_({
); );
const askTimes = useChatAskTimes(); const askTimes = useChatAskTimes();
const isHuman = message.type === 'human'; const isHuman = message.type === 'human';
const isSingleRoundRag =
message.additional_kwargs?.single_round_rag === true;
const isMultiRoundRag = isMultiRoundRagMessage(message);
const multiRoundTrace = isMultiRoundRag
? getMultiRoundRagTrace(message)
: null;
const [selectedCitation, setSelectedCitation] =
useState<RuntimeDisplaySource | null>(null);
const resolveArtifact = useArtifactResolver(threadId); const resolveArtifact = useArtifactResolver(threadId);
const handleCitationClick = useCallback(
(referenceId: string) => {
const referenceIndex = Number(referenceId);
if (!Number.isInteger(referenceIndex) || referenceIndex < 1) return;
const source =
displaySources.find((item) => item.index === referenceIndex) ??
displaySources[referenceIndex - 1];
if (source) setSelectedCitation(source);
},
[displaySources],
);
const components = useMemo( const components = useMemo(
() => ({ () => ({
img: (props: ImgHTMLAttributes<HTMLImageElement>) => ( img: (props: ImgHTMLAttributes<HTMLImageElement>) => (
@@ -622,15 +571,7 @@ function MessageContent_({
), ),
a: ({ href, ...props }: AnchorHTMLAttributes<HTMLAnchorElement>) => { a: ({ href, ...props }: AnchorHTMLAttributes<HTMLAnchorElement>) => {
if (href?.startsWith('#reference-')) { if (href?.startsWith('#reference-')) {
return ( return <CitationLink href={href} {...props} />;
<CitationLink
href={href}
{...props}
onReferenceClick={
isSingleRoundRag ? handleCitationClick : undefined
}
/>
);
} }
if ( if (
typeof props.children === 'string' && typeof props.children === 'string' &&
@@ -652,12 +593,7 @@ function MessageContent_({
return <a {...props} href={href} />; return <a {...props} href={href} />;
}, },
}), }),
[ [threadId, resolveArtifact],
handleCitationClick,
isSingleRoundRag,
resolveArtifact,
threadId,
],
); );
// Question carries its own `client_ts` (round-trips through the checkpoint). // Question carries its own `client_ts` (round-trips through the checkpoint).
@@ -692,16 +628,9 @@ function MessageContent_({
? stripArtifactTag(stripUploadedFilesTag(rawContent)) ? stripArtifactTag(stripUploadedFilesTag(rawContent))
: ''; : '';
} }
if (isMultiRoundRag) {
return stripIncompleteCitationMarker(rawContent ?? '');
}
const withCitations = applyInlineCitations(rawContent ?? '', displaySources); const withCitations = applyInlineCitations(rawContent ?? '', displaySources);
return stripIncompleteCitationMarker(withCitations); return stripIncompleteCitationMarker(withCitations);
}, [rawContent, isHuman, isMultiRoundRag, displaySources]); }, [rawContent, isHuman, displaySources]);
const markdownRehypePlugins = useMemo(
() => [...rehypePlugins, [rehypeKatex, { output: 'html' as const }]],
[rehypePlugins],
);
const parsedHumanContent = useMemo( const parsedHumanContent = useMemo(
() => () =>
isHuman isHuman
@@ -732,7 +661,7 @@ function MessageContent_({
} }
// Reasoning-only AI message (no main response content yet) // Reasoning-only AI message (no main response content yet)
if (!isHuman && reasoningContent && !rawContent && !isMultiRoundRag) { if (!isHuman && reasoningContent && !rawContent) {
return ( return (
<AIElementMessageContent className={className}> <AIElementMessageContent className={className}>
<Reasoning isStreaming={isLoading}> <Reasoning isStreaming={isLoading}>
@@ -753,11 +682,7 @@ function MessageContent_({
// it exists server-side (real, non-optimistic id). Deleting it cascades to // it exists server-side (real, non-optimistic id). Deleting it cascades to
// its answer on the backend. // its answer on the backend.
const canDelete = const canDelete =
!!onMessageDeleted && !!onMessageDeleted && !!message.id && !message.id.startsWith('opt-');
!!message.id &&
!message.id.startsWith('opt-') &&
!isMultiRoundRag &&
!isSingleRoundRag;
return ( return (
<HumanMessageBlock <HumanMessageBlock
messageId={message.id} messageId={message.id}
@@ -766,10 +691,8 @@ function MessageContent_({
filesList={filesList} filesList={filesList}
messageTime={messageTime} messageTime={messageTime}
components={components} components={components}
onEditResubmit={ onEditResubmit={onEditResubmit}
isMultiRoundRag || isSingleRoundRag ? undefined : onEditResubmit onEditSave={onEditSave}
}
onEditSave={isMultiRoundRag || isSingleRoundRag ? undefined : onEditSave}
deleteButton={ deleteButton={
canDelete ? ( canDelete ? (
<DeleteMessageButton <DeleteMessageButton
@@ -785,34 +708,18 @@ function MessageContent_({
} }
return ( return (
<>
<AIElementMessageContent className={className}> <AIElementMessageContent className={className}>
{filesList} {filesList}
<div data-reference-batch-id={message.id} className="contents"> <div data-reference-batch-id={message.id} className="contents">
{isMultiRoundRag ? (
<MultiRoundRagAssistantBody
content={contentToDisplay}
thinkingTrace={multiRoundTrace}
isLoading={isLoading}
rehypePlugins={markdownRehypePlugins}
/>
) : (
<AssistantDisplayContent <AssistantDisplayContent
content={contentToDisplay} content={contentToDisplay}
displaySources={displaySources} displaySources={displaySources}
isLoading={isLoading} isLoading={isLoading}
renderSkillDisplayBlocks={false} renderSkillDisplayBlocks={false}
rehypePlugins={markdownRehypePlugins} rehypePlugins={[...rehypePlugins, [rehypeKatex, { output: 'html' }]]}
components={components} components={components}
/> />
)}
</div> </div>
{isSingleRoundRag && displaySources.length > 0 && (
<FrontendRagSourcesPanel
sources={displaySources}
onSelect={setSelectedCitation}
/>
)}
<MessageTokenUsage <MessageTokenUsage
enabled={tokenUsageEnabled} enabled={tokenUsageEnabled}
isLoading={isLoading} isLoading={isLoading}
@@ -822,148 +729,9 @@ function MessageContent_({
<MessageTimeStamp time={messageTime} align="left" /> <MessageTimeStamp time={messageTime} align="left" />
) : null} ) : null}
</AIElementMessageContent> </AIElementMessageContent>
{isSingleRoundRag && (
<SingleRoundRagCitationDialog
source={selectedCitation}
onOpenChange={(open) => {
if (!open) setSelectedCitation(null);
}}
/>
)}
</>
); );
} }
/**
* 单轮 RAG 专属的「引用来源」折叠面板。
*
* 多轮 RAG 的检索卡片已经画在思考过程里,正文下面不再重复一份来源列表。
*/
function FrontendRagSourcesPanel({
sources,
onSelect,
}: {
sources: RuntimeDisplaySource[];
onSelect: (source: RuntimeDisplaySource) => void;
}) {
const [open, setOpen] = useState(false);
if (sources.length === 0) return null;
return (
<Collapsible open={open} onOpenChange={setOpen} className="mt-3 w-full max-w-5xl">
<CollapsibleTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5 text-xs transition-colors"
>
<BookMarkedIcon className="size-3.5" />
<span className="font-medium">引用来源</span>
<span className="text-muted-foreground/70">({sources.length})</span>
<ChevronDownIcon
className={cn(
'size-3.5 transition-transform duration-200',
!open && '-rotate-90',
)}
/>
</button>
</CollapsibleTrigger>
<CollapsibleContent className="mt-2 grid gap-2">
{sources.map((source, idx) => (
<button
key={source.id ?? `${source.title}-${idx}`}
type="button"
onClick={() => onSelect(source)}
className="bg-card hover:bg-accent block w-full cursor-pointer rounded-lg border p-3 text-left transition-colors"
>
<div className="flex items-center gap-2">
<span className="bg-primary/10 text-primary flex size-5 shrink-0 items-center justify-center rounded-full text-xs font-semibold">
{source.index}
</span>
<span
className="text-foreground line-clamp-1 min-w-0 flex-1 text-sm font-medium"
title={source.title}
>
{source.title}
</span>
{source.type && (
<span className="bg-muted text-muted-foreground shrink-0 rounded px-1.5 py-0.5 text-xs">
{source.type}
</span>
)}
</div>
{source.snippet && (
<p className="text-muted-foreground mt-1.5 line-clamp-2 text-xs leading-relaxed">
{source.snippet}
</p>
)}
</button>
))}
</CollapsibleContent>
</Collapsible>
);
}
export function SingleRoundRagCitationDialog({
source,
onOpenChange,
}: {
source: RuntimeDisplaySource | null;
onOpenChange: (open: boolean) => void;
}) {
const sourceUrl = resolveSingleRoundRagSourceUrl(source);
return (
<Dialog open={!!source} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[min(42rem,calc(100vh-2rem))] max-w-2xl overflow-hidden p-5 sm:max-w-2xl">
<DialogHeader className="pr-8">
<DialogTitle className="leading-relaxed">
{source?.title || "引用资料"}
</DialogTitle>
<DialogDescription className="space-y-1 text-xs">
<span className="block">来源:{source?.source || source?.type || "未知来源"}</span>
{source?.time && <span className="block">时间:{source.time}</span>}
</DialogDescription>
</DialogHeader>
{sourceUrl && (
<a
href={sourceUrl}
target="_blank"
rel="noopener noreferrer"
className="border-input hover:bg-accent inline-flex w-fit items-center gap-1.5 rounded-md border px-3 py-1.5 text-sm transition-colors"
>
<ExternalLinkIcon className="size-4" />
查看原文链接
</a>
)}
<div className="bg-muted/50 max-h-[min(26rem,calc(100vh-16rem))] overflow-auto rounded-lg p-3 text-sm leading-7 whitespace-pre-wrap">
{source?.content || source?.snippet || "暂无引用内容"}
</div>
</DialogContent>
</Dialog>
);
}
function resolveSingleRoundRagSourceUrl(
source: RuntimeDisplaySource | null,
): string | undefined {
if (!source) return undefined;
if (source.url && /^https?:\/\//i.test(source.url)) return source.url;
const raw = source.raw ?? {};
const recordId =
source.id ??
readString(raw.recUuid) ??
readString(raw.rec_uuid) ??
readString(raw.uuid);
const knowledgeUrl = readRuntimeEnv("VITE_AIPI_KNOWLEDGE_URL")?.replace(/\/$/, "");
if (!knowledgeUrl || !recordId) return undefined;
return `${knowledgeUrl}/#/knowledge/mid-detail?recUuid=${encodeURIComponent(recordId)}`;
}
function readString(value: unknown): string | undefined {
if (typeof value === "string" && value.trim()) return value;
if (typeof value === "number" && Number.isFinite(value)) return String(value);
return undefined;
}
function EmbeddedPageContextCard({ function EmbeddedPageContextCard({
pageContext, pageContext,
}: { }: {
@@ -1,7 +1,7 @@
import type { Message } from "@langchain/langgraph-sdk"; import type { Message } from "@langchain/langgraph-sdk";
import type { BaseStream } from "@langchain/langgraph-sdk/react"; import type { BaseStream } from "@langchain/langgraph-sdk/react";
import { CheckIcon, PenLineIcon, SendIcon, XIcon } from "lucide-react"; import { CheckIcon, PenLineIcon, SendIcon, XIcon } from "lucide-react";
import { useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useStickToBottomContext } from "use-stick-to-bottom"; import { useStickToBottomContext } from "use-stick-to-bottom";
import { import {
@@ -12,10 +12,6 @@ import {
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { rememberAskTimes, useChatAskTimes } from "@/core/chat-timestamps"; import { rememberAskTimes, useChatAskTimes } from "@/core/chat-timestamps";
import {
DOCUMENT_REWRITE_STARTED_EVENT,
useDocumentRewritePresentation,
} from "@/core/document-rewrite/context";
import { useI18n } from "@/core/i18n/hooks"; import { useI18n } from "@/core/i18n/hooks";
import { import {
extractContentFromMessage, extractContentFromMessage,
@@ -31,17 +27,13 @@ import {
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype"; import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings"; import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
import { useSkills } from "@/core/skills/hooks"; import { useSkills } from "@/core/skills/hooks";
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
import { import {
buildSkillDisplayMap, buildSkillDisplayMap,
collectRuntimeDisplaySources, collectRuntimeDisplaySources,
type RuntimeDisplaySource,
} from "@/core/skill-display/runtime"; } from "@/core/skill-display/runtime";
import type { Subtask } from "@/core/tasks"; import type { Subtask } from "@/core/tasks";
import { useUpdateSubtask } from "@/core/tasks/context"; import { useUpdateSubtask } from "@/core/tasks/context";
import type { AgentThreadState } from "@/core/threads"; import type { AgentThreadState } from "@/core/threads";
import { isSingleRoundRagMessage } from "@/core/threads/use-single-round-rag";
import { isMultiRoundRagMessage } from "@/core/threads/use-multi-round-rag";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification"; import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
@@ -51,7 +43,6 @@ import { StreamingIndicator } from "../streaming-indicator";
import { ReferenceBatchesContext, ThreadContext } from "./context"; import { ReferenceBatchesContext, ThreadContext } from "./context";
import { MarkdownContent } from "./markdown-content"; import { MarkdownContent } from "./markdown-content";
import { DocumentRewriteTimeline } from "./document-rewrite-timeline";
import { MessageGroup } from "./message-group"; import { MessageGroup } from "./message-group";
import { MessageListItem } from "./message-list-item"; import { MessageListItem } from "./message-list-item";
import { import {
@@ -93,22 +84,6 @@ function ScrollToBottomOnUserMessage({
} }
}, [messages, scrollToBottom]); }, [messages, scrollToBottom]);
useEffect(() => {
const handleDocumentRewriteStarted = (event: Event) => {
const detail = (event as CustomEvent<{ threadId?: string }>).detail;
if (detail?.threadId !== threadId) return;
// The presentation card is inserted by a context update in the same
// interaction. Two frames let React commit it before the smooth scroll.
requestAnimationFrame(() => {
requestAnimationFrame(() => {
void scrollToBottom("smooth");
});
});
};
window.addEventListener(DOCUMENT_REWRITE_STARTED_EVENT, handleDocumentRewriteStarted);
return () => window.removeEventListener(DOCUMENT_REWRITE_STARTED_EVENT, handleDocumentRewriteStarted);
}, [scrollToBottom, threadId]);
return null; return null;
} }
@@ -132,15 +107,7 @@ export function MessageList({
onSetupWritingApprove, onSetupWritingApprove,
onSetupWritingReject, onSetupWritingReject,
onSetupWritingStart, onSetupWritingStart,
onSetupReportStructureApprove,
onSetupReportStructureReject,
researchApprovalSlot,
taskReportImportSlot,
businessCardSlot,
speakerShell,
onOpenArtifact, onOpenArtifact,
onDownloadArtifact,
afterDocumentRewriteItems,
}: { }: {
className?: string; className?: string;
contentClassName?: string; contentClassName?: string;
@@ -163,39 +130,7 @@ export function MessageList({
onSetupWritingReject?: (payload: SetupWritingApprovalPayload) => void | Promise<void>; onSetupWritingReject?: (payload: SetupWritingApprovalPayload) => void | Promise<void>;
/** 审批卡「直接开始写作」回调:应用配置(含已确认大纲)并立即启动写作流程(仅写作页提供,模板编辑等场景缺省隐藏该按钮)。 */ /** 审批卡「直接开始写作」回调:应用配置(含已确认大纲)并立即启动写作流程(仅写作页提供,模板编辑等场景缺省隐藏该按钮)。 */
onSetupWritingStart?: (payload: SetupWritingApprovalPayload) => void | Promise<void>; onSetupWritingStart?: (payload: SetupWritingApprovalPayload) => void | Promise<void>;
onSetupReportStructureApprove?: (payload: SetupReportStructureApprovalPayload) => void | Promise<void>;
onSetupReportStructureReject?: (payload: SetupReportStructureApprovalPayload) => void | Promise<void>;
/**
* 深度研究的交互卡插槽(报告配置、计划确认、失败重试):workbench 向
* displayThread 注入带 `additional_kwargs.setup_research_approval` 的虚拟 ai
* 消息。撰写步骤和完成摘要不走此插槽,而是分别复用原生 tool-call 步骤条和
* assistant 消息行;不传该 slot 时普通对话/AI 写作零行为变化。
*/
researchApprovalSlot?: (message: Message) => React.ReactNode;
/**
* agentfx「入库」协助卡插槽:任务工作区宿主(AgentChatPage taskBind)向 displayThread
* 注入带 `additional_kwargs.task_report_import_approval` 的虚拟 ai 消息,由本插槽渲染
* 「是否入库」卡片。不传该 slot 时(普通对话等)该分组不渲染,零行为变化。
*/
taskReportImportSlot?: (message: Message) => React.ReactNode;
/**
* 通用业务卡插槽(报告协作工作台等):宿主向 displayThread 注入带
* `additional_kwargs.report_collaboration_card` 的虚拟 ai 消息(方案组 /
* 命令确认 / 报告入口),由本插槽渲染。不传该 slot 时(普通对话等)该
* 分组不渲染,零行为变化;卡 payload 结构由各页面在 message-adapter
* 层定义,MessageList 不感知具体业务字段。
*/
businessCardSlot?: (message: Message) => React.ReactNode;
/**
* 可选说话人壳(报告协作对齐会商第二步):包住 assistant / processing 分组。
* 不传则问答页零变化。
*/
speakerShell?: (messages: Message[], children: ReactNode) => ReactNode;
onOpenArtifact?: (filepath: string) => void; onOpenArtifact?: (filepath: string) => void;
/** Host override for downloading virtual/session-owned files in a present-files card. */
onDownloadArtifact?: (filepath: string) => void | Promise<void>;
/** Optional host content placed immediately after document-rewrite timelines. */
afterDocumentRewriteItems?: React.ReactNode;
}) { }) {
const baseRehypePlugins = useRehypeSplitWordsIntoSpans(thread.isLoading); const baseRehypePlugins = useRehypeSplitWordsIntoSpans(thread.isLoading);
const rehypePlugins = useMemo( const rehypePlugins = useMemo(
@@ -203,7 +138,6 @@ export function MessageList({
[baseRehypePlugins, extraRehypePlugins], [baseRehypePlugins, extraRehypePlugins],
); );
const updateSubtask = useUpdateSubtask(); const updateSubtask = useUpdateSubtask();
const documentRewritePresentation = useDocumentRewritePresentation();
const { t } = useI18n(); const { t } = useI18n();
const threadContext = useContext(ThreadContext); const threadContext = useContext(ThreadContext);
// Read-only contexts (public share, mock previews) must not offer deletion. // Read-only contexts (public share, mock previews) must not offer deletion.
@@ -256,7 +190,6 @@ export function MessageList({
}, },
[allMessages, externallyHiddenMessageIds, hiddenMessageIds], [allMessages, externallyHiddenMessageIds, hiddenMessageIds],
); );
const documentRewriteItems = documentRewritePresentation?.forThread(threadId) ?? [];
const askTimes = useChatAskTimes(); const askTimes = useChatAskTimes();
@@ -301,40 +234,13 @@ export function MessageList({
return map; return map;
}, [messages, askTimes]); }, [messages, askTimes]);
// Associate each assistant answer with the nearest preceding user question.
// This powers the per-answer Word menu without changing message persistence.
const questionMarkdownByAssistantId = useMemo(() => {
const map = new Map<string, string>();
let currentQuestion = "";
for (const message of messages) {
if (message.type === "human") {
currentQuestion = extractContentFromMessage(message)?.trim() ?? "";
} else if (message.type === "ai" && message.id && currentQuestion) {
map.set(message.id, currentQuestion);
}
}
return map;
}, [messages]);
const [settings] = useLocalSettings(); const [settings] = useLocalSettings();
const { data: citationDisplay } = useCitationDisplaySettings();
const referenceModeEntryEnabled =
citationDisplay?.reference_mode_enabled ?? false;
const knowledgeReferencesEnabled =
threadContext?.knowledgeReferencesEnabled === true;
const ragModeEnabled = const ragModeEnabled =
(referenceModeEntryEnabled && settings.display.ragModeEnabled) || settings.display.ragModeEnabled || isThreadRagModeLocked(threadId);
isThreadRagModeLocked(threadId) ||
knowledgeReferencesEnabled;
const hasSingleRoundRag = useMemo(
() => messages.some((message) => isSingleRoundRagMessage(message)),
[messages],
);
const referencesEnabled = ragModeEnabled || hasSingleRoundRag;
const { skills } = useSkills(); const { skills } = useSkills();
const skillDisplayMap = useMemo( const skillDisplayMap = useMemo(
() => (referencesEnabled ? buildSkillDisplayMap(skills) : new Map()), () => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
[referencesEnabled, skills], [ragModeEnabled, skills],
); );
// Same per-turn reference batches the right-side panel renders (backend // Same per-turn reference batches the right-side panel renders (backend
// batches preferred). Inline [n] tokens must resolve against these so badge // batches preferred). Inline [n] tokens must resolve against these so badge
@@ -342,74 +248,6 @@ export function MessageList({
// frontend tool-message scan below comes up empty (e.g. after a reload). // frontend tool-message scan below comes up empty (e.g. after a reload).
const referenceBatches = useContext(ReferenceBatchesContext); const referenceBatches = useContext(ReferenceBatchesContext);
// 单轮 RAG 的参考资料存放在一条 hide_from_ui 的 tool 消息里(紧挨在
// assistant 消息之前)。allMessages 会把 hide_from_ui 消息过滤掉,导致通用
// 的 collectRuntimeDisplaySources 扫描不到它们。这里直接在原始消息流里按
// assistant 消息提取其对应的参考资料,保证 `[1]` 等编号能解析成可点击引用。
const frontendRagSourcesByAiId = useMemo(() => {
const map = new Map<string, RuntimeDisplaySource[]>();
const raw = thread.messages;
for (let i = 0; i < raw.length; i++) {
const msg = raw[i];
if (!msg || msg.type !== "ai" || !msg.id) continue;
const kwargs = msg.additional_kwargs;
if (!kwargs || kwargs.single_round_rag !== true) {
continue;
}
let sources: RuntimeDisplaySource[] = [];
for (let j = i - 1; j >= 0; j--) {
const prev = raw[j];
if (!prev) break;
// 前一条 human/ai 消息即为本轮边界,跨边界即停止。
if (prev.type === "human" || prev.type === "ai") break;
if (prev.type !== "tool") continue;
const prevKwargs = prev.additional_kwargs;
if (!prevKwargs || prevKwargs.single_round_rag !== true) {
continue;
}
const results = extractFrontendRagResults(prev.content);
if (results && results.length > 0) {
const toolName = String(
(prev as { name?: unknown }).name ?? "knowledge_base_search",
);
sources = results.map((item, index) =>
toRuntimeDisplaySource(item, index + 1, toolName),
);
}
break;
}
map.set(msg.id, sources);
}
return map;
}, [thread.messages]);
const resolveDisplaySources = useCallback(
(msg: Message | undefined): RuntimeDisplaySource[] => {
if (!referencesEnabled || !msg || msg.type !== "ai") return [];
if (isMultiRoundRagMessage(msg)) return [];
const batchSources =
referenceBatches.find((batch) => batch.assistant_message_id === msg.id)
?.sources ?? [];
const frontendRagSources = msg.id
? frontendRagSourcesByAiId.get(msg.id) ?? []
: [];
if (batchSources.length > 0) return batchSources;
if (frontendRagSources.length > 0) return frontendRagSources;
return collectRuntimeDisplaySources(messages, skillDisplayMap, {
afterMessageId: findPreviousHumanMessageId(messages, msg.id),
beforeMessageId: msg.id,
includeBeforeMessage: true,
});
},
[
frontendRagSourcesByAiId,
messages,
referenceBatches,
referencesEnabled,
skillDisplayMap,
],
);
// Track which clarification messages are still awaiting an answer. // Track which clarification messages are still awaiting an answer.
// Pending = clarification tool messages that appear after the last human message // Pending = clarification tool messages that appear after the last human message
// (no user reply has been sent for them yet). // (no user reply has been sent for them yet).
@@ -526,35 +364,31 @@ export function MessageList({
<ScrollToBottomOnUserMessage threadId={threadId} messages={messages} /> <ScrollToBottomOnUserMessage threadId={threadId} messages={messages} />
<ConversationContent <ConversationContent
className={cn( className={cn(
"mx-auto w-full max-w-(--container-width-lg)", "mx-auto w-full max-w-(--container-width-lg) gap-8 pt-12",
hasSingleRoundRag ? "gap-4 pt-4" : "gap-8 pt-12",
contentClassName, contentClassName,
)} )}
> >
<MessageMetricsProvider messages={messages} isLoading={thread.isLoading}> <MessageMetricsProvider messages={messages} isLoading={thread.isLoading}>
{(() => { {groupMessages(messages, (group) => {
const rewriteItemsAboveFile = documentRewriteItems.filter(
(item) => item.operation !== "generate",
);
const rewriteItemsBelowFile = documentRewriteItems.filter(
(item) => item.operation === "generate",
);
let didRenderRewriteAboveFile = false;
const grouped = groupMessages(messages, (group) => {
if (group.type === "human" || group.type === "assistant") { if (group.type === "human" || group.type === "assistant") {
const items = group.messages.map((msg) => { return group.messages.map((msg) => {
// 深度研究的报告摘要由独立 SSE 作业驱动;把它接入既有 assistant 流式状态,
// 便于 Streamdown 在每次 summary_delta 到达时立即更新该普通消息行。
const messageIsLoading =
thread.isLoading ||
msg.additional_kwargs?.deep_research_summary_streaming === true ||
msg.additional_kwargs?.deep_research_follow_up_streaming === true;
const isAssistantMessage = const isAssistantMessage =
referencesEnabled && ragModeEnabled &&
group.type === "assistant" && group.type === "assistant" &&
msg.type === "ai"; msg.type === "ai";
const batchSources = isAssistantMessage
? referenceBatches.find(
(batch) => batch.assistant_message_id === msg.id,
)?.sources ?? []
: [];
const displaySources = isAssistantMessage const displaySources = isAssistantMessage
? resolveDisplaySources(msg) ? batchSources.length > 0
? batchSources
: collectRuntimeDisplaySources(messages, skillDisplayMap, {
afterMessageId: findPreviousHumanMessageId(messages, msg.id),
beforeMessageId: msg.id,
includeBeforeMessage: true,
})
: []; : [];
return ( return (
<MessageListItem <MessageListItem
@@ -566,15 +400,7 @@ export function MessageList({
: undefined : undefined
} }
message={msg} message={msg}
questionMarkdown={ isLoading={thread.isLoading}
msg.id ? questionMarkdownByAssistantId.get(msg.id) : undefined
}
isLoading={
isMultiRoundRagMessage(msg)
? thread.isLoading &&
msg.id === messages[messages.length - 1]?.id
: messageIsLoading
}
threadId={threadId} threadId={threadId}
tokenUsageEnabled={tokenUsageEnabled} tokenUsageEnabled={tokenUsageEnabled}
displaySources={displaySources} displaySources={displaySources}
@@ -588,14 +414,6 @@ export function MessageList({
/> />
); );
}); });
if (speakerShell && group.type === "assistant") {
return (
<div key={group.id} className="w-full">
{speakerShell(group.messages, items)}
</div>
);
}
return items;
} else if (group.type === "assistant:clarification") { } else if (group.type === "assistant:clarification") {
const message = group.messages[0]; const message = group.messages[0];
if (message && hasContent(message)) { if (message && hasContent(message)) {
@@ -677,48 +495,6 @@ export function MessageList({
/> />
</div> </div>
) : null; ) : null;
} else if (group.type === "assistant:setup-report-structure-approval") {
const message = group.messages[0];
return message ? (
<div key={group.id} className="w-full">
<SetupReportStructureApprovalCard
disabled={thread.isLoading}
message={message}
onApprove={onSetupReportStructureApprove}
onReject={onSetupReportStructureReject}
/>
<MessageTokenUsageList
enabled={tokenUsageEnabled}
isLoading={thread.isLoading}
messages={group.messages}
/>
</div>
) : null;
} else if (group.type === "assistant:research-approval") {
// 深度研究交互卡(配置/计划确认/失败重试):宿主不传渲染函数时该
// 分组不渲染。撰写步骤和完成摘要会经过普通的 processing/assistant 分组。
const message = group.messages[0];
return researchApprovalSlot && message ? (
<div key={group.id} className="w-full pb-2">
{researchApprovalSlot(message)}
</div>
) : null;
} else if (group.type === "assistant:task-report-import") {
// agentfx「入库」协助卡:宿主不传渲染函数时该分组不渲染。
const message = group.messages[0];
return taskReportImportSlot && message ? (
<div key={group.id} className="w-full pb-2">
{taskReportImportSlot(message)}
</div>
) : null;
} else if (group.type === "assistant:business-card") {
// 通用业务卡(报告协作):宿主不传渲染函数时该分组不渲染。
const message = group.messages[0];
return businessCardSlot && message ? (
<div key={group.id} className="w-full pb-2">
{businessCardSlot(message)}
</div>
) : null;
} else if (group.type === "assistant:present-files") { } else if (group.type === "assistant:present-files") {
const files: string[] = []; const files: string[] = [];
for (const message of group.messages) { for (const message of group.messages) {
@@ -727,15 +503,8 @@ export function MessageList({
files.push(...presentFiles); files.push(...presentFiles);
} }
} }
const rewriteAbove = !didRenderRewriteAboveFile
? rewriteItemsAboveFile
: [];
didRenderRewriteAboveFile = true;
return ( return (
<div className="w-full" key={group.id}> <div className="w-full" key={group.id}>
{rewriteAbove.map((item) => (
<DocumentRewriteTimeline key={`rewrite-above-${item.id}`} item={item} />
))}
{group.messages[0] && hasContent(group.messages[0]) && ( {group.messages[0] && hasContent(group.messages[0]) && (
<MarkdownContent <MarkdownContent
content={extractContentFromMessage(group.messages[0])} content={extractContentFromMessage(group.messages[0])}
@@ -748,7 +517,6 @@ export function MessageList({
files={files} files={files}
threadId={threadId} threadId={threadId}
onOpenArtifact={onOpenArtifact} onOpenArtifact={onOpenArtifact}
onDownloadArtifact={onDownloadArtifact}
/> />
<MessageTokenUsageList <MessageTokenUsageList
enabled={tokenUsageEnabled} enabled={tokenUsageEnabled}
@@ -817,8 +585,6 @@ export function MessageList({
key={"thinking-group-" + message.id} key={"thinking-group-" + message.id}
messages={[message]} messages={[message]}
isLoading={thread.isLoading} isLoading={thread.isLoading}
displaySources={resolveDisplaySources(message)}
ragModeEnabled={ragModeEnabled}
/>, />,
); );
} }
@@ -862,16 +628,11 @@ export function MessageList({
message.type === "ai" && message.type === "ai" &&
(hasToolCalls(message) ? true : !hasContent(message)), (hasToolCalls(message) ? true : !hasContent(message)),
); );
const processingAi = [...group.messages] return (
.reverse() <div key={"group-" + group.id} className="w-full">
.find((message) => message.type === "ai");
const processingBody = (
<div className="w-full">
<MessageGroup <MessageGroup
messages={group.messages} messages={group.messages}
isLoading={thread.isLoading} isLoading={thread.isLoading}
displaySources={resolveDisplaySources(processingAi)}
ragModeEnabled={ragModeEnabled}
/> />
<MessageTokenUsageList <MessageTokenUsageList
enabled={tokenUsageEnabled} enabled={tokenUsageEnabled}
@@ -880,25 +641,7 @@ export function MessageList({
/> />
</div> </div>
); );
return ( })}
<div key={"group-" + group.id} className="w-full">
{speakerShell ? speakerShell(group.messages, processingBody) : processingBody}
</div>
);
});
const leftoverRewriteItems = didRenderRewriteAboveFile
? rewriteItemsBelowFile
: documentRewriteItems;
return (
<>
{grouped}
{leftoverRewriteItems.map((item) => (
<DocumentRewriteTimeline key={item.id} item={item} />
))}
{afterDocumentRewriteItems}
</>
);
})()}
{thread.isLoading && <StreamingIndicator className="my-4" />} {thread.isLoading && <StreamingIndicator className="my-4" />}
<div style={{ height: `${paddingBottom}px` }} /> <div style={{ height: `${paddingBottom}px` }} />
</MessageMetricsProvider> </MessageMetricsProvider>
@@ -956,15 +699,6 @@ export type SetupWritingApprovalPayload = {
outline?: string; outline?: string;
}; };
export type SetupReportStructureApprovalPayload = {
title?: string;
name?: string;
content?: string;
structure_mode?: string;
retrieval_directions?: string[];
retrieval_skills?: string[];
};
function findPreviousHumanMessageId( function findPreviousHumanMessageId(
messages: Message[], messages: Message[],
beforeMessageId?: string, beforeMessageId?: string,
@@ -983,46 +717,6 @@ function findPreviousHumanMessageId(
return undefined; return undefined;
} }
/** 从单轮/多轮 RAG 的 tool 消息体里取出 `content.results`。 */
function extractFrontendRagResults(content: unknown): unknown[] | null {
if (content && typeof content === "object" && !Array.isArray(content)) {
const results = (content as { results?: unknown }).results;
if (Array.isArray(results)) return results;
}
return null;
}
/** 把单轮/多轮 RAG 的一条参考资料归一化为展示用的 RuntimeDisplaySource。 */
function toRuntimeDisplaySource(
item: unknown,
index: number,
skillName: string,
): RuntimeDisplaySource {
const record =
item && typeof item === "object" && !Array.isArray(item)
? (item as Record<string, unknown>)
: {};
const raw =
(record.raw as Record<string, unknown> | undefined) ?? record;
const content = String(record.content ?? record.snippet ?? "");
return {
id: typeof record.id === "string" && record.id ? record.id : undefined,
title: String(record.title ?? `参考资料 ${index}`),
type: String(record.type ?? "result"),
snippet: String(record.snippet ?? content),
content,
source:
typeof record.source === "string" && record.source ? record.source : undefined,
author: undefined,
time: typeof record.time === "string" && record.time ? record.time : undefined,
url: typeof record.url === "string" && record.url ? record.url : undefined,
raw,
index,
skillName,
mode: "citation",
};
}
function getSetupAgentApprovalPayload( function getSetupAgentApprovalPayload(
message: unknown, message: unknown,
): SetupAgentApprovalPayload | null { ): SetupAgentApprovalPayload | null {
@@ -1335,147 +1029,6 @@ function SetupWritingApprovalCard({
); );
} }
function getSetupReportStructureApprovalPayload(
message: unknown,
): SetupReportStructureApprovalPayload | null {
if (typeof message !== "object" || message === null) {
return null;
}
const additionalKwargs = Reflect.get(message, "additional_kwargs");
if (typeof additionalKwargs !== "object" || additionalKwargs === null) {
return null;
}
const approval = Reflect.get(additionalKwargs, "setup_report_structure_approval");
if (typeof approval !== "object" || approval === null) {
return null;
}
return approval as SetupReportStructureApprovalPayload;
}
const STRUCTURE_MODE_LABELS: Record<string, string> = {
fixed: "固定大纲",
adaptive: "弹性大纲",
};
function SetupReportStructureApprovalCard({
disabled,
message,
onApprove,
onReject,
}: {
disabled: boolean;
message: unknown;
onApprove?: (payload: SetupReportStructureApprovalPayload) => void | Promise<void>;
onReject?: (payload: SetupReportStructureApprovalPayload) => void | Promise<void>;
}) {
const payload = getSetupReportStructureApprovalPayload(message);
const [submitting, setSubmitting] = useState<"approve" | "reject" | null>(null);
if (!payload) {
return null;
}
const approvalPayload = payload;
const busy = disabled || submitting !== null;
const directions = approvalPayload.retrieval_directions ?? [];
const skills = approvalPayload.retrieval_skills ?? [];
async function run(action: "approve" | "reject") {
if (busy) {
return;
}
setSubmitting(action);
try {
if (action === "approve") {
await onApprove?.(approvalPayload);
} else {
await onReject?.(approvalPayload);
}
} finally {
setSubmitting(null);
}
}
return (
<div className="border-border bg-card text-card-foreground w-full rounded-lg border p-4 shadow-sm">
<div className="space-y-3">
<div>
<div className="text-muted-foreground text-xs font-medium">报告结构建议</div>
<div className="text-sm font-medium">确认后将应用到右侧表单,再点保存入库。</div>
</div>
{approvalPayload.title ? (
<div className="space-y-1">
<div className="text-muted-foreground text-xs">标题</div>
<p className="text-sm font-medium">{approvalPayload.title}</p>
</div>
) : null}
{approvalPayload.name ? (
<div className="space-y-1">
<div className="text-muted-foreground text-xs">描述</div>
<p className="text-sm leading-6">{approvalPayload.name}</p>
</div>
) : null}
<div className="flex flex-wrap gap-x-6 gap-y-1.5">
{approvalPayload.structure_mode ? (
<div className="space-y-0.5">
<div className="text-muted-foreground text-xs">结构约束</div>
<p className="text-sm font-medium">
{STRUCTURE_MODE_LABELS[approvalPayload.structure_mode] ?? approvalPayload.structure_mode}
</p>
</div>
) : null}
{directions.length > 0 ? (
<div className="space-y-0.5">
<div className="text-muted-foreground text-xs">检索方向</div>
<p className="text-sm font-medium">{directions.join("、")}</p>
</div>
) : null}
{skills.length > 0 ? (
<div className="space-y-0.5">
<div className="text-muted-foreground text-xs">检索来源</div>
<p className="text-sm font-medium">{skills.join("、")}</p>
</div>
) : null}
</div>
{approvalPayload.content ? (
<div className="space-y-1">
<div className="text-muted-foreground text-xs">报告大纲</div>
<pre className="bg-muted max-h-52 overflow-auto rounded-md p-3 text-xs whitespace-pre-wrap">
{approvalPayload.content}
</pre>
</div>
) : null}
</div>
<div className="mt-4 flex justify-end gap-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={busy || !onReject}
onClick={() => void run("reject")}
>
<XIcon className="h-4 w-4" />
忽略
</Button>
<Button
type="button"
size="sm"
disabled={busy || !onApprove}
onClick={() => void run("approve")}
>
<CheckIcon className="h-4 w-4" />
应用到表单
</Button>
</div>
</div>
);
}
function getClarificationPayload(message: unknown): ClarificationPayload | null { function getClarificationPayload(message: unknown): ClarificationPayload | null {
if (typeof message !== "object" || message === null) { if (typeof message !== "object" || message === null) {
return null; return null;
@@ -1,472 +0,0 @@
import {
BookOpenIcon,
ChevronDownIcon,
FileTextIcon,
Loader2Icon,
SearchIcon,
SparklesIcon,
} from "lucide-react";
import { useState } from "react";
import {
Conversation,
ConversationContent,
ConversationScrollButton,
} from "@/components/ai-elements/conversation";
import {
Message as AIElementMessage,
MessageContent as AIElementMessageContent,
} from "@/components/ai-elements/message";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import type { MessageResponseProps } from "@/components/ai-elements/message";
import type {
MultiRoundRagChatMessage,
MultiRoundRagRetrieval,
MultiRoundRagRound,
MultiRoundRagTrace,
} from "@/core/threads/use-multi-round-rag";
import { cn } from "@/lib/utils";
import { MarkdownContent } from "./markdown-content";
export function MultiRoundRagMessageList({
className,
messages,
isLoading,
paddingBottom = 160,
}: {
className?: string;
messages: MultiRoundRagChatMessage[];
isLoading: boolean;
paddingBottom?: number;
}) {
const rehypePlugins = useRehypeSplitWordsIntoSpans(isLoading);
return (
<Conversation className={cn("flex size-full flex-col justify-center", className)}>
<ConversationContent
className="mx-auto w-full max-w-(--container-width-lg) gap-8 pt-10"
>
{messages.map((message, index) => {
const isLastAssistant =
message.role === "assistant" && index === messages.length - 1;
return (
<AIElementMessage
key={message.id}
className="group/conversation-message relative w-full"
from={message.role === "user" ? "user" : "assistant"}
>
{message.role === "user" ? (
<AIElementMessageContent className="w-fit">
<p className="whitespace-pre-wrap text-[15px] leading-7">
{message.content}
</p>
</AIElementMessageContent>
) : (
<AIElementMessageContent className="w-full">
<MultiRoundRagAssistantBody
content={
typeof message.content === "string" ? message.content : ""
}
thinkingTrace={message.thinkingTrace}
isLoading={isLastAssistant && isLoading}
rehypePlugins={rehypePlugins}
/>
</AIElementMessageContent>
)}
</AIElementMessage>
);
})}
<div style={{ height: `${paddingBottom}px` }} />
</ConversationContent>
<ConversationScrollButton
className="pointer-events-auto z-20 size-9 shadow-md bottom-40"
aria-label="回到最新"
title="回到最新"
/>
</Conversation>
);
}
export function MultiRoundRagAssistantBody({
content,
thinkingTrace,
isLoading,
rehypePlugins,
}: {
content: string;
thinkingTrace?: MultiRoundRagTrace | null;
isLoading: boolean;
rehypePlugins: MessageResponseProps["rehypePlugins"];
}) {
const [selected, setSelected] = useState<MultiRoundRagRetrieval | null>(
null,
);
const trace = thinkingTrace;
const answer = trace?.finalAnswerMarkdown || content;
return (
<>
{trace && (
<MultiRoundRagTraceView
trace={trace}
isLoading={isLoading}
rehypePlugins={rehypePlugins}
onSelectRetrieval={setSelected}
/>
)}
<section className="mt-4">
<div className="text-foreground mb-2 text-sm font-medium">最终回答</div>
{answer ? (
<MarkdownContent
content={answer}
isLoading={isLoading}
rehypePlugins={rehypePlugins}
className="my-0 text-[15px] leading-7"
/>
) : (
<div className="text-muted-foreground flex items-center gap-2 text-sm">
<Loader2Icon className="size-4 animate-spin" />
正在生成思考过程与检索内容...
</div>
)}
</section>
<RetrievalDetailDialog
item={selected}
onOpenChange={(open) => {
if (!open) setSelected(null);
}}
/>
</>
);
}
function MultiRoundRagTraceView({
trace,
isLoading,
rehypePlugins,
onSelectRetrieval,
}: {
trace: MultiRoundRagTrace;
isLoading: boolean;
rehypePlugins: MessageResponseProps["rehypePlugins"];
onSelectRetrieval: (item: MultiRoundRagRetrieval) => void;
}) {
const [open, setOpen] = useState(!trace.thinkingComplete);
return (
<Collapsible
open={open}
onOpenChange={setOpen}
className="not-prose w-full min-w-0 max-w-5xl"
>
<CollapsibleTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:text-foreground flex w-full items-center gap-2 text-sm transition-colors"
>
{trace.thinkingComplete ? (
<SparklesIcon className="text-primary size-4 shrink-0" />
) : (
<Loader2Icon className="text-primary size-4 shrink-0 animate-spin" />
)}
<span>{trace.title || "思考过程"}</span>
<span className="text-muted-foreground/70 text-xs">
共 {trace.rounds.length} 轮推理与检索
</span>
<ChevronDownIcon
className={cn("ml-auto size-4 transition-transform", !open && "-rotate-90")}
/>
</button>
</CollapsibleTrigger>
<CollapsibleContent className="mt-3 space-y-3">
{trace.rounds.map((round, index) => (
<div
key={round.id}
className={cn("relative pl-5", index < trace.rounds.length - 1 && "pb-1")}
>
{index < trace.rounds.length - 1 && (
<span className="bg-primary/25 absolute bottom-0 left-[7px] top-8 w-px" />
)}
<span className="border-primary bg-background absolute left-0 top-4 size-3.5 rounded-full border-2" />
<MultiRoundRagRoundCard
index={index + 1}
round={round}
isLoading={isLoading}
isActiveRound={isLoading && index === trace.rounds.length - 1}
rehypePlugins={rehypePlugins}
onSelectRetrieval={onSelectRetrieval}
/>
</div>
))}
</CollapsibleContent>
</Collapsible>
);
}
function MultiRoundRagRoundCard({
index,
round,
isLoading,
isActiveRound,
rehypePlugins,
onSelectRetrieval,
}: {
index: number;
round: MultiRoundRagRound;
isLoading: boolean;
isActiveRound: boolean;
rehypePlugins: MessageResponseProps["rehypePlugins"];
onSelectRetrieval: (item: MultiRoundRagRetrieval) => void;
}) {
const query = round.query.trim();
const searching = Boolean(query && round.queryLoading);
const showQuery = Boolean(query);
const showRetrievals = showQuery || round.retrievals.length > 0;
const [open, setOpen] = useState(true);
return (
<Collapsible open={open} onOpenChange={setOpen}>
<article className="overflow-hidden rounded-lg border border-border/70 bg-background">
<CollapsibleTrigger asChild>
<button
type="button"
className="hover:bg-muted/40 flex min-h-11 w-full items-center gap-2 px-3 py-2.5 text-left text-sm transition-colors"
>
<span className="bg-primary/10 text-primary flex size-6 shrink-0 items-center justify-center rounded-full text-xs font-medium">
{index}
</span>
<span className="min-w-0 flex-1 truncate font-medium">{round.title}</span>
{searching ? (
<span className="text-primary inline-flex items-center gap-1 text-[11px]">
<Loader2Icon className="size-3 animate-spin" />
检索中
</span>
) : isActiveRound ? null : (
<span className="text-muted-foreground text-[11px]">已完成</span>
)}
<ChevronDownIcon
className={cn("text-muted-foreground size-4 shrink-0 transition-transform", !open && "-rotate-90")}
/>
</button>
</CollapsibleTrigger>
<CollapsibleContent className="border-border/60 space-y-3 border-t px-3 pb-3 pt-3">
{round.thoughtMarkdown && (
<section>
<div className="text-muted-foreground mb-1.5 flex items-center gap-2 text-sm font-medium">
<SparklesIcon className="size-4" />
思考内容
</div>
<MarkdownContent
content={round.thoughtMarkdown}
isLoading={isLoading}
rehypePlugins={rehypePlugins}
className="text-muted-foreground my-0 text-sm leading-6"
/>
</section>
)}
{showQuery && (
<div
className="border-primary/20 bg-primary/5 text-primary inline-flex max-w-full items-center gap-2 rounded-full border px-3 py-1.5"
aria-live={searching ? "polite" : undefined}
>
{searching ? (
<Loader2Icon className="size-3.5 shrink-0 animate-spin" />
) : (
<SearchIcon className="size-3.5 shrink-0" />
)}
<span className="text-primary/80 shrink-0 text-xs">
{round.queryTitle || "检索词"}
</span>
<span className="min-w-0 truncate text-xs font-medium">
{query}
</span>
</div>
)}
{showRetrievals && (
<section>
<div className="mb-2 flex items-center gap-2 text-sm font-medium">
<FileTextIcon className="text-muted-foreground size-4" />
检索内容
<span className="text-muted-foreground text-xs font-normal">
{round.retrievals.length} 条
</span>
</div>
{searching ? (
<div className="text-muted-foreground flex items-center gap-2 rounded-lg border border-border/70 px-3 py-3 text-sm">
<Loader2Icon className="text-primary size-4 animate-spin" />
正在召回相关内容...
</div>
) : (
<RetrievalCardList
items={round.retrievals}
onSelect={onSelectRetrieval}
/>
)}
</section>
)}
{(round.extractInfo || round.extractContent || round.extractLoading) && (
<section className="rounded-lg border border-border/70 px-3 py-3">
<div className="mb-2 flex items-center gap-2 text-sm font-medium">
<BookOpenIcon className="text-muted-foreground size-4" />
阅读内容
{round.extractLoading && <Loader2Icon className="text-primary size-3.5 animate-spin" />}
</div>
{round.extractInfo && (
<p className="text-muted-foreground text-sm leading-6">{round.extractInfo}</p>
)}
{round.extractContent && (
<p className="mt-2 text-sm leading-6 whitespace-pre-wrap">{round.extractContent}</p>
)}
</section>
)}
{round.textidContent && (
<section className="rounded-lg border border-border/70 px-3 py-3 text-sm leading-6 whitespace-pre-wrap">
{round.textidContent}
</section>
)}
</CollapsibleContent>
</article>
</Collapsible>
);
}
function RetrievalCardList({
items,
onSelect,
}: {
items: MultiRoundRagRetrieval[];
onSelect: (item: MultiRoundRagRetrieval) => void;
}) {
if (items.length === 0) {
return <p className="text-muted-foreground py-1 text-sm">本轮未召回相关资料。</p>;
}
return (
<div className="space-y-2">
{items.map((item, index) => (
<RetrievalCard
key={`${item.id ?? item.title}-${index}`}
item={item}
index={index + 1}
defaultOpen={index === 0}
onSelect={onSelect}
/>
))}
</div>
);
}
function RetrievalCard({
item,
index,
defaultOpen,
onSelect,
}: {
item: MultiRoundRagRetrieval;
index: number;
defaultOpen: boolean;
onSelect: (item: MultiRoundRagRetrieval) => void;
}) {
const [open, setOpen] = useState(defaultOpen);
const meta = retrievalMeta(item);
if (item.type === "user_behavior") {
return (
<div className="rounded-xl border border-border/70 px-3 py-2 text-sm">
<span className="text-muted-foreground mr-2 font-medium">{index}.</span>
{item.title}
</div>
);
}
return (
<Collapsible open={open} onOpenChange={setOpen}>
<div className="overflow-hidden rounded-xl border border-border/70 bg-background">
<CollapsibleTrigger asChild>
<button
type="button"
className="hover:bg-muted/40 flex min-h-11 w-full items-center gap-2 px-3 py-2.5 text-left transition-colors"
>
<span className="bg-muted text-muted-foreground flex size-5 shrink-0 items-center justify-center rounded-md text-[11px] font-medium">
{index}
</span>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium" title={item.title}>
{item.title}
</div>
{meta && (
<div className="text-muted-foreground truncate text-xs">{meta}</div>
)}
</div>
<ChevronDownIcon
className={cn("text-muted-foreground size-4 shrink-0 transition-transform", !open && "-rotate-90")}
/>
</button>
</CollapsibleTrigger>
<CollapsibleContent className="border-border/60 border-t px-3 pb-3 pt-2.5">
<button
type="button"
className="text-muted-foreground hover:text-foreground line-clamp-3 w-full text-left text-sm leading-6 whitespace-pre-wrap"
onClick={() => onSelect(item)}
>
{item.content || "暂无资料摘要"}
</button>
</CollapsibleContent>
</div>
</Collapsible>
);
}
function retrievalMeta(item: MultiRoundRagRetrieval): string {
if (item.type === "more") return `时间:${item.time || "-"}`;
if (item.type === "task") return `关键词:${item.keywords || "-"}`;
if (item.type === "hx") return `平台:${item.platform || "-"} 粉丝数:${item.fans ?? "-"}`;
if (
item.type === "taiwan_news" ||
item.type === "world_news" ||
item.type === "messaage_comment" ||
item.type === "america_news"
) {
return `平台:${item.platform || "-"}${item.comment_count ? ` 评论数:${item.comment_count}` : ""}`;
}
if (item.type === "get_time_data") return `时间:${item.time || "-"} 热度:${item.hot_num ?? "-"}`;
return [item.source, item.time].filter(Boolean).join(" · ");
}
function RetrievalDetailDialog({
item,
onOpenChange,
}: {
item: MultiRoundRagRetrieval | null;
onOpenChange: (open: boolean) => void;
}) {
const content = item?.content;
return (
<Dialog open={!!item} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[min(42rem,calc(100vh-2rem))] max-w-2xl overflow-hidden p-5 sm:max-w-2xl">
<DialogHeader className="pr-8">
<DialogTitle className="leading-relaxed">{item?.title || "引用资料"}</DialogTitle>
<DialogDescription className="space-y-1 text-xs">
{item?.time && <span className="block">时间:{item.time}</span>}
{item?.source && <span className="block">来源:{item.source}</span>}
</DialogDescription>
</DialogHeader>
<div className="bg-muted/50 max-h-[min(26rem,calc(100vh-16rem))] overflow-auto rounded-xl p-3 text-sm leading-7 whitespace-pre-wrap">
{content || "暂无引用内容"}
</div>
</DialogContent>
</Dialog>
);
}
@@ -50,19 +50,16 @@ export function ModeHoverGuide({
mode, mode,
children, children,
showTitle = true, showTitle = true,
tooltipContent,
}: { }: {
mode: AgentMode; mode: AgentMode;
children: React.ReactNode; children: React.ReactNode;
/** When true, tooltip shows "ModeName: Description". When false, only description. */ /** When true, tooltip shows "ModeName: Description". When false, only description. */
showTitle?: boolean; showTitle?: boolean;
/** Overrides the standard mode tooltip for page-specific execution modes. */
tooltipContent?: string;
}) { }) {
const { t } = useI18n(); const { t } = useI18n();
const label = t.inputBox[getModeLabelKey(mode)]; const label = t.inputBox[getModeLabelKey(mode)];
const description = t.inputBox[getModeDescriptionKey(mode)]; const description = t.inputBox[getModeDescriptionKey(mode)];
const content = tooltipContent ?? (showTitle ? `${label}: ${description}` : description); const content = showTitle ? `${label}: ${description}` : description;
return <Tooltip content={content}>{children}</Tooltip>; return <Tooltip content={content}>{children}</Tooltip>;
} }
@@ -66,7 +66,6 @@ import {
import type { AgentThread, AgentThreadState } from "@/core/threads/types"; import type { AgentThread, AgentThreadState } from "@/core/threads/types";
import { import {
isBootstrapThread, isBootstrapThread,
isHiddenFromRecentChats,
isThreadFavorite, isThreadFavorite,
isThreadPinned, isThreadPinned,
listPathOfThread, listPathOfThread,
@@ -194,9 +193,13 @@ export function RecentChatList({
); );
// 智能体创建(bootstrap)会话也展示在常用对话里(带机器人图标、点击回创建页); // 智能体创建(bootstrap)会话也展示在常用对话里(带机器人图标、点击回创建页);
// 排除调度 / 会商 / 报告结构&写作配置向导等系统会话。 // 仅排除调度 / 会商类系统会话。
const visibleThreads = sortThreadsPinnedFirst( const visibleThreads = sortThreadsPinnedFirst(
threads.filter((thread) => !isHiddenFromRecentChats(thread)), threads.filter(
(thread) =>
thread.metadata?.thread_type !== "scheduler" &&
thread.metadata?.thread_type !== "roundtable",
),
); );
if (visibleThreads.length === 0) { if (visibleThreads.length === 0) {
@@ -206,10 +209,7 @@ export function RecentChatList({
limit != null ? visibleThreads.slice(0, limit) : visibleThreads; limit != null ? visibleThreads.slice(0, limit) : visibleThreads;
return ( return (
<> <>
<SidebarGroup <SidebarGroup className="px-2 pt-3 mt-2 border-t border-sidebar-border/60">
className="px-2 pt-3 mt-2 border-t border-sidebar-border/60"
data-compact-guide="recent-chats"
>
<SidebarGroupLabel <SidebarGroupLabel
className={cn( className={cn(
"text-muted-foreground/70 px-3 mb-1 text-[10px] font-semibold tracking-[0.12em] uppercase select-none flex items-center justify-between transition-colors", "text-muted-foreground/70 px-3 mb-1 text-[10px] font-semibold tracking-[0.12em] uppercase select-none flex items-center justify-between transition-colors",
@@ -0,0 +1,267 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { ChevronDown, Loader2, MoreHorizontal, Pencil, Share2, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuAction,
SidebarMenuItem,
SidebarMenuButton,
} from "@/components/ui/sidebar";
import { ShareRoundtableDraftDialog } from "@/components/workspace/roundtable-draft-share-dialogs";
import { formatRelative } from "@/open-canvas/components/ai-writing/AIWritingHistoryDropdown";
import { useRoundtableDrafts } from "@/roundtable-planning/hooks/useRoundtableDrafts";
import type { DraftMeta } from "@/roundtable-planning/api/drafts";
import { isIMEComposing } from "@/lib/ime";
const ROUNDTABLE_PATH = "/page/workspace/roundtable/planning";
function openDraft(
draft: DraftMeta,
isOnPage: boolean,
router: ReturnType<typeof useRouter>,
) {
if (isOnPage) {
// 已在会商页面:直接派事件让页面加载该草稿(仿 AI 写作的 open-session)。
window.dispatchEvent(
new CustomEvent("roundtable:open-draft", { detail: draft.id }),
);
} else {
// 不在该页面:把草稿 id 暂存到 sessionStorage,跳转后由页面消费。
sessionStorage.setItem("roundtable:pending-draft", draft.id);
router.push(ROUNDTABLE_PATH);
}
}
/** 把草稿的后台作业状态 / 步骤映射成侧边栏小标签(仿页面内 HistoryDropdown)。 */
function StatusBadge({ draft }: { draft: DraftMeta }) {
if (draft.status === "running") {
return (
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-primary">
<Loader2 className="w-2.5 h-2.5 animate-spin" />
进行中
</span>
);
}
if (draft.status === "awaiting_input") {
return <span className="text-[10px] font-medium text-amber-500">待澄清</span>;
}
if (draft.status === "error") {
return <span className="text-[10px] font-medium text-rose-500">出错</span>;
}
// 非进行中/待澄清/出错时,展示本次会商所用业务链(无链条 → 自由模式)。
return (
<span className="text-[10px] font-medium text-muted-foreground">
{draft.chainTitle || "自由模式"}
</span>
);
}
export function RecentRoundtableList() {
const router = useRouter();
const pathname = usePathname();
const { drafts, loading, refresh, rename, remove } = useRoundtableDrafts();
const [collapsed, setCollapsed] = useState(
() => localStorage.getItem("sidebar:recent-roundtable-collapsed") === "true",
);
// 重命名对话框状态。
const [renameId, setRenameId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
// 分享对话框 —— 正在分享的草稿 id。
const [shareId, setShareId] = useState<string | null>(null);
const toggleCollapsed = () => {
const next = !collapsed;
setCollapsed(next);
localStorage.setItem("sidebar:recent-roundtable-collapsed", String(next));
};
useEffect(() => {
void refresh();
}, [refresh]);
const handleRenameSubmit = useCallback(async () => {
const id = renameId;
const title = renameValue.trim();
if (!id || !title) {
setRenameId(null);
return;
}
try {
await rename(id, title);
toast.success("已重命名");
} catch {
toast.error("重命名失败,请重试");
} finally {
setRenameId(null);
setRenameValue("");
}
}, [renameId, renameValue, rename]);
const handleDelete = useCallback(
async (draft: DraftMeta) => {
if (!window.confirm("确定删除这条会商记录吗?此操作不可恢复。")) return;
try {
await remove(draft.id);
toast.success("已删除会商记录");
} catch {
toast.error("删除失败,请重试");
}
},
[remove],
);
if (!loading && drafts.length === 0) return null;
const isOnPage = pathname === ROUNDTABLE_PATH;
return (
<>
<SidebarGroup className="px-2 pt-3 mt-0 border-t border-sidebar-border/60">
<SidebarGroupLabel
className="text-muted-foreground/70 px-3 mb-1 text-[10px] font-semibold tracking-[0.12em] uppercase cursor-pointer select-none flex items-center justify-between hover:text-muted-foreground transition-colors"
onClick={toggleCollapsed}
>
<span>多智能体会商</span>
<ChevronDown
className={`w-3 h-3 shrink-0 transition-transform duration-200 ${collapsed ? "-rotate-90" : ""}`}
/>
</SidebarGroupLabel>
<SidebarGroupContent
className={`group-data-[collapsible=icon]:pointer-events-none group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 overflow-hidden transition-all duration-200 ${
collapsed ? "max-h-0 opacity-0 pointer-events-none" : "max-h-[600px] opacity-100"
}`}
>
<SidebarMenu>
<div className="flex w-full flex-col gap-0.5">
{loading && drafts.length === 0 ? (
<p className="px-3 py-1 text-[12px] text-muted-foreground">加载中…</p>
) : (
drafts.slice(0, 10).map((draft) => (
<SidebarMenuItem key={draft.id} className="group/side-menu-item">
<SidebarMenuButton
className={
"rounded-lg h-auto py-1.5 px-3 text-muted-foreground " +
"hover:text-foreground hover:bg-sidebar-accent/60"
}
onClick={() => openDraft(draft, isOnPage, router)}
>
<div className="flex flex-col items-start min-w-0 w-full">
<span className="text-[13px] truncate w-full leading-snug">
{draft.title || "未命名草稿"}
</span>
<div className="flex items-center gap-1 mt-0.5">
<StatusBadge draft={draft} />
<span className="text-[10px] text-muted-foreground">·</span>
<span className="text-[10px] text-muted-foreground">
{formatRelative(draft.updatedAt)}
</span>
</div>
</div>
</SidebarMenuButton>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuAction
showOnHover
className="bg-background/50 hover:bg-background top-2"
>
<MoreHorizontal />
<span className="sr-only">更多</span>
</SidebarMenuAction>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-44 rounded-lg"
side="right"
align="start"
>
<DropdownMenuItem
onSelect={() => {
setRenameId(draft.id);
setRenameValue(draft.title || "");
}}
>
<Pencil className="text-muted-foreground" />
<span>重命名</span>
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => setShareId(draft.id)}>
<Share2 className="text-muted-foreground" />
<span>分享</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => void handleDelete(draft)}>
<Trash2 className="text-muted-foreground" />
<span>删除</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
))
)}
</div>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
{/* 重命名对话框 */}
<Dialog open={renameId !== null} onOpenChange={(o) => !o && setRenameId(null)}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>重命名会商</DialogTitle>
</DialogHeader>
<div className="py-4">
<Input
autoFocus
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
placeholder="输入新名称"
onKeyDown={(e) => {
if (e.key === "Enter" && !isIMEComposing(e)) {
e.preventDefault();
void handleRenameSubmit();
}
}}
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setRenameId(null)}>
取消
</Button>
<Button onClick={() => void handleRenameSubmit()}>保存</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 分享对话框 */}
<ShareRoundtableDraftDialog
draftId={shareId}
open={shareId !== null}
onOpenChange={(o) => {
if (!o) setShareId(null);
}}
/>
</>
);
}
Loaded 100 of 1233 files, more files were not shown because too many files have changed in this diff. Show more