diff --git a/.gitignore b/.gitignore index aee22e47..7f1164a1 100644 --- a/.gitignore +++ b/.gitignore @@ -90,12 +90,13 @@ 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/ - -.codegraph -codegraph.mdc +# 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 @@ -112,4 +113,4 @@ offline-backend-20260512/backend/uv.lock __pycache__/ # misc -.DS_Store \ No newline at end of file +.DS_Store diff --git a/AGENTS.md b/AGENTS.md index 69d4c914..d12c33ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,6 +79,7 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA: - **Routing**: React Router v7; top-level routes in `src/pages/PageRoutes.tsx`, workspace sub-routes in `src/pages/WorkspaceRoutes.tsx` - **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps) +- **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). - **菜单管理 (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-`). The static tree (`core/page-layout/sidebar-menu.ts`) stays the source of icons/routes; only per-node deltas (`label`/`disabled`/`parentId`/`sortOrder`) persist to the backend. Merge logic in `core/page-layout/menu-overrides.ts` (`applyMenuOverrides`, applied in `use-sidebar-menu.ts` after light-app injection, before role filter; disabling a node hides its whole subtree) — strict **3-level cap** (`wouldExceedDepth`). Client `strategy-components/api/menu-overrides.ts`. Backend: `/api/menu-overrides` (global/shared; open read, admin atomic replace-all). - **敏感词管理 (Sensitive Word Management)**: configures the **展示层脱敏映射** (原始词 → 替换词). **Gated on the username `lqq`** (not the admin role) — `getAccountDisplayName().toLowerCase() === "lqq"` (username = email `@` prefix, else `user_id`, same as the profile page); the dropdown entry, the route guard, and the page-level guard all use this check. `src/lib/desensitize.ts` ships a frozen seed map `SEED_DESENSITIZE_MAP` (the deployment seed) plus a live mutable `DESENSITIZE_MAP` (initialized from the seed so `desensitize()` works before any fetch). `DesensitizeWordsLoader` (mounted in `App.tsx` `AppProviders`) fetches `/api/sensitive-words` on startup and, if non-empty, calls `replaceDesensitizeMap(...)` to make the backend config the source of truth (empty/failed → keep seed). Page `SensitiveWordsPage.tsx` (route `/page/strategy/admin/sensitive-words`, opened from the 「敏感词管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`, present in **both** full + collapsed sidebar modes) lists/adds/edits/启停/deletes words and saves the **whole set atomically** (replace-all); a 「导入种子词」 button merges any missing `SEED_DESENSITIZE_MAP` entries into the editor. Client + hooks in `strategy-components/api/sensitive-words.ts` (`wordsToMap` folds enabled rows into the runtime map). Backend: `/api/sensitive-words` (global/shared; open read, write allowed for admin **or** the `lqq` account), mirroring 菜单管理's store shape. **侧边栏 + 导航栏 menu labels are desensitized** at the data source: `useSidebarMenuItems`/`useActiveThirdLevel` (`core/page-layout/use-sidebar-menu.ts`) map every node's `label` through a desensitizer built **directly from the `/api/sensitive-words` query** (`makeDesensitizer(wordsToMap(words))`, falling back to the global seed `desensitize` while empty) — this sidesteps the `replaceDesensitizeMap` effect-timing race. Only `label` is rewritten; `path`/`id`/`icon` are untouched so routing/highlight are unaffected. All nav surfaces (`page-sidebar.tsx`, `page-sidebar-dark.tsx`, `page-sidebar-v1.tsx`, `strategy-components/Header.tsx`, `PageRoutes.tsx`) consume this hook and are covered; `MenuManagementPage` uses the raw tree so admins still edit real labels. diff --git a/CLAUDE.md b/CLAUDE.md index 52c64c90..c0c669d4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,6 +80,7 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA: - **Routing**: React Router v7; top-level routes in `src/pages/PageRoutes.tsx`, workspace sub-routes in `src/pages/WorkspaceRoutes.tsx` - **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps) - **定时任务「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`. - **轻应用中心 (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-`). 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`. diff --git a/frontend-web/.env.development b/frontend-web/.env.development index ac6db962..3837c075 100644 --- a/frontend-web/.env.development +++ b/frontend-web/.env.development @@ -5,7 +5,7 @@ VITE_USE_REAL_DATA=true # 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(consumer 外网不可达时调试用)。 -VITE_MOCK_COP_TASK_DETAIL=flase +VITE_MOCK_COP_TASK_DETAIL=true # 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:true 走本地样例假数据(真实接口未就绪时调试用);联调通过后置 false。 VITE_MOCK_SQ_REPORT=true diff --git a/frontend-web/.env.example b/frontend-web/.env.example index 1b3d80bb..68e79a97 100644 --- a/frontend-web/.env.example +++ b/frontend-web/.env.example @@ -37,6 +37,10 @@ # 默认真实接口(未设/false);改成 true 时该接口走本地假数据(consumer 外网不可达时调试用)。 # 与 VITE_USE_REAL_DATA 独立。改后需重启 dev / 重新打包生效。 # VITE_MOCK_COP_TASK_DETAIL=false +# VITE_POSITION_ROUNDTABLE_DEMO_MODE=false +# true=免登录直达岗位分析,完全使用前端 JSON,不请求任何后台接口。 +# 仅限离线演示环境;生产环境请保持 false。 +# VITE_POSITION_ROUNDTABLE_STANDALONE_MODE=false # MaxKey 鉴权根地址(无界 onlineTicket 换 token) # VITE_AUTH_BASE_URL=https://auth.y.sit.4.cn @@ -50,4 +54,6 @@ # 可选 # VITE_CANVAS_LANGGRAPH_BASE_URL= # VITE_STATIC_WEBSITE_ONLY= +# 部署级紧凑导航:true 时固定收起工作台左侧栏,并隐藏换肤与全量/简洁模式切换。 +# VITE_FORCE_COLLAPSED_SIDEBAR=false # VITE_GITHUB_OAUTH_TOKEN= diff --git a/frontend-web/design-qa.md b/frontend-web/design-qa.md new file mode 100644 index 00000000..7260e9cb --- /dev/null +++ b/frontend-web/design-qa.md @@ -0,0 +1,46 @@ +**Comparison target** + +- Source visual truth (dark intelligent-agent list): `C:/Users/董宏凯/AppData/Local/Temp/codex-clipboard-75f6ce1c-cd70-4b8c-a80a-a3d100105c69.png` +- Additional source references: `C:/Users/董宏凯/AppData/Local/Temp/codex-clipboard-00567484-ba8a-4595-b386-52e1467ae9cf.png` (segmented switch), `C:/Users/董宏凯/AppData/Local/Temp/codex-clipboard-02808803-05ba-4f2c-be50-c72b484a9f06.png` (business-chain node card), `C:/Users/董宏凯/AppData/Local/Temp/codex-clipboard-adf38fec-7baf-4d01-9c73-bdbae94b774e.png` (business-chain selector) +- Implementation screenshots: `C:/Users/董宏凯/AppData/Local/Temp/position-roundtable-revised-light.png`, `C:/Users/董宏凯/AppData/Local/Temp/position-roundtable-revised-dark.png` +- Full-view comparison evidence: `C:/Users/董宏凯/AppData/Local/Temp/position-roundtable-revised-comparison.png` +- Viewport: 1280 × 720. Light route: `#/page/strategy/qa/position-roundtable`; dark embedded route: `#/page/strategy/qa/position-roundtable?embed=1&theme=dark`. +- State: local browser has no authenticated API session. The original intent API is invoked and reports `Authentication required`; business-chain and agent endpoints return no usable data. + +**Findings** + +- [P1] Populated agent and business-chain states cannot be compared yet. + Location: right agent list and non-planning-role chain diagram. + Evidence: reference images show populated cards and nodes; the implementation has `0 个` agents and no available business chain in the unauthenticated preview. + Impact: card density, selected-card indicator, chain node flow, and agent-detail transition cannot be truthfully verified against live data. + Fix: verify the route in an authenticated session with at least one public chain and tagged agents. + +**Open Questions** + +- The final business-chain stage arrangement is still pending product confirmation. The compact graph maps whatever stage configuration is returned, while intentionally omitting dependency-label text as requested. + +**Implementation Checklist** + +1. Left task panel is now display-only and retains its independent position-roundtable task adapter. +2. Business-chain selection uses the original roundtable card/radio/relationship-entry pattern. +3. Every position uses the original `useStep1Intent` interface and `Step1Panel` message list/input panel; only the position header changes. +4. The right switch now uses the exact `课题研究 / ai写作` segmented-control treatment (light gray track, white active state; dark blue glass equivalent). +5. The embedded layout widens the left panel to 360px and applies the deep-blue right-panel tokens used by the reference. +6. Other roles render a taller top-to-bottom card-node flow without dependency labels. The canvas supports mouse-drag panning, and each node retains only a name plus a single-line description. + +**Follow-up Polish** + +- [P3] If live content is unusually long, tune the compact flow node width or horizontal scrolling after seeing the production chain data. + +**Comparison history** + +- Iteration 1: task fields were editable and the right TDesign card tabs looked unlike the reference. Replaced the task form with display-only information and replaced the tabs with the existing `课题研究 / ai写作` segmented switch. +- Iteration 2: business-chain selection was a dropdown and the flow was vertical avatar chips. Replaced it with original-roundtable selection cards and compact business-chain configuration-style node cards with link lines but no dependency labels. +- Iteration 3: dark right-panel background differed from the supplied deep-blue reference. Applied the `#032650` / `#042b59` / `#2b8ffe` token family and captured the revised embedded dark state in the full-view comparison. +- Iteration 4: removed the custom disabled input from non-planning positions and reused the original roundtable input panel. Enlarged the left flow viewport, retained its connection lines, and removed node level/seat/status metadata. +- Iteration 5: converted the compact flow from left-to-right to top-to-bottom. Added mouse-drag panning and single-line description truncation; populated-chain visual QA remains blocked by the unauthenticated preview. +- Iteration 6: constrained the flow canvas to its card viewport, narrowed nodes from 190px to 158px, and realigned branch gaps plus connector anchors to prevent clipping and offset lines. + +**Final result** + +blocked diff --git a/frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md b/frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md new file mode 100644 index 00000000..35554757 --- /dev/null +++ b/frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md @@ -0,0 +1,507 @@ +# AI 写作「对话驱动写作台」实现方案(可落地版) + +> 需求:**复制**现有 AI 写作代码,新增一个独立页面(**原页面/原路由零改动**)。在新页面里 +> **大改交互流程**——去掉「素材收集 / 大纲规划 / 作家写作 / 编辑审核」四个阶段干预卡里的**输入框**, +> 只**保留原来的确认按钮**;在页面**底部新增一个统一的多行智能输入框**,具备**强意图理解**能力: +> 重新搜索、新增检索词、添加检索素材、重新规划大纲、按要求改大纲、提修改意见、审核意见、 +> 素材不足继续搜集、对写作内容提问……**覆盖现有全部交互甚至更多**。 +> +> 交互节奏不变:**一步一确认**——进行到某个专家阶段时,交互就针对该专家(阶段作用域); +> 用户可以**点原来的确认按钮**,也可以**在底部输入框里发「继续下一步」的意图**推进。 +> 意图**拿不准时**主动向用户**发起协助/澄清**,绝不盲目触发高代价动作(定稿 / 重搜等)。 + +本文是**实现指引**,落地时按第 9 节路线图分阶段推进。文中所有文件路径、符号名均对齐当前代码。 + +--- + +## 1. 现状梳理(改造地基) + +现有 AI 写作是一套**独立 LangGraph 子系统**(不是 lead_agent),前后端都已成型、可复用。 + +### 1.1 后端 `ai_writing` graph + +- 图工厂:`offline-backend-20260512/backend/packages/harness/deerflow/agents/ai_writing/graph.py` + (`make_ai_writing_graph`,registered as `assistant_id="ai_writing"`) +- 状态:`.../ai_writing/state.py`(`AIWritingState`) +- 四个「阶段大脑」节点: + +| 阶段 | 节点 | 文件 | +|------|------|------| +| 素材收集 | `researcher` | `nodes/researcher.py` | +| 大纲规划 | `writer_outline` | `nodes/writer_outline.py` | +| 作家写作 | `writer_draft` | `nodes/writer_draft.py` | +| 编辑审核 | `editor` | `nodes/editor.py` | + +- **五个暂停点**(`interrupt()`,`Command(resume=payload)` 续跑)——这是对话改造的核心可复用资产: + +| pause_point | 语义 | 现有 action | +|-------------|------|-------------| +| `material_confirm` | 素材确认 | `confirm` / `re_search` / `enable_skill_search` | +| `outline_confirm` | 大纲确认 | `confirm` / `re_outline` | +| `draft_confirm` | 草稿确认 | `to_editor` / `finalize` / `user_revise` | +| `review_confirm` | 编辑打回确认 | `accept_review` / `force_finalize` | +| `section_help` | 素材不足求助 | `section_help`(+`sectionDecisions`) | + +- resume 载荷(`UserInterventionPayload`,`types/ai-writing.ts`)字段:`action`、`approvedMaterialIds`、 + `userQuery`(自然语言补充检索)、`editedOutline`、`outlineFeedback`、`userRevisionNotes`、 + `overrideVerdict`、`selectedIssueIndices`、`sectionDecisions`。 + **协议已同时支持「自然语言 + 结构化 action」**——这是对话层能复用的关键。 + +> 结论:**状态机 / 流式 / 暂停·续跑协议 / 持久化都可复用**,无需重写引擎。改造本质是 +> 「把分散在干预卡里的输入框,换成一个底部智能输入框 + 意图路由层」,再把意图翻译回**现有 +> `action + payload`**;仅少量新意图(对内容提问、素材不足自动回退重搜、追加审核意见)需新增能力。 + +### 1.2 前端 `open-canvas` 子系统 + +- 主页面:`frontend-web/src/open-canvas/pages/AIWritingPage.tsx` + - 路由注册:`open-canvas/routes/OpenCanvasRoutes.tsx`(`/page/canvas/ai-writing/*`)、 + `pages/WorkspaceRoutes.tsx`(`/page/workspace/ai-writing/*`)、`pages/NotebookAIWritingPage.tsx` +- 状态机 + 流式:`contexts/AIWritingContext.tsx`(`useReducer` + LangGraph `useStream`,`assistantId:'ai_writing'`) +- 事件翻译 / reducer:`hooks/useAIWritingStream.ts` +- 类型:`types/ai-writing.ts` +- **左栏面板**:`components/ai-writing/AIWritingPanel.tsx`(时间线 + 干预卡 + 状态栏;idle 时挂启动表单) +- **要改造的输入 UI**(本次重点): + - 干预卡 `components/ai-writing/InterventionCard.tsx`:内含 + `MaterialConfirmCard`(素材:有 `MaterialsToolbar` 输入框)、 + `OutlineConfirmCard`(大纲:有 feedback textarea)、 + `DraftConfirmCard`(草稿:有「修改意见」textarea)、 + `ReviewConfirmCard`(审核:有「补充修改指令」textarea)、 + `SectionHelpCard`(素材不足:按钮组)。 + **每张卡里都既有输入框又有确认/动作按钮**——本次要**去掉输入框、保留按钮**。 + - 启动表单 `components/ai-writing/AIWritingForm.tsx`(idle 阶段的配置表单)——本次由底部输入框接管启动。 +- **已存在的对话原型**(可借鉴):`components/ai-writing/WritingSetupChat.tsx` + (`useThreadStream` 起 lead_agent 线程 + `setup_writing` 审批卡回填表单;仅管启动前配置,不直接复用)。 +- 底部输入框可直接复用 UI 组件:`@/components/ai-elements/prompt-input` + (`PromptInput` / `PromptInputTextarea` / `PromptInputSubmit` / `PromptInputFooter`,见 `WritingSetupChat`)。 + +--- + +## 2. 目标与范围 + +### 2.1 必须满足 + +1. **复制式新增**:新目录 / 新路由 / 新侧边栏入口,**旧页面、旧路由、旧组件零改动**(「初始的不用动」)。 +2. 页面**底部单一多行智能输入框**接管全流程交互;四个阶段干预卡里的**输入框全部移除**。 +3. **保留确认按钮**:每个阶段到达暂停点时,消息流里仍渲染**产物卡 + 原来的确认/动作按钮** + (素材「确认素材」、大纲「确认大纲」、草稿「让编辑审核 / 确认定稿」、审核「按编辑意见修改 / 强制定稿」、 + 素材不足的三选一按钮)。用户**点按钮**或**在底部输入框发自然语言意图**二选一均可推进。 +4. **强意图理解**:把用户自由文本准确路由到正确动作,**覆盖现有全部交互 + 更多**(见 3.2)。 +5. **阶段作用域**:意图解析必须知道「当前停在哪个专家阶段」,把同一句话按当前阶段翻译成对应 action。 +6. **素材不足自动回退重搜**:修改意见需要的信息现有素材没有时,先重搜补素材、补完自动继续原意图。 +7. **拿不准就协助**:低置信意图**不猜着执行**,走澄清追问(clarify)或用户协助。 +8. 保留右侧草稿实时预览(可编辑)与时间线 / 进度展示。 + +### 2.2 明确不做(本期) + +- 不改旧 `AIWritingPage` 及其 `AIWritingForm` / `InterventionCard`(这两个是要在**副本**里改的)。 +- 不替换 `ai_writing` graph 四个阶段大脑逻辑,不动五个暂停点 / checkpoint / 持久化。 +- 不引新状态管理库(继续 `useReducer` + `useStream`)。 + +### 2.3 复制策略(关键决策) + +「复制一份」= **复制会被大改的表现层组件**(页面 + 干预卡 + 面板),**复用不改的引擎层**: + +| 复制(新建副本,大改) | 复用(原样,不改;仅对 `types` 做**追加式**扩展) | +|------------------------|--------------------------------------------------| +| 新页面 `AIWritingChatPage.tsx` | `contexts/AIWritingContext.tsx`(状态机 + 流式) | +| 新面板 `WritingChatPanel.tsx`(消息流 + 底部输入框) | `hooks/useAIWritingStream.ts`(事件 → state) | +| 新消息卡 `chat-cards/*`(产物卡+确认按钮,**无输入框**) | `components/ai-writing/AIWritingDraftPanel.tsx`(右侧草稿预览) | +| 新意图客户端 `api/ai-writing-intent.ts` | 各流式展示子组件(`MaterialsCard`/`OutlineCard`/`ReviewCard`/`SkillStepsCard`…) | +| (可选)新 `contexts/WritingChatContext.tsx` 包一层「pending 意图 / 澄清态」 | `types/ai-writing.ts`(**只加字段不改旧字段**,保证旧页面不受影响) | + +> **不复用、也不改** 的三个「输入框组件」:`AIWritingForm` / `InterventionCard` / `WritingFormContext`—— +> 旧页面继续用它们,新页面完全不引用它们。这样「初始的不用动」得到硬保证。 +> +> 为什么复用 `AIWritingContext` 而不复制它?它**不含任何输入框 UI**,只是「状态机 + 与后端 graph 的 +> 流式桥」,复用它**不会改动旧页面的任何呈现**(旧页面照常在自己的 Provider 实例里跑)。复用能显著 +> 降低维护成本、避免两套引擎漂移。若要绝对物理隔离,也可整目录复制 `AIWritingContext` + +> `useAIWritingStream` 到新目录——**推荐先复用**,仅当后续需要给对话态加大量图内新协议时再分叉。 + +--- + +## 3. 核心设计 + +### 3.1 三层结构 + +``` +┌──────────────────────────────────────────────────────────────┐ +│ 对话 UI 层(新) WritingChatPanel │ +│ - 消息流:用户消息 + AI 阶段产物卡(含【保留的确认按钮】)+ 进度 │ +│ - 底部:统一多行智能输入框(唯一自由输入入口) │ +│ - 右侧:草稿实时预览(复用 AIWritingDraftPanel) │ +└───────────────┬──────────────────────────────────────────────┘ + │ 用户自然语言(+ 当前 status/pausePoint 上下文) + ▼ +┌──────────────────────────────────────────────────────────────┐ +│ 意图解析层(新,核心) POST /api/ai-writing/sessions/{id}/intent │ +│ 输出:{ intent, pausePoint, action, payload, │ +│ needResearch, researchQuery, answer, confidence, clarify }│ +└───────────────┬──────────────────────────────────────────────┘ + │ 结构化 action + payload + ▼ +┌──────────────────────────────────────────────────────────────┐ +│ 执行层(复用现有 AIWritingContext) │ +│ idle → startWriting(AIWritingRequest) │ +│ 暂停 → submitIntervention(UserInterventionPayload) │ +│ 问答 → 旁路回答(不改写作状态) │ +│ 素材不足 → 先重搜、缓存 pending、补完自动续跑 │ +└──────────────────────────────────────────────────────────────┘ +``` + +**设计原则**:意图解析层是「翻译官」——把自由文本翻译成**执行层已经懂的指令**。能复用 +`action + payload` 的绝不新造协议;确认按钮点击**直接走执行层**(不经意图层,零延迟、零误判)。 + +### 3.2 意图分类体系(覆盖全流程 + 更多) + +按「意图 → 触发时机(当前 status/pausePoint)→ 映射执行」组织,即意图解析引擎的目标 schema。 +**「甚至更多」** = G(问答)、H(控制)、以及 B/C/D/E 里的「素材不足自动回退重搜」。 + +#### A. 启动类(status = `idle`) +| 意图 | 用户说法示例 | 映射 | +|------|-------------|------| +| `start_writing` | 「写一篇关于新能源出口的深度分析,2000 字」 | 解析成 `AIWritingRequest` → `startWriting()` | +| `start_with_outline` | 「按这个大纲写:…」 | `AIWritingRequest.userOutline` | +| `start_imitate` | 「仿照这篇样文写…」 | `writingModeType='imitate'` + `sampleText` | + +#### B. 素材类(pausePoint = `material_confirm`) +| 意图 | 示例 | 映射 | +|------|------|------| +| `confirm_materials` | 「素材可以,继续 / 下一步」 | `{action:'confirm', approvedMaterialIds}` | +| `research_again` | 「重新搜索素材」 | `{action:'re_search'}`(无 userQuery=覆盖式重检) | +| `add_material`/`add_keyword` | 「再补点关于 X 的素材」「加个关键词 Y」 | `{action:'re_search', userQuery:'X/Y'}`(追加) | +| `select_materials` | 「只用第 1、3 条」 | `{action:'confirm', approvedMaterialIds:[…]}` | +| `drop_materials` | 「去掉第 2 条」 | 同上(反选后的子集) | + +#### C. 大纲类(pausePoint = `outline_confirm`) +| 意图 | 示例 | 映射 | +|------|------|------| +| `confirm_outline` | 「大纲 OK,开始写」 | `{action:'confirm'}` | +| `reoutline` | 「重写大纲」 | `{action:'re_outline'}`(feedback 可空) | +| `revise_outline` | 「第二章拆成两节」「调整顺序」 | `{action:'re_outline', outlineFeedback:自然语言}` | + +#### D. 写作 / 草稿类(pausePoint = `draft_confirm`) +| 意图 | 示例 | 映射 | +|------|------|------| +| `to_editor` | 「交给编辑审核」 | `{action:'to_editor'}` | +| `finalize` | 「就这样定稿」 | `{action:'finalize'}` **(高代价:低置信必澄清)** | +| `revise_draft` | 「第三段太啰嗦,精简」「补个 2024 案例」 | `{action:'user_revise', userRevisionNotes:意见}` | +| `rewrite_section` | 「重写第二章」 | `user_revise` + 章节定位写进 notes | +| `change_tone/style` | 「更口语一点 / 更正式」 | `user_revise` + notes | +| `apply_review`(若已有审核结果) | 「按编辑意见改」「只接受第 1、2 条」 | `{action:'user_revise', selectedIssueIndices:[…]}` | + +#### E. 编辑审核类(pausePoint = `review_confirm`) +| 意图 | 示例 | 映射 | +|------|------|------| +| `accept_review` | 「按编辑意见改」 | `{action:'accept_review', selectedIssueIndices}` | +| `partial_accept_review` | 「只接受第 1、2 条」 | `accept_review` + `selectedIssueIndices` 子集 | +| `add_review_opinion` | 「再补一条:核查数据准确性」 | `accept_review` + `userRevisionNotes`(并入补充指令,现协议已支持) | +| `force_finalize` | 「不改了,强制定稿」 | `{action:'force_finalize', overrideVerdict:true}` **(高代价:必澄清)** | + +#### F. 素材不足求助类(pausePoint = `section_help`) +| 意图 | 映射 | +|------|------| +| `section_supplement` | `{action:'section_help', sectionDecisions:[…'supplement']}` | +| `section_loose` | `sectionDecisions:[…'loose']` | +| `section_delete` | `sectionDecisions:[…'delete']` | + +#### G. 问答类(**新**;任意 status;旁路,不改写作状态) +| 意图 | 示例 | 映射 | +|------|------|------| +| `ask_about_content` | 「第二章讲了啥?」「为什么用这个论点?」 | 意图节点直接带回 `answer`,对话流渲染(见 5.4) | +| `ask_meta` | 「现在到哪步了?」「用了哪些素材?」 | 读当前 state 直接回答,不走图 | + +#### H. 控制类(**新 / 半新**) +| 意图 | 映射 | +|------|------| +| `next_step`(通用「继续/下一步」) | 按**当前 pausePoint** 映射到该阶段的默认确认(material/outline→`confirm`,draft→`to_editor`…;等价点确认按钮) | +| `restart_stage` | 重跑当前阶段(复用 `resumeWriting()` 空 command 续跑) | +| `run_background` | 转后台自动跑:`suspendAIWritingToBackground()` | +| `cancel` | `pauseWriting()`(`stream.stop()`) | +| `unknown/clarify` | 无法判定 → 反问澄清 / 用户协助(**防误触发硬指标**) | + +### 3.3 「素材不足自动重搜」判定与回退(用户强调点) + +触发:用户在**大纲/草稿/审核**阶段提出修改意见,但意见需要的信息现有素材里没有。 + +判定来源(组合): +1. **意图节点直接判**:把「素材摘要(keywords + 每条 title/source)」喂给意图 prompt,让它判断 + 「这条意见能否用现有素材满足」;不能 → `needResearch=true` + `researchQuery`。 +2. **执行阶段兜底**:`writer_draft` 严格模式已有 `blocked_sections` → `section_help` 暂停点, + 对话层把它翻译成「素材不足,是否重搜?」的追问。 + +回退动作(**首期纯前端实现,不动后端协议**):`needResearch=true` 时,前端把用户的修改 +`payload` 缓存为 `pendingIntent`,先 `submitIntervention({action:'re_search', userQuery:researchQuery})` +补素材;监听到新一轮 `material_confirm`(素材追加完成)后,**自动提交** `pendingIntent`。 +需处理「重搜期间用户又改主意」→ 允许覆盖 pending。 + +--- + +## 4. 意图解析引擎:方案与契约 + +**采用方案 A:后端 LLM 意图节点(独立 REST)**,叠加高频短句**规则快路径**优化。 + +理由:`needResearch` 判定需要**完整写作上下文**(素材/大纲/草稿),后端天然持有 checkpoint state; +与 `setup_writing` 一脉相承,离线模型选择策略统一;输出 schema 稳定、前端只消费。 + +### 4.1 后端入口 + +`app/gateway/routers/ai_writing.py` 新增: + +``` +POST /api/ai-writing/sessions/{session_id}/intent +Body: { text: string, status: string, pausePoint?: string } +Resp: IntentResult(见 4.3) +``` + +实现:读该 session 的 checkpoint state(素材摘要 / 大纲纲要 / 草稿字数·章节 / 审核意见)→ +用 `ai_writing` 配置模型(复用 `intent_parser.py` 同套 `create_chat_model` + `parse_json` + +模型容错 `_model_fallback`)解析 → 返回结构化契约。**不改图拓扑**。 + +新增 prompt:`agents/ai_writing/prompts/intent_router_prompts.py` +- 输入:用户文本、`current_status`/`pause_point`、素材摘要、大纲纲要、草稿字数+章节标题、审核意见列表。 +- 输出:严格 JSON(4.3 契约)。硬要求:**只在证据充分时给高 confidence,否则给 `clarify`**; + `finalize`/`force_finalize`/`re_search` 等高代价意图**必须**高置信才不澄清。 + +### 4.2 前端快路径(先跑规则,未命中再调后端) + +`api/ai-writing-intent.ts` 里对**当前 pausePoint** 做少量确定性短语命中,直接产出 payload,省一次往返: +- 「继续/下一步/确认/可以/ok/好的」→ 当前阶段默认 `confirm`(draft 阶段=`to_editor`)。 +- 「重新搜索/重搜」(material)→ `re_search`。「重写大纲」(outline)→ `re_outline`。 +- 「定稿/强制定稿」→ **不进快路径**(高代价,一律走后端 + 可能澄清)。 +- 命中即执行;未命中 → 调后端 `intent` 接口。 + +### 4.3 意图解析输出契约 + +```jsonc +{ + "intent": "revise_draft", // 见 3.2 分类 + "pausePoint": "draft_confirm", // 需要 resume 时;否则 null + "action": "user_revise", // 映射到现有 action + "payload": { // 直接可喂 submitIntervention 的字段(camelCase) + "userRevisionNotes": "第三段精简,并补一个 2024 年的案例" + }, + "needResearch": true, // 素材是否不足 + "researchQuery": "2024 行业案例", // needResearch 时的检索意图 + "answer": null, // 问答类意图的直接回答(旁路) + "confidence": 0.86, + "clarify": null // 低置信时的反问话术(非空则不执行、只追问) +} +``` + +前端消费顺序: +1. `answer` 非空 → 对话流渲染回答(问答旁路,不动写作状态)。 +2. `clarify` 非空 **或** `confidence < 阈值(建议 0.6)` → 渲染反问气泡,等用户澄清(**防误触发**)。 +3. `needResearch=true` → 缓存 `pendingIntent=payload`,先重搜,收到新素材后自动提交。 +4. 否则 → `idle` 走 `startWriting(...)`;暂停态走 `submitIntervention({action, ...payload})`。 + +--- + +## 5. 前端改造方案 + +### 5.1 新页面与路由(复制式) + +- 新页面:`open-canvas/pages/AIWritingChatPage.tsx` + (骨架照抄 `AIWritingPage.tsx` 的 Provider 包裹与左右分栏;左栏换成 `WritingChatPanel`,右栏仍 + `AIWritingDraftPanel`;idle 不再挂 `AIWritingForm`,改由底部输入框启动)。 +- 路由注册(**新增,不动旧行**): + - `open-canvas/routes/OpenCanvasRoutes.tsx` 加 `path="ai-writing-chat/*"`。 + - 侧边栏 `core/page-layout/sidebar-menu.ts`:在 `qa-research` 旁新增 + `{ id:"qa-research-chat", label:"AI写作(对话版)", icon:FileText, path:"/page/canvas/ai-writing-chat" }`。 + (或先不加、内部灰度直链验证。) + +### 5.2 新面板 `WritingChatPanel.tsx`(左栏主体) + +职责 = 消息流容器 + 底部输入框,替代 `AIWritingPanel` 里的「时间线 + InterventionCard + 状态栏」。 +复用 `useAIWriting()` 读 state / 调 `startWriting` / `submitIntervention` / `pauseWriting` / +`suspendAIWritingToBackground`。 + +消息流渲染(把 `ProgressEvent` / 阶段产物适配成消息卡,复用现有展示子组件): +- 运行中:`research_progress`/`outline_chunk`/`draft_chunk`/`review_chunk` → 进度 / 流式卡 + (复用 `SkillStepsCard`/`OutlineStreamingView`/`DraftGeneratingView`/`ReviewStreamingView` 的展示部分)。 +- 到达暂停点:渲染 **产物卡 + 保留的确认按钮**(见 5.3),不再有输入框。 +- 用户消息、AI 澄清追问、问答回答:普通气泡。 + +底部输入框:直接复用 `@/components/ai-elements/prompt-input`(`PromptInput`+`PromptInputTextarea`+ +`PromptInputSubmit`),Enter 发送、Shift+Enter 换行;发送时读当前 `state.status`/`currentPause?.pausePoint` +交给意图路由(见 5.5)。运行中(非暂停点)可禁用发送或转「排队/提示当前在生成」。 + +### 5.3 新消息卡 `chat-cards/*`(**保留按钮、去掉输入框**) + +把 `InterventionCard.tsx` 的五张卡各复制一份到 `open-canvas/components/ai-writing-chat/chat-cards/`, +**删掉其中的 textarea / MaterialsToolbar 输入部分,保留产物展示 + 确认/动作按钮**: + +| 新卡 | 展示(复用) | 保留的按钮 | 删除的输入 | +|------|-------------|-----------|-----------| +| `MaterialConfirmChatCard` | `MaterialsCard`(勾选保留)+ `SkillStepsCard` | 「确认素材,规划大纲」「重新搜索」 | `MaterialsToolbar` 的 userQuery 输入框 | +| `OutlineConfirmChatCard` | `OutlineCard`(可点标题微调保留) | 「确认大纲,开始写作」 | feedback textarea + 发送 | +| `DraftConfirmChatCard` | `ReviewCard`(若有审核,勾选保留) | 「按编辑审核意见修改」「让编辑继续审核」「确认定稿」 | 「修改意见」textarea | +| `ReviewConfirmChatCard` | `ReviewCard`(勾选保留) | 「按编辑意见修改」「强制定稿」 | 「补充修改指令」textarea | +| `SectionHelpChatCard` | 章节 + 三选一按钮组 | 三选一 + 「提交并继续」 | (本就无自由输入,原样保留) | + +> 勾选态(素材/审核意见)**保留**——它是「点按钮」路径的一部分,不算自由输入框。用户想用自然语言 +> 「只用第 1、3 条」也能走底部输入框(意图层产出 `approvedMaterialIds`/`selectedIssueIndices`)。 +> 按钮点击 **直接调 `submitIntervention`**,与旧卡完全一致,零改动风险。 + +### 5.4 问答旁路(新能力) + +「对写作内容提问」不改写作 state。首期**轻量实现**:意图节点检出 `ask_*` 时读 state 直接带回 `answer`, +前端在消息流渲染为普通 AI 气泡即可(一次调用出答案)。完整版(后续)可另起只读 lead_agent 线程注入 +草稿/大纲作背景,类似 `WritingSetupChat` 的 `useThreadStream`。 + +### 5.5 交互流程(对话版)串起来 + +1. **空闲**:底部输入「写一篇关于 X 的深度分析,2000 字」→ 意图 `start_writing` → 组 `AIWritingRequest` + → `startWriting()`。(缺关键字段时先 `clarify` 追问字数/读者/类型。) +2. **运行中**:进度/流式卡渲染。 +3. **到暂停点**:渲染产物卡 + 按钮 + 一句提示「你可以点上面的按钮,或直接说:确认继续 / 补充素材 / 改大纲…」。 + - **点按钮** → 直接 `submitIntervention`(旧逻辑)。 + - **发文字** → `resolveIntent(text, status, pausePoint)`(先快路径、后后端)→ 按 4.3 消费。 +4. **问答**:任意时刻提问 → 旁路 `answer`,不打断写作。 +5. **素材不足**:`needResearch` 或 `section_help` → 追问/执行「重搜 → 自动续跑 pending 意图」。 +6. **拿不准**:`clarify`/低置信 → 反问气泡,不执行。 + +### 5.6 pending 意图 & 澄清态(新增本地状态) + +在 `WritingChatPanel`(或新 `WritingChatContext`)维护: +- `pendingIntent: UserInterventionPayload | null` —— 素材不足重搜完成后自动提交。 +- `awaitingClarify: { originalText: string } | null` —— 澄清态,用户下一句与上一句拼接再解析。 +- pending 生命周期:设置 → 提交 `re_search` → 监听 reducer 里新一轮 `awaiting_material_confirm` + (`state.status` 从 `researching` 回到 `awaiting_material_confirm`)→ 自动 `submitIntervention(pending)` → 清空。 + +--- + +## 6. 后端改造方案 + +### 6.1 意图解析入口(新增,唯一后端改动主体) + +- `app/gateway/routers/ai_writing.py`:新增 `POST /sessions/{id}/intent`(见 4.1)。 + 读 checkpoint state 用 `app.state.checkpointer` + `make_ai_writing_graph().aget_state(...)` + (参照 `ai_writing_job_executor.py` 的读法)取素材/大纲/草稿/审核摘要。 +- `agents/ai_writing/prompts/intent_router_prompts.py`:新增意图 prompt(见 4.1)。 +- 复用 `nodes/intent_parser.py` 的模型创建 / `parse_json` / `_model_fallback` 容错。 + +### 6.2 不需要改的部分 + +- 四个阶段大脑节点、五个暂停点、checkpoint、StreamBridge、持久化、sessions/transcript REST——**全不动**。 +- 「素材不足自动续跑」「问答旁路」首期都在**前端 / 意图节点**实现,**不扩 resume 协议**。 + +### 6.3 可选增强(阶段 3,按需) + +- `add_review_opinion` 完整版:`review_confirm` resume 增字段 `extra_review_notes`(首期已用现有 + `userRevisionNotes` 降级承载,够用)。 +- `resume_intent` 后端化(把「重搜完自动续跑」搬到后端,减少前端状态机复杂度)。 +- undo / 回退到上一暂停点(依赖 checkpoint 回滚)。 + +--- + +## 7. 数据流时序(改稿 + 素材不足自动重搜) + +``` +用户(draft_confirm 暂停): "第三段补个2024年的行业案例" + │ 底部输入框 → resolveIntent(text, status='awaiting_draft_confirm', pausePoint='draft_confirm') + ▼ POST /api/ai-writing/sessions/{id}/intent { text, status, pausePoint } +后端: 读 state(素材摘要) + LLM 解析 + │ 返回 { intent:revise_draft, action:user_revise, + │ payload:{userRevisionNotes:"第三段…补2024案例"}, + │ needResearch:true, researchQuery:"2024 行业案例", confidence:0.9 } + ▼ +前端: needResearch=true → pendingIntent = payload + │ submitIntervention({action:'re_search', userQuery:"2024 行业案例"}) + ▼ LangGraph resume → researcher 追加素材 → status 回到 awaiting_material_confirm +前端: 监听到新一轮素材确认 → 自动提交 pendingIntent + │ submitIntervention({action:'user_revise', userRevisionNotes:"第三段…补2024案例"}) + ▼ writer_draft 用新素材改稿 → draft_chunk… → draft_ready → draft_confirm +前端: 消息流展示新草稿卡 + "已按你的意见改写并补充了 2024 案例" +``` + +--- + +## 8. 关键实现细节与坑 + +1. **阶段作用域**:`resolveIntent` 必须带 `state.currentPause?.pausePoint` + `state.status`—— + 同一句「重新来」在 material 是重搜、在 outline 是重写大纲。`AIWritingContext` 已有这两个字段,直接读。 +2. **确认按钮零改动**:新卡的按钮 `onClick` 原样调 `submitIntervention(payload)`,与旧卡逐字一致, + 风险最低;**只删输入框**。 +3. **防误触发**:低置信(<0.6)或 `clarify` 非空一律追问;`finalize`/`force_finalize`/`re_search` + 即使命中也要求高置信,否则澄清。绝不盲目定稿/覆盖重搜。 +4. **pending 意图队列**:素材不足是「先插重搜、再回原意图」,用 5.6 的小状态机;重搜完成前允许覆盖 pending。 +5. **问答不污染 transcript**:问答/澄清消息在前端标记 `kind:'qa'|'clarify'`,与写作进度事件区分( + `AIWritingContext` 的 transcript 只存 progressEvents/completedInterventions,问答气泡是纯前端消息, + 默认不入 transcript,避免历史回看错乱)。 +6. **流式产物→消息卡**:复用 `OutlineStreamingView`/`DraftGeneratingView`/`ReviewStreamingView`/ + `SkillStepsCard` 的**展示部分**,套进消息容器,不重写渲染。 +7. **右侧草稿预览**:`AIWritingDraftPanel` + `DraftSync` 原样复用(`DraftSync` 依据 status/markdown + 同步右侧画布)。 +8. **离线内网**:意图模型走 `config.yaml → ai_writing` 配置模型;检索仍走技能/内网 ES,不联网。 +9. **模型选择透传**:`submitIntervention` 的 resume 已把 `state.request?.modelName` 一并回传(见 + `AIWritingContext`),新页面沿用即可。 +10. **旧页面隔离验证**:改完后回归旧 `/page/canvas/ai-writing` 与 `/page/workspace/ai-writing`、 + 笔记本嵌入页,确认零变化(新代码不 import 旧的 `AIWritingForm`/`InterventionCard`/`WritingFormContext`)。 + +--- + +## 9. 分阶段实施路线图 + +**阶段 0 — 骨架(不含意图)** +- 复制 `AIWritingChatPage` + 注册新路由 + 侧边栏入口;复用 `AIWritingContext`/`useStream`/`DraftPanel`。 +- 复制五张 `chat-cards`(删输入框、留按钮);底部输入框先只做 idle 直发 `start_writing` + (文本原样当 `userIntent`,其余字段取默认)+ 暂停点靠按钮推进。端到端跑通。 + +**阶段 1 — 意图解析(核心)** +- 后端 `POST /sessions/{id}/intent` + `intent_router_prompts.py`,返回 4.3 契约。 +- 前端 `api/ai-writing-intent.ts`(快路径 + 后端)接入 `WritingChatPanel`,覆盖 A~F 类意图。 +- 低置信 `clarify` 澄清态(5.6)。 + +**阶段 2 — 问答旁路 + 素材不足自动重搜** +- G 类问答(意图节点直接带 `answer`)。 +- `needResearch` + pending 意图机制(前端实现重搜后自动续跑,5.6)。 + +**阶段 3 — 增强(按需)** +- `add_review_opinion` 扩协议、`resume_intent` 后端化、undo/回退、完整问答只读线程。 + +**阶段 4 — 打磨** +- 消息卡视觉、历史回看(transcript)、后台挂起入口、灰度到侧边栏。 + +--- + +## 10. 关键文件清单(落地对照) + +### 新增(前端) +- `open-canvas/pages/AIWritingChatPage.tsx` — 新页面(复制 `AIWritingPage` 骨架改造) +- `open-canvas/components/ai-writing-chat/WritingChatPanel.tsx` — 消息流 + 底部输入框 +- `open-canvas/components/ai-writing-chat/chat-cards/{MaterialConfirmChatCard,OutlineConfirmChatCard,DraftConfirmChatCard,ReviewConfirmChatCard,SectionHelpChatCard}.tsx` — 保留按钮、去掉输入框 +- `open-canvas/components/ai-writing-chat/progressToMessage.ts` — `ProgressEvent` → 消息卡适配 +- `open-canvas/api/ai-writing-intent.ts` — 意图解析客户端(快路径 + `POST …/intent`) +- (可选)`open-canvas/contexts/WritingChatContext.tsx` — pending 意图 / 澄清态 + +### 修改(前端,仅追加,不动旧逻辑) +- `open-canvas/routes/OpenCanvasRoutes.tsx` — 加一条 `ai-writing-chat/*` 路由 +- `core/page-layout/sidebar-menu.ts` — 加一个侧边栏入口(可选) +- `open-canvas/types/ai-writing.ts` — **仅追加** `IntentResult` 等新类型,不改旧字段 + +### 新增(后端) +- `app/gateway/routers/ai_writing.py` — 加 `POST /sessions/{id}/intent` +- `agents/ai_writing/prompts/intent_router_prompts.py` — 意图 prompt +- `tests/test_ai_writing_intent.py` — 意图接口单测(TDD 强制) + +### 复用(不改) +- `open-canvas/contexts/AIWritingContext.tsx`、`hooks/useAIWritingStream.ts` +- `open-canvas/components/ai-writing/{AIWritingDraftPanel,DraftSync,MaterialsCard,OutlineCard,ReviewCard,SkillStepsCard,OutlineStreamingView,DraftGeneratingView,ReviewStreamingView}.tsx` +- `agents/ai_writing/graph.py`、四个阶段节点、五个暂停点、`nodes/intent_parser.py` + +### 绝不动(保证「初始的不用动」) +- `open-canvas/pages/AIWritingPage.tsx` 及其引用的 + `components/ai-writing/{AIWritingForm,InterventionCard}.tsx`、`contexts/WritingFormContext.tsx` +- 旧路由 `/page/canvas/ai-writing`、`/page/workspace/ai-writing`、笔记本嵌入页 + +--- + +## 11. 待确认(默认取值已给出,可直接推进) + +1. 意图引擎:**后端 LLM 节点(方案 A)+ 前端短句快路径** —— 默认采用。 +2. `AIWritingContext` / `useAIWritingStream`:**复用**(不物理复制)——默认采用;需绝对隔离可改为复制。 +3. 新页面入口:**侧边栏新增「AI写作(对话版)」** —— 默认加;若要先灰度可只留直链。 +4. 「素材不足自动重搜」:**首期前端 pending 续跑**(不动后端 resume 协议)——默认采用。 +5. 问答旁路:**首期意图节点直接带 `answer`** —— 默认采用。 + +> 以上默认按「A + 复用引擎 + 侧边栏入口 + 前端 pending + 意图节点带答案」推进,如需调整请指出。 diff --git a/frontend-web/docs/ai-writing-对话驱动改造方案.md b/frontend-web/docs/ai-writing-对话驱动改造方案.md new file mode 100644 index 00000000..6a3f6032 --- /dev/null +++ b/frontend-web/docs/ai-writing-对话驱动改造方案.md @@ -0,0 +1,454 @@ +# AI 写作「对话驱动 + 意图解析」改造方案 + +> 目标:在**不动现有 AI 写作页面**的前提下,新建一个「对话驱动」的写作工作台。 +> 去掉素材收集 / 大纲规划 / 作家写作 / 编辑审核各阶段**分散的输入框/表单**, +> 用**底部一个统一的智能输入框**接管全流程交互;该输入框具备**强意图解析**能力, +> 能准确识别用户意图(重新搜索、加素材、加关键词、重写大纲、按要求改大纲、改写作、 +> 改编辑、提编辑意见、对写作内容提问……),并在**素材不足**时自动回退去重新检索素材。 + +本文只做**方案与实现指引**,不含代码改动。落地时按第 9 节的路线图分阶段推进。 + +--- + +## 1. 现状梳理(改造的地基) + +现有 AI 写作是一套**独立的 LangGraph 子系统**(不是 lead_agent),前后端都已成型。 + +### 1.1 后端:`ai_writing` graph + +- 图工厂:`offline-backend-20260512/backend/packages/harness/deerflow/agents/ai_writing/graph.py` +- 状态:`.../agents/ai_writing/state.py`(`AIWritingState` + `UserInterventionPayload`) +- 注册:`offline-backend-20260512/backend/langgraph.json` → `assistant_id = "ai_writing"` +- 执行:与 lead agent **共用** RunManager + StreamBridge + checkpointer(`app/gateway/services.py` 里 `assistant_id=="ai_writing"` 分发到 `make_ai_writing_graph`) + +节点拓扑(实际): + +``` +sample_analyzer → intent_parser → researcher + → [cond] pause_material | writer_draft + → writer_outline → pause_outline + → writer_draft → [cond] pause_section_help | pause_draft | END + → editor → [cond] pause_draft | pause_review + → pause_review → END | writer_draft +``` + +四个「阶段大脑」节点: + +| 阶段 | 节点 | 文件 | +|------|------|------| +| 素材收集 | `researcher` | `nodes/researcher.py` | +| 大纲规划 | `writer_outline` | `nodes/writer_outline.py` | +| 作家写作 | `writer_draft` | `nodes/writer_draft.py` | +| 编辑审核 | `editor` | `nodes/editor.py` | + +五个**暂停点**(`interrupt()`,靠 `Command(resume=payload)` 续跑): + +| pause_point | 语义 | 可用 action(现有) | +|-------------|------|---------------------| +| `material_confirm` | 素材确认 | `confirm` / `re_search` / `supplement_search` / `enable_skill_search` | +| `outline_confirm` | 大纲确认 | `confirm` / `re_outline` | +| `draft_confirm` | 草稿确认 | `to_editor` / `finalize` / `user_revise` / `custom_revise` | +| `review_confirm` | 编辑打回确认 | `accept_review` / `force_finalize` | +| `section_help` | 素材不足求助 | `supplement` / `loose` / `delete` | + +> resume 载荷字段(`UserInterventionPayload`):`action`、`approved_material_ids`、 +> `extra_keywords`、`user_query`(自然语言补充检索)、`edited_outline`、`outline_feedback`、 +> `user_revision_notes`、`override_verdict`、`selected_issue_indices`、`section_decisions`。 +> **关键点**:现有协议已经支持「自然语言 + 结构化 action」,这是对话改造的核心可复用资产。 + +REST(业务元数据,非图执行):`app/gateway/routers/ai_writing.py`,前缀 `/api/ai-writing` +(sessions CRUD、transcript 保存、article-types、后台挂起 `/background` + `/progress` 等)。 + +持久化:`ai_writing_sessions` 表(`transcript` 为 `PortableLongText`) ++ `ai_writing_article_types`(`deerflow/persistence/...`)。 + +配置:`config.yaml → ai_writing`(`keyword_model`、`rank_model`、`max_materials`、 +`use_builtin_agents.{researcher,outliner,writer,editor}` 等)。 + +### 1.2 前端:`open-canvas` 子系统 + +- 主页面:`frontend-web/src/open-canvas/pages/AIWritingPage.tsx` +- 路由:`/page/canvas/ai-writing`、`/page/workspace/ai-writing` +- 状态机:`contexts/AIWritingContext.tsx`(`useReducer` + LangGraph `useStream`) +- 事件翻译/reducer:`hooks/useAIWritingStream.ts` +- 类型:`types/ai-writing.ts`(`WritingStatus`、`ProgressEvent`、`UserInterventionPayload`、`AIWritingRequest`…) +- 流式:LangGraph `useStream`,`assistantId: 'ai_writing'`,`streamMode: ['values','updates','custom','messages-tuple']` +- **要去掉的输入 UI**(改造重点): + - 启动表单 `components/ai-writing/AIWritingForm.tsx` + `WritingFormContext` + - 阶段暂停输入 `components/ai-writing/InterventionCard.tsx`(素材/大纲/草稿/审核四套内嵌表单) +- **已存在的对话原型**:`components/ai-writing/WritingSetupChat.tsx` + (用 `useThreadStream` 起一条 lead_agent 线程 + `setup_writing` 工具审批卡回填表单)—— + 这是「对话 → 结构化配置」的现成范式,可借鉴但**不直接复用**(它只管启动前配置)。 + +### 1.3 结论 + +- **状态机、流式、暂停/续跑协议、持久化都可复用**,无需重写引擎。 +- 改造本质 = **把「分散表单」换成「一个对话输入框 + 意图路由层」**, + 再把意图映射回**现有的 `action + payload`**(大部分场景), + 少量新意图(如「对内容提问」「素材不足自动重搜」)需要**新增协议/节点**。 + +--- + +## 2. 目标与范围 + +### 2.1 必须满足 + +1. 新页面/新路由,**旧页面零改动**(用户要求「初始的不用动」)。 +2. 底部**单一对话输入框**控制所有阶段交互,移除各阶段独立输入框。 +3. **强意图解析**:准确识别用户自然语言意图并路由到正确动作,覆盖全流程 + 更多。 +4. 用户给修改意见后,**若现有素材不足以满足要求 → 自动/建议重新检索素材**再继续。 +5. 保留右侧草稿实时预览(可编辑)与时间线/进度展示。 + +### 2.2 明确不做(本期) + +- 不改旧 `AIWritingPage` 及其表单/干预卡组件。 +- 不替换底层 `ai_writing` graph 的四个阶段大脑逻辑(只加意图层与少量新协议)。 +- 不引入新的状态管理库(继续 `useReducer` + `useStream`)。 + +--- + +## 3. 核心设计 + +### 3.1 总体思路:三层结构 + +``` +┌─────────────────────────────────────────────────────────┐ +│ 对话 UI 层(新) │ +│ - 左:消息流(用户消息 + AI 阶段产物卡片 + 进度) │ +│ - 底:统一智能输入框(唯一交互入口) │ +│ - 右:草稿实时预览(复用 AIWritingDraftPanel) │ +└───────────────┬─────────────────────────────────────────┘ + │ 用户自然语言 + ▼ +┌─────────────────────────────────────────────────────────┐ +│ 意图解析层(新,核心) │ +│ - 输入:用户文本 + 当前 WritingStatus + 上下文快照 │ +│ - 输出:{ intent, action, payload, needResearch, ... } │ +└───────────────┬─────────────────────────────────────────┘ + │ 结构化 action + payload + ▼ +┌─────────────────────────────────────────────────────────┐ +│ 执行层(复用现有) │ +│ - 空闲态:startWriting(AIWritingRequest) │ +│ - 暂停态:submitIntervention(UserInterventionPayload) │ +│ - 运行中:stream.stop() → 续跑 / 新命令 │ +│ - 提问态:旁路问答(不改写作状态) │ +└─────────────────────────────────────────────────────────┘ +``` + +**设计原则**:意图解析层是「翻译官」——把自由文本翻译成**现有执行层已经懂的指令**。 +能复用 `action + payload` 的绝不新造协议;只有现有协议表达不了的才扩展。 + +### 3.2 意图分类体系(覆盖用户全流程 + 更多) + +按「意图类别 → 触发时机(当前 status)→ 映射到的执行」组织。这是**意图解析引擎的目标 schema**。 + +#### A. 启动类(status = idle) + +| 意图 | 说明 | 映射 | +|------|------|------| +| `start_writing` | 用户描述要写什么 | 解析成 `AIWritingRequest` → `startWriting()` | +| `start_with_outline` | 用户自带大纲 | `AIWritingRequest.userOutline` | +| `start_imitate` | 样文仿写 | `writingModeType=imitate` + 样文 | + +#### B. 素材类(status ≈ awaiting_material_confirm / 运行中) + +| 意图 | 用户说法示例 | 映射 | +|------|-------------|------| +| `confirm_materials` | 「素材可以,继续」 | `material_confirm` + `confirm`(可带勾选 ids) | +| `research_again` | 「重新搜索素材」 | `material_confirm` + `re_search` | +| `add_material` / `add_keyword` | 「补充关于 X 的素材」「加个关键词 Y」 | `material_confirm` + `supplement_search`,`user_query`=X/Y | +| `use_skill_search` | 「用 XX 技能查」 | `material_confirm` + `enable_skill_search`,`user_query`=技能/来源 | +| `select_materials` | 「只用第 1、3 条」 | `confirm` + `approved_material_ids` 子集 | +| `drop_materials` | 「去掉第 2 条」 | 同上,反选后 `approved_material_ids` | + +#### C. 大纲类(status ≈ awaiting_outline_confirm) + +| 意图 | 示例 | 映射 | +|------|------|------| +| `confirm_outline` | 「大纲 OK」 | `outline_confirm` + `confirm` | +| `reoutline` | 「重写大纲」 | `outline_confirm` + `re_outline`(`outline_feedback` 可空) | +| `revise_outline` | 「第二章拆成两节」「调整顺序」 | `re_outline` + `outline_feedback`=自然语言 | +| `edit_outline_manually` | 用户直接给出新大纲文本 | 解析成 `edited_outline` | + +#### D. 写作/草稿类(status ≈ awaiting_draft_confirm / writing_draft) + +| 意图 | 示例 | 映射 | +|------|------|------| +| `to_editor` | 「交给编辑审核」 | `draft_confirm` + `to_editor` | +| `finalize` | 「就这样定稿」 | `draft_confirm` + `finalize` | +| `revise_draft` | 「第三段太啰嗦,精简」「补个案例」 | `draft_confirm` + `user_revise`,`user_revision_notes`=意见 | +| `rewrite_section` | 「重写第二章」 | `user_revise` + 定位信息(章节)写进 notes | +| `change_tone/style` | 「更口语一点」 | `user_revise` + notes | + +#### E. 编辑审核类(status ≈ awaiting_review_confirm) + +| 意图 | 示例 | 映射 | +|------|------|------| +| `accept_review` | 「按编辑意见改」 | `review_confirm` + `accept_review`(可带 `selected_issue_indices`) | +| `partial_accept_review` | 「只接受第 1、2 条意见」 | `accept_review` + `selected_issue_indices` | +| `force_finalize` | 「不改了,强制定稿」 | `review_confirm` + `force_finalize` | +| `add_review_opinion` | 「你再补一条:检查数据准确性」 | 追加自定义审核意见(见 5.3 扩展) | + +#### F. 素材不足求助类(status = awaiting_section_help) + +| 意图 | 映射 | +|------|------| +| `section_supplement` | `section_help` + `supplement`(去重搜) | +| `section_loose` | `section_help` + `loose`(放宽续写) | +| `section_delete` | `section_help` + `delete` | + +#### G. 问答类(**新**,任意 status,旁路,不改写作状态) + +| 意图 | 示例 | 映射 | +|------|------|------| +| `ask_about_content` | 「第二章讲了啥?」「为什么用这个论点?」 | 旁路问答(见 5.4) | +| `ask_meta` | 「现在进行到哪一步?」「用了哪些素材?」 | 读当前 state 直接回答,不走图 | + +#### H. 控制类(**新/半新**) + +| 意图 | 映射 | +|------|------| +| `undo/back` | 回退到上一暂停点(依赖 checkpoint 回滚,见 8.4) | +| `restart_stage` | 重跑当前阶段 | +| `run_background` | 挂起后台自动跑 → `POST /sessions/{id}/background` | +| `cancel` | `stream.stop()` | +| `unknown/clarify` | 无法判定 → 反问澄清(对话追问,不误触发) | + +> **覆盖「甚至更多」**:G(问答)、H(控制)、以及 D/E 里「素材不足自动回退重搜」都是超出原表单能力的新增。 + +### 3.3 「素材不足自动重搜」的判定与回退(用户强调的重点) + +触发场景:用户在**大纲/草稿/审核**阶段提出修改意见,但意见需要的**信息现有素材里没有**。 + +判定放在**意图解析层**输出一个 `needResearch: boolean` + `researchQuery`,判定来源二选一(推荐组合): + +1. **意图解析 LLM 直接判断**:把「当前素材摘要(keywords + 每条 title/来源)」喂给意图解析 + prompt,让它判断「用户这条意见能否用现有素材满足」。不能 → `needResearch=true` 并给出检索词。 +2. **执行阶段兜底**:`writer_draft` 严格模式本就有 `blocked_sections` → `pause_section_help`, + 这是**已有的**素材不足闸门;对话层把它翻译成「素材不足,是否重新检索?」的对话追问。 + +回退动作:`needResearch=true` 时,先走 `material_confirm + supplement_search`(或新的 +「带目标的重搜」协议,见 8.3)补素材,**补完自动继续**用户原本的修改意图(需要在对话层 +记住「pending 修改意图」,重搜结束后再提交)。 + +--- + +## 4. 意图解析引擎:方案对比与推荐 + +| 方案 | 做法 | 优点 | 缺点 | +|------|------|------|------| +| **A. 后端 LLM 意图节点**(推荐) | 新增 `/api/ai-writing/intent/parse`(或图内新节点),后端用 LLM 把 `{text, status, contextSnapshot}` → 结构化意图 JSON | 能吃到完整 state(素材/大纲/草稿);可判 `needResearch`;prompt/模型集中可控;离线内网可用配置模型 | 多一次网络往返(可接受,交互本就等待) | +| B. 前端调模型接口分类 | 前端直接调现有 `/api/models` 聊天做分类 | 少一层后端改动 | 前端难拿全后端 state 快照;prompt 分散;鉴权/模型选择复杂 | +| C. 规则 + LLM 混合 | 常见短句走关键词规则快路径,兜底 LLM | 快、省 token | 规则易漏、维护成本高;中文表达多样命中率低 | + +**推荐 A(后端 LLM 意图节点)**,并在其上**叠加 C 的快路径**做优化(如「确认/继续/定稿」等 +高频短句先走轻量规则,未命中再调 LLM)。理由: + +- 意图判定需要**当前写作上下文**(尤其 `needResearch` 判定),后端天然持有 state/checkpoint。 +- 与现有「配置助手 `setup_writing`」一脉相承,模型选择/离线部署策略统一。 +- 输出 schema 稳定,前端只消费结构化结果,UI 简单。 + +### 4.1 意图解析输出契约(建议) + +```jsonc +{ + "intent": "revise_draft", // 见第 3.2 分类 + "pausePoint": "draft_confirm", // 若需 resume;否则 null + "action": "user_revise", // 映射到现有 action;新意图可为新值 + "payload": { // 直接可喂 submitIntervention 的字段 + "userRevisionNotes": "第三段精简,并补一个 2024 年的案例" + }, + "needResearch": true, // 素材是否不足 + "researchQuery": "2024 行业案例", // needResearch 时的检索意图 + "answer": null, // 问答类意图的直接回答(旁路) + "confidence": 0.86, + "clarify": null // 低置信时的反问话术 +} +``` + +前端拿到后: +- `answer` 非空 → 直接在对话流渲染回答(问答旁路,不动写作状态)。 +- `clarify` 非空或 `confidence` 低 → 渲染反问,等用户澄清(**防误触发**)。 +- `needResearch=true` → 先重搜,缓存 `payload` 为 pending,重搜完再提交。 +- 否则 → `submitIntervention({action, ...payload})` 或 `startWriting(...)`。 + +--- + +## 5. 前端改造方案 + +### 5.1 新页面与路由 + +- 新目录:`frontend-web/src/open-canvas/pages/AIWritingChatPage.tsx`(或 `conversational/` 子目录)。 +- 新路由:`/page/canvas/ai-writing-chat`(在 `OpenCanvasRoutes.tsx` 注册;旧路由保留)。 +- 侧边栏:`sidebar-menu.ts` 加一个入口(如「AI 写作(对话版)」),或先不加、内部灰度。 + +### 5.2 复用 vs 新建 + +| 复用(尽量不改) | 新建 | +|------------------|------| +| `AIWritingContext` / `useAIWritingStream`(状态机 + 流式) | 统一对话输入框组件 `WritingChatComposer` | +| `AIWritingDraftPanel`(右侧草稿预览) | 消息流容器 `WritingChatThread`(渲染阶段产物为消息卡片) | +| `types/ai-writing.ts`(按需扩展) | 意图解析客户端 `api/ai-writing-intent.ts` | +| `ProgressEvent` 事件模型 | 阶段产物 → 消息卡片的适配器 `progressToMessage.ts` | +| 会话持久化 REST | 「pending 意图」暂存逻辑(重搜后续跑) | + +**不复用**:`AIWritingForm` / `WritingFormContext` / `InterventionCard`(这三个就是要去掉的表单)。 + +### 5.3 交互流程(对话版) + +1. 空闲:用户在底部输入「写一篇关于 X 的深度分析,2000 字」→ 意图解析 `start_writing` + → 组装 `AIWritingRequest` → `startWriting()`。 +2. 运行中:`ProgressEvent`(`research_progress`/`outline_chunk`/`draft_chunk`…) + → 适配成消息流里的**进度卡片/流式卡片**(复用现有流式视图组件的展示部分)。 +3. 到达暂停点:不再弹 `InterventionCard`,而是在消息流里展示**阶段产物卡片** + (素材列表 / 大纲 / 草稿 / 审核结果)+ 一句提示「你可以说:确认继续 / 补充素材 / 改大纲…」。 + 用户下一句自然语言 → 意图解析 → `submitIntervention`。 +4. 问答:任意时刻用户提问 → 旁路回答,不打断写作状态。 +5. 素材不足:意图解析 `needResearch` 或后端 `section_help` → 对话追问「素材不足,帮你重搜?」 + → 确认后重搜 → 自动续跑 pending 意图。 + +### 5.4 问答旁路(新能力) + +「对写作内容提问」不应改写作 state。两种实现: + +- **轻量(推荐先做)**:意图解析节点直接带回 `answer`(后端能读 state,一次调用出答案)。 +- **完整**:新起一条**只读**问答线程(lead_agent,context 注入当前草稿/大纲作为背景), + 类似 `WritingSetupChat` 的 `useThreadStream` 模式,但只读不回填。 + +--- + +## 6. 后端改造方案 + +### 6.1 意图解析入口(二选一) + +- **方案 A1(推荐,独立 REST)**:`app/gateway/routers/ai_writing.py` 新增 + `POST /api/ai-writing/sessions/{id}/intent`,入参 `{text}`,后端读该 session 的 + checkpoint state(素材/大纲/草稿摘要)+ 用 `ai_writing` 配置模型解析,返回第 4.1 的契约。 + - 好处:不改图拓扑;前端拿到结果后再决定调 `startWriting`/`submitIntervention`。 +- 方案 A2(图内节点):在图里加 `conversation_router` 节点。改动大、状态耦合高,**不推荐**首期。 + +### 6.2 意图解析 prompt + +新增 `agents/ai_writing/prompts/intent_router_prompts.py`(或复用/扩展 `intent_parser.py`): +- 输入:用户文本、`current_status`、素材摘要(keywords + 每条 title/source)、大纲纲要、 + 草稿字数/章节标题、审核意见列表。 +- 输出:严格 JSON(第 4.1 契约)。要求模型**只在证据充分时给高 confidence**, + 否则给 `clarify`(防误触发是硬指标)。 + +### 6.3 「带目标的重搜」协议扩展(可选增强) + +现有 `supplement_search` 用 `user_query` 追加检索。为支持「改稿意见 → 缺素材 → 重搜 → 自动续跑」, +建议在 `material_confirm` 的 resume 里新增可选字段 `resume_intent`(重搜完成后要自动执行的原始意图)。 +- 前端也可**纯前端**实现(重搜完成事件回来后再自动提交缓存的 pending payload),**首期优先前端实现**,避免动后端协议。 + +### 6.4 追加自定义审核意见(`add_review_opinion`) + +`editor`/`pause_review` 目前只接受「接受/强制定稿」。要支持「你再补一条审核意见」, +需在 `review_confirm` resume 里接受 `extra_review_notes`,`editor` 或 `writer_draft` +修订时并入。首期可先降级为 `user_revise` + notes(把用户的审核诉求当作改稿意见), +**完整版**再扩协议。 + +### 6.5 不需要改的部分 + +- 四个阶段大脑节点(researcher/writer_outline/writer_draft/editor)逻辑不动。 +- 五个暂停点、checkpoint、StreamBridge、持久化不动。 + +--- + +## 7. 数据流时序(改稿 + 素材不足自动重搜) + +``` +用户: "第三段补个2024年的行业案例" + │ + ▼ POST /api/ai-writing/sessions/{id}/intent { text } +后端: 读 state(素材摘要) + LLM 解析 + │ 返回 { intent:revise_draft, action:user_revise, + │ payload:{userRevisionNotes:...}, + │ needResearch:true, researchQuery:"2024 行业案例" } + ▼ +前端: needResearch=true → 缓存 pending=payload + │ 对话追问/直接执行: submitIntervention(material_confirm, supplement_search, user_query="2024 行业案例") + ▼ LangGraph resume → researcher 补素材 → materials_ready +前端: 收到新素材 → 自动提交 pending + │ submitIntervention(draft_confirm, user_revise, userRevisionNotes=...) + ▼ writer_draft 用新素材改稿 → draft_chunk... → draft_ready → pause_draft +前端: 消息流展示新草稿 + "已按你的意见改写并补充了案例" +``` + +--- + +## 8. 关键实现细节与坑 + +1. **暂停态识别**:对话层必须知道「现在停在哪个 pause_point」才能正确映射 action。 + `AIWritingContext` 已有 `currentPause`/`status`,直接读。 +2. **防误触发**:低置信意图一律走 `clarify` 反问,绝不猜着执行(尤其 `finalize`/`re_search` 这种代价大的)。 +3. **pending 意图队列**:素材不足重搜是「先插一段、再回原意图」,需要一个小状态机记住 pending, + 并处理「重搜后用户又改主意」的情况(重搜完成前允许覆盖 pending)。 +4. **回退/undo(H 类)**:依赖 checkpoint 回滚,`runtime/runs/worker.py` 有 `rollback` 概念, + 首期可**不做**或只做「重跑当前阶段」。 +5. **问答旁路不污染 transcript**:问答消息可标记 `kind:'qa'`,与写作进度事件区分持久化。 +6. **流式产物→消息卡片**:复用现有 `OutlineStreamingView`/`DraftStreamingPreview` 等的**展示部分**, + 套进消息气泡即可,不必重写渲染。 +7. **离线内网**:意图解析模型走 `config.yaml → ai_writing` 里的配置模型;检索仍走技能/内网 ES, + 不联网(与现有并行席位「禁 web_search」的离线策略一致)。 + +--- + +## 9. 分阶段实施路线图 + +**阶段 0 — 骨架(不含意图)** +- 新路由 + 新页面 `AIWritingChatPage`,复用 `AIWritingContext`/`useStream`/`DraftPanel`。 +- 底部对话框先只做「空闲 `start_writing` + 暂停点固定按钮」跑通端到端(相当于把干预卡换成消息)。 + +**阶段 1 — 意图解析(核心)** +- 后端 `POST /sessions/{id}/intent` + intent prompt,返回第 4.1 契约。 +- 前端接入:自然语言 → 意图 → `startWriting`/`submitIntervention`,覆盖 A~F 类意图。 +- 加高频短句规则快路径 + 低置信 `clarify` 反问。 + +**阶段 2 — 问答旁路 + 素材不足自动重搜** +- G 类问答(先用 intent 节点直接带 `answer`)。 +- `needResearch` + pending 意图机制(前端实现重搜后自动续跑)。 + +**阶段 3 — 增强协议(按需)** +- `add_review_opinion` 扩 `review_confirm` 协议、`resume_intent` 后端化、undo/回退。 + +**阶段 4 — 打磨** +- 消息卡片视觉、历史回看(复用 transcript)、后台挂起入口、灰度到侧边栏。 + +--- + +## 10. 关键文件清单(落地时对照) + +### 新增(前端) +- `open-canvas/pages/AIWritingChatPage.tsx` — 新页面 +- `open-canvas/components/ai-writing-chat/WritingChatComposer.tsx` — 统一输入框 +- `open-canvas/components/ai-writing-chat/WritingChatThread.tsx` — 消息流 +- `open-canvas/components/ai-writing-chat/progressToMessage.ts` — 事件→消息适配 +- `open-canvas/api/ai-writing-intent.ts` — 意图解析客户端 +- 路由注册:`open-canvas/OpenCanvasRoutes.tsx`(+ 可选 `sidebar-menu.ts`) + +### 新增(后端) +- `app/gateway/routers/ai_writing.py` — 加 `POST /sessions/{id}/intent` +- `agents/ai_writing/prompts/intent_router_prompts.py` — 意图 prompt +- (阶段 3)`state.py` / `nodes/*` — 扩 `review_confirm`、`resume_intent` + +### 复用(尽量不改) +- `open-canvas/contexts/AIWritingContext.tsx`、`hooks/useAIWritingStream.ts` +- `open-canvas/components/ai-writing/AIWritingDraftPanel.tsx` 及各流式展示组件 +- `open-canvas/types/ai-writing.ts`(按需扩字段) +- `agents/ai_writing/graph.py`、四个阶段节点、五个暂停点 + +### 不动 +- 旧 `open-canvas/pages/AIWritingPage.tsx` 及 `AIWritingForm`/`WritingFormContext`/`InterventionCard` + +--- + +## 11. 待确认 + +1. 意图解析引擎是否采用**推荐的方案 A(后端 LLM 节点)**? +2. 新页面是**独立入口**(侧边栏新增)还是先**内部灰度**(仅直链)? +3. 「素材不足自动重搜」首期是否接受**前端实现 pending 续跑**(不动后端 resume 协议)? +4. 问答旁路首期是否接受**意图节点直接带答案**(不新起只读线程)? + +> 以上默认按「A / 内部灰度 / 前端 pending / 意图节点带答案」推进,如需调整请指出。 diff --git a/frontend-web/docs/position-roundtable-delivery-workflow-plan.md b/frontend-web/docs/position-roundtable-delivery-workflow-plan.md new file mode 100644 index 00000000..62503eed --- /dev/null +++ b/frontend-web/docs/position-roundtable-delivery-workflow-plan.md @@ -0,0 +1,362 @@ +# 岗位会商交付闭环与内置智能体实现计划 + +> 页面:`/page/strategy/qa/position-roundtable` +> +> 目标:在现有岗位会商基础上补齐“产物交付、查看、驳回、方案总结、行动规划”的完整闭环,同时继续保持原多智能体会商页面不受影响。 + +## 实施核对(2026-07-21) + +本计划已按“岗位会商独立路由、无总控、各席位直接问答”的边界完成第一轮闭环。实际流程调整为: + +```text +任务信息 → 情报分析岗识别并确认意图 → 启动校验并冻结业务链 +→ 分阶段席位直接问答/交付 Markdown → 全部有效交付 +→ 方案总结智能体(roundtable-summary)→ 行动规划智能体(position-action-planner) +→ 可随时返回交付产物驳回 → 后续阶段及内置产物级联失效 → 重做后重新收口 +``` + +- [x] 情报意图、业务链选择、席位岗位归属和席位智能体配置均在启动前校验;启动后保存业务链快照。 +- [x] 普通席位直接调用各自分配的智能体,并注入任务、意图及已完成上游席位的问答/产物;不经过总控智能体。 +- [x] 普通席位必须在 `outputs` 中交付 Markdown 才会完成;情报分析岗以确认的结构化意图完成为准。 +- [x] 节点、交付卡片、流程图和大图弹窗均展示 `locked / ready / running / done / rejected / stale / error` 状态,并可回看节点会话和产物。 +- [x] 驳回要求标题和理由;当前节点转为 `rejected`,后续阶段按依赖转为 `stale/locked`,总结和行动规划同时失效,历史内容保留可查看。 +- [x] 被驳回或失效的普通席位必须写入一份**新的或已改写** Markdown 才能再次完成;单纯继续问答且没有新交付不会误使下游产物失效。 +- [x] 方案总结复用 `roundtable-summary` 的真实流式线程;行动规划新增 `position-action-planner`,强制输出 Markdown 报告和 `action-plan-subtasks.json`。 +- [x] 两个内置智能体的线程、产物快照和来源节点版本栅栏均持久化;流式期间若上游版本变化,旧运行不能覆盖最新状态。 +- [x] 右侧“交付产物”可查看内置节点结果、继续同一线程问答/修改交付,并在打开 Markdown 沙箱时自动收起右栏。 + +设计收敛:当前版本以节点的 `artifact_manifest`、`latest_answer`、版本、驳回记录及 Session 内置快照作为唯一事实来源,已能覆盖统一产物卡片和级联逻辑,因此不新增重复的 `position_roundtable_deliverables` 表。若后续需要“单个文件独立驳回、跨会话检索或完整版本对比”,再将清单归一化为独立产物表,避免现在的双写一致性风险。 + +## 数据持久化与灾难恢复(2026-07-23) + +岗位会商现在使用“两层持久化”,两层职责不同: + +1. LangGraph checkpoint/thread 是智能体继续推理与流式问答的执行源。 +2. `position_roundtable_sessions` / `position_roundtable_nodes` 是页面历史的数据库恢复源。 + +数据库恢复源会保存: + +- 情报分析岗完整消息、步骤时间线和未发送输入草稿; +- 每个业务链岗位的完整消息和未发送输入草稿; +- 方案总结、行动规划两个收口智能体的完整消息和未发送输入草稿; +- 已确认意图、冻结任务与业务链快照、节点状态、版本、驳回记录; +- Markdown / JSON 等文本产物正文(单文件最多 400 万字符)和文件元数据。 + +因此即使线上重启后 checkpoint 或沙箱 outputs 卷丢失,历史页仍能从数据库展示对话与产物正文,后续收口智能体也能继续读取数据库中的有效上游交付。新任务在意图识别开始前就会创建 Session,用户不必等到“启动业务链”才获得持久化保护。历史下拉支持删除,删除会显式清理 Session 与全部节点恢复快照,不依赖 SQLite 外键开关。 + +对应迁移:`20260723_05_position_roundtable_conversations.py`。部署时必须执行到 Alembic head。 + +## 0. 核心结论 + +- 方案总结智能体建议复用现有会商里的 `roundtable-summary` 能力,但不要直接搬整套 Step 3 页面流程。 + - 可复用:内置智能体 ID、总结报告 prompt 组织方式、Markdown 报告产物、流式对话、报告续问与文件预览能力。 + - 需要改造:输入材料从“总控共识 + 各席位交付”改成“任务信息 + 意图结果 + 已通过的岗位产物 + 业务链快照”,并把结果存到岗位会商 Session 下。 +- 行动规划智能体建议作为新的内置智能体新增。 + - 输入:方案总结报告、各岗位最终有效产物、业务链阶段信息、任务意图。 + - 输出:行动规划报告、结构化子任务清单。 +- 这个模式仍然不需要总控智能体。情报分析岗负责意图识别,业务链节点直接调用各自配置的智能体,最终再由内置总结/规划智能体收口。 +- 驳回不删除历史内容,只改变“当前有效版本”的状态;被驳回节点和后续节点需要重新交付,既保留可追溯性,也方便后续返回查看。 + +## 1. 目标业务流程 + +1. 情报分析岗进入页面,查看任务信息并完成意图识别。 +2. 用户点击“确认意图并启动业务链”。 +3. 启动前做校验: + - 未选择业务链:提示“请先选择业务链”。 + - 业务链存在未配置岗位的席位:提示并引导去业务链配置页。 + - 业务链席位缺少智能体:提示具体席位名称。 + - 意图尚未完成:提示先完成任务意图识别。 +4. 校验通过后冻结业务链快照,初始化岗位会商节点。 +5. 各岗位只对分配给本岗位的智能体进行问答。 +6. 节点问答完成后形成交付产物,右侧产物卡片显示“已完成 / 未完成 / 进行中 / 已驳回 / 已失效”。 +7. 左侧流程图显示各节点状态,节点可点击查看该节点对话与产物。 +8. 流程图右上角提供“查看”按钮,打开弹窗展示更完整的业务链流程图。 +9. 当业务链中所有岗位产物都处于有效已交付状态后,开放“方案总结”。 +10. 方案总结完成后开放“行动规划”。 +11. 即使进入方案总结或行动规划,用户仍可返回产物列表执行驳回。 +12. 若驳回早期阶段产物,后续阶段产物、方案总结、行动规划都一起失效并回到待重新完成状态。 + +## 2. 状态设计 + +### 2.1 节点状态 + +现有节点状态需要扩展或映射为更贴近页面的展示状态: + +| 展示状态 | 建议内部状态 | 含义 | +| --- | --- | --- | +| 未完成 | `ready` / `locked` / `rejected` | 尚未有效交付,或被驳回后等待重做 | +| 进行中 | `running` | 当前智能体正在回答或产物正在生成 | +| 已完成 | `done` | 当前节点已有有效交付 | +| 已失效 | `stale` | 上游被更新或驳回,当前结果不可作为最终材料 | +| 异常 | `error` | 生成或保存失败 | + +建议新增 `rejected` 状态,便于区分“从未完成”和“被驳回后待重做”。如果第一轮想少改后端,也可以先用 `ready + rejection_record` 表示被驳回。 + +### 2.2 产物状态 + +产物状态建议独立于节点状态保存,因为一个节点可能同时有回答文本和多个文件产物。 + +| 状态 | 含义 | +| --- | --- | +| `pending` | 还没有交付 | +| `running` | 正在生成 | +| `delivered` | 已交付且当前有效 | +| `rejected` | 被用户驳回 | +| `stale` | 受上游驳回或重做影响,已经失效 | + +### 2.3 内置收口节点 + +在流程图中把两个内置节点追加到业务链末尾: + +1. `builtin:summary`:方案总结智能体。 +2. `builtin:action-plan`:行动规划智能体。 + +这两个节点不属于普通业务链席位,但要和普通节点一样显示状态、支持点击查看结果。 + +## 3. 数据模型调整 + +### 3.1 Session 扩展 + +`position_roundtable_sessions` 已使用下列持久化字段: + +| 字段 | 含义 | +| --- | --- | +| `status` | `intent_pending / active / completed / archived`;总结/规划运行态由前端瞬时状态与对应快照的 `status` 表示,避免一次运行中断后留下伪运行态 | +| `summary_thread_id` | 方案总结智能体线程 | +| `summary_snapshot` | 最新有效总结报告快照 | +| `action_plan_thread_id` | 行动规划智能体线程 | +| `action_plan_snapshot` | 最新有效行动规划快照 | +| `invalidated_at` | 记录在 `summary_snapshot` / `action_plan_snapshot` 内,包含 `invalidated_by`,无需重复写 Session 字段 | + +### 3.2 Node 扩展 + +`position_roundtable_nodes` 已使用下列字段(展示状态由前端按状态映射): + +| 字段 | 含义 | +| --- | --- | +| `status` | `locked / ready / running / done / stale / rejected / error`,前端直接映射为展示状态 | +| `rejection_count` | 当前节点累计驳回次数 | +| `last_rejection` | 最新驳回标题、理由、操作者、时间 | +| `revision` | 当前有效交付版本 | +| `invalidated_by` | 导致当前节点失效的上游节点 key | + +### 3.3 Deliverable 新表(后续可选) + +当需要“单个文件独立驳回、跨会话检索或完整版本对比”时,再新增 `position_roundtable_deliverables`,不要只依赖 `artifact_manifest`。 + +| 字段 | 含义 | +| --- | --- | +| `id` | 产物 ID | +| `session_id` | 会话 ID | +| `node_key` | 来源节点 | +| `agent_id` | 来源智能体 | +| `position_id` | 来源岗位 | +| `title` | 产物名称 | +| `kind` | `answer / file / summary / action_plan` | +| `content` | 文本产物内容摘要或正文 | +| `artifact_path` | 文件产物虚拟路径 | +| `thread_id` | 所属线程 | +| `status` | `pending / running / delivered / rejected / stale` | +| `revision` | 来源节点版本 | +| `rejection_title` | 驳回标题 | +| `rejection_reason` | 驳回理由 | +| `created_at` | 创建时间 | +| `updated_at` | 更新时间 | + +当前第一轮不新增这张表:右侧产物卡片、驳回记录、总结输入材料从节点 `artifact_manifest`、节点版本/驳回记录和 Session 快照聚合,避免节点表与产物表双写。后续引入该表时,应把它提升为唯一事实来源,而不是并行维护两套状态。 + +## 4. 驳回与级联失效规则 + +### 4.1 基本驳回 + +用户点击产物卡片的“驳回”后弹窗填写: + +- 驳回标题。 +- 驳回理由。 + +提交后: + +- 当前产物状态改为 `rejected`。 +- 当前节点状态改为 `rejected` 或 `ready`。 +- 当前节点的 `latest_answer` 和历史文件不删除,但不再作为有效交付输入。 +- 记录 `last_rejection`,用于页面展示和后续追踪。 + +### 4.2 级联失效 + +如果驳回的节点位于第 N 阶段: + +- 同阶段其他节点不自动驳回,除非业务链未来明确配置了依赖关系。 +- 第 N+1 阶段及之后所有节点的有效产物全部标记为 `stale`。 +- 后续节点状态回到未完成展示态。 +- `builtin:summary` 和 `builtin:action-plan` 如果已经生成,也标记为 `stale`。 +- 页面允许用户继续查看旧报告和旧行动规划,但必须提示“上游产物已变更,需要重新生成”。 + +### 4.3 重新交付 + +被驳回节点重新问答并完成后: + +- 当前节点产生新的 `revision`。 +- 当前节点产物状态变为 `delivered`。 +- 只有当该阶段所有必要节点都重新有效交付后,下一阶段才重新解锁。 +- 方案总结和行动规划必须基于最新有效产物重新生成。 + +## 5. 接口规划 + +### 5.1 启动与校验 + +| 方法 | 路径 | 用途 | +| --- | --- | --- | +| `POST` | `/api/position-roundtable/sessions/{id}/validate-activation` | 校验业务链、岗位、智能体、意图状态 | +| `POST` | `/api/position-roundtable/sessions/{id}/activate` | 校验通过后冻结链条并初始化节点 | + +第一轮也可以先把校验合并在 `activate` 内,前端根据后端返回的错误码提示。 + +### 5.2 产物 + +| 方法 | 路径 | 用途 | +| --- | --- | --- | +| `GET` | `/api/position-roundtable/sessions/{id}/results` | 获取右侧统一产物来源节点(前端聚合文件与内置快照) | +| `GET` | `/api/position-roundtable/sessions/{id}/nodes/{node_key}` | 获取节点详情;文件正文由既有线程产物预览接口读取 | +| `POST` | `/api/position-roundtable/sessions/{id}/nodes/{node_key}/reject` | 驳回当前节点交付并触发级联失效 | +| `POST` | `/api/position-roundtable/sessions/{id}/nodes/{node_key}/complete-turn` | 节点回答结束后同步回答与产物 | + +### 5.3 方案总结与行动规划 + +| 方法 | 路径 | 用途 | +| --- | --- | --- | +| `POST` | `/api/position-roundtable/sessions/{id}/summary/prepare` | 服务端准备版本锁定的总结材料和线程信息 | +| `POST` | `/api/position-roundtable/sessions/{id}/summary/ask` | 服务端准备总结的同线程续问材料 | +| `POST` | `/api/position-roundtable/sessions/{id}/summary/complete` | 校验 Markdown 交付与来源版本后持久化总结快照 | +| `POST` | `/api/position-roundtable/sessions/{id}/action-plan/prepare` | 服务端准备行动规划材料和线程信息 | +| `POST` | `/api/position-roundtable/sessions/{id}/action-plan/ask` | 服务端准备行动规划同线程续问材料 | +| `POST` | `/api/position-roundtable/sessions/{id}/action-plan/complete` | 校验 Markdown + JSON 交付与来源版本后持久化行动规划快照 | + +可以复用现有 `streamMultiAgent` 流式协议,但建议在岗位会商下包一层 API,由后端负责拼装岗位会商材料,前端不直接拼长 prompt。 + +## 6. 前端实施步骤 + +### 阶段 1:状态与启动校验(已完成) + +- 扩展 `PositionNodeStatus` 和状态显示映射。 +- “确认意图并启动业务链”前补齐校验提示。 +- 后端 `activate` 返回未配置岗位、缺智能体、未选择链条等具体错误。 +- 左侧流程图节点右上角添加状态小图标。 +- 节点样式调整为上方智能体名称、下方岗位名称,移除左侧 logo。 + +验收标准:未选择业务链、岗位未配齐、意图未完成时都能准确阻止启动;启动后流程图能显示各节点状态。 + +### 阶段 2:流程图弹窗(已完成) + +- 左侧保留小型从上到下流程图。 +- 流程图右上角增加“查看”按钮。 +- 点击后打开弹窗,展示更大的流程图。 +- 弹窗内支持点击节点查看对话与产物,保持和主页面选中节点同步。 + +验收标准:小图不挤占左侧空间,大图能完整展示业务链和两个内置收口节点。 + +### 阶段 3:产物卡片与预览(已完成) + +- 右侧新增或改造“分析结果”Tab 为“交付产物”列表。 +- 卡片展示智能体名称、产物名称、岗位名称、时间、状态。 +- 点击卡片打开详情弹窗。 +- 文本产物直接展示正文,文件产物复用现有 `ArtifactPreviewModal`。 +- 每个有效产物提供“驳回”入口。 + +验收标准:节点回答和文件产物能进入统一产物列表;点击可查看详情。 + +### 阶段 4:驳回弹窗与级联失效(已完成) + +- 新增 `RejectDeliverableDialog`。 +- 驳回表单包含标题和理由,均必填。 +- 后端事务内完成当前产物驳回、当前节点状态更新、后续阶段级联失效、总结和行动规划失效。 +- 前端刷新 Session、Node、Deliverable 和流程图状态。 +- 被驳回节点在对话区显示驳回信息,提示用户重新交付。 + +验收标准:驳回第一阶段任意节点后,第二阶段及之后产物都显示未完成或已失效;旧内容可查看但不能作为总结输入。 + +### 阶段 5:方案总结智能体(已完成) + +- 封装 `usePositionSummary`,内部复用 `roundtable-summary` 的线程初始化、流式输出和 Markdown 产物预览能力。 +- 输入材料改为岗位会商材料: + - 任务信息。 + - 情报分析岗意图结果。 + - 业务链快照。 + - 所有状态为 `delivered` 的岗位产物。 + - 已驳回或失效产物只作为历史参考,不进入默认总结材料。 +- 方案总结节点追加到流程图末尾。 +- 所有产物有效交付后才允许点击“生成方案总结”。 +- 总结结果写入 `summary_snapshot`,同时进入产物列表。 + +验收标准:总结报告使用现有方案总结能力生成 Markdown;刷新页面后可恢复;上游驳回后总结标记失效。 + +### 阶段 6:行动规划智能体(已完成) + +- 新增内置智能体 ID,建议先命名为 `position-action-planner`。 +- 新增行动规划 prompt: + - 读取方案总结报告。 + - 读取各岗位最终有效产物。 + - 拆解为若干子任务。 + - 每个子任务包含名称、目标、输入依据、责任岗位建议、前置依赖、交付物、验收标准。 +- 输出两类产物: + - `行动规划报告.md`。 + - `action-plan-subtasks.json`。 +- 行动规划节点追加到方案总结之后。 +- 方案总结有效完成后才允许启动行动规划。 + +验收标准:行动规划能生成可读报告和结构化子任务;刷新可恢复;上游驳回后自动失效。 + +### 阶段 7:返回修改与重新生成(已完成) + +- 用户在方案总结或行动规划视图中仍可切回“交付产物”。 +- 驳回后自动显示需要重做的节点。 +- 重做节点完成后,允许重新生成方案总结和行动规划。 +- 旧总结、旧行动规划保留历史查看,但状态显示“已失效”。 + +验收标准:不会因为进入总结/规划阶段而锁死前序产物;前序重做后能形成新版本闭环。 + +### 阶段 8:测试与回归(已完成) + +- 后端测试: + - activate 校验。 + - 节点完成后产物入库。 + - 驳回当前节点。 + - 驳回第一阶段时后续阶段级联失效。 + - 总结和行动规划失效。 +- 前端测试: + - 启动校验提示。 + - 状态图标显示。 + - 产物卡片筛选和预览。 + - 驳回弹窗必填校验。 +- 回归验证: + - 原多智能体会商页面不受影响。 + - 业务链普通配置入口不显示岗位配置。 + - 岗位会商页面刷新恢复正常。 + - 深色模式和嵌入模式布局不溢出。 + +## 7. 推荐提交拆分 + +1. `feat(position-roundtable): add delivery status model` +2. `feat(position-roundtable): validate chain activation` +3. `feat(position-roundtable): add workflow status graph` +4. `feat(position-roundtable): add deliverable cards and preview` +5. `feat(position-roundtable): support rejection cascade` +6. `feat(position-roundtable): add summary builtin node` +7. `feat(position-roundtable): add action planning builtin node` +8. `test(position-roundtable): cover delivery workflow` + +## 8. 第一轮建议范围 + +第一轮优先做最小可闭环: + +```text +意图识别 +→ 启动校验 +→ 业务链节点状态 +→ 节点产物列表 +→ 产物详情查看 +→ 驳回与级联失效 +→ 全部交付后生成方案总结 +→ 基于总结生成行动规划 +``` + +如果时间紧,行动规划可以先生成 Markdown 报告,结构化 `subtasks.json` 放到第二轮;但数据模型和 UI 入口第一轮就要预留,否则后面会返工。 diff --git a/frontend-web/package-lock.json b/frontend-web/package-lock.json index 4b51ccb8..a590dbe8 100644 --- a/frontend-web/package-lock.json +++ b/frontend-web/package-lock.json @@ -70,6 +70,7 @@ "hast": "^1.0.0", "katex": "^0.16.28", "lucide-react": "^0.562.0", + "mermaid": "^11.15.0", "motion": "^12.26.2", "nanoid": "^5.1.6", "next-themes": "^0.4.6", @@ -104,6 +105,7 @@ "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.4", + "lightningcss": "^1.30.2", "postcss": "^8.5.3", "tailwindcss": "^4.0.15", "tw-animate-css": "^1.4.0", @@ -460,37 +462,11 @@ "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==" }, - "node_modules/@chevrotain/cst-dts-gen": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-12.0.0.tgz", - "integrity": "sha512-fSL4KXjTl7cDgf0B5Rip9Q05BOrYvkJV/RrBTE/bKDN096E4hN/ySpcBK5B24T76dlQ2i32Zc3PAE27jFnFrKg==", - "dependencies": { - "@chevrotain/gast": "12.0.0", - "@chevrotain/types": "12.0.0" - } - }, - "node_modules/@chevrotain/gast": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-12.0.0.tgz", - "integrity": "sha512-1ne/m3XsIT8aEdrvT33so0GUC+wkctpUPK6zU9IlOyJLUbR0rg4G7ZiApiJbggpgPir9ERy3FRjT6T7lpgetnQ==", - "dependencies": { - "@chevrotain/types": "12.0.0" - } - }, - "node_modules/@chevrotain/regexp-to-ast": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-12.0.0.tgz", - "integrity": "sha512-p+EW9MaJwgaHguhoqwOtx/FwuGr+DnNn857sXWOi/mClXIkPGl3rn7hGNWvo31HA3vyeQxjqe+H36yZJwYU8cA==" - }, "node_modules/@chevrotain/types": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-12.0.0.tgz", - "integrity": "sha512-S+04vjFQKeuYw0/eW3U52LkAHQsB1ASxsPGsLPUyQgrZ2iNNibQrsidruDzjEX2JYfespXMG0eZmXlhA6z7nWA==" - }, - "node_modules/@chevrotain/utils": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-12.0.0.tgz", - "integrity": "sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==" + "version": "11.1.2", + "resolved": "https://registry.npmmirror.com/@chevrotain/types/-/types-11.1.2.tgz", + "integrity": "sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==", + "license": "Apache-2.0" }, "node_modules/@codemirror/autocomplete": { "version": "6.20.1", @@ -1732,11 +1708,12 @@ "integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==" }, "node_modules/@mermaid-js/parser": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.1.0.tgz", - "integrity": "sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==", + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/@mermaid-js/parser/-/parser-1.2.0.tgz", + "integrity": "sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==", + "license": "MIT", "dependencies": { - "langium": "^4.0.0" + "@chevrotain/types": "~11.1.2" } }, "node_modules/@opentelemetry/api": { @@ -4274,6 +4251,66 @@ "node": ">=14.0.0" } }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.7.1", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.1.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.7.1", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.1.0", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.0", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1", + "@tybys/wasm-util": "^0.10.1" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.1", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { "version": "4.1.18", "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.1.18.tgz", @@ -5650,32 +5687,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/chevrotain": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-12.0.0.tgz", - "integrity": "sha512-csJvb+6kEiQaqo1woTdSAuOWdN0WTLIydkKrBnS+V5gZz0oqBrp4kQ35519QgK6TpBThiG3V1vNSHlIkv4AglQ==", - "dependencies": { - "@chevrotain/cst-dts-gen": "12.0.0", - "@chevrotain/gast": "12.0.0", - "@chevrotain/regexp-to-ast": "12.0.0", - "@chevrotain/types": "12.0.0", - "@chevrotain/utils": "12.0.0" - }, - "engines": { - "node": ">=22.0.0" - } - }, - "node_modules/chevrotain-allstar": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.4.3.tgz", - "integrity": "sha512-2X4mkroolSMKqW+H22pyPMUVDqYZzPhephTmg/NODKb1IGYPHfxfhcW0EjS7wcPJNbze2i4vBWT7zT5FKF2lrQ==", - "dependencies": { - "lodash-es": "^4.18.1" - }, - "peerDependencies": { - "chevrotain": "^12.0.0" - } - }, "node_modules/class-variance-authority": { "version": "0.7.1", "license": "Apache-2.0", @@ -6547,6 +6558,16 @@ "node": ">= 0.4" } }, + "node_modules/es-toolkit": { + "version": "1.49.0", + "resolved": "https://registry.npmmirror.com/es-toolkit/-/es-toolkit-1.49.0.tgz", + "integrity": "sha512-G5iZ6Pc/FNRY/soKZHC+TxGDD83rHUDXxzaWhGCX44vAv/tMs56WMusnm/KMNK+luUPsgA9U28cGr4RDlSzL2g==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, "node_modules/esbuild": { "version": "0.25.12", "resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.25.12.tgz", @@ -7354,7 +7375,9 @@ } }, "node_modules/katex": { - "version": "0.16.28", + "version": "0.16.47", + "resolved": "https://registry.npmmirror.com/katex/-/katex-0.16.47.tgz", + "integrity": "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==", "funding": [ "https://opencollective.com/katex", "https://github.com/sponsors/katex" @@ -7372,23 +7395,6 @@ "resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz", "integrity": "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==" }, - "node_modules/langium": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/langium/-/langium-4.2.3.tgz", - "integrity": "sha512-sOPIi4hISFnY7twwV97ca1TsxpBtXq0URu/LL1AvxwccPG/RIBBlKS7a/f/EL6w8lTNaS0EFs/F+IdSOaqYpng==", - "dependencies": { - "@chevrotain/regexp-to-ast": "~12.0.0", - "chevrotain": "~12.0.0", - "chevrotain-allstar": "~0.4.3", - "vscode-languageserver": "~9.0.1", - "vscode-languageserver-textdocument": "~1.0.11", - "vscode-uri": "~3.1.0" - }, - "engines": { - "node": ">=20.10.0", - "npm": ">=10.2.3" - } - }, "node_modules/langsmith": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.6.0.tgz", @@ -8100,43 +8106,32 @@ "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==" }, "node_modules/mermaid": { - "version": "11.14.0", - "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.14.0.tgz", - "integrity": "sha512-GSGloRsBs+JINmmhl0JDwjpuezCsHB4WGI4NASHxL3fHo3o/BRXTxhDLKnln8/Q0lRFRyDdEjmk1/d5Sn1Xz8g==", + "version": "11.16.0", + "resolved": "https://registry.npmmirror.com/mermaid/-/mermaid-11.16.0.tgz", + "integrity": "sha512-Zvm3kbstgdpvIJPPItlL7fppIZ3kibvc1oZIGxdvk9t6UFz6flv+Jw7FtRGKwfcI8OckmH04LqG6LlS6X4B1pA==", + "license": "MIT", "dependencies": { - "@braintree/sanitize-url": "^7.1.1", + "@braintree/sanitize-url": "^7.1.2", "@iconify/utils": "^3.0.2", - "@mermaid-js/parser": "^1.1.0", + "@mermaid-js/parser": "^1.2.0", "@types/d3": "^7.4.3", "@upsetjs/venn.js": "^2.0.0", - "cytoscape": "^3.33.1", + "cytoscape": "^3.33.3", "cytoscape-cose-bilkent": "^4.1.0", "cytoscape-fcose": "^2.2.0", "d3": "^7.9.0", "d3-sankey": "^0.12.3", "dagre-d3-es": "7.0.14", - "dayjs": "^1.11.19", - "dompurify": "^3.3.1", - "katex": "^0.16.25", + "dayjs": "^1.11.20", + "dompurify": "^3.3.3", + "es-toolkit": "^1.45.1", + "katex": "^0.16.45", "khroma": "^2.1.0", - "lodash-es": "^4.17.23", "marked": "^16.3.0", "roughjs": "^4.6.6", "stylis": "^4.3.6", "ts-dedent": "^2.2.0", - "uuid": "^11.1.0" - } - }, - "node_modules/mermaid/node_modules/uuid": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", - "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "bin": { - "uuid": "dist/esm/bin/uuid" + "uuid": "^11.1.0 || ^12 || ^13 || ^14.0.0" } }, "node_modules/micromark": { @@ -10414,49 +10409,6 @@ "vite": ">=5.0.0" } }, - "node_modules/vscode-jsonrpc": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", - "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/vscode-languageserver": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz", - "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==", - "dependencies": { - "vscode-languageserver-protocol": "3.17.5" - }, - "bin": { - "installServerIntoExtension": "bin/installServerIntoExtension" - } - }, - "node_modules/vscode-languageserver-protocol": { - "version": "3.17.5", - "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", - "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", - "dependencies": { - "vscode-jsonrpc": "8.2.0", - "vscode-languageserver-types": "3.17.5" - } - }, - "node_modules/vscode-languageserver-textdocument": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", - "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==" - }, - "node_modules/vscode-languageserver-types": { - "version": "3.17.5", - "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", - "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==" - }, - "node_modules/vscode-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", - "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==" - }, "node_modules/w3c-keyname": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", diff --git a/frontend-web/public/runtime-config.js b/frontend-web/public/runtime-config.js index 27b50ee4..02984b26 100644 --- a/frontend-web/public/runtime-config.js +++ b/frontend-web/public/runtime-config.js @@ -19,20 +19,23 @@ window.__CM_RUNTIME_CONFIG__ = { VITE_BRAND_LOGO_LIGHT_URL: "brand-assets/brand-logo-light.png", // 浅蓝主题的顶栏系统 Logo 图片地址。 VITE_BRAND_LOGO_LIGHTBLUE_URL: "brand-assets/brand-logo-lightblue.png", + // 绿色主题可单独替换 Logo;默认复用浅色 Logo。 + VITE_BRAND_LOGO_LIGHTGREEN_URL: "brand-assets/brand-logo-light.png", // 深色主题的顶栏系统 Logo 图片地址。 VITE_BRAND_LOGO_DARK_URL: "brand-assets/brand-logo-dark.png", // 红白主题的欢迎页 Logo 图片地址:为空时显示原有 CM 文字和渐变背景。 VITE_BRAND_WELCOME_LIGHT_URL: "", // 浅蓝主题的欢迎页 Logo 图片地址:为空时显示原有 CM 文字和渐变背景。 VITE_BRAND_WELCOME_LIGHTBLUE_URL: "", + VITE_BRAND_WELCOME_LIGHTGREEN_URL: "", // 深色主题的欢迎页 Logo 图片地址:为空时显示原有 CM 文字和渐变背景。 VITE_BRAND_WELCOME_DARK_URL: "", // DeerFlow Gateway 地址:前端自有后端接口,例如 /api/agents、/api/auth、/api/threads 等。 - VITE_BACKEND_BASE_URL: "http://10.19.200.5:2026", + // VITE_BACKEND_BASE_URL: "http://10.19.200.5:2026", // LangGraph 流式对话接口地址:普通问答、智能体对话等流式能力使用。 - VITE_LANGGRAPH_BASE_URL: "http://10.19.200.5:2026/api", + // VITE_LANGGRAPH_BASE_URL: "http://10.19.200.5:2026/api", // Canvas/AI 写作独立 LangGraph 地址:为空时前端会回退使用 VITE_LANGGRAPH_BASE_URL。 VITE_CANVAS_LANGGRAPH_BASE_URL: "", @@ -106,12 +109,23 @@ window.__CM_RUNTIME_CONFIG__ = { // 登录深链任务详情是否使用本地 mock:false=真实接口;true=本地 mock。 VITE_MOCK_COP_TASK_DETAIL: "false", - // 大屏绘制 selectSqReport 是否使用本地 mock:false=真实接口;true=本地 mock。 - VITE_MOCK_SQ_REPORT: "false", + // 岗位会商完整演示数据:true=启动时幂等写入后端;后端不可用时直接使用前端 JSON 兜底。 + // 默认关闭,避免演示历史记录出现在正常生产账号中。 + VITE_POSITION_ROUNDTABLE_DEMO_MODE: "false", + // 纯前端岗位分析演示:跳过登录,直接进入岗位分析页,并禁止所有后台请求。 + // 仅用于离线展台/演示环境,生产环境必须保持 false。 + VITE_POSITION_ROUNDTABLE_STANDALONE_MODE: "false", + + // 大屏绘制 selectSqReport 是否使用本地 mock:不在运行时强制覆盖, + // 由各环境的 .env 文件决定(开发环境为 true,生产环境为 false)。 // 静态站点模式开关;一般部署业务系统时保持 false。 VITE_STATIC_WEBSITE_ONLY: "false", + // 紧凑导航开关:true 时固定使用简洁布局,工作台左侧栏收起为菜单图标, + // 隐藏系统 Logo、换肤按钮以及“全量/简洁模式”切换。修改后刷新页面即可生效。 + VITE_FORCE_COLLAPSED_SIDEBAR: "false", + // GitHub OAuth Token;不使用 GitHub 相关能力时留空。 VITE_GITHUB_OAUTH_TOKEN: "", }; diff --git a/frontend-web/src/App.tsx b/frontend-web/src/App.tsx index 0235b013..2833dea3 100644 --- a/frontend-web/src/App.tsx +++ b/frontend-web/src/App.tsx @@ -37,6 +37,11 @@ import PublicRoundtableSharePage from "./pages/PublicRoundtableSharePage"; import EmbedChatPage from "./pages/EmbedChatPage"; import EmbedRoundtablePage from "./pages/EmbedRoundtablePage"; import DashboardStandalonePage from "@/roundtable-planning/pages/DashboardStandalonePage"; +import PositionRoundtablePage from "@/position-roundtable/pages/PositionRoundtablePage"; +import { + isPositionRoundtableStandaloneMode, + POSITION_ROUNDTABLE_ROUTE, +} from "@/position-roundtable/demo/position-roundtable-demo-config"; import { ChatRuntime } from "./pages/WorkspaceRoutes"; import { NotFoundPage } from "./pages/NotFoundPage"; @@ -46,6 +51,7 @@ function AppProviders({ children }: { children: React.ReactNode }) { const locale = useMemo(() => detectLocale(), []); const location = useLocation(); const publicEmbedTheme = usePublicEmbedTheme(); + const positionStandaloneMode = isPositionRoundtableStandaloneMode(); // iframe 嵌入会话(按标签页 sessionStorage)集中在此同步:任何带 `&embed=1` 的入口(深链登录页 // 或直接深链路由)一进来就启用、`embed=0` 关闭,后续干净路由靠会话维持去 chrome + 强制主题。 useEffect(() => { @@ -54,8 +60,9 @@ function AppProviders({ children }: { children: React.ReactNode }) { // 操作日志(Y-Log):启动早期预热上报配置,使 writeYLog 同步读缓存即可工作 // (刷新后 module 缓存清空,token 登录用户也能继续上报)。失败静默。 useEffect(() => { + if (positionStandaloneMode) return; void fetchYLogConfig(); - }, []); + }, [positionStandaloneMode]); const forcedTheme = useMemo(() => { // iframe 嵌入模式(外部系统 `&embed=1`)最高优先:按本标签页的嵌入主题强制明/暗。 // 走 next-themes forcedTheme(不写 localStorage)→ 同浏览器另开的正常系统页不受影响。 @@ -89,7 +96,7 @@ function AppProviders({ children }: { children: React.ReactNode }) { attribute="class" storageKey="strategy-theme" defaultTheme="light" - themes={["light", "dark", "lightblue"]} + themes={["light", "dark", "lightblue", "lightgreen", "iceblue", "lightyellow"]} enableSystem={false} disableTransitionOnChange forcedTheme={forcedTheme} @@ -98,8 +105,8 @@ function AppProviders({ children }: { children: React.ReactNode }) { - - + {!positionStandaloneMode && } + {!positionStandaloneMode && } {children} @@ -117,17 +124,38 @@ function AppProviders({ children }: { children: React.ReactNode }) { */ function RootRedirect() { const { search } = useLocation(); + if (isPositionRoundtableStandaloneMode()) { + return ; + } return ; } export function App() { + const positionStandaloneMode = isPositionRoundtableStandaloneMode(); + const standaloneLoginRedirect = ( + + ); + const pageElement = positionStandaloneMode ? ( + + + + ) : ( + + ); + return ( } /> - } /> - } /> + } + /> + } + /> } /> } /> } /> @@ -164,7 +192,7 @@ export function App() { path="/roundtable-dashboard" element={} /> - } /> + } /> diff --git a/frontend-web/src/assets/position-roundtable/down-logo.svg b/frontend-web/src/assets/position-roundtable/down-logo.svg new file mode 100644 index 00000000..eafe014d --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/down-logo.svg @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/frontend-web/src/assets/position-roundtable/expand-logo.svg b/frontend-web/src/assets/position-roundtable/expand-logo.svg new file mode 100644 index 00000000..a1b533ac --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/expand-logo.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/frontend-web/src/components/page-sdebar.css b/frontend-web/src/components/page-sdebar.css index e6eb7677..091df5fd 100644 --- a/frontend-web/src/components/page-sdebar.css +++ b/frontend-web/src/components/page-sdebar.css @@ -564,6 +564,37 @@ background: #ffffff; } +/* Ice blue has a deliberately light banner. Keep top-level navigation and + its active marker dark enough to remain readable against #9BCEF1. */ +html.iceblue .light-topnav-item { + color: rgba(24, 50, 74, 0.78); +} + +html.iceblue .light-topnav-item:hover, +html.iceblue .light-topnav-item--active, +html.iceblue .light-topnav-item--active:hover { + color: #18324a; +} + +html.iceblue .light-topnav-item--active::after { + background: #3d6e96; +} + +/* Pale yellow has the same light-banner contrast requirement as ice blue. */ +html.lightyellow .light-topnav-item { + color: rgba(48, 61, 35, 0.78); +} + +html.lightyellow .light-topnav-item:hover, +html.lightyellow .light-topnav-item--active, +html.lightyellow .light-topnav-item--active:hover { + color: #303d23; +} + +html.lightyellow .light-topnav-item--active::after { + background: #4c6330; +} + /* ── 侧边栏:二级图标卡片列(96px)+ 右侧三级列(展开时整体变宽,带过渡)──────── */ .light-sidebar { position: fixed; diff --git a/frontend-web/src/components/ui/button.tsx b/frontend-web/src/components/ui/button.tsx index 836b8705..6baca704 100644 --- a/frontend-web/src/components/ui/button.tsx +++ b/frontend-web/src/components/ui/button.tsx @@ -10,7 +10,7 @@ const buttonVariants = cva( variants: { variant: { default: - "cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90", + "cursor-pointer bg-primary text-[var(--button-foreground,var(--primary-foreground))] hover:bg-primary/90", destructive: "cursor-pointer bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", outline: diff --git a/frontend-web/src/components/ui/dialog.tsx b/frontend-web/src/components/ui/dialog.tsx index a95a00ae..3474709e 100644 --- a/frontend-web/src/components/ui/dialog.tsx +++ b/frontend-web/src/components/ui/dialog.tsx @@ -71,15 +71,17 @@ const DialogOverlay = React.forwardRef< DialogOverlay.displayName = DialogPrimitive.Overlay.displayName; -const DialogContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef & { - showCloseButton?: boolean; - } ->(({ className, children, showCloseButton = true, ...props }, ref) => { - return ( - - +const DialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + showCloseButton?: boolean; + /** Use when this dialog is opened from a higher-layer surface such as a Drawer. */ + overlayClassName?: string; + } +>(({ className, children, showCloseButton = true, overlayClassName, ...props }, ref) => { + return ( + + & { - defaultOpen?: boolean; - open?: boolean; - onOpenChange?: (open: boolean) => void; +}: React.ComponentProps<"div"> & { + defaultOpen?: boolean; + open?: boolean; + onOpenChange?: (open: boolean) => void; + /** Keep a controlled deployment-level rail from being reopened by hotkeys. */ + disableToggle?: boolean; }) { const isMobile = useIsMobile(); const [openMobile, setOpenMobile] = React.useState(false); @@ -92,10 +95,11 @@ function SidebarProvider({ [setOpenProp, open], ); - // Helper to toggle the sidebar. - const toggleSidebar = React.useCallback(() => { - return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open); - }, [isMobile, setOpen, setOpenMobile]); + // Helper to toggle the sidebar. + const toggleSidebar = React.useCallback(() => { + if (disableToggle) return; + return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open); + }, [disableToggle, isMobile, setOpen, setOpenMobile]); // Adds a keyboard shortcut to toggle the sidebar. React.useEffect(() => { diff --git a/frontend-web/src/components/workspace/agent-icon-color.ts b/frontend-web/src/components/workspace/agent-icon-color.ts index 5f78c7e6..56b7e693 100644 --- a/frontend-web/src/components/workspace/agent-icon-color.ts +++ b/frontend-web/src/components/workspace/agent-icon-color.ts @@ -24,12 +24,60 @@ const AGENT_COLORS_DARK = [ { from: "#69B1FF", to: "#003EB3" }, // 浅蓝 → 主色按下 ] as const; -/** 按 agent id 稳定散列出一对渐变色(from → to)。`isDark` 切换深蓝/浅色调色板。 */ -export function agentColor(id: string, isDark: boolean) { +/** 按 agent id 稳定散列出一对渐变色,并根据当前主题返回可读的图标前景色。 */ +const AGENT_COLORS_ICEBLUE = [ + { from: "#eff8fd", to: "#b7dcf5" }, + { from: "#e3f2fb", to: "#9bcef1" }, + { from: "#ebf6fb", to: "#add8e9" }, + { from: "#edf2fc", to: "#b7cdef" }, + { from: "#e9f7f5", to: "#afe0dc" }, +] as const; + +const AGENT_COLORS_LIGHTYELLOW = [ + { from: "#fbfdef", to: "#e4efbf" }, + { from: "#f7fae9", to: "#F3FBD9" }, + { from: "#f9fbe8", to: "#dcebad" }, + { from: "#faf8e9", to: "#e7dfb9" }, + { from: "#f1f8e5", to: "#cce0af" }, +] as const; + +type AgentAvatarTheme = + | "dark" + | "iceblue" + | "lightyellow" + | "light" + | "lightblue" + | "lightgreen" + | `custom-theme-${string}`; + +/** Returns a stable avatar gradient and readable icon color for each theme. */ +export function agentColor(id: string, theme: AgentAvatarTheme) { + if (theme.startsWith("custom-theme-")) { + return { + from: "var(--accent)", + to: "var(--brand-200)", + foreground: "var(--accent-foreground)", + }; + } let hash = 0; for (let i = 0; i < id.length; i++) { hash = (hash * 31 + id.charCodeAt(i)) >>> 0; } - const palette = isDark ? AGENT_COLORS_DARK : AGENT_COLORS_LIGHT; - return palette[hash % palette.length]!; + const palette = + theme === "dark" + ? AGENT_COLORS_DARK + : theme === "iceblue" + ? AGENT_COLORS_ICEBLUE + : theme === "lightyellow" + ? AGENT_COLORS_LIGHTYELLOW + : AGENT_COLORS_LIGHT; + return { + ...palette[hash % palette.length]!, + foreground: + theme === "iceblue" + ? "#2d587a" + : theme === "lightyellow" + ? "#4c6330" + : "#ffffff", + }; } diff --git a/frontend-web/src/components/workspace/agents/agent-chat-sidebar.tsx b/frontend-web/src/components/workspace/agents/agent-chat-sidebar.tsx index b7452f1e..8f75052a 100644 --- a/frontend-web/src/components/workspace/agents/agent-chat-sidebar.tsx +++ b/frontend-web/src/components/workspace/agents/agent-chat-sidebar.tsx @@ -254,7 +254,7 @@ export function AgentChatSidebar({ activeAgentId }: { activeAgentId?: string }) {agents.map((agent) => { const href = `${routeBase}/agents/${agent.id}/chats/new`; const isActive = agent.id === activeAgentId; - const { from, to } = agentColor(agent.id, isDark); + const { from, to, foreground } = agentColor(agent.id, theme); return ( diff --git a/frontend-web/src/components/workspace/agents/agent-module-sidebar.tsx b/frontend-web/src/components/workspace/agents/agent-module-sidebar.tsx index c5cf8ae1..18951da6 100644 --- a/frontend-web/src/components/workspace/agents/agent-module-sidebar.tsx +++ b/frontend-web/src/components/workspace/agents/agent-module-sidebar.tsx @@ -206,7 +206,7 @@ export function AgentModuleSidebar({ const renderAgentCard = (agent: Agent, keyPrefix: string) => { const href = `${routeBase}/agents/${agent.id}/chats/new`; const isActive = agent.id === activeAgentId; - const { from, to } = agentColor(agent.id, isDark); + const { from, to, foreground } = agentColor(agent.id, theme); return ( diff --git a/frontend-web/src/components/workspace/appearance-controls.tsx b/frontend-web/src/components/workspace/appearance-controls.tsx index c11534b0..03f8f81d 100644 --- a/frontend-web/src/components/workspace/appearance-controls.tsx +++ b/frontend-web/src/components/workspace/appearance-controls.tsx @@ -1,7 +1,7 @@ "use client"; import { Check, ExternalLink, LayoutIcon, PanelLeftIcon, Shirt } from "lucide-react"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; import { Button } from "@/components/ui/button"; @@ -15,6 +15,8 @@ import { } from "@/components/ui/dropdown-menu"; import { useTheme, type ThemeType } from "@/contexts/ThemeContext"; import { useAppearanceSettings, useLayoutMode } from "@/core/system-settings/hooks"; +import { isHideChromeActive } from "@/core/embed/embed-session"; +import { env } from "@/env"; import { cn } from "@/lib/utils"; import { buildLightAppUrl } from "@/strategy-components/lib/light-app"; @@ -26,10 +28,13 @@ import { buildLightAppUrl } from "@/strategy-components/lib/light-app"; */ export type AppearanceControlTone = "banner-dark" | "banner-light" | "content"; -// 换肤色板:红色=红白主题(light),蓝色=浅蓝主题(lightblue),深蓝色=深色主题(dark) +// 换肤色板:红色=红白主题(light),蓝色=浅蓝主题(lightblue),冰川蓝=柔和浅蓝主题(iceblue),浅黄色=柔和黄主题(lightyellow),深蓝色=深色主题(dark) export const THEME_SWATCHES: { id: ThemeType; label: string; color: string }[] = [ { id: "light", label: "红色", color: "#cf1322" }, + { id: "lightgreen", label: "绿色", color: "#07c05f" }, { id: "lightblue", label: "蓝色", color: "#0062d9" }, + { id: "iceblue", label: "冰川蓝", color: "#9BCEF1" }, + { id: "lightyellow", label: "浅黄色", color: "#F3FBD9" }, { id: "dark", label: "深蓝色", color: "#002466" }, ]; @@ -79,8 +84,23 @@ export function CompactShortcutButtons({ tone }: { tone: AppearanceControlTone } export function ThemeSwitcher({ tone }: { tone: AppearanceControlTone }) { const { theme, setTheme } = useTheme(); + const { data: appearance } = useAppearanceSettings(); const [open, setOpen] = useState(false); const closeTimer = useRef | null>(null); + const swatches = useMemo( + () => [ + ...THEME_SWATCHES, + ...(appearance?.custom_themes ?? []) + .filter((preset) => preset.enabled) + .sort((a, b) => a.sort_order - b.sort_order) + .map((preset) => ({ + id: preset.id as ThemeType, + label: preset.name, + color: preset.primary, + })), + ], + [appearance?.custom_themes], + ); const cancelClose = () => { if (closeTimer.current) { @@ -95,6 +115,8 @@ export function ThemeSwitcher({ tone }: { tone: AppearanceControlTone }) { useEffect(() => () => cancelClose(), []); + if (env.FORCE_COLLAPSED_SIDEBAR || isHideChromeActive()) return null; + return (
{open ? (
-
-
- {THEME_SWATCHES.map((swatch) => { +
+
+ {swatches.map((swatch) => { const active = theme === swatch.id; return (