# Conflicts:
#	CLAUDE.md
This commit is contained in:
Administrator committed 2026-06-23 20:52:39 +08:00
commit 6f0f9fb1fc
180 files changed
+14037 -1445

No files matched your search

+3
View File
@@ -110,3 +110,6 @@ offline-backend-20260512/backend/uv.lock
# Python bytecode cache
__pycache__/
# misc
.DS_Store
+102
View File
@@ -0,0 +1,102 @@
# AGENTS.md
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
## Project Overview
This is a customized offline deployment of **DeerFlow** — a LangGraph-based AI super agent platform. The repo contains two sub-projects:
- `offline-backend-20260512/backend/` — Python backend (FastAPI Gateway + LangGraph agent runtime)
- `frontend-web/` — Vite + React 19 frontend (TypeScript, pnpm)
Managed together via shell scripts in `scripts/`.
## Commands
### Full Application (from repo root)
```bash
./scripts/start-all.sh # Start backend + frontend as background daemons
./scripts/stop-all.sh # Stop both
./scripts/restart-all.sh # Restart both
./scripts/status.sh # Check running status
```
Logs and PID files are written to `.runtime/logs/` and `.runtime/pids/`.
### Backend Only (from `offline-backend-20260512/backend/`)
```bash
make install # Install Python dependencies (uv)
make dev # Run Gateway API with hot-reload on port 8001
make gateway # Run Gateway API without reload
make test # Run all tests: PYTHONPATH=. uv run pytest tests/ -v
make lint # Lint with ruff
make format # Format with ruff
```
Run a single test file:
```bash
PYTHONPATH=. uv run pytest tests/test_<feature>.py -v
```
### Frontend Only (from `frontend-web/`)
```bash
pnpm install # Install dependencies
pnpm dev # Start Vite dev server on port 5174
pnpm build # Production build
pnpm typecheck # TypeScript type checking (tsc --noEmit)
```
## Service Ports
| Service | Port | Notes |
|---------|------|-------|
| Backend (Gateway API) | 8001 | FastAPI + LangGraph runtime |
| Frontend (Vite) | 5174 | React SPA |
Frontend connects to backend via env vars `VITE_BACKEND_BASE_URL` and `VITE_LANGGRAPH_BASE_URL` (injected by `scripts/start-frontend.sh`).
## Architecture
### Backend
The backend (`offline-backend-20260512/backend/`) is split into two layers:
- **`packages/harness/deerflow/`** — publishable agent framework (`deerflow.*` imports): LangGraph lead agent, middleware chain, sandbox, tools, MCP, memory, models, skills. **Never imports from `app.*`.**
- **`app/`** — application layer (`app.*` imports): FastAPI Gateway routers, IM channel integrations (Feishu, Slack, Telegram, DingTalk).
The **Lead Agent** (`deerflow/agents/lead_agent/`) is the single LangGraph graph entry point. It wraps a middleware chain (~18 middlewares assembled in strict order) around LLM calls, handling: thread isolation, sandbox lifecycle, uploads, memory, plan mode, vision, subagent delegation, and loop detection.
**Middleware order matters** — middlewares are appended in a fixed sequence; `ClarificationMiddleware` must always be last. See `offline-backend-20260512/backend/AGENTS.md` for the full ordered list.
**Harness → App import firewall** is enforced by `tests/test_harness_boundary.py` (runs in CI).
### Frontend
The frontend (`frontend-web/`) is a React 19 + Vite SPA:
- **Routing**: React Router v7; top-level routes in `src/pages/PageRoutes.tsx`, workspace sub-routes in `src/pages/WorkspaceRoutes.tsx`
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
- **轻应用中心 (Light App Center)**: a sibling of 任务管理 in the sidebar with two pages — 应用管理 (admin registers `window_open` or `iframe` mini-apps with a route-param builder: login params resolved from `localStorage.userInfo`, theme params literal) and 应用列表 (card grid of `window_open` apps, `window.open` launch). `iframe` apps are mounted under a chosen parent menu (XK/PG/TY/综合管理) and **dynamically injected into the sidebar** by `core/page-layout/use-sidebar-menu.ts` (`useSidebarMenuItems`), opening in the `LightAppIframeView` host. Client + React Query hooks in `strategy-components/api/light-apps.ts`; URL builder/constants in `strategy-components/lib/light-app.ts`. Backend: `/api/light-apps` (global/shared, admin-gated writes).
- **菜单管理 (Menu Management, admin-only)**: an **overlay** over the static sidebar menu — `MenuManagementPage` (`pages/MenuManagementPage.tsx`, route `/page/strategy/admin/menu-management`, opened from the admin-only 「菜单管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`). Admins rename / 停用·启用 / reorder (↑↓ or @dnd-kit drag) / re-parent (horizontal drag **or** the edit dialog's 「移动到」parent selector) any node across 一级/二级/三级, **including injected iframe light-app nodes** (`light-app-<appId>`). The static tree (`core/page-layout/sidebar-menu.ts`) stays the source of icons/routes; only per-node deltas (`label`/`disabled`/`parentId`/`sortOrder`) persist to the backend. Merge logic in `core/page-layout/menu-overrides.ts` (`applyMenuOverrides`, applied in `use-sidebar-menu.ts` after light-app injection, before role filter; disabling a node hides its whole subtree) — strict **3-level cap** (`wouldExceedDepth`). Client `strategy-components/api/menu-overrides.ts`. Backend: `/api/menu-overrides` (global/shared; open read, admin atomic replace-all).
- **敏感词管理 (Sensitive Word Management)**: configures the **展示层脱敏映射** (原始词 → 替换词). **Gated on the username `lqq`** (not the admin role) — `getAccountDisplayName().toLowerCase() === "lqq"` (username = email `@` prefix, else `user_id`, same as the profile page); the dropdown entry, the route guard, and the page-level guard all use this check. `src/lib/desensitize.ts` ships a frozen seed map `SEED_DESENSITIZE_MAP` (the deployment seed) plus a live mutable `DESENSITIZE_MAP` (initialized from the seed so `desensitize()` works before any fetch). `DesensitizeWordsLoader` (mounted in `App.tsx` `AppProviders`) fetches `/api/sensitive-words` on startup and, if non-empty, calls `replaceDesensitizeMap(...)` to make the backend config the source of truth (empty/failed → keep seed). Page `SensitiveWordsPage.tsx` (route `/page/strategy/admin/sensitive-words`, opened from the 「敏感词管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`, present in **both** full + collapsed sidebar modes) lists/adds/edits/启停/deletes words and saves the **whole set atomically** (replace-all); a 「导入种子词」 button merges any missing `SEED_DESENSITIZE_MAP` entries into the editor. Client + hooks in `strategy-components/api/sensitive-words.ts` (`wordsToMap` folds enabled rows into the runtime map). Backend: `/api/sensitive-words` (global/shared; open read, write allowed for admin **or** the `lqq` account), mirroring 菜单管理's store shape. **侧边栏 + 导航栏 menu labels are desensitized** at the data source: `useSidebarMenuItems`/`useActiveThirdLevel` (`core/page-layout/use-sidebar-menu.ts`) map every node's `label` through a desensitizer built **directly from the `/api/sensitive-words` query** (`makeDesensitizer(wordsToMap(words))`, falling back to the global seed `desensitize` while empty) — this sidesteps the `replaceDesensitizeMap` effect-timing race. Only `label` is rewritten; `path`/`id`/`icon` are untouched so routing/highlight are unaffected. All nav surfaces (`page-sidebar.tsx`, `page-sidebar-dark.tsx`, `page-sidebar-v1.tsx`, `strategy-components/Header.tsx`, `PageRoutes.tsx`) consume this hook and are covered; `MenuManagementPage` uses the raw tree so admins still edit real labels.
- **技能地址管理 (Skill Address Management, admin-only)**: 扫描运行中的技能(`skills/{public,custom}` 下所有 `.md`/`.py`)里的 **http(s) URL 与 IP/IP:端口**,按唯一地址聚合全部出现位置(跨 .md/.py),支持**批量替换**(如把 UAT 地址一次性改成生产)。主体抽成可复用组件 `SkillAddressesPanel`(`pages/SkillAddressesPage.tsx` 导出,默认导出 `SkillAddressesPage` 仍保留旧路由 `/page/strategy/admin/skill-addresses` 作直链回退),**作为「技能地址管理」标签页嵌入管理员「技能管理」页 `pages/AdminSkillsPage.tsx`**(该页加 Tabs:「技能列表」+「技能地址管理」;入口在「设置和更多」下拉的「技能管理」`workspace-nav-menu.tsx` → `/page/workspace/admin/skills`,不再单列于 `components/page-sidebar.tsx` 左下角设置下拉):打开自动扫描并带**进度条**(扫描逐技能 / 应用逐文件 X/N,应对 150+ 技能),URL/IP 类型过滤 + 搜索 + 「片段批量套用」(如所有 `uat.4.cn` → `prod.4.cn`)、每地址「替换为」输入框(可展开看 `file:line` 片段)、内联**预览**、**应用**、**多关键词检索**(空格分隔全部命中),以及**修改记录**面板——每次应用生成一条记录(显示时间/改了哪些地址 from→to/文件数/处数),可**针对单次记录回退**(二次确认)。client + NDJSON 流式解析在 `strategy-components/api/skill-addresses.ts`。后端 `/api/skill-addresses`(**仅管理员**):所有文件 IO 走 `asyncio.to_thread` 不阻塞事件循环;`GET /scan`(+`/scan/stream`)、`POST /preview`、`POST /apply`(+`/apply/stream`)、`GET /backups`、`POST /rollback/{id}`;**子串安全替换**(基于 token span,不会误伤子串)、`expected_total` 乐观锁(409)、写前自动磁盘备份到 `{skills_root}/.address-edits/`(同时写一份 `{id}.manifest.json` 记录本次替换明细,供修改记录展示)、应用后刷新技能系统提示缓存。纯引擎 `deerflow/skills/address_scan.py`,router `app/gateway/routers/skill_addresses.py`,tests `tests/test_skill_addresses.py`。范围仅运行中技能,不动 `deploy/minimal/skills/`。
- **按钮管理 (Task Button Management, admin-only)**: configures the **可配置跳转按钮** rendered in the left task panel of the task deep-link workspaces (rwfx / 3qfx / xdfx, see `TaskFxWorkspace`). Each button = `{business, label, linkType, target, appendTaskId, idParam, idKind, enabled, sortOrder}`; `linkType` is `url` (外链 `window.open`, optional append of `?{idParam}={id}` — **`idParam` is the editable query-param name**, e.g. `id`/`task_id`), `business` (内部切换到另一业务, reuses `resolveTaskDeeplinkTarget`, always task id), or `purpose` (弹出当前任务的「任务目的」表格 via the shared `TaskPurposeDialog`, no target — configurable for any page incl. xdfx). **`idKind` (`task`/`action`) only matters for xdfx**: its deep-link `?taskId=` is an 行动id and the 任务id is resolved at login (`fetchTaskIdFromAction`) — `TaskContext` now also stashes the raw `actionId`, so a url button can append either (default `task`). Page `TaskButtonsPage.tsx` (route `/page/strategy/admin/task-buttons`, **admin-gated**, entry「按钮管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both full + collapsed modes) has per-business tabs, edits name/type/target/启停/排序/增删, saves the **whole set atomically** (replace-all), plus 「导入默认」 to merge code-seed defaults. **Seed/fallback** (like 敏感词管理): only when the whole table is empty (fresh deploy, never saved) do the workspace + page fall back to `defaultTaskButtons(cfg)` — rwfx's url buttons (编辑/下一步/3q详情) built from the **live** `/api/public/config/task-deeplink` plus cross-business switch buttons for **all three** businesses (each switches to the other two — rwfx→三情/行动, 3qfx→任务/行动, xdfx→任务/三情). Once saved, the store is the sole source of truth. The old hardcoded jump buttons were migrated out: `TaskFxWorkspace` no longer hardcodes 切换到三情分析, `TaskActionsPanel` keeps only the non-jump 清除记录, and `TaskPurposePanel` dropped its 3q详情 button (now configurable) **and defaults the 目的树 table to collapsed** (chevron toggle). Helpers `core/auth/task-buttons.ts` (`TaskButton`, `defaultTaskButtons`, `resolveTaskButtons`, `buttonsForBusiness`, `runTaskButton`), client+hooks `strategy-components/api/task-buttons.ts`. Backend: `/api/task-buttons` (global/shared; open read, admin replace-all), store `deerflow.persistence.task_buttons` (table `task_buttons`, auto-created by `create_all`), wired `app.state.task_button_store`. Tests: `tests/test_task_buttons.py`.
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). **xdfx additionally partitions its chat records by 行动id (action_id), NOT by task_id**: `resolveTaskDeeplinkTarget` sets `partitionByAction:true` + keeps the raw action_id as `TaskContext.actionId`, so new threads are tagged `metadata.{taskId,actionId}` (taskId kept only to preserve the backend「任务深链对话全局共享」semantics, which keys off `metadata.taskId`) and the conversation list filters by `actionId` (+`agent_id`) — different actions of the same task get separate lists. xdfx's first-question opening text also appends `行动id(action_id)为…` (see `buildOpeningText` / `taskThreadMetadata`). goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. The roundtable target also threads the URL `taskId` into `roundtablePrefill.taskId` (`resolveTaskDeeplinkTarget(goPath, detail, taskId)`), which turns on two taskId-scoped behaviors: (1) **separate, unpartitioned per-task storage** — taskId 会商聊天记录 live in their **own** store/table (`roundtable_task_drafts`), keyed **only by `task_id`** (one taskId = many records, shared across users, **no user 分权** at all; `created_by` is audit-only), kept entirely out of the per-user personal store (`roundtable_drafts`, now strictly per-user) so the two never mix. Backend router `/api/roundtable-task-drafts` (`GET /by-task/{id}` + `/by-task/{id}/latest`, `POST`, `GET/PUT/DELETE /{id}` — all user-agnostic); frontend client `roundtable-planning/api/task-drafts.ts`, and `useDraftPersistence`/`useRoundtableDrafts` route **all** CRUD to it when a `taskId` is present (else the personal `drafts.ts`). The matching **background jobs** are shared by task too: `roundtable_jobs.task_id` marks a task job; reads/dedup/stream/resume/cancel pass `?task_id=` so any user opening the task sees the same running 研讨 (progress/flowchart), and the executor writes the final report back to the task-draft store. Existing rows are moved over by `scripts/migrate_roundtable_task_drafts.py` (migration `20260618_01`). The history dropdown filters to the task and 新建 keeps the binding; (2) **Step-3 auto structured output** — after the `roundtable-summary` agent writes the Markdown report it automatically runs a second round emitting a `flow-json` flowchart (`useStep3Summary` `autoFlow`+`chainLevels`), whose hierarchy follows the business chain's stage goals (任务 → 目的 → 行为体 → …; coordinatorPrompt-specified hierarchy wins) and whose nodes never carry 阶段编号/阶段名 (the prior bug). **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. **All three single-agent businesses share `TaskFxWorkspace`** (`task-components/TaskFxWorkspace.tsx`): left = a「当前任务」card (`readCopTaskDetail()` 任务名称 + 简介, desensitized, 留存 above 新建对话) + per-task 1:N conversation list (`useTaskThreads(taskId, agentId, actionId?)` — filtered by **both** `metadata.taskId` AND `metadata.agent_id` so the three businesses' conversations staLine truncated
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
### Configuration
Backend config lives in `offline-backend-20260512/backend/config.yaml`. Values starting with `$` resolve as environment variables (e.g., `$OPENAI_API_KEY`). MCP servers and skills are configured in `extensions_config.json` in the same directory.
## Detailed Backend Reference
The backend has its own comprehensive documentation at:
- `offline-backend-20260512/backend/AGENTS.md` — architecture, middleware chain, all API routes, config schema, sandbox/memory/subagent systems
- `offline-backend-20260512/backend/README.md` — setup guide, technology stack
+3 -2
View File
@@ -79,17 +79,18 @@ 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 JSON is **any** shape — the agent's `SOUL.md` maps it to the template's schema skeleton. See the backend CLAUDE.md「Template-fill mode」for the engine (`deerflow/runtime/scheduler/template_fill.py`), agent seed, and dispatch.
- **轻应用中心 (Light App Center)**: a sibling of 任务管理 in the sidebar with two pages — 应用管理 (admin registers `window_open` or `iframe` mini-apps with a route-param builder: login params resolved from `localStorage.userInfo`, theme params literal) and 应用列表 (card grid of `window_open` apps, `window.open` launch). `iframe` apps are mounted under a chosen parent menu (XK/PG/TY/综合管理) and **dynamically injected into the sidebar** by `core/page-layout/use-sidebar-menu.ts` (`useSidebarMenuItems`), opening in the `LightAppIframeView` host. Client + React Query hooks in `strategy-components/api/light-apps.ts`; URL builder/constants in `strategy-components/lib/light-app.ts`. Backend: `/api/light-apps` (global/shared, admin-gated writes).
- **菜单管理 (Menu Management, admin-only)**: an **overlay** over the static sidebar menu — `MenuManagementPage` (`pages/MenuManagementPage.tsx`, route `/page/strategy/admin/menu-management`, opened from the admin-only 「菜单管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`). Admins rename / 停用·启用 / reorder (↑↓ or @dnd-kit drag) / re-parent (horizontal drag **or** the edit dialog's 「移动到」parent selector) any node across 一级/二级/三级, **including injected iframe light-app nodes** (`light-app-<appId>`). The static tree (`core/page-layout/sidebar-menu.ts`) stays the source of icons/routes; only per-node deltas (`label`/`disabled`/`parentId`/`sortOrder`) persist to the backend. Merge logic in `core/page-layout/menu-overrides.ts` (`applyMenuOverrides`, applied in `use-sidebar-menu.ts` after light-app injection, before role filter; disabling a node hides its whole subtree) — strict **3-level cap** (`wouldExceedDepth`). Client `strategy-components/api/menu-overrides.ts`. Backend: `/api/menu-overrides` (global/shared; open read, admin atomic replace-all).
- **敏感词管理 (Sensitive Word Management)**: configures the **展示层脱敏映射** (原始词 → 替换词). **Gated on the username `lqq`** (not the admin role) — `getAccountDisplayName().toLowerCase() === "lqq"` (username = email `@` prefix, else `user_id`, same as the profile page); the dropdown entry, the route guard, and the page-level guard all use this check. `src/lib/desensitize.ts` ships a frozen seed map `SEED_DESENSITIZE_MAP` (the deployment seed) plus a live mutable `DESENSITIZE_MAP` (initialized from the seed so `desensitize()` works before any fetch). `DesensitizeWordsLoader` (mounted in `App.tsx` `AppProviders`) fetches `/api/sensitive-words` on startup and, if non-empty, calls `replaceDesensitizeMap(...)` to make the backend config the source of truth (empty/failed → keep seed). Page `SensitiveWordsPage.tsx` (route `/page/strategy/admin/sensitive-words`, opened from the 「敏感词管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`, present in **both** full + collapsed sidebar modes) lists/adds/edits/启停/deletes words and saves the **whole set atomically** (replace-all); a 「导入种子词」 button merges any missing `SEED_DESENSITIZE_MAP` entries into the editor. Client + hooks in `strategy-components/api/sensitive-words.ts` (`wordsToMap` folds enabled rows into the runtime map). Backend: `/api/sensitive-words` (global/shared; open read, write allowed for admin **or** the `lqq` account), mirroring 菜单管理's store shape. **侧边栏 + 导航栏 menu labels are desensitized** at the data source: `useSidebarMenuItems`/`useActiveThirdLevel` (`core/page-layout/use-sidebar-menu.ts`) map every node's `label` through a desensitizer built **directly from the `/api/sensitive-words` query** (`makeDesensitizer(wordsToMap(words))`, falling back to the global seed `desensitize` while empty) — this sidesteps the `replaceDesensitizeMap` effect-timing race. Only `label` is rewritten; `path`/`id`/`icon` are untouched so routing/highlight are unaffected. All nav surfaces (`page-sidebar.tsx`, `page-sidebar-dark.tsx`, `page-sidebar-v1.tsx`, `strategy-components/Header.tsx`, `PageRoutes.tsx`) consume this hook and are covered; `MenuManagementPage` uses the raw tree so admins still edit real labels.
- **技能地址管理 (Skill Address Management, admin-only)**: 扫描运行中的技能(`skills/{public,custom}` 下所有 `.md`/`.py`)里的 **http(s) URL 与 IP/IP:端口**,按唯一地址聚合全部出现位置(跨 .md/.py),支持**批量替换**(如把 UAT 地址一次性改成生产)。主体抽成可复用组件 `SkillAddressesPanel`(`pages/SkillAddressesPage.tsx` 导出,默认导出 `SkillAddressesPage` 仍保留旧路由 `/page/strategy/admin/skill-addresses` 作直链回退),**作为「技能地址管理」标签页嵌入管理员「技能管理」页 `pages/AdminSkillsPage.tsx`**(该页加 Tabs:「技能列表」+「技能地址管理」;入口在「设置和更多」下拉的「技能管理」`workspace-nav-menu.tsx` → `/page/workspace/admin/skills`,不再单列于 `components/page-sidebar.tsx` 左下角设置下拉):打开自动扫描并带**进度条**(扫描逐技能 / 应用逐文件 X/N,应对 150+ 技能),URL/IP 类型过滤 + 搜索 + 「片段批量套用」(如所有 `uat.4.cn` → `prod.4.cn`)、每地址「替换为」输入框(可展开看 `file:line` 片段)、内联**预览**、**应用**、**多关键词检索**(空格分隔全部命中),以及**修改记录**面板——每次应用生成一条记录(显示时间/改了哪些地址 from→to/文件数/处数),可**针对单次记录回退**(二次确认)。client + NDJSON 流式解析在 `strategy-components/api/skill-addresses.ts`。后端 `/api/skill-addresses`(**仅管理员**):所有文件 IO 走 `asyncio.to_thread` 不阻塞事件循环;`GET /scan`(+`/scan/stream`)、`POST /preview`、`POST /apply`(+`/apply/stream`)、`GET /backups`、`POST /rollback/{id}`;**子串安全替换**(基于 token span,不会误伤子串)、`expected_total` 乐观锁(409)、写前自动磁盘备份到 `{skills_root}/.address-edits/`(同时写一份 `{id}.manifest.json` 记录本次替换明细,供修改记录展示)、应用后刷新技能系统提示缓存。纯引擎 `deerflow/skills/address_scan.py`,router `app/gateway/routers/skill_addresses.py`,tests `tests/test_skill_addresses.py`。范围仅运行中技能,不动 `deploy/minimal/skills/`。
- **按钮管理 (Task Button Management, admin-only)**: configures the **可配置跳转按钮** rendered in the left task panel of the task deep-link workspaces (rwfx / 3qfx / xdfx, see `TaskFxWorkspace`). Each button = `{business, label, linkType, target, appendTaskId, idParam, idKind, enabled, sortOrder}`; `linkType` is `url` (外链 `window.open`, optional append of `?{idParam}={id}` — **`idParam` is the editable query-param name**, e.g. `id`/`task_id`), `business` (内部切换到另一业务, reuses `resolveTaskDeeplinkTarget`, always task id), or `purpose` (弹出当前任务的「任务目的」表格 via the shared `TaskPurposeDialog`, no target — configurable for any page incl. xdfx). **`idKind` (`task`/`action`) only matters for xdfx**: its deep-link `?taskId=` is an 行动id and the 任务id is resolved at login (`fetchTaskIdFromAction`) — `TaskContext` now also stashes the raw `actionId`, so a url button can append either (default `task`). Page `TaskButtonsPage.tsx` (route `/page/strategy/admin/task-buttons`, **admin-gated**, entry「按钮管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both full + collapsed modes) has per-business tabs, edits name/type/target/启停/排序/增删, saves the **whole set atomically** (replace-all), plus 「导入默认」 to merge code-seed defaults. **Seed/fallback** (like 敏感词管理): only when the whole table is empty (fresh deploy, never saved) do the workspace + page fall back to `defaultTaskButtons(cfg)` — rwfx's url buttons (编辑/下一步/3q详情) built from the **live** `/api/public/config/task-deeplink` plus cross-business switch buttons for **all three** businesses (each switches to the other two — rwfx→三情/行动, 3qfx→任务/行动, xdfx→任务/三情). Once saved, the store is the sole source of truth. The old hardcoded jump buttons were migrated out: `TaskFxWorkspace` no longer hardcodes 切换到三情分析, `TaskActionsPanel` keeps only the non-jump 清除记录, and `TaskPurposePanel` dropped its 3q详情 button (now configurable) **and defaults the 目的树 table to collapsed** (chevron toggle). Helpers `core/auth/task-buttons.ts` (`TaskButton`, `defaultTaskButtons`, `resolveTaskButtons`, `buttonsForBusiness`, `runTaskButton`), client+hooks `strategy-components/api/task-buttons.ts`. Backend: `/api/task-buttons` (global/shared; open read, admin replace-all), store `deerflow.persistence.task_buttons` (table `task_buttons`, auto-created by `create_all`), wired `app.state.task_button_store`. Tests: `tests/test_task_buttons.py`.
- **按钮管理 (Task Button Management, admin-only)**: configures the **可配置跳转按钮** rendered in the left task panel of the task deep-link workspaces (rwfx / 3qfx / xdfx, see `TaskFxWorkspace`). Each button = `{business, label, linkType, target, appendTaskId, idParam, idKind, enabled, sortOrder}`; `linkType` is `url` (外链 `window.open`, optional append of `?{idParam}={id}` — **`idParam` is the editable query-param name**, e.g. `id`/`task_id`), `business` (内部切换到另一业务, reuses `resolveTaskDeeplinkTarget`, always task id), or `purpose` (弹出当前任务的「任务目的」表格 via the shared `TaskPurposeDialog`, no target — configurable for any page incl. xdfx). **`idKind` (`task`/`action`) only matters for xdfx**: its deep-link `?taskId=` is an 行动id and the 任务id is resolved at login (`fetchTaskIdFromAction`) — `TaskContext` now also stashes the raw `actionId`, so a url button can append either (default `task`). Page `TaskButtonsPage.tsx` (route `/page/strategy/admin/task-buttons`, **admin-gated**, entry「按钮管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both full + collapsed modes) has per-business tabs, edits name/type/target/启停/排序/增删, saves the **whole set atomically** (replace-all), plus 「导入默认」 to merge code-seed defaults. **Seed/fallback** (like 敏感词管理): only when the whole table is empty (fresh deploy, never saved) do the workspace + page fall back to `defaultTaskButtons(cfg)` — rwfx's url buttons (编辑/上一步/下一步/3q详情) built from the **live** `/api/public/config/task-deeplink` plus cross-business switch buttons for **all three** businesses (each switches to the other two — rwfx→三情/行动, 3qfx→任务/行动, xdfx→任务/三情). Once saved, the store is the sole source of truth. **Bottom 快捷跳转 bar groups by prev/next**: `TaskJumpBar` renders only「上一步/下一步」-type buttons in the bottom bar — a `prev` group (id 含 `prev` 或文案「上一步」, 描边次要样式 + ←图标) rendered **左侧**, then a `next` group (id 含 `next` 或文案「下一步」, 实心主色) on the **右侧** (container `justify-end`); everything else goes to the right-edge floating menu. The default 上一步 button (`rwfx-prev`, `url`, target = `DASHBOARD_AGENT_ROUTE` `/page/strategy/dashboard-agent`, `appendTaskId` + `idParam=taskId` → `?taskId=任务id`, `openMode=self`) 默认指向**应用内**「大屏绘制」页,在 **both** 单智能体 (`TaskFxWorkspace`) 与 多智能体会商 (`RoundtablePlanningPage` 深链 rwfx-A) 都显示(共用 `TaskJumpBar`)。**`runTaskButton` 的 `url` 类型支持应用内路由**:target 以单个 `/` 开头时按内部路由处理——`self` 走 react-router 同窗导航(不刷新),`blank` 拼成当前源的 hash 路由新标签打开;外链行为不变。 The old hardcoded jump buttons were migrated out: `TaskFxWorkspace` no longer hardcodes 切换到三情分析, `TaskActionsPanel` keeps only the non-jump 清除记录, and `TaskPurposePanel` dropped its 3q详情 button (now configurable) **and defaults the 目的树 table to collapsed** (chevron toggle). Helpers `core/auth/task-buttons.ts` (`TaskButton`, `defaultTaskButtons`, `resolveTaskButtons`, `buttonsForBusiness`, `runTaskButton`), client+hooks `strategy-components/api/task-buttons.ts`. Backend: `/api/task-buttons` (global/shared; open read, admin replace-all), store `deerflow.persistence.task_buttons` (table `task_buttons`, auto-created by `create_all`), wired `app.state.task_button_store`. Tests: `tests/test_task_buttons.py`.
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). **xdfx additionally partitions its chat records by 行动id (action_id), NOT by task_id**: `resolveTaskDeeplinkTarget` sets `partitionByAction:true` + keeps the raw action_id as `TaskContext.actionId`, so new threads are tagged `metadata.{taskId,actionId}` (taskId kept only to preserve the backend「任务深链对话全局共享」semantics, which keys off `metadata.taskId`) and the conversation list filters by `actionId` (+`agent_id`) — different actions of the same task get separate lists. xdfx's first-question opening text also appends `行动id(action_id)为…` (see `buildOpeningText` / `taskThreadMetadata`). goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. The roundtable target also threads the URL `taskId` into `roundtablePrefill.taskId` (`resolveTaskDeeplinkTarget(goPath, detail, taskId)`), which turns on two taskId-scoped behaviors: (1) **separate, unpartitioned per-task storage** — taskId 会商聊天记录 live in their **own** store/table (`roundtable_task_drafts`), keyed **only by `task_id`** (one taskId = many records, shared across users, **no user 分权** at all; `created_by` is audit-only), kept entirely out of the per-user personal store (`roundtable_drafts`, now strictly per-user) so the two never mix. Backend router `/api/roundtable-task-drafts` (`GET /by-task/{id}` + `/by-task/{id}/latest`, `POST`, `GET/PUT/DELETE /{id}` — all user-agnostic); frontend client `roundtable-planning/api/task-drafts.ts`, and `useDraftPersistence`/`useRoundtableDrafts` route **all** CRUD to it when a `taskId` is present (else the personal `drafts.ts`). The matching **background jobs** are shared by task too: `roundtable_jobs.task_id` marks a task job; reads/dedup/stream/resume/cancel pass `?task_id=` so any user opening the task sees the same running 研讨 (progress/flowchart), and the executor writes the final report back to the task-draft store. Existing rows are moved over by `scripts/migrate_roundtable_task_drafts.py` (migration `20260618_01`). The history dropdown filters to the task and 新建 keeps the binding; (2) **Step-3 auto structured output** — after the `roundtable-summary` agent writes the Markdown report it automatically runs a second round emitting a `flow-json` flowchart (`useStep3Summary` `autoFlow`+`chainLevels`), whose hierarchy follows the business chain's stage goals (任务 → 目的 → 行为体 → …; coordinatorPrompt-specified hierarchy wins) and whose nodes never carry 阶段编号/阶段名 (the prior bug). **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. **All three single-agent businesses share `TaskFxWorkspace`** (`task-components/TaskFxWorkspace.tsx`): left = a「当前任务」card (`readCopTaskDetail()` 任务名称 + 简介, desensitized, 留存 above 新建对话) + per-task 1:N conversation list (`useTaskThreads(taskId, agentId, actionId?)` — filtered by **both** `metadata.taskId` AND `metadata.agent_id` so the three businesses' conversations staLine truncated
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
- **操作日志(Y-Log)上报** — 用户的关键操作(登录登出/查询/查看/增删改/启停/导入导出/问答等)成功后,**前端直连**外部接口 `POST {write_url}`(默认 `https://ch1.b.uat.4.cn/api/y-log/write`)记一条审计日志。核心模块 `src/core/log/`:`y-log.ts`(`writeYLog(params)` + `OptType` 枚举 0/1/3..12;**异步即发即忘、永不 await、永不抛错、失败静默**,自动把完整 url 转相对路径去 ip/host、对象入参/返回自动 `JSON.stringify` + 50k 裁剪、`optResult` 恒 0 只报成功),`y-log-config.ts`(从公开只读 `GET /api/public/config/y-log` 拉 `{enabled, writeUrl}`,模块级缓存 + 去重 + 默认兜底;`App.tsx` `AppProviders` 启动预热 `fetchYLogConfig()`),`y-log-token.ts`(token1 = token 登录的 `?authToken=`,经 [[scoped-storage]] 的 `authStorage*` 存取,嵌入态自动隔离)。**双门控**:仅当①存在 token1(即用 token 登录,`LoginPage` 成功后 `persistYLogToken(authToken)`,登出 `account-settings-page.tsx` 先报后清 token1)且②配置 `enabled && writeUrl` 才上报;否则一律不发。`optDetail` 统一「B1-CM助手-…」(**禁内部框架名**)。埋点**广覆盖**各 API client 的成功路径——原则是「一个用户操作(查看/查询/新增/编辑/删除/启停/导入导出)= 一条日志」,每个 API client 的**单条详情 GET(查看→view 4)/ 列表查询 GET(search 3)/ 新增 POST(create 9)/ 改 PUT·PATCH(edit 5)/ 删 DELETE(delete 6)/ 启停(enabled 11 / disabled 10)/ 导入导出(import 7 / export 8)**都各落一条,仅跳过高频 typeahead/状态轮询/纯 bootstrap config 读。覆盖文件:`strategy-components/api/{sensitive-words,menu-overrides,task-buttons,skill-addresses,light-apps,business-mapping}.ts`、`roundtable-planning/api/{drafts,task-drafts,roundtable-jobs,recommend,chains,multi-agent,dashboard-sessions}.ts`、`core/{agents,scheduled-tasks,knowledge,positions,tags,studio,system-settings,memory,mcp,models,custom-prompts,user-preferences,notifications,recommended-questions,user-qa,curator,admin,thread-shares,roundtable-draft-shares,tool-metrics,llm-metrics,note,artifacts}/api.ts`、`core/api/markdown-docx-export.ts`。**问答(Q&A)改为「一次大模型调用 = 一条日志」**:在共享的 `core/threads/hooks.ts` `useThreadStream` 的 `onLangChainEvent` 里监听 `on_chat_model_end`,每次模型调用结束就上报一条(optType 12,`reqParam` 取本次 input 的最后一条 user 文本 + 模型名,`returnParam` 取本次输出文本)——一个问答轮次里 lead agent / 子代理的**每次** LLM 调用都各记一条,覆盖所有走 `useThreadStream` 的页面(`ChatPage`/`AgentChatPage`/创建智能体/iframe/会商等);`ChatPage`/`AgentChatPage` 的 `onFinish` 仍额外保留一条轮次汇总。后端仅新增公开只读配置:`deerflow/config/y_log_config.py`(`YLogConfig{enabled,write_url}`)挂到 `AppConfig.y_log`,`app/gateway/routers/public_config.py` 加 `GET /api/public/config/y-log`,地址写在 `config.yaml` 的 `y_log` 段(mtime 热重载,前端无需重建);**不做后端代理**。Tests:`tests/test_y_log_config.py`。
### Configuration
+3
View File
@@ -10,6 +10,9 @@ VITE_MOCK_COP_TASK_DETAIL=true
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:true 走本地样例假数据(真实接口未就绪时调试用);联调通过后置 false。
VITE_MOCK_SQ_REPORT=true
# 深链任务详情(cop-task-detail:任务名称/描述)数据源:true 走本地假数据(真实接口未就绪时调试用);联调通过后置 false。
VITE_MOCK_COP_TASK_DETAIL=true
# Gateway / DeerFlow API
VITE_BACKEND_BASE_URL=http://127.0.0.1:8001
VITE_LANGGRAPH_BASE_URL=http://127.0.0.1:8001/api
+3
View File
@@ -10,6 +10,9 @@ VITE_MOCK_COP_TASK_DETAIL=false
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:默认真实接口;真实接口未就绪可改 true 走本地样例假数据。
VITE_MOCK_SQ_REPORT=false
# 深链任务详情(cop-task-detail)数据源:默认真实接口;真实接口未就绪可改 true 走本地假数据。
VITE_MOCK_COP_TASK_DETAIL=false
# Gateway / DeerFlow API
VITE_BACKEND_BASE_URL=http://47.88.25.99:7001
VITE_LANGGRAPH_BASE_URL=http://47.88.25.99:7001/api
+3
View File
@@ -10,6 +10,9 @@ VITE_MOCK_COP_TASK_DETAIL=false
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:默认真实接口;真实接口未就绪可改 true 走本地样例假数据。
VITE_MOCK_SQ_REPORT=false
# 深链任务详情(cop-task-detail)数据源:默认真实接口;真实接口未就绪可改 true 走本地假数据。
VITE_MOCK_COP_TASK_DETAIL=false
# Gateway / DeerFlow API
VITE_BACKEND_BASE_URL=https://ch1.b.sit.4.cn/deerflow
VITE_LANGGRAPH_BASE_URL=https://ch1.b.sit.4.cn/deerflow/api
@@ -826,7 +826,13 @@ const DocumentUploadPopupContent: FC<{
</Button>
</div>
)}
{listData.length === 0 && <Empty />}
{isSearching ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : (
listData.length === 0 && <Empty />
)}
{searchType === "human" && (
<div className="bg-white p-[10px] grid grid-cols-5 gap-[10px]">
{listData.map((item: listDataItem, index: number) => {
@@ -545,7 +545,12 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
</div>
)}
<div className="p-[10px]">
<div className="grid grid-cols-4 gap-[10px] user-list">
{isSearching ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : null}
<div className={`grid grid-cols-4 gap-[10px] user-list${isSearching ? ' hidden' : ''}`}>
{userList.map((item, index) => (
<div key={index} className="user-item p-[10px] relative">
<div className="absolute top-[5px] right-[10px]">
@@ -230,6 +230,10 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
);
const [editPublished, setEditPublished] = useState(agent.published);
const [editIsPrivate, setEditIsPrivate] = useState(agent.is_private);
// 会商席位「技能识别强化」开关(弱模型补偿)。默认关。
const [editSeatSkillDirective, setEditSeatSkillDirective] = useState(
agent.seat_skill_directive ?? false,
);
const [editSquareId, setEditSquareId] = useState(agent.square_id ?? "");
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
const { data: publishSquares } = usePublishSquares();
@@ -277,6 +281,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
setEditSquareId(agent.square_id ?? "");
setSelectedSkills(agent.skills ?? []);
setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions));
setEditSeatSkillDirective(agent.seat_skill_directive ?? false);
}, [
agent.common_questions,
agent.description,
@@ -285,6 +290,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
agent.published,
agent.square_id,
agent.skills,
agent.seat_skill_directive,
editOpen,
]);
@@ -298,6 +304,8 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
if (agentDetail) {
setEditSoul(agentDetail.soul ?? "");
setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions));
// 列表响应不带 config 额外字段(seat_skill_directive 为 null),详情才有真值。
setEditSeatSkillDirective(agentDetail.seat_skill_directive ?? false);
} else {
setEditSoul(agent.soul ?? "");
}
@@ -389,6 +397,8 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
request.skills = selectedSkills;
if (JSON.stringify(nextQuestions) !== JSON.stringify(baselineQuestions))
request.common_questions = nextQuestions;
if (editSeatSkillDirective !== ((agentDetail?.seat_skill_directive ?? agent.seat_skill_directive) ?? false))
request.seat_skill_directive = editSeatSkillDirective;
if (Object.keys(request).length === 0) {
setEditOpen(false);
@@ -983,6 +993,19 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
onChange={setEditCommonQuestions}
/>
</div>
<div className="flex items-center justify-between gap-3 rounded-md border p-3">
<div>
<p className="text-sm font-medium">会商技能识别强化</p>
<p className="text-muted-foreground text-xs">
作为会商席位时,把已配置技能(含 SKILL.md 路径与「先 read_file
再用」硬指令)拼进任务,补偿弱模型不识别技能。也可在业务链条配置里打开(任一即生效)。
</p>
</div>
<Switch
checked={editSeatSkillDirective}
onCheckedChange={setEditSeatSkillDirective}
/>
</div>
<div className="flex items-center justify-between rounded-md border p-3">
<div>
<p className="text-sm font-medium">公开发布</p>
@@ -78,6 +78,8 @@ interface AgentDraft {
published: boolean;
featured: boolean;
templateName: string;
/** 会商席位「技能识别强化」开关。 */
seatSkillDirective: boolean;
}
function draftFromAgent(agent: Agent): AgentDraft {
@@ -90,6 +92,7 @@ function draftFromAgent(agent: Agent): AgentDraft {
published: agent.published,
featured: agent.featured_order != null,
templateName: agent.template_name ?? "",
seatSkillDirective: agent.seat_skill_directive ?? false,
};
}
@@ -302,6 +305,8 @@ export function AgentDetailPanel({
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
if (draft.templateName.trim() !== (agent.template_name ?? ""))
request.template_name = draft.templateName.trim();
if (draft.seatSkillDirective !== (agent.seat_skill_directive ?? false))
request.seat_skill_directive = draft.seatSkillDirective;
if (nextPublished !== agent.published) request.published = nextPublished;
if (JSON.stringify(draft.skills) !== JSON.stringify(agent.skills ?? []))
request.skills = draft.skills;
@@ -588,6 +593,21 @@ export function AgentDetailPanel({
配置后,对话生成的 Markdown 文件可一键发布到知识入库接口。
</p>
</div>
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
<div className="pr-3">
<p className="text-sm font-medium">会商技能识别强化</p>
<p className="text-muted-foreground text-xs">
作为会商席位时,把已配置技能(含 SKILL.md 路径与「先 read_file
再用」硬指令)拼进任务,补偿弱模型不识别技能。也可在业务链条配置中打开(任一即生效)。
</p>
</div>
<Switch
checked={draft.seatSkillDirective}
onCheckedChange={(checked) =>
setDraft({ ...draft, seatSkillDirective: checked })
}
/>
</div>
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
<div>
<p className="text-sm font-medium">公开发布</p>
@@ -32,6 +32,10 @@ interface AgentSelectorProps {
disabled?: boolean;
/** 紧凑模式(CM 参考图):触发器改为灰底胶囊 + 主色机器人图标。 */
compact?: boolean;
/** 图标模式:用于 iframe 等底栏场景,仅显示机器人图标和可选清空按钮。 */
triggerVariant?: "default" | "icon";
iconButtonClassName?: string;
iconActiveClassName?: string;
}
/**
@@ -48,6 +52,9 @@ export function AgentSelector({
onAgentChange,
disabled,
compact = false,
triggerVariant = "default",
iconButtonClassName,
iconActiveClassName,
}: AgentSelectorProps) {
const [open, setOpen] = useState(false);
const [manageOpen, setManageOpen] = useState(false);
@@ -79,48 +86,84 @@ export function AgentSelector({
};
const triggerLabel = selectedAgent ? desensitize(selectedAgent.name) : "选择 Agent";
const iconMode = triggerVariant === "icon";
return (
<>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<PromptInputButton
type="button"
disabled={disabled}
className={cn(
"gap-1.5! rounded-full border px-3! shadow-none transition-colors",
compact && "rounded-lg px-2.5! py-1! text-[11px] font-medium",
compact
? "border-transparent bg-gray-50/60 text-gray-600 hover:bg-gray-100/80 hover:text-gray-800 dark:bg-slate-700/50 dark:text-slate-300 dark:hover:bg-slate-700"
: selectedAgent
? "border-[#d6a868] bg-[#fff3df] text-[#7a5417] hover:bg-[#ffe8c4]"
: "border-[#eee3d5] bg-[#fffaf5] text-[#7e6a57] hover:bg-white dark:border-slate-600 dark:bg-slate-700/50 dark:text-slate-300 dark:hover:bg-slate-700",
)}
>
<BotIcon
className={cn("size-3", compact && "text-[var(--primary)]")}
/>
<span className="max-w-[140px] truncate text-xs font-normal">
{triggerLabel}
</span>
{selectedAgent && (
<span
role="button"
tabIndex={0}
aria-label="清除已选 agent"
className="ml-0.5 inline-flex items-center justify-center rounded-full p-0.5 hover:bg-[#ffd9a7]"
onClick={handleClear}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onAgentChange(null);
}
}}
>
<XIcon className="size-3" />
{iconMode ? (
<Button
type="button"
variant="ghost"
size="icon"
disabled={disabled}
aria-label={selectedAgent ? `已选择智能体:${triggerLabel}` : "选择智能体"}
className={cn(
"relative size-9 rounded-full text-muted-foreground shadow-none hover:bg-muted/60 hover:text-foreground",
selectedAgent && "text-amber-600 hover:text-amber-700",
selectedAgent && iconActiveClassName,
iconButtonClassName,
)}
>
<BotIcon className="size-4" />
{selectedAgent && (
<span
role="button"
tabIndex={0}
aria-label="清除已选 agent"
className="absolute -right-1 -top-1 inline-flex size-4 items-center justify-center rounded-full border bg-background text-foreground shadow-sm hover:bg-muted"
onClick={handleClear}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onAgentChange(null);
}
}}
>
<XIcon className="size-2.5" />
</span>
)}
</Button>
) : (
<PromptInputButton
type="button"
disabled={disabled}
className={cn(
"gap-1.5! rounded-full border px-3! shadow-none transition-colors",
compact && "rounded-lg px-2.5! py-1! text-[11px] font-medium",
compact
? "border-transparent bg-gray-50/60 text-gray-600 hover:bg-gray-100/80 hover:text-gray-800 dark:bg-slate-700/50 dark:text-slate-300 dark:hover:bg-slate-700"
: selectedAgent
? "border-[#d6a868] bg-[#fff3df] text-[#7a5417] hover:bg-[#ffe8c4]"
: "border-[#eee3d5] bg-[#fffaf5] text-[#7e6a57] hover:bg-white dark:border-slate-600 dark:bg-slate-700/50 dark:text-slate-300 dark:hover:bg-slate-700",
)}
>
<BotIcon
className={cn("size-3", compact && "text-[var(--primary)]")}
/>
<span className="max-w-[140px] truncate text-xs font-normal">
{triggerLabel}
</span>
)}
</PromptInputButton>
{selectedAgent && (
<span
role="button"
tabIndex={0}
aria-label="清除已选 agent"
className="ml-0.5 inline-flex items-center justify-center rounded-full p-0.5 hover:bg-[#ffd9a7]"
onClick={handleClear}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onAgentChange(null);
}
}}
>
<XIcon className="size-3" />
</span>
)}
</PromptInputButton>
)}
</DialogTrigger>
<DialogContent className="overflow-hidden p-0 sm:max-w-md">
<DialogTitle className="sr-only">选择 Agent</DialogTitle>
@@ -0,0 +1,186 @@
"use client";
import { Check, LayoutIcon, PanelLeftIcon, Shirt } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useTheme, type ThemeType } from "@/contexts/ThemeContext";
import { useLayoutMode } from "@/core/system-settings/hooks";
import { cn } from "@/lib/utils";
/**
* 换肤 / 界面模式 顶栏控件。深色顶栏(Header)与简洁模式页面级顶栏(ChatPage 等)共用,
* 通过 `tone` 适配不同底色:
* - "banner-dark" / "banner-light":Header 落在主题 banner 上(白字 / 浅色 hover)。
* - "content":简洁模式聊天页浅底顶栏,走 foreground / muted-foreground。
*/
export type AppearanceControlTone = "banner-dark" | "banner-light" | "content";
// 换肤色板:红色=红白主题(light),蓝色=浅蓝主题(lightblue),深蓝色=深色主题(dark)
export const THEME_SWATCHES: { id: ThemeType; label: string; color: string }[] = [
{ id: "light", label: "红色", color: "#cf1322" },
{ id: "lightblue", label: "蓝色", color: "#0062d9" },
{ id: "dark", label: "深蓝色", color: "#002466" },
];
const triggerToneClass = (tone: AppearanceControlTone) =>
tone === "banner-dark"
? "text-slate-400 hover:bg-slate-800/50 hover:text-slate-400"
: tone === "banner-light"
? "text-white hover:bg-[var(--brand-950)] hover:text-white active:bg-[#8a0618]"
: "text-muted-foreground hover:bg-muted hover:text-foreground";
export function ThemeSwitcher({ tone }: { tone: AppearanceControlTone }) {
const { theme, setTheme } = useTheme();
const [open, setOpen] = useState(false);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const cancelClose = () => {
if (closeTimer.current) {
clearTimeout(closeTimer.current);
closeTimer.current = null;
}
};
const scheduleClose = () => {
cancelClose();
closeTimer.current = setTimeout(() => setOpen(false), 120);
};
useEffect(() => () => cancelClose(), []);
return (
<div
className="relative"
onMouseEnter={() => {
cancelClose();
setOpen(true);
}}
onMouseLeave={scheduleClose}
>
<Button
type="button"
variant="ghost"
size="icon-sm"
className={cn("size-8 shrink-0 rounded-sm", triggerToneClass(tone))}
title="换肤"
aria-haspopup="true"
aria-expanded={open}
>
<Shirt className="size-4" />
</Button>
{open ? (
<div className="absolute top-full left-1/2 z-50 -translate-x-1/2 pt-2">
<div className="relative flex items-center gap-2 rounded-lg border border-black/5 bg-white px-2.5 py-1.5 shadow-lg">
<div className="absolute -top-1 left-1/2 size-2 -translate-x-1/2 rotate-45 rounded-[1px] border-t border-l border-black/5 bg-white" />
{THEME_SWATCHES.map((swatch) => {
const active = theme === swatch.id;
return (
<button
key={swatch.id}
type="button"
title={swatch.label}
aria-label={swatch.label}
aria-pressed={active}
onClick={() => {
setTheme(swatch.id);
setOpen(false);
}}
className="size-5 rounded-full transition-transform hover:scale-110"
style={{
backgroundColor: swatch.color,
boxShadow: active
? `0 0 0 1.5px #ffffff, 0 0 0 3px ${swatch.color}`
: undefined,
}}
/>
);
})}
</div>
</div>
) : null}
</div>
);
}
const LAYOUT_OPTIONS = [
{
id: "full" as const,
label: "全量模式",
description: "展示侧边栏与顶栏导航",
icon: PanelLeftIcon,
},
{
id: "compact" as const,
label: "简洁模式",
description: "隐藏侧边栏与顶栏,获得更大工作区",
icon: LayoutIcon,
},
];
/**
* 界面模式(全量 / 简洁)下拉切换。换肤旁并排,图标 + 下拉:
* - 简洁模式 ChatPage 顶栏(全局顶栏被隐藏)。
* - 全量模式 Header 右上角。
* 用户未显式设置过界面模式时(mode === undefined),当前态按调用方所在的实际界面
* 兜底——`fallback` 指明这一回退值(Header 传 "full",ChatPage 传 "compact")。
*/
export function LayoutModeSwitcher({
tone,
fallback = "compact",
}: {
tone: AppearanceControlTone;
fallback?: "full" | "compact";
}) {
const [mode, setLayoutMode] = useLayoutMode();
const current = mode ?? fallback;
const TriggerIcon = current === "full" ? PanelLeftIcon : LayoutIcon;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-sm"
className={cn("size-8 shrink-0 rounded-sm", triggerToneClass(tone))}
title="界面模式"
aria-label="界面模式"
>
<TriggerIcon className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={8} className="min-w-56 rounded-lg">
<DropdownMenuLabel>界面模式</DropdownMenuLabel>
<DropdownMenuSeparator />
{LAYOUT_OPTIONS.map((option) => {
const Icon = option.icon;
const active = current === option.id;
return (
<DropdownMenuItem
key={option.id}
onClick={() => setLayoutMode(option.id)}
className="gap-2"
>
<Icon className="size-4 shrink-0" />
<div className="flex min-w-0 flex-col">
<span className="text-sm leading-tight">{option.label}</span>
<span className="text-muted-foreground text-xs leading-tight">
{option.description}
</span>
</div>
{active && <Check className="ml-auto size-4 shrink-0" />}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -1,6 +1,6 @@
import type { Message } from "@langchain/langgraph-sdk";
import type { BaseStream } from "@langchain/langgraph-sdk/react";
import { CheckIcon, SendIcon, XIcon } from "lucide-react";
import { CheckIcon, PenLineIcon, SendIcon, XIcon } from "lucide-react";
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useStickToBottomContext } from "use-stick-to-bottom";
@@ -20,10 +20,10 @@ import {
groupMessages,
hasContent,
hasPresentFiles,
hasReasoning,
hasToolCalls,
isHiddenFromUIMessage,
} from "@/core/messages/utils";
hasReasoning,
hasToolCalls,
isHiddenFromUIMessage,
} from "@/core/messages/utils";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
import { useSkills } from "@/core/skills/hooks";
@@ -103,6 +103,7 @@ export function MessageList({
onSetupAgentReject,
onSetupWritingApprove,
onSetupWritingReject,
onSetupWritingStart,
}: {
className?: string;
contentClassName?: string;
@@ -120,6 +121,8 @@ export function MessageList({
onSetupAgentReject?: (payload: SetupAgentApprovalPayload) => void | Promise<void>;
onSetupWritingApprove?: (payload: SetupWritingApprovalPayload) => void | Promise<void>;
onSetupWritingReject?: (payload: SetupWritingApprovalPayload) => void | Promise<void>;
/** 审批卡「直接开始写作」回调:应用配置(含已确认大纲)并立即启动写作流程(仅写作页提供,模板编辑等场景缺省隐藏该按钮)。 */
onSetupWritingStart?: (payload: SetupWritingApprovalPayload) => void | Promise<void>;
}) {
const baseRehypePlugins = useRehypeSplitWordsIntoSpans(thread.isLoading);
const rehypePlugins = useMemo(
@@ -152,10 +155,10 @@ export function MessageList({
});
}, []);
const allMessages = useMemo(
() => thread.messages.filter((m) => !isHiddenFromUIMessage(m)),
[thread.messages],
);
const allMessages = useMemo(
() => thread.messages.filter((m) => !isHiddenFromUIMessage(m)),
[thread.messages],
);
const messages = useMemo(
() =>
hiddenMessageIds.size === 0
@@ -430,6 +433,7 @@ export function MessageList({
message={message}
onApprove={onSetupWritingApprove}
onReject={onSetupWritingReject}
onStart={onSetupWritingStart}
/>
<MessageTokenUsageList
enabled={tokenUsageEnabled}
@@ -629,6 +633,8 @@ export type SetupAgentApprovalPayload = {
export type SetupWritingApprovalPayload = {
user_intent?: string;
article_type?: string;
/** 当 article_type 是已有类型库里没有的新类型时,模型识别出的一句话特征说明(命中已有类型时为空)。 */
article_type_detail?: string;
word_count_target?: number | null;
target_audience?: string;
writing_mode?: string;
@@ -820,14 +826,16 @@ function SetupWritingApprovalCard({
message,
onApprove,
onReject,
onStart,
}: {
disabled: boolean;
message: unknown;
onApprove?: (payload: SetupWritingApprovalPayload) => void | Promise<void>;
onReject?: (payload: SetupWritingApprovalPayload) => void | Promise<void>;
onStart?: (payload: SetupWritingApprovalPayload) => void | Promise<void>;
}) {
const payload = getSetupWritingApprovalPayload(message);
const [submitting, setSubmitting] = useState<"approve" | "reject" | null>(
const [submitting, setSubmitting] = useState<"approve" | "reject" | "start" | null>(
null,
);
@@ -838,7 +846,7 @@ function SetupWritingApprovalCard({
const approvalPayload = payload;
const busy = disabled || submitting !== null;
async function run(action: "approve" | "reject") {
async function run(action: "approve" | "reject" | "start") {
if (busy) {
return;
}
@@ -846,6 +854,8 @@ function SetupWritingApprovalCard({
try {
if (action === "approve") {
await onApprove?.(approvalPayload);
} else if (action === "start") {
await onStart?.(approvalPayload);
} else {
await onReject?.(approvalPayload);
}
@@ -854,9 +864,14 @@ function SetupWritingApprovalCard({
}
}
const hasNewType = !!approvalPayload.article_type_detail?.trim();
const rows: Array<{ label: string; value: string }> = [];
if (approvalPayload.article_type) {
rows.push({ label: "文章类型", value: approvalPayload.article_type });
rows.push({
label: "文章类型",
// 新类型(列表外)标注「· 新」,让用户知道这是模型新识别的类型。
value: hasNewType ? `${approvalPayload.article_type} · 新` : approvalPayload.article_type,
});
}
if (typeof approvalPayload.word_count_target === "number") {
rows.push({ label: "目标字数", value: `${approvalPayload.word_count_target} 字` });
@@ -903,6 +918,13 @@ function SetupWritingApprovalCard({
</div>
) : null}
{hasNewType ? (
<div className="space-y-1">
<div className="text-muted-foreground text-xs">新类型说明</div>
<p className="text-sm leading-6">{approvalPayload.article_type_detail}</p>
</div>
) : null}
{approvalPayload.outline ? (
<div className="space-y-1">
<div className="text-muted-foreground text-xs">已有大纲</div>
@@ -926,6 +948,7 @@ function SetupWritingApprovalCard({
</Button>
<Button
type="button"
variant={onStart ? "outline" : "default"}
size="sm"
disabled={busy || !onApprove}
onClick={() => void run("approve")}
@@ -933,6 +956,17 @@ function SetupWritingApprovalCard({
<CheckIcon className="h-4 w-4" />
应用到表单
</Button>
{onStart ? (
<Button
type="button"
size="sm"
disabled={busy}
onClick={() => void run("start")}
>
<PenLineIcon className="h-4 w-4" />
直接开始写作
</Button>
) : null}
</div>
</div>
);
@@ -71,9 +71,10 @@ function StatusBadge({ draft }: { draft: DraftMeta }) {
if (draft.status === "error") {
return <span className="text-[10px] font-medium text-rose-500">出错</span>;
}
// 非进行中/待澄清/出错时,展示本次会商所用业务链(无链条 → 自由模式)。
return (
<span className="text-[10px] font-medium text-muted-foreground">
第 {draft.furthestStep} 步
{draft.chainTitle || "自由模式"}
</span>
);
}
@@ -1,7 +1,7 @@
"use client";
import { DropletIcon, LayoutGridIcon, LayoutIcon, ListIcon, MoonIcon, PanelLeftIcon, SunIcon } from "lucide-react";
import { useMemo, type ComponentType, type SVGProps } from "react";
import { useMemo, useState, type ComponentType, type SVGProps } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
@@ -20,6 +20,8 @@ import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { getStoredAuth } from "@/core/auth";
import { migrateAuthToSession } from "@/core/auth/scoped-storage";
import { isIsolatedSession, setIsolatedSession } from "@/core/embed/embed-session";
import { enUS, isLocale, zhCN, type Locale } from "@/core/i18n";
import { useI18n } from "@/core/i18n/hooks";
import { useLocalSettings } from "@/core/settings";
@@ -64,6 +66,29 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
const cleanupWords =
citationDisplay?.cleanup_words ?? settings.display.citationCleanupWords ?? [];
// 独立登录会话(本标签页):开关切换鉴权存储 localStorage ↔ sessionStorage(见 scoped-storage)。
const [isolatedSession, setIsolatedSessionState] = useState(() => isIsolatedSession());
const handleToggleIsolatedSession = (checked: boolean) => {
if (checked) {
// 先把当前账号从 localStorage 快照搬进 sessionStorage,再翻标志,避免切换存储后被登出。
migrateAuthToSession();
setIsolatedSession(true);
setIsolatedSessionState(true);
toast.success("已开启独立登录会话", {
description:
"本标签页的登录已与其它标签页隔离:在别的窗口登录或切换其它账号都不会影响这里,你也可以在此单独登录另一个账号。该独立会话只存在于当前标签页,关闭此标签后即结束(需重新登录)。",
duration: 9000,
});
} else {
setIsolatedSession(false);
setIsolatedSessionState(false);
toast.info("已关闭独立登录会话", {
description: "本标签页恢复与其它标签页共享同一登录。如页面显示未及时同步,请刷新本页。",
duration: 6000,
});
}
};
const handleSetGlobalDefault = async (
value: "light" | "dark" | "lightblue",
) => {
@@ -395,6 +420,28 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
<Separator />
<SettingsSection
title="登录会话"
description="控制本标签页的登录身份是否与浏览器其它标签页隔离。"
>
<div className="flex items-start justify-between gap-4 rounded-lg border p-4">
<div>
<div className="text-sm font-medium">独立登录会话(本标签页)</div>
<p className="text-muted-foreground mt-1 max-w-md text-xs leading-relaxed">
开启后,本标签页的登录状态仅保存在当前标签页:在别的窗口登录或切换其它账号都不会影响这里,
你也可以在此单独登录另一个账号。关闭浏览器标签后该独立会话即结束(需重新登录)。
</p>
</div>
<Switch
checked={isolatedSession}
onCheckedChange={handleToggleIsolatedSession}
aria-label="独立登录会话"
/>
</div>
</SettingsSection>
<Separator />
<SettingsSection
title="对话体验"
description="问答过程中的辅助显示。"
+8
View File
@@ -58,6 +58,10 @@ export interface Agent {
/** 入库模板名(外部知识入库接口的 templateName)。配置后该智能体会话中的
* Markdown 产物右上角出现"发布入库"按钮。空/缺省 = 不支持入库。 */
template_name?: string | null;
/** 会商席位「技能识别强化」开关。作为会商席位运行时,是否把本智能体配置的技能
* (名称 + SKILL.md 路径 + 必须先 read_file 的硬指令) 拼进本轮任务以补偿弱模型。
* 与业务链条同名开关取 OR。null/false = 关 (默认)。 */
seat_skill_directive?: boolean | null;
tags?: Tag[];
featured_order?: number | null;
/** Whether the current user has favorited (收藏) this agent. */
@@ -91,6 +95,8 @@ export interface CreateAgentRequest {
tool_groups?: string[] | null;
common_questions?: AgentQuestion[] | null;
template_name?: string | null;
/** 会商席位「技能识别强化」开关;缺省/false = 关。 */
seat_skill_directive?: boolean | null;
}
export interface UpdateAgentRequest {
@@ -106,4 +112,6 @@ export interface UpdateAgentRequest {
common_questions?: AgentQuestion[] | null;
/** 入库模板名;传空字符串表示清除。 */
template_name?: string | null;
/** 会商席位「技能识别强化」开关;缺省/false = 关。 */
seat_skill_directive?: boolean | null;
}
+42 -4
View File
@@ -17,15 +17,17 @@
* sessionStorage、正常态恒为 localStorage;嵌入标志一进程内不翻转,故一致)。
*/
import { isEmbedActive } from "@/core/embed/embed-session";
import { isEmbedActive, isIsolatedSession } from "@/core/embed/embed-session";
/**
* 返回当前应使用的鉴权存储:嵌入态 → sessionStorage(按标签页隔离);否则 → localStorage。
* 非浏览器环境返回 null(调用方各自有 SSR 守卫)。
* 返回当前应使用的鉴权存储:嵌入态(iframe)**或**独立会话态(`?isolate=1`)→ sessionStorage
* (按标签页隔离);否则 → localStorage(跨标签共享、持久)。非浏览器环境返回 null(调用方各自
* 有 SSR 守卫)。两种隔离态等价于「本标签页鉴权独立、绝不污染其它标签页登录态」,区别仅在于嵌入态
* 还会去 chrome / 强制主题,独立会话态只切换存储。
*/
export function authStorage(): Storage | null {
if (typeof window === "undefined") return null;
return isEmbedActive() ? window.sessionStorage : window.localStorage;
return isEmbedActive() || isIsolatedSession() ? window.sessionStorage : window.localStorage;
}
/** 读受保护键(嵌入态 sessionStorage / 正常态 localStorage)。 */
@@ -54,3 +56,39 @@ export function authStorageRemove(key: string): void {
/* noop */
}
}
/**
* 受 `authStorage()` 收口管理的鉴权 / 身份键:四个精确键 + `login.` 前缀(外部登录参数族
* ticket/userId/env/maxkeyOnlineToken/userDetailToken)。用于「开启独立会话」时把当前登录态从
* localStorage 快照搬进 sessionStorage,避免切换存储后被登出。
*/
const PROTECTED_AUTH_EXACT_KEYS = ["deerflow.auth", "userInfo", "userId", "tools_token"];
const PROTECTED_AUTH_PREFIX = "login.";
function isProtectedAuthKey(key: string): boolean {
return PROTECTED_AUTH_EXACT_KEYS.includes(key) || key.startsWith(PROTECTED_AUTH_PREFIX);
}
/**
* 把 localStorage 里的鉴权 / 身份键**快照复制**进 sessionStorage(覆盖式)。
*
* 「外观」设置开启独立会话时调用:此后 `authStorage()` 改读 sessionStorage,若不先搬一份当前账号
* 过去就会瞬间「未登录」。每次开启都重新快照(覆盖旧值),确保拿到的是当前 localStorage 的最新账号。
* 仅搬受保护键,不动 sessionStorage 里既有的本标签页专属态(embed.session / 任务上下文等)。
*/
export function migrateAuthToSession(): void {
if (typeof window === "undefined") return;
try {
const ls = window.localStorage;
const ss = window.sessionStorage;
for (let i = 0; i < ls.length; i++) {
const key = ls.key(i);
if (key && isProtectedAuthKey(key)) {
const value = ls.getItem(key);
if (value !== null) ss.setItem(key, value);
}
}
} catch {
/* noop */
}
}
+9 -4
View File
@@ -4,7 +4,7 @@ import { useEffect, useRef } from "react";
import { toast } from "sonner";
import { getStoredAuth } from "@/core/auth";
import { isEmbedActive } from "@/core/embed/embed-session";
import { isEmbedActive, isIsolatedSession } from "@/core/embed/embed-session";
const AUTH_STORAGE_KEY = "deerflow.auth";
const SETTLE_DELAY_MS = 1200;
@@ -22,9 +22,9 @@ export function AuthSyncWatcher() {
const lastUserIdRef = useRef<string | null>(readUserId());
useEffect(() => {
// 嵌入(iframe)态:鉴权走按标签页的 sessionStorage,本就不与其它标签页共享,且不应被正常
// 标签页的 localStorage 账号变更打扰 —— 直接不挂跨标签监听。
if (isEmbedActive()) return;
// 嵌入(iframe)态 / 独立会话态(?isolate=1):鉴权走按标签页的 sessionStorage,本就不与其它标签页
// 共享,且不应被其它标签页的 localStorage 账号变更打扰 —— 直接不挂跨标签监听。
if (isEmbedActive() || isIsolatedSession()) return;
let settleTimer: ReturnType<typeof setTimeout> | null = null;
@@ -52,6 +52,11 @@ export function AuthSyncWatcher() {
}
function handleStorage(event: StorageEvent) {
// 运行时若已切到独立会话(「外观」开关在挂载后才开启):鉴权改读本标签页 sessionStorage,
// 不应再被其它标签页的 localStorage 账号变更打扰 —— 即时忽略,无需刷新页面。
if (isEmbedActive() || isIsolatedSession()) {
return;
}
// Ignore unrelated keys and localStorage.clear(). Backend session loss is
// handled centrally through 401 responses.
if (event.key !== AUTH_STORAGE_KEY) {
+57 -8
View File
@@ -7,7 +7,8 @@
* 任务深链配置读出 rwfx 的 4 个历史按钮,3qfx/xdfx 为空)——这样真实跳转地址通过实时
* config 进种子,避免写死;一旦保存过,后端即唯一数据源。
*
* 按钮两类(``linkType``):``url`` 外链(``window.open``,可选追加 ``?id=任务id``)/
* 按钮两类(``linkType``):``url``(外链 ``window.open``;**或应用内路由**——target 以 ``/`` 开头
* 时按内部路由处理:``self`` 走 react-router 同窗导航、``blank`` 拼 hash 路由新标签;可选追加 ``?{idParam}=id``)/
* ``business`` 内部切换到另一业务(复用 [[task-deeplink]] 的 ``resolveTaskDeeplinkTarget``)。
*/
@@ -20,6 +21,9 @@ import {
resolveTaskDeeplinkTarget,
} from "@/core/auth/task-deeplink";
/** 「大屏绘制」独立页应用内路由(深链「上一步」默认指向它,跳转追加 ?taskId=)。 */
export const DASHBOARD_AGENT_ROUTE = "/page/strategy/dashboard-agent";
/** 任务工作区业务码(与路由 taskBase 一一对应)。 */
export type TaskBusiness = "rwfx" | "3qfx" | "xdfx";
@@ -59,6 +63,9 @@ export type TaskButtonLinkType = "url" | "business" | "purpose";
/** 追加的 id 取哪种:``task``=任务id(默认)/ ``action``=行动id(仅 xdfx 二者不同)。 */
export type TaskButtonIdKind = "task" | "action";
/** ``url`` 外链打开方式:``blank``=新窗口(默认)/ ``self``=当前窗口(嵌入态即当前 iframe)。 */
export type TaskButtonOpenMode = "blank" | "self";
/** 一个可配置跳转按钮。 */
export interface TaskButton {
id: string;
@@ -76,6 +83,8 @@ export interface TaskButton {
* 实为行动id,任务id 由 action 接口解析。其它业务两者相同。
*/
idKind: TaskButtonIdKind;
/** ``url`` 外链打开方式:``blank``=新窗口(默认)/ ``self``=当前窗口。仅 ``url`` 类型有意义。 */
openMode: TaskButtonOpenMode;
enabled: boolean;
sortOrder: number;
}
@@ -89,7 +98,8 @@ export const TASK_BUSINESS_TARGETS: { code: TaskBusiness; label: string }[] = [
/**
* 代码种子默认按钮(仅在后端整张表为空时使用):
* - rwfx:历史 4 个按钮(编辑/下一步/3q详情,地址取自实时任务深链配置)+ 切换到三情/行动分析;
* - rwfx:历史按钮(编辑/下一步/3q详情,地址取自实时任务深链配置)+「上一步」+ 切换到三情/行动分析;
* 「上一步」紧邻「下一步」左侧(底部栏 prev 组在 next 组前),默认指向应用内大屏绘制页(?taskId=任务id);
* - 3qfx / xdfx:互相切换到另外两个业务。
* 即「三个业务都带切换按钮」。已保存过则用页面「导入默认」把缺失项补进来。
*/
@@ -109,6 +119,7 @@ export function defaultTaskButtons(cfg: TaskDeeplinkConfig): TaskButton[] {
appendTaskId: false,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder,
});
@@ -122,6 +133,7 @@ export function defaultTaskButtons(cfg: TaskDeeplinkConfig): TaskButton[] {
appendTaskId: false,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder,
});
@@ -136,9 +148,28 @@ export function defaultTaskButtons(cfg: TaskDeeplinkConfig): TaskButton[] {
appendTaskId: true,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder: 0,
},
{
// 上一步:放在「下一步」左边(底部快捷跳转栏,prev 组渲染在 next 组之前)。
// 默认指向**应用内**「大屏绘制」页 /page/strategy/dashboard-agent(内部路由,以 / 开头),
// 携带 ?taskId=任务id(大屏页按 taskId 取数)。openMode=self → 同窗 react-router 导航;
// 大屏页路由在 PageLayout 里被**强制显示全局 chrome**(见 PageRoutes 的 forceChromeForDashboardAgent),
// 故即便从去 chrome 的工作区进来也带回顶部导航栏 + 侧边栏(embed=1 外部嵌入态仍隐藏)。
id: "rwfx-prev",
business: "rwfx",
label: "上一步",
linkType: "url",
target: DASHBOARD_AGENT_ROUTE,
appendTaskId: true,
idParam: "taskId",
idKind: "task",
openMode: "self",
enabled: true,
sortOrder: 1,
},
{
id: "rwfx-next",
business: "rwfx",
@@ -148,8 +179,9 @@ export function defaultTaskButtons(cfg: TaskDeeplinkConfig): TaskButton[] {
appendTaskId: true,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder: 1,
sortOrder: 2,
},
{
id: "rwfx-detail3q",
@@ -160,12 +192,13 @@ export function defaultTaskButtons(cfg: TaskDeeplinkConfig): TaskButton[] {
appendTaskId: true,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder: 2,
sortOrder: 3,
},
sw("rwfx-switch3q", "rwfx", "切换到三情分析", "3qfx", 3),
sw("rwfx-switchxd", "rwfx", "切换到行动分析", "xdfx", 4),
pz("rwfx-purpose", "rwfx", 5),
sw("rwfx-switch3q", "rwfx", "切换到三情分析", "3qfx", 4),
sw("rwfx-switchxd", "rwfx", "切换到行动分析", "xdfx", 5),
pz("rwfx-purpose", "rwfx", 6),
// 3qfx(三情分析):切换到任务/行动分析
sw("3qfx-switchrw", "3qfx", "切换到任务分析", "rwfx", 0),
sw("3qfx-switchxd", "3qfx", "切换到行动分析", "xdfx", 1),
@@ -227,7 +260,23 @@ export async function runTaskButton(btn: TaskButton, ctx: RunTaskButtonCtx): Pro
const id = btn.idKind === "action" ? ctx.actionId || ctx.taskId : ctx.taskId;
const param = (btn.idParam || "id").trim() || "id";
const url = btn.appendTaskId && id ? appendQueryParam(base, param, id) : base;
window.open(url, "_blank", "noopener,noreferrer");
// 应用内部路由(以单个 / 开头,如「上一步」→ 大屏绘制页):
// self → 走 react-router 同窗导航(不刷新、保留 SPA);blank → 拼成当前源的 hash 路由新标签打开。
if (base.startsWith("/") && !base.startsWith("//")) {
if (btn.openMode === "blank") {
const full = `${window.location.origin}${window.location.pathname}#${url}`;
window.open(full, "_blank", "noopener,noreferrer");
} else {
ctx.navigate(url);
}
return;
}
// 外链:self=当前窗口(嵌入态即当前 iframe);否则 blank=新窗口(默认)。
if (btn.openMode === "self") {
window.location.assign(url);
} else {
window.open(url, "_blank", "noopener,noreferrer");
}
return;
}
// business:内部切换到另一业务
+59 -2
View File
@@ -35,6 +35,9 @@ export interface CopTaskDetail {
/** 任务详情整包暂存的 sessionStorage key(目标页/后续可读取)。 */
export const COP_TASK_DETAIL_STORAGE_KEY = "login.copTaskDetail";
/** 行动详情整包暂存的 sessionStorage key(xdfx 行动分析:会商/单智能体读取行动名称/叙事)。 */
export const ACTION_DETAIL_STORAGE_KEY = "login.actionDetail";
/** goPath 基础码 → 业务码(配置管理 businessCode)。 */
const GOPATH_BUSINESS_CODE: Record<string, string> = {
"3qfx": "3Q", // 三情分析
@@ -74,8 +77,28 @@ function consumerBaseUrl(): string {
return typeof value === "string" ? value.replace(/\/+$/, "") : "";
}
/** 拉取任务详情;缺少 consumer 地址 / 返回不合法时返回 null。 */
/** cop-task-detail 是否走本地假数据:开关 `VITE_MOCK_COP_TASK_DETAIL=true`(真实接口未就绪时调试用)。 */
function copTaskDetailMockEnabled(): boolean {
return (import.meta.env as Record<string, unknown>).VITE_MOCK_COP_TASK_DETAIL === "true";
}
/** cop-task-detail 本地假数据(与真实 data 字段同构;mock 开关开启时返回)。 */
function mockCopTaskDetail(taskId: string): CopTaskDetail {
return {
id: taskId || "2055",
overview: "暑期文旅消费高峰期间的舆情态势综合研判与引导任务(本地假数据)。",
taskDirection: "正向引导 + 风险预警",
taskName: "任务01:暑期文旅舆情综合研判",
taskContent:
"围绕暑期文旅消费高峰,对重点城市、重点景区的公众情绪与舆情态势做综合研判,识别情绪拐点与潜在风险,提出正向引导与处置建议。",
};
}
/** 拉取任务详情;``VITE_MOCK_COP_TASK_DETAIL=true`` 走假数据;缺少 consumer 地址 / 返回不合法时返回 null。 */
export async function fetchCopTaskDetail(taskId: string): Promise<CopTaskDetail | null> {
if (copTaskDetailMockEnabled()) {
return mockCopTaskDetail(taskId);
}
const base = consumerBaseUrl();
if (!base || !taskId) return null;
// service 拦截器已统一注入 `Authorization: Bearer admin` 并返回 response.data(整包 body)。
@@ -111,6 +134,25 @@ export function readCopTaskDetail(): CopTaskDetail | null {
}
}
/** 把行动详情整包暂存到 sessionStorage(xdfx 行动分析用;隐私模式/quota 异常时静默失败)。 */
export function persistActionDetail(detail: ActionDetail): void {
try {
sessionStorage.setItem(ACTION_DETAIL_STORAGE_KEY, JSON.stringify(detail));
} catch {
/* noop */
}
}
/** 读取暂存的行动详情(会商左上角「当前行动」、单智能体行动详情卡都可读)。 */
export function readActionDetail(): ActionDetail | null {
try {
const raw = sessionStorage.getItem(ACTION_DETAIL_STORAGE_KEY);
return raw ? (JSON.parse(raw) as ActionDetail) : null;
} catch {
return null;
}
}
/** 行动详情接口 ``{action_detail_url}/{actionId}`` 返回的 ``data`` 字段(xdfx 行动分析用)。 */
export interface ActionDetail {
/** 行动id(深链 ?taskId= 传入的就是它)。 */
@@ -148,7 +190,7 @@ export async function fetchActionDetail(actionId: string): Promise<ActionDetail
const data = body && typeof body === "object" ? (body as { data?: unknown }).data : null;
if (!data || typeof data !== "object") return null;
const d = data as Record<string, unknown>;
return {
const detail: ActionDetail = {
id: d.id != null ? String(d.id) : "",
taskId: d.taskId != null ? String(d.taskId) : "",
purposeId: d.purposeId != null ? String(d.purposeId) : "",
@@ -157,6 +199,10 @@ export async function fetchActionDetail(actionId: string): Promise<ActionDetail
typeof d.actionStatus === "number" || typeof d.actionStatus === "string" ? d.actionStatus : "",
narration: typeof d.narration === "string" ? d.narration : "",
};
// 取到即整包暂存:登录解析任务id 时(resolveDeeplinkTaskId→fetchTaskIdFromAction)就会缓存它,
// 之后会商左上角「当前行动」、单智能体行动详情卡都能直接 readActionDetail(),避免重复请求。
persistActionDetail(detail);
return detail;
}
/**
@@ -232,6 +278,15 @@ export async function resolveTaskDeeplinkTarget(
if (parsed.roundtable) {
// 多智能体会商:嵌进对应业务的「任务管理」布局;businessCode 让会商页自动选用配置的业务链条;
// taskId 让会商页按任务隔离存取草稿(一个 taskId 多条记录),并触发第三步自动结构化输出。
// xdfx(行动分析):根是「行动」——把行动名称随首条消息交给任务理解,左上角展示「当前行动」。
// 行动详情登录解析任务id 时已缓存(fetchActionDetail 内 persistActionDetail);这里优先读缓存。
let actionName = "";
let actionId = "";
if (parsed.businessCode === XDFX_BUSINESS_CODE && rawId) {
actionId = rawId;
const ad = readActionDetail() ?? (await fetchActionDetail(rawId));
actionName = ad?.actionName ?? "";
}
return {
path: `${taskBase}/roundtable`,
state: {
@@ -240,6 +295,8 @@ export async function resolveTaskDeeplinkTarget(
taskGoal: detail.taskContent,
businessCode: parsed.businessCode,
taskId: taskId || undefined,
...(actionId ? { actionId } : {}),
...(actionName ? { actionName } : {}),
autoStart: true,
},
},
+3 -1
View File
@@ -282,12 +282,14 @@ export async function deleteTaskPurpose(
if (!cfg.deleteUrl) return { message: "缺少删除接口地址", success: false };
// 只放要传的那个 id key:另一参数直接不出现在 URL(axios 不会序列化缺省 key)。
const params = idKind === "action" ? { actionId: id } : { taskId: id };
// 该删除接口(dropSixOrSevenData)成功时**什么都不返回**(空响应体),所以只要请求没抛错
// (HTTP 成功)就直接判定为成功;仅当后端偶尔回了 {success:false} 这类显式失败标记才算失败。
const body = await requestCrudService.get(cfg.deleteUrl, params);
const obj =
body && typeof body === "object" ? (body as unknown as Record<string, unknown>) : {};
return {
message: typeof obj.message === "string" ? obj.message : "",
success: obj.success === true,
success: obj.success !== false,
};
}
+46 -5
View File
@@ -1,13 +1,19 @@
/**
* 「外部系统 iframe 套用深链」相关的**按标签页**会话开关。承载两个相互独立的能力,均由 URL
* 路由参数开启、存进同一份 sessionStorage 会话、跨登录跳转/刷新/页内导航存活:
* 「外部系统 iframe 套用深链」相关的**按标签页**会话开关。承载三个相互独立的能力,多由 URL
* 路由参数开启(独立会话 `isolate` 另可由「外观」设置里的开关在运行时切换,见 `setIsolatedSession`),
* 存进同一份 sessionStorage 会话、跨登录跳转/刷新/页内导航存活:
*
* 1. `embed=1`(可带 `&theme=`)—— **嵌入模式**:去掉全局导航栏(Header)+ 侧边栏(PageSidebar),
* 并按外部主题色强制系统明/暗(离散切换)。
* 2. `hideJump=1` —— **隐藏深链底部「快捷跳转」栏**:去掉 `TaskJumpBar` 的两部分——底部的
* 「下一步」等按钮 + 右侧垂直居中的悬浮菜单(单智能体问答 / 多智能体会商深链共用该栏)。
* 3. `isolate=1` —— **独立会话登录**:本标签页的鉴权身份按标签页隔离(见 [[scoped-storage]]
* `authStorage()`,嵌入态与独立态同走 sessionStorage)。用于同一浏览器里**另开一个标签页登
* 录不同账号**而**不覆盖**当前标签页(localStorage)的登录态——`embed` 已隐含此隔离,`isolate`
* 则是把同一套隔离单独提供给**普通(带 chrome)标签页**,不去 chrome、不强制主题、不动跳转栏。
*
* 两者可单独使用,也可叠加:`hideJump` **只**隐藏跳转栏,不动 chrome / 主题;`embed` 不影响跳转栏。
* 三者可单独使用,也可叠加:`hideJump` **只**隐藏跳转栏,不动 chrome / 主题;`embed` 不影响跳转栏;
* `isolate` 只切换鉴权存储,不影响 chrome / 主题 / 跳转栏。
*
* 隔离要点(核心诉求:同一浏览器另开咱们正常系统页,**绝不能**被这些开关影响):
* - 用 **sessionStorage**(按标签页隔离、绝不跨标签)持有这些 flag,而**不用** localStorage
@@ -33,6 +39,8 @@ export interface EmbedSession {
theme: EmbedTheme;
/** 隐藏深链底部「快捷跳转」栏(TaskJumpBar:底部按钮 + 右侧悬浮菜单)。 */
hideJump: boolean;
/** 独立会话:鉴权身份按本标签页隔离(走 sessionStorage),用于同浏览器登录不同账号互不覆盖。 */
isolate: boolean;
}
/** URL 布尔参数的三态:显式开 / 显式关 / 未带。 */
@@ -61,6 +69,11 @@ export function readHideJumpParam(search: string): FlagParam {
return readFlagParam(search, "hideJump");
}
/** 读 URL 里的 `isolate` 三态(独立会话登录)。 */
export function readIsolateParam(search: string): FlagParam {
return readFlagParam(search, "isolate");
}
/**
* 把外部传入的主题色映射成离散明/暗。与 `resolveThemeFromQuery` 同源约定(dark-blue → 深色),
* 另外宽松接受 `dark` / 中文「深色/深蓝」直传;其余(含空)一律浅色。
@@ -86,6 +99,7 @@ export function readEmbedSession(): EmbedSession | null {
embed: p.embed === true,
theme: p.theme === "dark" ? "dark" : "light",
hideJump: p.hideJump === true,
isolate: p.isolate === true,
};
} catch {
return null;
@@ -95,7 +109,7 @@ export function readEmbedSession(): EmbedSession | null {
/** 写会话;无任何开关置位时直接清除(保持 sessionStorage 干净)。隐私模式/quota 异常静默失败。 */
function writeEmbedSession(next: EmbedSession): void {
try {
if (!next.embed && !next.hideJump) {
if (!next.embed && !next.hideJump && !next.isolate) {
sessionStorage.removeItem(EMBED_SESSION_KEY);
return;
}
@@ -115,13 +129,24 @@ export function isJumpBarHidden(): boolean {
return readEmbedSession()?.hideJump === true;
}
/**
* 本标签页是否处于独立会话态:鉴权身份按标签页隔离(走 sessionStorage)。
* `embed` 已隐含同样的隔离,故 `authStorage()` 取「embed || isolate」之并;这里只判 `isolate`,
* 供需要区分「纯独立会话(带 chrome)」与「嵌入态(去 chrome)」的场合使用。
*/
export function isIsolatedSession(): boolean {
return readEmbedSession()?.isolate === true;
}
/**
* 按 URL 参数同步 sessionStorage 会话(AppProviders 在每次 search 变化时调用一次)。
* **合并语义**:on 置位、off 清位、未带则沿用既有值——这样登录后跳到不带参数的干净路由时,
* 之前置位的开关不会被抹掉。
*/
export function syncEmbedSessionFromSearch(search: string): void {
const cur = readEmbedSession() ?? { embed: false, theme: "light" as EmbedTheme, hideJump: false };
const cur =
readEmbedSession() ??
{ embed: false, theme: "light" as EmbedTheme, hideJump: false, isolate: false };
const next: EmbedSession = { ...cur };
const embedParam = readEmbedParam(search);
@@ -136,6 +161,10 @@ export function syncEmbedSessionFromSearch(search: string): void {
if (hideJumpParam === "on") next.hideJump = true;
else if (hideJumpParam === "off") next.hideJump = false;
const isolateParam = readIsolateParam(search);
if (isolateParam === "on") next.isolate = true;
else if (isolateParam === "off") next.isolate = false;
writeEmbedSession(next);
}
@@ -170,3 +199,15 @@ export function resolveForcedEmbedTheme(search: string): EmbedTheme | undefined
const session = readEmbedSession();
return session?.embed ? session.theme : undefined;
}
/**
* 运行时直接置位/清除本标签页的独立会话标志(供「外观」设置里的开关用,区别于 URL 参数驱动)。
* 仅切换标志;登录态的「localStorage 快照搬进 sessionStorage」由 [[scoped-storage]]
* `migrateAuthToSession()` 负责,调用顺序见 appearance 设置页。
*/
export function setIsolatedSession(on: boolean): void {
const cur =
readEmbedSession() ??
{ embed: false, theme: "light" as EmbedTheme, hideJump: false, isolate: false };
writeEmbedSession({ ...cur, isolate: on });
}
+22 -10
View File
@@ -212,21 +212,33 @@ export function extractToolResultPayload(
}
const THINK_TAG_RE = /<think>\s*([\s\S]*?)\s*<\/think>/g;
const THINK_OPEN = "<think>";
function splitInlineReasoning(content: string) {
const reasoningParts: string[] = [];
const cleaned = content
.replace(THINK_TAG_RE, (_, reasoning: string) => {
const normalized = reasoning.trim();
if (normalized) {
reasoningParts.push(normalized);
}
return "";
})
.trim();
// 1) 先抽出所有**已闭合**的 <think>...</think>。
let working = content.replace(THINK_TAG_RE, (_, reasoning: string) => {
const normalized = reasoning.trim();
if (normalized) {
reasoningParts.push(normalized);
}
return "";
});
// 2) 流式中常见**未闭合**的 <think>(还没等到 </think> 就先到达):把开标签之后的内容
// 当作「实时思考」抽到 reasoning、从答案正文里移除。否则模型慢/先思考时,用户既会看到
// 字面 "<think>",又会因答案区长时间空白而以为卡死。这样思考内容会实时流进思考区。
const openIdx = working.indexOf(THINK_OPEN);
if (openIdx !== -1 && !working.slice(openIdx).includes("</think>")) {
const partial = working.slice(openIdx + THINK_OPEN.length).trim();
if (partial) {
reasoningParts.push(partial);
}
working = working.slice(0, openIdx);
}
return {
content: cleaned,
content: working.trim(),
reasoning: reasoningParts.length > 0 ? reasoningParts.join("\n\n") : null,
};
}
@@ -4,6 +4,7 @@ import { OptType, writeYLog } from "@/core/log/y-log";
import type {
HtmlPageFavorite,
HtmlTemplateOption,
PublishedScheduledTask,
ScheduledTask,
ScheduledTaskDeliveryProfile,
@@ -33,6 +34,14 @@ export async function getSchedulerThread() {
return parseResponse<SchedulerThread>(await apiFetch(`${baseUrl()}/thread`));
}
/** 可选的 HTML 模板清单(模板数据转换器填充用)。 */
export async function listHtmlTemplates() {
const data = await parseResponse<{ templates: HtmlTemplateOption[] }>(
await apiFetch(`${baseUrl()}/html-templates`),
);
return data.templates ?? [];
}
export interface ListScheduledTasksParams {
search?: string;
tagIds?: string[];
@@ -16,6 +16,7 @@ import {
deleteScheduledTask,
deleteScheduledTaskRun,
getSchedulerThread,
listHtmlTemplates,
getScheduledTaskDeliveryProfile,
getScheduledTaskRun,
getScheduledTaskRunHtml,
@@ -45,6 +46,17 @@ export function useSchedulerThread() {
});
}
/** 可选的 HTML 模板清单(模板数据转换器填充用)。模板是后端静态注册,长缓存即可。 */
export function useHtmlTemplates(enabled = true) {
return useQuery({
queryKey: ["scheduled-tasks", "html-templates"],
queryFn: listHtmlTemplates,
enabled,
staleTime: 5 * 60_000,
refetchOnWindowFocus: false,
});
}
/** A task is currently executing — used to drive live polling of the task list. */
function taskIsLive(status?: string | null): boolean {
return status === "running" || status === "pending";
@@ -24,8 +24,27 @@ export type HtmlPageConfig = {
model_name?: string | null;
};
/** 选中内置「模板数据转换器」agent 后,要把源 JSON 填充进的 HTML 模板。
* 持久化在 ``execution_context.template_config`` 里(无独立列)。 */
export type TemplateFillConfig = {
template_id?: string | null;
/** 可选:覆盖转换所用模型(留空走 agent.model / 系统默认)。 */
model_name?: string | null;
};
/** ``GET /api/scheduled-tasks/html-templates`` 返回的一条模板选项。 */
export type HtmlTemplateOption = {
id: string;
name: string;
description?: string | null;
/** false = 暂只「直接展示已有数据」,不需要也不会用源 JSON 转换填充。 */
convertible?: boolean;
};
export type ScheduledTaskExecutionContext = {
require_markdown?: boolean;
/** 模板填充模式:选中「模板数据转换器」+ 选模板后填充进固定 HTML 模板。 */
template_config?: TemplateFillConfig;
/**
* The unified "必须生成 HTML" switch. The task form no longer splits "普通任务 /
* HTML 页面" into separate kinds — instead ``require_html`` and
@@ -65,6 +65,7 @@ export function AIWritingForm({
audience, setAudience,
wordCountInput, setWordCountInput,
strictMode, setStrictMode,
addReferences, setAddReferences,
materialSource, setMaterialSource,
// 笔记来源(search_space_id + document_id 列表)已上提到 WritingFormContext,
// 以便左栏「笔记本」点击可直接设为素材来源(需求 0616 #5)。
@@ -164,6 +165,7 @@ export function AIWritingForm({
wordCountTarget: wordCount,
keywordCount: DEFAULT_KEYWORD_COUNT,
writingMode: hideAdvancedFields ? 'loose' : strictMode ? 'strict' : 'loose',
addReferences,
materialSource: materialSource,
modelName: selectedModel?.name || modelName || undefined,
// 只有选了"我的空间"才传笔记参数
@@ -192,7 +194,7 @@ export function AIWritingForm({
</span>
</div>
<Textarea
placeholder="描述你想写的文章,例如:写一篇分析今年 AI 大模型发展趋势的文章,重点关注国内企业的布局..."
placeholder="描述你想写的文章"
value={intent}
onChange={(e) => setIntent(e.target.value)}
disabled={disabled}
@@ -381,6 +383,23 @@ export function AIWritingForm({
</Select>
</div>
<div className="mt-4 flex items-start gap-2 rounded-xl border border-[#e8dedd] bg-[#f9f5f5] px-3 py-3 dark:border-[#1B477E] dark:bg-[#022248]/40">
<input
type="checkbox"
id="add-references"
checked={addReferences}
onChange={(e) => setAddReferences(e.target.checked)}
disabled={disabled}
className="mt-0.5 size-3.5 shrink-0 cursor-pointer accent-primary"
/>
<label htmlFor="add-references" className="cursor-pointer select-none">
<span className="text-sm font-medium text-foreground/90">添加参考文献</span>
<p className="mt-0.5 text-xs leading-relaxed text-muted-foreground/80">
开启后,正文引用素材处自动加角标 [n],文末按出现顺序生成「参考文献」列表(像论文一样)。
</p>
</label>
</div>
<Button
type="submit"
disabled={disabled || !intent.trim()}
@@ -41,6 +41,7 @@ import {
* 把这个 flag 翻成 true 即可,UI / hook 全套代码都已就位。
*/
const ENABLE_PAUSE_RESUME_UI = false;
import { countArticleWords } from '../../utils/wordCount';
import { AIWritingForm } from './AIWritingForm';
import { AIWritingTimeline } from './AIWritingTimeline';
import { InterventionCard } from './InterventionCard';
@@ -91,7 +92,7 @@ export function AIWritingPanel({
const { state, startWriting, submitIntervention, pauseWriting, resumeWriting, reset } = useAIWriting();
const { historySession, isHistoryMode, openHistory, closeHistory } = useAIWritingHistory();
const writingForm = useWritingFormOptional();
const { sessions, loading: sessionsLoading, refresh, rename, remove } = useAIWritingSessions();
const { sessions, loading: sessionsLoading, refresh, rename, remove, markBackground, clearBackground } = useAIWritingSessions();
const { articleTypes, refresh: refreshArticleTypes } = useArticleTypes();
useEffect(() => { refreshArticleTypes(); }, [refreshArticleTypes]);
@@ -207,24 +208,31 @@ export function AIWritingPanel({
}, [closeHistory, reset]);
// ── 后台挂起:把当前写作转后台,后端自动驱动到定稿(离页/刷新/切号不打断) ──
const handleBackgroundSuspend = useCallback(async () => {
// 与「多智能体会商」一致:点击后**立刻**回到初始页面,挂起请求 fire-and-forget;
// 历史下拉靠乐观标记马上显示「挂起中」,不等后端确认。
const handleBackgroundSuspend = useCallback(() => {
const sid = state.sessionId;
if (!sid) {
toast.error('当前没有可挂起的写作会话');
return;
}
try {
await suspendAIWritingToBackground(sid);
} catch (e) {
toast.error(e instanceof Error ? e.message : '后台挂起失败');
return;
}
toast.success('已转入后台自动完成,稍后可在「历史记录」查看进度与结果');
// reset() 会 stop 客户端 SSE 订阅并回到 idle —— 后端驱动器接管续跑,不冲突。
// 1) 立刻:乐观标记 + 重置 UI 回到 idle(reset() 会 stop 客户端 SSE 订阅,
// 后端驱动器接管续跑,不冲突)。
markBackground(sid);
reset();
// 刷新历史列表,让「挂起中」徽标立刻出现。
refresh();
}, [state.sessionId, reset, refresh]);
toast.success('已转入后台自动完成,稍后可在「历史记录」查看进度与结果');
// 2) 后台:fire-and-forget 通知后端拉起驱动;完成后刷新真实状态并清除乐观标记。
void (async () => {
try {
await suspendAIWritingToBackground(sid);
} catch (e) {
toast.error(e instanceof Error ? e.message : '后台挂起失败');
} finally {
await refresh();
clearBackground(sid);
}
})();
}, [state.sessionId, reset, refresh, markBackground, clearBackground]);
// 离页 / 刷新 / 关标签页时,若写作仍在进行中则自动转后台(与圆桌「自动挂起」一致)。
// 用 ref 持有最新的「是否在跑 + 会话 id」,让卸载/卸载前回调读到即时值。
@@ -475,6 +483,8 @@ export function AIWritingPanel({
outline={state.outline}
reviewResult={state.reviewResult}
draftTitle={state.currentDraftTitle}
draftWordCount={countArticleWords(state.currentDraftMarkdown)}
wordCountTarget={state.request?.wordCountTarget}
revisionCount={state.revisionCount}
skillSearchSteps={state.skillSearchSteps}
skillSearchInProgress={state.status === 'researching' && state.skillSearchSteps.length > 0}
@@ -19,6 +19,7 @@ const DISPLAYED_TYPES = new Set([
'await_user',
'resumed',
'notice',
'model_switch',
'done',
'error',
]);
@@ -24,6 +24,10 @@ interface InterventionCardProps {
outline: AIOutline | null;
reviewResult: ReviewResult | null;
draftTitle: string;
/** 当前草稿实际字数(与目标对比展示,让用户在确认时即看到字数是否达标) */
draftWordCount?: number;
/** 用户设定的目标字数 */
wordCountTarget?: number;
revisionCount: number;
skillSearchSteps?: SkillSearchStep[];
/** 是否正在检索中(researching/awaiting 切换之间,前端用于流式展示步骤进行中) */
@@ -34,7 +38,7 @@ interface InterventionCardProps {
export function InterventionCard({
pauseEvent, materials, outline, reviewResult,
draftTitle, revisionCount, skillSearchSteps, skillSearchInProgress, onSubmit, disabled,
draftTitle, draftWordCount, wordCountTarget, revisionCount, skillSearchSteps, skillSearchInProgress, onSubmit, disabled,
}: InterventionCardProps) {
const pausePoint = pauseEvent.pausePoint;
@@ -64,6 +68,8 @@ export function InterventionCard({
return (
<DraftConfirmCard
draftTitle={draftTitle}
draftWordCount={draftWordCount}
wordCountTarget={wordCountTarget}
revisionCount={revisionCount}
reviewResult={reviewResult}
onSubmit={onSubmit}
@@ -357,13 +363,15 @@ function OutlineConfirmCard({ outline: initialOutline, onSubmit, disabled }: Out
interface DraftConfirmCardProps {
draftTitle: string;
draftWordCount?: number;
wordCountTarget?: number;
revisionCount: number;
reviewResult: ReviewResult | null;
onSubmit: (payload: UserInterventionPayload) => void;
disabled?: boolean;
}
function DraftConfirmCard({ draftTitle, revisionCount, reviewResult, onSubmit, disabled }: DraftConfirmCardProps) {
function DraftConfirmCard({ draftTitle, draftWordCount, wordCountTarget, revisionCount, reviewResult, onSubmit, disabled }: DraftConfirmCardProps) {
const [notes, setNotes] = useState('');
const [showNotes, setShowNotes] = useState(false);
const [submitting, setSubmitting] = useState(false);
@@ -399,6 +407,11 @@ function DraftConfirmCard({ draftTitle, revisionCount, reviewResult, onSubmit, d
const hasReview = reviewResult != null && reviewResult.revisionNotes.length > 0;
// 实际字数 vs 目标字数对比:让用户在确认时直接看到是否达标,偏差超 100 字标橙提醒
const showWordCmp = wordCountTarget != null && wordCountTarget > 0 && draftWordCount != null && draftWordCount > 0;
const wordDiff = showWordCmp ? draftWordCount! - wordCountTarget! : 0;
const wordWithin = Math.abs(wordDiff) <= 100;
return (
<div className="rounded-md border bg-background space-y-3 p-3">
<div className="flex items-start gap-2">
@@ -410,6 +423,12 @@ function DraftConfirmCard({ draftTitle, revisionCount, reviewResult, onSubmit, d
{revisionCount > 0 ? `(第 ${revisionCount} 次修改稿)` : '(初稿)'}
· 右侧可预览完整内容
</p>
{showWordCmp && (
<p className={cn('text-xs mt-0.5', wordWithin ? 'text-muted-foreground' : 'text-orange-600 dark:text-orange-400')}>
实际 {draftWordCount} 字 / 目标 {wordCountTarget} 字
{wordDiff !== 0 && `(${wordDiff > 0 ? '超出' : '不足'} ${Math.abs(wordDiff)} 字${wordWithin ? ',在误差范围内' : ''})`}
</p>
)}
</div>
</div>
@@ -73,7 +73,7 @@ export function MaterialsToolbar({
value={userQuery}
onChange={handleInput}
onKeyDown={handleKeyDown}
placeholder={placeholder ?? '例如:检索新能源汽车销量数据。按 Enter 检索并追加…'}
placeholder={placeholder ?? '按 Enter 检索并追加…'}
disabled={disabled}
className="w-full resize-none rounded-md border border-input bg-background px-2.5 py-1.5 text-xs leading-5 placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50 min-h-[28px] max-h-24"
/>
@@ -1,7 +1,21 @@
import { useState } from 'react';
import { ListTree, Plus } from 'lucide-react';
import { ListTree, Plus, GripVertical } from 'lucide-react';
import {
DndContext,
DragOverlay,
PointerSensor,
pointerWithin,
rectIntersection,
useSensor,
useSensors,
type CollisionDetection,
type DragEndEvent,
type DragStartEvent,
} from '@dnd-kit/core';
import { Button } from '@/components/ui/button';
import type { AIOutline, OutlineSection as OutlineSectionType } from '../../types/ai-writing';
import { cn } from '@/lib/utils';
import type { AIOutline, KeyPoint, OutlineSection as OutlineSectionType } from '../../types/ai-writing';
import { normalizeKeyPoint } from '../../types/ai-writing';
import { OutlineSection } from './OutlineSection';
import { CollapseTransition } from './CollapseTransition';
@@ -11,15 +25,177 @@ interface OutlineCardProps {
readOnly?: boolean;
}
// 节点路径(章节/小节/子要点)
export type DragPath =
| { type: 'section'; s: number }
| { type: 'keypoint'; s: number; k: number }
| { type: 'subpoint'; s: number; k: number; p: number };
// 节点 id:s{S} / s{S}-k{K} / s{S}-k{K}-p{P}
export function parseItemId(id: string): DragPath | null {
const m = id.match(/^s(\d+)(?:-k(\d+))?(?:-p(\d+))?$/);
if (!m) return null;
const s = parseInt(m[1], 10);
const k = m[2] !== undefined ? parseInt(m[2], 10) : undefined;
const p = m[3] !== undefined ? parseInt(m[3], 10) : undefined;
if (p !== undefined && k !== undefined) return { type: 'subpoint', s, k, p };
if (k !== undefined) return { type: 'keypoint', s, k };
return { type: 'section', s };
}
// 区域 id:before:<节点id> / after:<节点id> / into:<节点id>
type Zone = 'before' | 'after' | 'into';
function parseZoneId(zoneId: string): { zone: Zone; targetPath: DragPath; targetItemId: string } | null {
const m = zoneId.match(/^(before|after|into):(.+)$/);
if (!m) return null;
const targetItemId = m[2];
const targetPath = parseItemId(targetItemId);
if (!targetPath) return null;
return { zone: m[1] as Zone, targetPath, targetItemId };
}
function cloneOutline(outline: AIOutline): AIOutline {
return {
...outline,
sections: outline.sections.map((s) => ({
...s,
keyPoints: (s.keyPoints ?? []).map((kp) => {
const n = normalizeKeyPoint(kp);
return { ...n, subPoints: [...n.subPoints] } as KeyPoint;
}),
materialIds: [...(s.materialIds ?? [])],
})),
};
}
type SourceValue = OutlineSectionType | KeyPoint | string;
// 拖到自身子树内非法(章节扔进自己的小节/子要点 / 小节扔进自己的子要点)
function isDescendantTarget(from: DragPath, to: DragPath): boolean {
if (from.type === 'section') return to.s === from.s;
if (from.type === 'keypoint') return to.type !== 'section' && to.s === from.s && to.k === from.k;
return false;
}
function readAt(outline: AIOutline, p: DragPath): SourceValue {
if (p.type === 'section') return outline.sections[p.s];
const kps = outline.sections[p.s].keyPoints as KeyPoint[];
if (p.type === 'keypoint') return kps[p.k];
return kps[p.k].subPoints[p.p];
}
function removeAt(outline: AIOutline, p: DragPath): void {
if (p.type === 'section') { outline.sections.splice(p.s, 1); return; }
const kps = outline.sections[p.s].keyPoints as KeyPoint[];
if (p.type === 'keypoint') { kps.splice(p.k, 1); return; }
kps[p.k].subPoints.splice(p.p, 1);
}
function insertAt(outline: AIOutline, p: DragPath, value: SourceValue): void {
if (p.type === 'section') { outline.sections.splice(p.s, 0, value as OutlineSectionType); return; }
const kps = outline.sections[p.s].keyPoints as KeyPoint[];
if (p.type === 'keypoint') { kps.splice(p.k, 0, value as KeyPoint); return; }
kps[p.k].subPoints.splice(p.p, 0, value as string);
}
// 删源后,同一父列表里 target index 会前移一位
function adjustTargetAfterRemove(to: DragPath, from: DragPath): DragPath {
if (from.type === 'section') {
if (to.s > from.s) return { ...to, s: to.s - 1 } as DragPath;
return to;
}
if (from.type === 'keypoint') {
if (to.type !== 'section' && to.s === from.s && to.k > from.k) {
return { ...to, k: to.k - 1 } as DragPath;
}
return to;
}
if (to.type === 'subpoint' && to.s === from.s && to.k === from.k && to.p > from.p) {
return { ...to, p: to.p - 1 };
}
return to;
}
type Level = DragPath['type'];
function convertToLevel(value: SourceValue, fromLevel: Level, toLevel: Level): SourceValue {
if (fromLevel === toLevel) return value;
if (toLevel === 'section') {
if (fromLevel === 'keypoint') {
const kp = value as KeyPoint;
return {
sectionTitle: kp.pointTitle,
keyPoints: kp.subPoints.map((sp) => ({ pointTitle: sp, subPoints: [] })),
materialIds: [],
};
}
return { sectionTitle: value as string, keyPoints: [], materialIds: [] };
}
if (toLevel === 'keypoint') {
if (fromLevel === 'section') {
const sec = value as OutlineSectionType;
const sub = (sec.keyPoints ?? [])
.map((kp) => normalizeKeyPoint(kp).pointTitle)
.filter((s) => !!s);
return { pointTitle: sec.sectionTitle, subPoints: sub };
}
return { pointTitle: value as string, subPoints: [] };
}
if (fromLevel === 'section') return (value as OutlineSectionType).sectionTitle;
return (value as KeyPoint).pointTitle;
}
// into 区域:作为 target 节点的「末尾子项」插入
function childPathOf(outline: AIOutline, target: DragPath): DragPath | null {
if (target.type === 'section') {
const kps = outline.sections[target.s]?.keyPoints ?? [];
return { type: 'keypoint', s: target.s, k: kps.length };
}
if (target.type === 'keypoint') {
const kp = normalizeKeyPoint((outline.sections[target.s]?.keyPoints ?? [])[target.k]);
return { type: 'subpoint', s: target.s, k: target.k, p: kp.subPoints.length };
}
return null; // 子要点没有子节点
}
// before/after:作为 target 节点的兄弟插入
function siblingPathOf(target: DragPath, side: 'before' | 'after'): DragPath {
const delta = side === 'after' ? 1 : 0;
if (target.type === 'section') return { type: 'section', s: target.s + delta };
if (target.type === 'keypoint') return { type: 'keypoint', s: target.s, k: target.k + delta };
return { type: 'subpoint', s: target.s, k: target.k, p: target.p + delta };
}
// 自定义碰撞:pointerWithin 命中所有包含光标的 droppable,取 rect 最小的(最内层)
// —— 这是嵌套区域 (section > keypoint > subpoint,每层又分 before/into/after) 能
// 正确选中「最深的那个」的关键。
function getRectArea(rect: { width: number; height: number } | null | undefined): number {
if (!rect) return Infinity;
return rect.width * rect.height;
}
const innermostCollision: CollisionDetection = (args) => {
const pointer = pointerWithin(args);
if (pointer.length === 0) return rectIntersection(args);
let best = pointer[0];
let bestArea = getRectArea(args.droppableRects.get(best.id));
for (const c of pointer.slice(1)) {
const a = getRectArea(args.droppableRects.get(c.id));
if (a < bestArea) { best = c; bestArea = a; }
}
return [best];
};
export function OutlineCard({ outline, onChange, readOnly = false }: OutlineCardProps) {
const [collapsed, setCollapsed] = useState(false);
const [editingTitle, setEditingTitle] = useState(false);
const [titleDraft, setTitleDraft] = useState(outline.title);
const [dragIndex, setDragIndex] = useState<number | null>(null);
const [overIndex, setOverIndex] = useState<number | null>(null);
const [activeId, setActiveId] = useState<string | null>(null);
const editable = !readOnly && !!onChange;
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));
function commitTitle() {
setEditingTitle(false);
const trimmed = titleDraft.trim();
@@ -40,14 +216,6 @@ export function OutlineCard({ outline, onChange, readOnly = false }: OutlineCard
onChange?.({ ...outline, sections: outline.sections.filter((_, idx) => idx !== i) });
}
function reorderSections(from: number, to: number) {
if (from === to) return;
const sections = [...outline.sections];
const [moved] = sections.splice(from, 1);
sections.splice(to, 0, moved);
onChange?.({ ...outline, sections });
}
function addSection() {
onChange?.({
...outline,
@@ -55,9 +223,66 @@ export function OutlineCard({ outline, onChange, readOnly = false }: OutlineCard
});
}
function handleDragStart(event: DragStartEvent) {
setActiveId(String(event.active.id));
}
function handleDragCancel() {
setActiveId(null);
}
function handleDragEnd(event: DragEndEvent) {
setActiveId(null);
const { active, over } = event;
if (!over || !editable) return;
const fromId = String(active.id);
const overId = String(over.id);
const from = parseItemId(fromId);
const zoneInfo = parseZoneId(overId);
if (!from || !zoneInfo) return;
const { zone, targetPath, targetItemId } = zoneInfo;
// 落在源自身的任何区域 → 无操作
if (targetItemId === fromId) return;
// 计算插入路径:into = 末尾子项;before/after = 同级兄弟
const insertPath = zone === 'into'
? childPathOf(outline, targetPath)
: siblingPathOf(targetPath, zone);
if (!insertPath) return;
// 拖入源自身子树 → 非法
if (isDescendantTarget(from, insertPath)) return;
const next = cloneOutline(outline);
const sourceValue = readAt(next, from);
removeAt(next, from);
const adjusted = adjustTargetAfterRemove(insertPath, from);
const converted = convertToLevel(sourceValue, from.type, adjusted.type);
insertAt(next, adjusted, converted);
onChange?.(next);
}
function renderDragOverlay() {
if (!activeId) return null;
const path = parseItemId(activeId);
if (!path) return null;
const section = outline.sections[path.s];
if (!section) return null;
if (path.type === 'section') {
return <OverlayCard level="section" label={section.sectionTitle} />;
}
const kp = normalizeKeyPoint((section.keyPoints ?? [])[path.k]);
if (path.type === 'keypoint') {
return <OverlayCard level="keypoint" label={kp.pointTitle} />;
}
return <OverlayCard level="subpoint" label={kp.subPoints?.[path.p] ?? ''} />;
}
return (
<div className="rounded-md border bg-muted/20 overflow-hidden">
{/* 头部 */}
<div className="flex items-center gap-2 px-3 py-2 border-b">
<ListTree className="size-3.5 text-purple-500 shrink-0" />
<span className="text-xs font-medium flex-1">文章大纲</span>
@@ -97,34 +322,30 @@ export function OutlineCard({ outline, onChange, readOnly = false }: OutlineCard
)}
</div>
{/* 章节列表 */}
<div className="space-y-1.5">
{outline.sections.map((section, i) => (
<OutlineSection
key={i}
section={section}
index={i}
onChange={(updated) => updateSection(i, updated)}
onRemove={editable ? () => removeSection(i) : undefined}
readOnly={!editable}
isDragging={dragIndex === i}
isOver={overIndex === i && dragIndex !== null && dragIndex !== i}
onDragStart={() => setDragIndex(i)}
onDragEnter={() => setOverIndex(i)}
onDrop={() => {
if (dragIndex !== null && dragIndex !== i) reorderSections(dragIndex, i);
setDragIndex(null);
setOverIndex(null);
}}
onDragEnd={() => {
setDragIndex(null);
setOverIndex(null);
}}
/>
))}
</div>
{/* 章节列表 —— 三区域拖放:顶/底边重排,中间嵌入为子项 */}
<DndContext
sensors={sensors}
collisionDetection={innermostCollision}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragCancel={handleDragCancel}
>
<div className="space-y-1.5">
{outline.sections.map((section, i) => (
<OutlineSection
key={i}
section={section}
index={i}
sectionIndex={i}
onChange={(updated) => updateSection(i, updated)}
onRemove={editable ? () => removeSection(i) : undefined}
readOnly={!editable}
/>
))}
</div>
<DragOverlay dropAnimation={null}>{renderDragOverlay()}</DragOverlay>
</DndContext>
{/* 添加章节 */}
{editable && (
<Button
type="button"
@@ -142,3 +363,23 @@ export function OutlineCard({ outline, onChange, readOnly = false }: OutlineCard
</div>
);
}
// 拖动时跟随光标的浮动预览。DragOverlay 把这个节点 portal 到 body,
// 不受任何祖先 overflow:hidden 影响,所以拖出卡片也始终可见。
function OverlayCard({ level, label }: { level: Level; label: string }) {
const styleByLevel: Record<Level, string> = {
section: 'rounded border-2 border-blue-400 bg-background text-xs font-medium px-2.5 py-2 shadow-lg',
keypoint: 'rounded border-2 border-blue-400 bg-muted/40 text-xs px-2 py-1.5 shadow-lg',
subpoint: 'rounded border-2 border-blue-400 bg-background text-xs px-2 py-1 shadow-lg',
};
return (
<div className={cn('flex items-center gap-1.5 cursor-grabbing min-w-[180px] max-w-[420px]', styleByLevel[level])}>
<GripVertical className="size-3 text-muted-foreground/50 shrink-0" />
{level === 'keypoint' && <span className="text-purple-500/70 shrink-0">###</span>}
{level === 'subpoint' && <span className="text-pink-500/70 shrink-0 text-[10px] font-mono">####</span>}
<span className="truncate">
{label || <span className="italic text-muted-foreground">(未命名)</span>}
</span>
</div>
);
}
@@ -1,5 +1,6 @@
import { useState, useMemo } from 'react';
import { ChevronRight, Plus, X, GripVertical } from 'lucide-react';
import { useDraggable, useDroppable } from '@dnd-kit/core';
import { cn } from '@/lib/utils';
import type { KeyPoint, OutlineSection as OutlineSectionType } from '../../types/ai-writing';
import { normalizeKeyPoint } from '../../types/ai-writing';
@@ -8,36 +9,34 @@ import { CollapseTransition } from './CollapseTransition';
interface OutlineSectionProps {
section: OutlineSectionType;
index: number;
/** 章节在 outline.sections 中的下标,用于生成稳定 dnd id */
sectionIndex: number;
onChange: (updated: OutlineSectionType) => void;
onRemove?: () => void;
readOnly?: boolean;
// Drag-and-drop (章节级别)
isDragging?: boolean;
isOver?: boolean;
onDragStart?: () => void;
onDragEnter?: () => void;
onDrop?: () => void;
onDragEnd?: () => void;
}
/**
* 章节卡片(Level 1)。内部渲染 keyPoints[] 为「小节子卡片」(Level 2),小节里再渲染
* subPoints[] 为 bullet 列表(Level 3)。
*
* 兼容旧 2 级大纲:section.keyPoints 可能是 (string | KeyPoint)[];进入组件前通过
* normalizeKeyPoint 统一成 KeyPoint[],对外输出也一律是 KeyPoint[](自然升级,用户
* 编辑过的旧 session 大纲会被持久化为新格式)。
*/
// 各级 grip 标题提示文案
const DRAG_HINT = '按住拖动:项的顶/底边 = 同级重排;中间区域 = 嵌入为子项';
const DRAG_HINT_LEAF = '按住拖动重排(顶半区 = 上插入,底半区 = 下插入)';
// ─── 章节 (Level 1) ───────────────────────────────────────────────────────────
export function OutlineSection({
section, index, onChange, onRemove, readOnly,
isDragging, isOver, onDragStart, onDragEnter, onDrop, onDragEnd,
section, index, sectionIndex, onChange, onRemove, readOnly,
}: OutlineSectionProps) {
const [expanded, setExpanded] = useState(false);
const [expanded, setExpanded] = useState(true);
const [editingTitle, setEditingTitle] = useState(false);
const [titleDraft, setTitleDraft] = useState(section.sectionTitle);
// 把 keyPoints 统一成 KeyPoint[];旧 string 元素会被 lift。useMemo 避免每次 render
// 都生成新引用导致子组件无谓重渲染。
const id = `s${sectionIndex}`;
const { attributes, listeners, setNodeRef: setDragRef, isDragging } = useDraggable({
id, disabled: readOnly,
});
// 三个 drop 区:before / into / after
const beforeDrop = useDroppable({ id: `before:${id}`, disabled: readOnly });
const intoDrop = useDroppable({ id: `into:${id}`, disabled: readOnly });
const afterDrop = useDroppable({ id: `after:${id}`, disabled: readOnly });
const keyPoints: KeyPoint[] = useMemo(
() => (section.keyPoints ?? []).map(normalizeKeyPoint),
[section.keyPoints],
@@ -52,128 +51,153 @@ export function OutlineSection({
setTitleDraft(section.sectionTitle);
}
}
function updateKeyPoint(i: number, updated: KeyPoint) {
const next = [...keyPoints];
next[i] = updated;
onChange({ ...section, keyPoints: next });
}
function removeKeyPoint(i: number) {
onChange({ ...section, keyPoints: keyPoints.filter((_, idx) => idx !== i) });
}
function addKeyPoint() {
onChange({ ...section, keyPoints: [...keyPoints, { pointTitle: '', subPoints: [] }] });
}
// 子要点总数,显示在章节头给个粗略概览
const totalSubPoints = keyPoints.reduce((sum, kp) => sum + (kp.subPoints?.length || 0), 0);
return (
<div
draggable={!readOnly}
onDragStart={(e) => { e.stopPropagation(); onDragStart?.(); }}
onDragOver={(e) => { e.preventDefault(); e.stopPropagation(); onDragEnter?.(); }}
onDrop={(e) => { e.preventDefault(); e.stopPropagation(); onDrop?.(); }}
onDragEnd={(e) => { e.stopPropagation(); onDragEnd?.(); }}
ref={setDragRef}
{...attributes}
className={cn(
'rounded border bg-background text-xs transition-all duration-150 select-none',
isDragging ? 'opacity-40 border-border/60' : isOver ? 'border-blue-400 ring-1 ring-blue-400/40' : 'border-border/60',
'relative rounded border text-xs transition-colors duration-150',
isDragging ? 'opacity-40 border-blue-300' : 'border-border/60',
intoDrop.isOver ? 'ring-2 ring-blue-400 ring-inset bg-blue-50/40 dark:bg-blue-950/30' : 'bg-background',
)}
>
{/* 章节头 */}
<div className="flex items-center gap-1.5 px-2.5 py-2">
{!readOnly && (
<GripVertical className="size-3 text-muted-foreground/40 shrink-0 cursor-grab active:cursor-grabbing" />
)}
<button
type="button"
onClick={() => setExpanded((v) => !v)}
className="shrink-0"
>
<ChevronRight
className={cn(
'size-3.5 text-muted-foreground transition-transform duration-200',
expanded && 'rotate-90',
)}
/>
</button>
{/* before:顶部 12px 命中区,命中时顶边显示蓝色线 */}
<div ref={beforeDrop.setNodeRef} className="absolute top-0 inset-x-0 h-3 z-20 pointer-events-none" />
{beforeDrop.isOver && <DropLine position="top" />}
<span className="text-muted-foreground/60 shrink-0 w-4 text-center">{index + 1}.</span>
{editingTitle && !readOnly ? (
<input
autoFocus
value={titleDraft}
onChange={(e) => setTitleDraft(e.target.value)}
onBlur={commitTitle}
onKeyDown={(e) => {
if (e.key === 'Enter') commitTitle();
if (e.key === 'Escape') { setTitleDraft(section.sectionTitle); setEditingTitle(false); }
}}
className="flex-1 bg-transparent border-b border-primary outline-none font-medium"
/>
) : (
<span
className={cn('flex-1 font-medium', !readOnly && 'cursor-text hover:text-primary')}
onClick={() => !readOnly && setEditingTitle(true)}
>
{section.sectionTitle || <span className="text-muted-foreground italic">(未命名)</span>}
</span>
)}
<span className="text-muted-foreground/50 shrink-0">
{keyPoints.length} 小节{totalSubPoints > 0 ? ` · ${totalSubPoints} 子要点` : ''}
</span>
{!readOnly && onRemove && (
<button type="button" onClick={onRemove} className="shrink-0 text-muted-foreground/40 hover:text-destructive">
<X className="size-3" />
</button>
)}
</div>
{/* 小节列表 (Level 2) */}
<CollapseTransition open={expanded}>
<div className="px-6 pb-2.5 pt-1 space-y-1.5 border-t">
{keyPoints.map((kp, i) => (
<KeyPointRow
key={i}
keyPoint={kp}
onChange={(updated) => updateKeyPoint(i, updated)}
onRemove={readOnly ? undefined : () => removeKeyPoint(i)}
readOnly={readOnly}
/>
))}
{/* into:包住头部 + 折叠体;本身就是 drop 容器 */}
<div ref={intoDrop.setNodeRef}>
{/* 章节头 */}
<div className="flex items-center gap-1.5 px-2.5 py-2">
{!readOnly && (
<button
type="button"
onClick={addKeyPoint}
className="flex items-center gap-1 text-muted-foreground/60 hover:text-primary pt-0.5"
{...listeners}
className="shrink-0 cursor-grab active:cursor-grabbing touch-none p-0.5 -m-0.5 text-muted-foreground/40 hover:text-muted-foreground"
aria-label="拖动排序章节"
title={DRAG_HINT}
>
<Plus className="size-3" />
添加小节
<GripVertical className="size-3" />
</button>
)}
<button
type="button"
onClick={() => setExpanded((v) => !v)}
className="shrink-0"
>
<ChevronRight
className={cn(
'size-3.5 text-muted-foreground transition-transform duration-200',
expanded && 'rotate-90',
)}
/>
</button>
<span className="text-muted-foreground/60 shrink-0 w-4 text-center">{index + 1}.</span>
{editingTitle && !readOnly ? (
<input
autoFocus
value={titleDraft}
onChange={(e) => setTitleDraft(e.target.value)}
onBlur={commitTitle}
onKeyDown={(e) => {
if (e.key === 'Enter') commitTitle();
if (e.key === 'Escape') { setTitleDraft(section.sectionTitle); setEditingTitle(false); }
}}
className="flex-1 bg-transparent border-b border-primary outline-none font-medium"
/>
) : (
<span
className={cn('flex-1 font-medium', !readOnly && 'cursor-text hover:text-primary')}
onClick={() => !readOnly && setEditingTitle(true)}
>
{section.sectionTitle || <span className="text-muted-foreground italic">(未命名)</span>}
</span>
)}
<span className="text-muted-foreground/50 shrink-0">
{keyPoints.length} 小节{totalSubPoints > 0 ? ` · ${totalSubPoints} 子要点` : ''}
</span>
{!readOnly && onRemove && (
<button type="button" onClick={onRemove} className="shrink-0 text-muted-foreground/40 hover:text-destructive">
<X className="size-3" />
</button>
)}
</div>
</CollapseTransition>
{/* 小节列表 (Level 2) */}
<CollapseTransition open={expanded}>
<div className="px-6 pb-2.5 pt-1 space-y-1.5 border-t">
{keyPoints.map((kp, i) => (
<KeyPointRow
key={i}
keyPoint={kp}
sectionIndex={sectionIndex}
keyPointIndex={i}
onChange={(updated) => updateKeyPoint(i, updated)}
onRemove={readOnly ? undefined : () => removeKeyPoint(i)}
readOnly={readOnly}
/>
))}
{!readOnly && (
<button
type="button"
onClick={addKeyPoint}
className="flex items-center gap-1 text-muted-foreground/60 hover:text-primary pt-0.5"
>
<Plus className="size-3" />
添加小节
</button>
)}
</div>
</CollapseTransition>
</div>
{/* after:底部 12px 命中区 */}
<div ref={afterDrop.setNodeRef} className="absolute bottom-0 inset-x-0 h-3 z-20 pointer-events-none" />
{afterDrop.isOver && <DropLine position="bottom" />}
</div>
);
}
// ─── 小节行(Level 2,内嵌 Level 3 子要点) ───────────────────────────────────────
// ─── 小节 (Level 2) ───────────────────────────────────────────────────────────
interface KeyPointRowProps {
keyPoint: KeyPoint;
sectionIndex: number;
keyPointIndex: number;
onChange: (updated: KeyPoint) => void;
onRemove?: () => void;
readOnly?: boolean;
}
function KeyPointRow({ keyPoint, onChange, onRemove, readOnly }: KeyPointRowProps) {
const [expanded, setExpanded] = useState(false);
function KeyPointRow({ keyPoint, sectionIndex, keyPointIndex, onChange, onRemove, readOnly }: KeyPointRowProps) {
const [expanded, setExpanded] = useState(true);
const [editingTitle, setEditingTitle] = useState(false);
const [titleDraft, setTitleDraft] = useState(keyPoint.pointTitle);
const id = `s${sectionIndex}-k${keyPointIndex}`;
const { attributes, listeners, setNodeRef: setDragRef, isDragging } = useDraggable({
id, disabled: readOnly,
});
const beforeDrop = useDroppable({ id: `before:${id}`, disabled: readOnly });
const intoDrop = useDroppable({ id: `into:${id}`, disabled: readOnly });
const afterDrop = useDroppable({ id: `after:${id}`, disabled: readOnly });
function commitTitle() {
setEditingTitle(false);
const trimmed = titleDraft.trim();
@@ -181,120 +205,222 @@ function KeyPointRow({ keyPoint, onChange, onRemove, readOnly }: KeyPointRowProp
onChange({ ...keyPoint, pointTitle: trimmed });
}
}
function updateSubPoint(i: number, value: string) {
const next = [...keyPoint.subPoints];
next[i] = value;
onChange({ ...keyPoint, subPoints: next });
}
function removeSubPoint(i: number) {
onChange({ ...keyPoint, subPoints: keyPoint.subPoints.filter((_, idx) => idx !== i) });
}
function addSubPoint() {
onChange({ ...keyPoint, subPoints: [...keyPoint.subPoints, ''] });
setExpanded(true); // 添加时自动展开,免得用户看不到刚加的输入框
setExpanded(true);
}
return (
<div className="rounded border border-border/40 bg-muted/10">
{/* 小节头 */}
<div className="flex items-center gap-1.5 px-2 py-1.5">
<button
type="button"
onClick={() => setExpanded((v) => !v)}
className="shrink-0"
aria-label="展开/收起子要点"
>
<ChevronRight
className={cn(
'size-3 text-muted-foreground/60 transition-transform duration-200',
expanded && 'rotate-90',
)}
/>
</button>
<div
ref={setDragRef}
{...attributes}
className={cn(
'relative rounded border border-border/40 transition-colors duration-150',
isDragging && 'opacity-40 border-blue-300',
intoDrop.isOver ? 'ring-2 ring-blue-400 ring-inset bg-blue-50/40 dark:bg-blue-950/30' : 'bg-muted/10',
)}
>
<div ref={beforeDrop.setNodeRef} className="absolute top-0 inset-x-0 h-2 z-20 pointer-events-none" />
{beforeDrop.isOver && <DropLine position="top" />}
<span className="text-purple-500/70 shrink-0">###</span>
{editingTitle && !readOnly ? (
<input
autoFocus
value={titleDraft}
onChange={(e) => setTitleDraft(e.target.value)}
onBlur={commitTitle}
onKeyDown={(e) => {
if (e.key === 'Enter') commitTitle();
if (e.key === 'Escape') { setTitleDraft(keyPoint.pointTitle); setEditingTitle(false); }
}}
className="flex-1 bg-transparent border-b border-primary outline-none"
placeholder="小节标题"
/>
) : (
<span
className={cn('flex-1', !readOnly && 'cursor-text hover:text-primary')}
onClick={() => !readOnly && setEditingTitle(true)}
>
{keyPoint.pointTitle || <span className="text-muted-foreground italic">(未命名小节)</span>}
</span>
)}
<span className="text-muted-foreground/40 shrink-0 text-[10px]">
{keyPoint.subPoints.length > 0 ? `${keyPoint.subPoints.length} 子要点` : '无子要点'}
</span>
{!readOnly && onRemove && (
<button
type="button"
onClick={onRemove}
className="shrink-0 text-muted-foreground/40 hover:text-destructive"
aria-label="删除小节"
>
<X className="size-3" />
</button>
)}
</div>
{/* 子要点 (Level 3) — 每个子要点会变成正文里的 #### 标题 + 一段独立论述 */}
<CollapseTransition open={expanded}>
<div className="px-6 pb-1.5 space-y-0.5 border-t border-border/30 bg-background/40">
{keyPoint.subPoints.map((sp, i) => (
<div key={i} className="flex items-center gap-1.5 pt-1">
{/* 用 #### 标记替代 bullet,提示这是「四级标题」而非简单列表项 */}
<span className="text-pink-500/70 shrink-0 text-[10px] font-mono">####</span>
{readOnly ? (
<span className="flex-1 text-muted-foreground">{sp}</span>
) : (
<input
value={sp}
onChange={(e) => updateSubPoint(i, e.target.value)}
placeholder="子要点标题(会展开成一段正文)"
className="flex-1 bg-transparent border-b border-transparent hover:border-border focus:border-primary outline-none text-muted-foreground"
/>
)}
{!readOnly && (
<button
type="button"
onClick={() => removeSubPoint(i)}
className="shrink-0 text-muted-foreground/30 hover:text-destructive"
aria-label="删除子要点"
>
<X className="size-3" />
</button>
)}
</div>
))}
<div ref={intoDrop.setNodeRef}>
{/* 小节头 */}
<div className="flex items-center gap-1.5 px-2 py-1.5">
{!readOnly && (
<button
type="button"
onClick={addSubPoint}
className="flex items-center gap-1 text-muted-foreground/50 hover:text-primary pt-0.5 text-[11px]"
{...listeners}
className="shrink-0 cursor-grab active:cursor-grabbing touch-none p-0.5 -m-0.5 text-muted-foreground/30 hover:text-muted-foreground"
aria-label="拖动排序小节"
title={DRAG_HINT}
>
<Plus className="size-3" />
添加子要点
<GripVertical className="size-3" />
</button>
)}
<button
type="button"
onClick={() => setExpanded((v) => !v)}
className="shrink-0"
aria-label="展开/收起子要点"
>
<ChevronRight
className={cn(
'size-3 text-muted-foreground/60 transition-transform duration-200',
expanded && 'rotate-90',
)}
/>
</button>
<span className="text-purple-500/70 shrink-0">###</span>
{editingTitle && !readOnly ? (
<input
autoFocus
value={titleDraft}
onChange={(e) => setTitleDraft(e.target.value)}
onBlur={commitTitle}
onKeyDown={(e) => {
if (e.key === 'Enter') commitTitle();
if (e.key === 'Escape') { setTitleDraft(keyPoint.pointTitle); setEditingTitle(false); }
}}
className="flex-1 bg-transparent border-b border-primary outline-none"
placeholder="小节标题"
/>
) : (
<span
className={cn('flex-1', !readOnly && 'cursor-text hover:text-primary')}
onClick={() => !readOnly && setEditingTitle(true)}
>
{keyPoint.pointTitle || <span className="text-muted-foreground italic">(未命名小节)</span>}
</span>
)}
<span className="text-muted-foreground/40 shrink-0 text-[10px]">
{keyPoint.subPoints.length > 0 ? `${keyPoint.subPoints.length} 子要点` : '无子要点'}
</span>
{!readOnly && onRemove && (
<button
type="button"
onClick={onRemove}
className="shrink-0 text-muted-foreground/40 hover:text-destructive"
aria-label="删除小节"
>
<X className="size-3" />
</button>
)}
</div>
</CollapseTransition>
{/* 子要点 (Level 3) */}
<CollapseTransition open={expanded}>
<div className="px-6 pb-1.5 space-y-0.5 border-t border-border/30 bg-background/40">
{keyPoint.subPoints.map((sp, i) => (
<SubPointRow
key={i}
value={sp}
sectionIndex={sectionIndex}
keyPointIndex={keyPointIndex}
subPointIndex={i}
onChange={(value) => updateSubPoint(i, value)}
onRemove={readOnly ? undefined : () => removeSubPoint(i)}
readOnly={readOnly}
/>
))}
{!readOnly && (
<button
type="button"
onClick={addSubPoint}
className="flex items-center gap-1 text-muted-foreground/50 hover:text-primary pt-0.5 text-[11px]"
>
<Plus className="size-3" />
添加子要点
</button>
)}
</div>
</CollapseTransition>
</div>
<div ref={afterDrop.setNodeRef} className="absolute bottom-0 inset-x-0 h-2 z-20 pointer-events-none" />
{afterDrop.isOver && <DropLine position="bottom" />}
</div>
);
}
// ─── 子要点 (Level 3,叶节点,无 into) ────────────────────────────────────────
interface SubPointRowProps {
value: string;
sectionIndex: number;
keyPointIndex: number;
subPointIndex: number;
onChange: (value: string) => void;
onRemove?: () => void;
readOnly?: boolean;
}
function SubPointRow({
value, sectionIndex, keyPointIndex, subPointIndex, onChange, onRemove, readOnly,
}: SubPointRowProps) {
const id = `s${sectionIndex}-k${keyPointIndex}-p${subPointIndex}`;
const { attributes, listeners, setNodeRef: setDragRef, isDragging } = useDraggable({
id, disabled: readOnly,
});
// 叶节点:没有 into;顶半区 = before、底半区 = after,把整行高度铺满
const beforeDrop = useDroppable({ id: `before:${id}`, disabled: readOnly });
const afterDrop = useDroppable({ id: `after:${id}`, disabled: readOnly });
return (
<div
ref={setDragRef}
{...attributes}
className={cn(
'relative flex items-center gap-1.5 pt-1 rounded transition-colors duration-150',
isDragging && 'opacity-40',
)}
>
<div
ref={beforeDrop.setNodeRef}
className="absolute left-0 right-0 top-0 bottom-1/2 z-20 pointer-events-none"
/>
{beforeDrop.isOver && <DropLine position="top" thin />}
{!readOnly && (
<button
type="button"
{...listeners}
className="shrink-0 cursor-grab active:cursor-grabbing touch-none p-0.5 -m-0.5 text-muted-foreground/30 hover:text-muted-foreground"
aria-label="拖动排序子要点"
title={DRAG_HINT_LEAF}
>
<GripVertical className="size-2.5" />
</button>
)}
<span className="text-pink-500/70 shrink-0 text-[10px] font-mono">####</span>
{readOnly ? (
<span className="flex-1 text-muted-foreground">{value}</span>
) : (
<input
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder="子要点标题(会展开成一段正文)"
className="flex-1 bg-transparent border-b border-transparent hover:border-border focus:border-primary outline-none text-muted-foreground"
/>
)}
{!readOnly && onRemove && (
<button
type="button"
onClick={onRemove}
className="shrink-0 text-muted-foreground/30 hover:text-destructive"
aria-label="删除子要点"
>
<X className="size-3" />
</button>
)}
<div
ref={afterDrop.setNodeRef}
className="absolute left-0 right-0 top-1/2 bottom-0 z-20 pointer-events-none"
/>
{afterDrop.isOver && <DropLine position="bottom" thin />}
</div>
);
}
// ─── 蓝色插入指示线 ───────────────────────────────────────────────────────────
function DropLine({ position, thin }: { position: 'top' | 'bottom'; thin?: boolean }) {
return (
<div
className={cn(
'absolute inset-x-1 bg-blue-500 rounded-full z-30 pointer-events-none',
thin ? 'h-[2px]' : 'h-[3px]',
position === 'top' ? '-top-px' : '-bottom-px',
)}
/>
);
}
@@ -13,6 +13,7 @@ interface TimelineStepProps {
function statusOf(event: ProgressEvent, isLast: boolean): StepStatus {
if (event.type === 'error') return 'error';
if (event.type === 'notice') return 'warning';
if (event.type === 'model_switch') return 'warning';
if (event.type === 'await_user') return 'paused';
// step_start 只有在列表末尾(后续事件还未到达)时才显示转圈,否则已有后续事件说明该步骤已完成
if (event.type === 'step_start') return isLast ? 'running' : 'done';
@@ -30,8 +31,11 @@ const AGENT_COLOR: Record<string, string> = {
export function TimelineStep({ event, isLast, children }: TimelineStepProps) {
const status = statusOf(event, isLast ?? true);
// notice=非致命告警(如 ES 波动、模型兜底),error=致命错误,两者都展示「标题 + 真实原因」
const isAlert = event.type === 'error' || event.type === 'notice';
// notice=非致命告警(如 ES 波动、模型兜底),error=致命错误,model_switch=模型自动容错切换(amber 同 notice)
const isAlert =
event.type === 'error' ||
event.type === 'notice' ||
event.type === 'model_switch';
const isError = event.type === 'error';
return (
@@ -21,6 +21,7 @@ import {
type SetupWritingApprovalPayload,
} from '@/components/workspace/messages';
import { ThreadContext } from '@/components/workspace/messages/context';
import { extractContentFromMessage, extractReasoningContentFromMessage, hasToolCalls } from '@/core/messages/utils';
import { getAPIClient } from '@/core/api';
import { useModels } from '@/core/models/hooks';
import { useThreadStream } from '@/core/threads/hooks';
@@ -29,6 +30,8 @@ import { cn } from '@/lib/utils';
import { useArticleTypes } from '../../hooks/useArticleTypes';
import { useWritingFormOptional } from '../../contexts/WritingFormContext';
import { useAIWritingOptional } from '../../contexts/AIWritingContext';
import type { AIWritingRequest } from '../../types/ai-writing';
import { WritingWelcome } from './WritingWelcome';
/**
@@ -61,6 +64,9 @@ export function WritingSetupChat({
// 缺省回填写作表单;onApprove 传入时脱离 WritingFormProvider(如模板创建页)。
const formCtx = useWritingFormOptional();
const applyProposal = onApproveProp ?? formCtx?.applyProposal;
// 「直接开始写作」:仅在真正的写作上下文(AIWritingProvider 内、未被复用为模板编辑)提供。
const aiWriting = useAIWritingOptional();
const canStartWriting = !onApproveProp && !!aiWriting;
// 首个模型可用时默认选中
useEffect(() => {
@@ -116,9 +122,68 @@ export function WritingSetupChat({
[applyProposal],
);
// 「直接开始写作」:意图确认卡里已带上**用户已确认的大纲**(setup agent 在确认大纲后才提交),
// 这里把审批建议(含该大纲)直接组装成写作请求并启动 ai_writing 流程,同时回填表单保持一致。
const handleStart = useCallback(
async (payload: SetupWritingApprovalPayload) => {
if (!aiWriting) return;
applyProposal?.(payload);
const wordCount =
typeof payload.word_count_target === 'number' && payload.word_count_target > 0
? payload.word_count_target
: Math.max(100, parseInt(formCtx?.wordCountInput ?? '', 10) || 800);
const materialSource = formCtx?.materialSource ?? 'general';
const request: AIWritingRequest = {
userIntent: payload.user_intent?.trim() || formCtx?.intent?.trim() || '',
// 已与用户确认的大纲:作为用户大纲传入,后端据此规划(留空则后端自动规划)
userOutline: payload.outline?.trim() || formCtx?.outlineText?.trim() || undefined,
articleType: payload.article_type?.trim() || formCtx?.articleType || 'analysis',
// 新(列表外)文章类型的一句话特征,仅本次写作临时使用(命中已有类型时为空)。
articleTypeDetail: payload.article_type_detail?.trim() || undefined,
targetAudience: payload.target_audience?.trim() || formCtx?.audience?.trim() || '普通读者',
wordCountTarget: wordCount,
keywordCount: 1,
writingMode: payload.writing_mode === 'strict' ? 'strict' : 'loose',
// 跟随表单的「添加参考文献」开关(默认开)。
addReferences: formCtx?.addReferences ?? true,
materialSource,
modelName: chatModel || formCtx?.modelName || undefined,
noteSearchSpaceId:
materialSource === 'notebook' ? (formCtx?.selectedNotebookId ?? undefined) : undefined,
noteSourceIds:
materialSource === 'notebook' && formCtx?.selectedNotebookId != null
? formCtx.selectedDocumentIds
: undefined,
};
if (!request.userIntent) {
toast.error('写作意图为空,请先补充意图');
return;
}
await aiWriting.startWriting(request);
},
[aiWriting, applyProposal, formCtx, chatModel],
);
// 对话还没有任何消息时显示欢迎/空状态屏(与原型图一致)
const showWelcome = thread.messages.length === 0 && !thread.isLoading;
// 首 token 到达前的「正在整理…」占位:模型在跑(isLoading),但当前助手回合还没有任何
// 可见输出(无答案文本、无 <think> 思考、无工具调用)—— 这段纯网络/排队延迟下答案区空白,
// 加个轻量提示避免用户以为卡死(思考一旦开始流式,此提示自动消失,改由思考区接力)。
const showThinkingPlaceholder = useMemo(() => {
if (!thread.isLoading) return false;
const last = thread.messages[thread.messages.length - 1];
if (!last || last.type !== 'ai') return true; // 还停在用户消息,AI 尚未开口
const hasOutput =
!!extractContentFromMessage(last).trim() ||
!!extractReasoningContentFromMessage(last) ||
hasToolCalls(last);
return !hasOutput;
}, [thread.isLoading, thread.messages]);
const handleReject = useCallback(async () => {
await handleChatSubmit('这份配置先不应用,请继续帮我调整。');
}, [handleChatSubmit]);
@@ -147,10 +212,21 @@ export function WritingSetupChat({
onClarificationSubmit={handleChatSubmit}
onSetupWritingApprove={handleApprove}
onSetupWritingReject={handleReject}
onSetupWritingStart={canStartWriting ? handleStart : undefined}
/>
)}
</div>
{/* 首 token 前的「正在整理…」占位:避免模型慢/排队时答案区空白像卡死 */}
{showThinkingPlaceholder && (
<div className="shrink-0 border-t bg-background px-4 py-2 dark:bg-transparent">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="inline-block size-1.5 animate-pulse rounded-full bg-blue-500" />
正在整理…
</div>
</div>
)}
<div className="bg-background dark:bg-transparent shrink-0 border-t px-4 py-4">
{/* 与原型图一致:白色圆角卡片包裹「模型选择行 + 输入框」 */}
<div className="space-y-3 rounded-2xl border border-[#ece5e4] bg-card p-3 shadow-sm dark:border-[#1B477E] dark:bg-[#022248]/40">
@@ -44,7 +44,7 @@ export function WritingWelcome() {
<p className="mt-2 max-w-xl text-sm leading-relaxed text-slate-500 dark:text-white/60">
这是一个专业的自动化写作系统。你只需在下方对话框中
<strong className="font-semibold text-slate-700 dark:text-white/80">
输入你的本意(例如:「帮我写一篇 1500 字的新能源汽车报告」)
输入你的本意(例如:「帮我写一篇 1500 字的周报」)
</strong>
,系统即会自动为你在右侧填充所需的字数、体裁等格式进行对齐;你也可在右侧进行纯人工的参数深度定制,并一键开启 AI 深度协作创作。
</p>
@@ -23,7 +23,7 @@ import {
import { useCanvasGraphContext } from '../contexts/CanvasGraphContext';
import { saveAIWritingTranscript } from '../api/ai-writing-sessions';
import { countWords } from '../utils/wordCount';
import { countArticleWords } from '../utils/wordCount';
import {
INITIAL_STATE,
customToProgressEvent,
@@ -280,10 +280,14 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
// 用户自带大纲原文(留空则后端走自动规划)
user_outline_raw: request.userOutline?.trim() || '',
article_type: request.articleType,
// 新(列表外)文章类型的一句话特征,仅本次写作临时使用;命中已有类型时为空。
article_type_detail: request.articleTypeDetail?.trim() || '',
target_audience: request.targetAudience,
word_count_target: request.wordCountTarget,
keyword_count: Math.max(1, Math.min(10, request.keywordCount)),
writing_mode: request.writingMode === 'strict' ? 'strict' : 'loose',
// 是否加参考文献(正文 [n] + 文末「参考文献」列表);缺省 false 不改其它入口行为。
add_references: request.addReferences ?? false,
material_source: request.materialSource,
notebook_search_space_id: request.noteSearchSpaceId ?? null,
notebook_source_ids: request.noteSourceIds ?? null,
@@ -328,7 +332,7 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
else if (pausePoint === 'outline_confirm') record.outline = state.outline ?? undefined;
else if (pausePoint === 'draft_confirm') {
record.draftTitle = state.currentDraftTitle;
record.draftWordCount = countWords(state.currentDraftMarkdown);
record.draftWordCount = countArticleWords(state.currentDraftMarkdown);
record.reviewResult = state.reviewResult ?? undefined;
} else if (pausePoint === 'review_confirm') {
record.reviewResult = state.reviewResult ?? undefined;
@@ -342,7 +346,7 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
pendingRevisionContext = {
submittedIssues: allIssues.filter((_, i) => selectedSet.has(i)),
skippedIssues: allIssues.filter((_, i) => !selectedSet.has(i)),
oldWordCount: countWords(state.currentDraftMarkdown),
oldWordCount: countArticleWords(state.currentDraftMarkdown),
};
}
@@ -34,6 +34,9 @@ export interface WritingFormValue {
setAudience: (v: string) => void;
strictMode: boolean;
setStrictMode: (v: boolean) => void;
/** 是否在成稿里加参考文献(正文 [n] 角标 + 文末「参考文献」列表,像论文)。默认开。 */
addReferences: boolean;
setAddReferences: (v: boolean) => void;
materialSource: 'general' | 'notebook';
setMaterialSource: (v: 'general' | 'notebook') => void;
/** 我的空间(笔记本)来源:选中的 search_space_id;上提到 Context 以便左栏「笔记本」点击直接设为素材来源。 */
@@ -81,6 +84,7 @@ export function WritingFormProvider({
const [wordCountInput, setWordCountInput] = useState('800');
const [audience, setAudience] = useState('普通读者');
const [strictMode, setStrictMode] = useState(false);
const [addReferences, setAddReferences] = useState(true);
const [materialSource, setMaterialSource] = useState<'general' | 'notebook'>(initialMaterialSource ?? 'general');
const [selectedNotebookId, setSelectedNotebookId] = useState<number | null>(initialNotebookId ?? null);
const [selectedDocumentIds, setSelectedDocumentIds] = useState<number[]>(initialDocumentIds ?? []);
@@ -117,13 +121,14 @@ export function WritingFormProvider({
wordCountInput, setWordCountInput,
audience, setAudience,
strictMode, setStrictMode,
addReferences, setAddReferences,
materialSource, setMaterialSource,
selectedNotebookId, setSelectedNotebookId,
selectedDocumentIds, setSelectedDocumentIds,
modelName, setModelName,
applyProposal,
}),
[intent, formExpanded, showOutline, outlineText, articleType, wordCountInput, audience, strictMode, materialSource, selectedNotebookId, selectedDocumentIds, modelName, applyProposal],
[intent, formExpanded, showOutline, outlineText, articleType, wordCountInput, audience, strictMode, addReferences, materialSource, selectedNotebookId, selectedDocumentIds, modelName, applyProposal],
);
return <WritingFormContext.Provider value={value}>{children}</WritingFormContext.Provider>;
@@ -1,4 +1,4 @@
import { useCallback, useState } from 'react';
import { useCallback, useMemo, useState } from 'react';
import {
listAIWritingSessions,
@@ -10,6 +10,27 @@ import type { AIWritingSessionSummary } from '../api/ai-writing-sessions';
export function useAIWritingSessions() {
const [sessions, setSessions] = useState<AIWritingSessionSummary[]>([]);
const [loading, setLoading] = useState(false);
// 「后台挂起」乐观标记:点击挂起后立刻让历史下拉显示「挂起中」,不必等后端确认。
// 后端状态(status='background')刷新到位后由调用方 clearBackground 清除。
const [pendingBackground, setPendingBackground] = useState<Set<string>>(() => new Set());
const markBackground = useCallback((id: string) => {
setPendingBackground((prev) => {
if (prev.has(id)) return prev;
const next = new Set(prev);
next.add(id);
return next;
});
}, []);
const clearBackground = useCallback((id: string) => {
setPendingBackground((prev) => {
if (!prev.has(id)) return prev;
const next = new Set(prev);
next.delete(id);
return next;
});
}, []);
const refresh = useCallback(async () => {
setLoading(true);
@@ -41,5 +62,18 @@ export function useAIWritingSessions() {
}
}, []);
return { sessions, loading, refresh, rename, remove };
// 把乐观「挂起中」标记叠加到真实列表上:已在列表里的会话立刻显示 background。
const displaySessions = useMemo(
() =>
pendingBackground.size === 0
? sessions
: sessions.map((s) =>
pendingBackground.has(s.id) && s.status !== 'done'
? { ...s, status: 'background' }
: s,
),
[sessions, pendingBackground],
);
return { sessions: displaySessions, loading, refresh, rename, remove, markBackground, clearBackground };
}
@@ -21,7 +21,7 @@
* 这样 reducer 逻辑(INITIAL_STATE + switch 各分支)与老 hook 共享同一份代码,
* 只换"事件源"。阶段 7 删冗余时把老 hook 整个删掉就行。
*/
import { countWords } from '../utils/wordCount';
import { countArticleWords } from '../utils/wordCount';
import type {
AIWritingRequest,
AIWritingState,
@@ -339,7 +339,7 @@ function handleEvent(prev: AIWritingState, event: ProgressEvent): AIWritingState
case 'draft_ready': {
const newMarkdown = event.draftMarkdown ?? '';
const newWordCount = countWords(newMarkdown);
const newWordCount = countArticleWords(newMarkdown);
const summary = prev.pendingRevisionContext
? {
revisedIssues: prev.pendingRevisionContext.submittedIssues,
@@ -388,6 +388,37 @@ function handleEvent(prev: AIWritingState, event: ProgressEvent): AIWritingState
case 'notice':
return base;
case 'model_switch': {
// 模型自动容错:丢弃当前阶段已累积的流式缓冲,避免上一个失败模型的半截输出
// 与下一个模型的输出粘在一起;时间线展示侧由 TimelineStep 按 amber 渲染(同 notice)。
const stage = event.modelSwitch?.stage;
const sectionIndex = event.modelSwitch?.sectionIndex;
const resetByStage: Partial<AIWritingState> = (() => {
switch (stage) {
case 'intent':
return { intentStreamingText: '', intentThinkingText: '' };
case 'outline':
return { outlineStreamingText: '', outlineThinkingText: '' };
case 'draft': {
// 只清掉失败那一节的流式片段,已写好的章节保持不动
if (typeof sectionIndex === 'number') {
return {
streamingDraftSections: prev.streamingDraftSections.filter(
(s) => s.sectionIndex !== sectionIndex,
),
};
}
return { streamingDraftSections: [], streamingDraftTitle: '' };
}
case 'review':
return { streamingReviewItems: [] };
default:
return {};
}
})();
return { ...base, ...resetByStage };
}
default:
return base;
}
@@ -506,6 +537,22 @@ export function normalizeProgressDict(parsed: Record<string, unknown>, sessionId
out.reviewItemIssues = (out.issues as Record<string, unknown>[]).map(normalizeReviewIssue);
}
// model_switch(updates 通道里的 progress_events 也可能带):折成 modelSwitch 子对象
if (out.type === 'model_switch' && !out.modelSwitch) {
out.modelSwitch = {
stage: (out.stage as 'intent' | 'outline' | 'draft' | 'review') ?? 'intent',
failedModel: String(out.failed_model ?? out.failedModel ?? ''),
nextModel: String(out.next_model ?? out.nextModel ?? ''),
reason: String(out.reason ?? ''),
sectionIndex: typeof out.section_index === 'number'
? (out.section_index as number)
: (typeof out.sectionIndex === 'number' ? (out.sectionIndex as number) : undefined),
sectionTitle: typeof out.section_title === 'string'
? (out.section_title as string)
: (typeof out.sectionTitle === 'string' ? (out.sectionTitle as string) : undefined),
};
}
if (!out.message) out.message = '';
return out as unknown as ProgressEvent;
}
@@ -522,6 +569,7 @@ export function customToProgressEvent(raw: unknown, sessionId: string): Progress
'research_progress', 'outline_chunk', 'draft_chunk',
'review_chunk', 'review_item_done',
'skill_search_step', 'skill_select_chunk',
'model_switch',
];
if (!allowed.includes(type as ProgressEventType)) return null;
@@ -536,10 +584,30 @@ export function customToProgressEvent(raw: unknown, sessionId: string): Progress
if (Array.isArray(merged.issues)) {
merged.reviewItemIssues = (merged.issues as Record<string, unknown>[]).map(normalizeReviewIssue);
}
if ('agent_name' in merged && !merged.agentName) merged.agentName = merged.agent_name;
// skill_search_step:把字段折成 skillStep 子对象,方便 reducer / UI 取用
if (type === 'skill_search_step') {
merged.skillStep = normalizeSkillStep(o);
}
// model_switch:把 snake_case 字段折成 modelSwitch 子对象(reducer + TimelineStep 取用)
if (type === 'model_switch') {
merged.modelSwitch = {
stage: (o.stage as 'intent' | 'outline' | 'draft' | 'review') ?? 'intent',
failedModel: String(o.failed_model ?? (o as Record<string, unknown>).failedModel ?? ''),
nextModel: String(o.next_model ?? (o as Record<string, unknown>).nextModel ?? ''),
reason: String(o.reason ?? ''),
sectionIndex: typeof o.section_index === 'number'
? (o.section_index as number)
: (typeof (o as Record<string, unknown>).sectionIndex === 'number'
? ((o as Record<string, unknown>).sectionIndex as number)
: undefined),
sectionTitle: typeof o.section_title === 'string'
? (o.section_title as string)
: (typeof (o as Record<string, unknown>).sectionTitle === 'string'
? ((o as Record<string, unknown>).sectionTitle as string)
: undefined),
};
}
return merged as unknown as ProgressEvent;
}
@@ -633,6 +701,10 @@ export type AIWritingValues = {
user_intent?: string;
user_outline_raw?: string;
article_type?: string;
/** 新(列表外)文章类型的一句话特征,仅本次写作临时使用。 */
article_type_detail?: string;
/** 是否加参考文献(正文 [n] 角标 + 文末「参考文献」列表)。 */
add_references?: boolean;
status?: string;
material_package?: unknown;
current_outline?: unknown;
@@ -25,25 +25,33 @@ export function useWritingEditor({
const onChangeRef = useRef(onChange);
useEffect(() => { onChangeRef.current = onChange; }, [onChange]);
// 编辑器自身最近一次 emit 出去的 markdown。父级把它存进 state 后会作为新的 `markdown` prop
// 回灌进来,下面的同步 effect 据此识别「这是我自己刚产生的变更」并跳过 setContent。
const lastEmittedRef = useRef<string | null>(null);
const editor = useEditor({
extensions,
editable,
content: markdown,
onUpdate({ editor }) {
const fn = onChangeRef.current;
if (!fn) return;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const md = (editor as any).storage?.markdown?.getMarkdown?.() ?? editor.getText();
fn(md);
lastEmittedRef.current = md;
onChangeRef.current?.(md);
},
}, []);
// Sync external markdown changes (e.g. after streaming completes)
// Sync external markdown changes (e.g. after streaming completes / AI 改写)
useEffect(() => {
if (!editor) return;
if (markdown === prevMarkdownRef.current) return;
prevMarkdownRef.current = markdown;
// 跳过「编辑器自身刚 emit、又被父级回灌」的变更:此时编辑器内容已经是最新的,再 setContent
// 会重新解析整篇文档、重置光标。markdown 序列化对空格/换行是有损的(如行尾空格被裁剪),
// 自激回灌一旦触发 setContent,就会把刚输入的空格吞掉并让光标跳到下一个字(本次修的 bug)。
if (markdown === lastEmittedRef.current) return;
const { from, to } = editor.state.selection;
editor.commands.setContent(markdown, { emitUpdate: false });
const docSize = editor.state.doc.content.size;
@@ -202,7 +202,13 @@ function AIWritingLayout({ hideAdvancedFields, initialNotebookId, initialDocumen
<WritingFormPanel hideAdvancedFields={hideAdvancedFields} />
</ResizablePanel>
<ResizableHandle withHandle />
{/* 隐形拖拽热区只向右(草稿区)延伸、可见抓手也微微右移,二者都不再盖住左侧时间线的
滚动条——否则鼠标想抓滚动条会误触左右 resize、导致滑不动。右侧是草稿区留白(px-10),
盖住无副作用。 */}
<ResizableHandle
withHandle
className="after:left-0 after:w-3 after:translate-x-0 [&>div]:translate-x-1.5"
/>
{/* 右侧:草稿预览面板 */}
<ResizablePanel
@@ -172,6 +172,7 @@ export type ProgressEventType =
| "await_user"
| "resumed"
| "notice"
| "model_switch"
| "skill_search_step"
| "skill_select_chunk"
| "done"
@@ -215,6 +216,16 @@ export interface ProgressEvent {
blockedSections?: BlockedSection[];
// skill_search_step:技能检索步骤事件(list_skills / select_skills / invoke_skill)
skillStep?: SkillSearchStep;
// model_switch:模型自动容错切换(某模型挂掉,换下一个模型继续)
// stage ∈ intent / outline / draft / review,前端 reducer 据此清掉对应阶段的流式缓冲。
modelSwitch?: {
stage: "intent" | "outline" | "draft" | "review";
failedModel: string;
nextModel: string;
reason: string;
sectionIndex?: number;
sectionTitle?: string;
};
}
// ── 用户干预提交体 ────────────────────────────────────────────────────────────
@@ -243,6 +254,8 @@ export interface AIWritingRequest {
/** 用户粘贴的「已有大纲」原文(可选)。非空时后端按此大纲生成,不再自动规划 */
userOutline?: string;
articleType: string;
/** 当 articleType 是已有类型库里没有的新类型时,配置助手识别的一句话特征说明(仅本次写作临时使用,不入库)。 */
articleTypeDetail?: string;
targetAudience: string;
wordCountTarget: number;
modelName?: string;
@@ -250,6 +263,8 @@ export interface AIWritingRequest {
keywordCount: number;
/** 写作模式:strict=严格依据素材 / loose=可结合通用知识(默认 loose) */
writingMode: "strict" | "loose";
/** 是否在成稿里加参考文献(正文 [n] 角标 + 文末「参考文献」列表,像论文)。默认 true。 */
addReferences?: boolean;
/** 检索类型:general=通用检索(素材收集专家按配置技能检索,默认知识库检索技能)/ notebook=我的空间 */
materialSource: "general" | "notebook";
/** 笔记来源(可选):空间 search_space_id */
@@ -10,3 +10,15 @@ export function countWords(text: string): number {
const alnumRuns = (text.match(/[A-Za-z0-9]+/g) ?? []).length;
return cjk + cjkPunct + alnumRuns;
}
/**
* 正文字数:与后端 word_count 同口径——**不计文末「参考文献」列表**。
* 后端在字数收敛后才追加 `## 参考文献` 段,其 word_count 只统计正文;前端展示「实际 vs 目标」
* 也必须排除该段,否则会因文献列表虚高几十~几百字,让用户误以为严重超标。
*/
export function countArticleWords(markdown: string): number {
if (!markdown) return 0;
const idx = markdown.lastIndexOf('## 参考文献');
const body = idx >= 0 ? markdown.slice(0, idx) : markdown;
return countWords(body);
}
+8
View File
@@ -26,6 +26,10 @@ import { ThreadContext } from "@/components/workspace/messages/context";
import { QuestionNavigator } from "@/components/workspace/question-navigator";
import { ThreadTitle } from "@/components/workspace/thread-title";
import { TodoList } from "@/components/workspace/todo-list";
import {
LayoutModeSwitcher,
ThemeSwitcher,
} from "@/components/workspace/appearance-controls";
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
import { UserIdentityBadge } from "@/components/workspace/user-identity-badge";
import { Welcome } from "@/components/workspace/welcome";
@@ -500,8 +504,12 @@ export default function ChatPage() {
<ArtifactTrigger />
{/* 不带全局顶栏(紧凑模式)时,名称+岗位回落到聊天页顶栏右侧,
与全量模式 Header 右上角保持一致。全量模式已有顶栏则不重复展示。 */}
{/* 简洁模式无全局顶栏:把换肤 + 界面模式切换搬到页面级顶栏右上角,
与全量模式 Header 右上角保持一致(content 配色贴浅底顶栏)。 */}
{!compactChrome && (
<>
<ThemeSwitcher tone="content" />
<LayoutModeSwitcher tone="content" />
<div
className="bg-border/70 mx-1 h-6 w-px shrink-0"
aria-hidden
+116 -69
View File
@@ -5,8 +5,8 @@ import {
BrainCircuitIcon,
FileTextIcon,
GraduationCapIcon,
ShrinkIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { type PromptInputMessage } from "@/components/ai-elements/prompt-input";
@@ -46,6 +46,8 @@ import {
type BrainyChatSubmitMessage,
parseBrainyChatSubmitMessage,
} from "./iframe-chat-submit";
import { resolveIframeAssistantId } from "./iframe-chat-agent";
import { buildIframeModeButtons } from "./iframe-chat-mode-buttons";
type BrainyChatStatus = "started" | "finished";
type BrainyAuthTokenMessage = {
@@ -93,7 +95,6 @@ function postBrainyAuthToken(accessToken: string) {
export default function IframeChatPage() {
const routeBase = useRouteBase();
const router = useRouter();
const { t } = useI18n();
const [hasStartedConversation, setHasStartedConversation] = useState(false);
const { threadId, setThreadId, isNewThread, setIsNewThread, isMock } =
@@ -152,11 +153,19 @@ export default function IframeChatPage() {
}, [selectedAgentId, selectorAgents, selectorLoading]);
const { showNotification } = useNotification();
const activeAssistantId = resolveIframeAssistantId({
selectedAgentId,
threadMetadataAgentId: null,
});
const [thread, sendMessage, isUploading] = useThreadStream({
threadId: isNewThread ? undefined : threadId,
context: settings.context,
context: {
...settings.context,
...(activeAssistantId ? { agent_id: activeAssistantId } : {}),
},
isMock,
assistantId: activeAssistantId,
onStart: (createdThreadId) => {
setThreadId(createdThreadId);
setIsNewThread(false);
@@ -193,6 +202,22 @@ export default function IframeChatPage() {
},
});
const threadMetadataAgentId = (() => {
const metadata = (thread as { metadata?: Record<string, unknown> | null })
.metadata;
return typeof metadata?.agent_id === "string" ? metadata.agent_id : null;
})();
useEffect(() => {
const resolvedAgentId = resolveIframeAssistantId({
selectedAgentId,
threadMetadataAgentId,
});
if (resolvedAgentId && resolvedAgentId !== selectedAgentId) {
setSelectedAgentId(resolvedAgentId);
}
}, [selectedAgentId, threadMetadataAgentId]);
const writingArtifactPath = useMemo(() => {
const isMarkdown = (path: string | null | undefined) =>
!!path && /\.(md|markdown)(?:$|[?#])/i.test(path);
@@ -210,31 +235,15 @@ export default function IframeChatPage() {
externalContext?: Record<string, unknown>,
options?: { additionalKwargs?: Record<string, unknown> },
) => {
if (
selectedAgentId &&
isNewThread &&
!hasStartedConversation &&
message.text &&
(!message.files || message.files.length === 0)
) {
try {
sessionStorage.setItem(
"pendingAgentMessage",
JSON.stringify({ agentId: selectedAgentId, text: message.text }),
);
} catch {
// sessionStorage may be unavailable in private mode; fall through.
}
router.push(`/page/workspace/agents/${selectedAgentId}/chats/new`);
return;
}
setHasStartedConversation(true);
window.dispatchEvent(
new CustomEvent("workspace:sandbox-resume-autoscroll"),
);
const extraContext: Record<string, unknown> = {};
if (activeAssistantId) {
extraContext.agent_id = activeAssistantId;
}
if (settings.context.writing_mode && writingArtifactPath) {
extraContext.writing_artifact_path = writingArtifactPath;
}
@@ -250,10 +259,8 @@ export default function IframeChatPage() {
);
},
[
activeAssistantId,
hasStartedConversation,
isNewThread,
router,
selectedAgentId,
sendMessage,
settings.context.writing_mode,
threadId,
@@ -277,6 +284,8 @@ export default function IframeChatPage() {
const ragModeLocked = isThreadRagModeLocked(threadId);
const ragModeEnabled =
localSettings.display.ragModeEnabled || ragModeLocked;
const contextCompressionEnabled =
localSettings.display.contextCompressionEnabled ?? false;
const proModeEnabled = settings.context.mode === "pro";
const toggleWritingMode = useCallback(() => {
@@ -301,6 +310,12 @@ export default function IframeChatPage() {
});
}, [ragModeEnabled, ragModeLocked, setLocalSettings]);
const toggleContextCompression = useCallback(() => {
setLocalSettings("display", {
contextCompressionEnabled: !contextCompressionEnabled,
});
}, [contextCompressionEnabled, setLocalSettings]);
const toggleProMode = useCallback(() => {
setSettings("context", {
mode: proModeEnabled ? "flash" : "pro",
@@ -333,28 +348,29 @@ export default function IframeChatPage() {
const data = event.data;
if (data?.source !== "brainy-extension") return;
if (data?.type === "brainy:chat-interrupt") {
void handleInterrupt(data);
void handleInterrupt(data as BrainyChatInterruptMessage);
return;
}
if (data?.type !== "brainy:chat-submit") return;
const submitMessage = data as BrainyChatSubmitMessage;
const { submitText, files, iframeContext, additionalKwargs } =
parseBrainyChatSubmitMessage(data);
parseBrainyChatSubmitMessage(submitMessage);
console.log("收到插件消息", {
text: data.payload?.text,
prompt: data.payload?.prompt,
pageContext: data.payload?.pageContext,
screenshot: data.payload?.screenshot,
model: data.payload?.model,
requestId: data.requestId,
text: submitMessage.payload?.text,
prompt: submitMessage.payload?.prompt,
pageContext: submitMessage.payload?.pageContext,
screenshot: submitMessage.payload?.screenshot,
model: submitMessage.payload?.model,
requestId: submitMessage.requestId,
filesCount: files.length,
iframeContext,
});
if (!submitText && files.length === 0) return;
pendingRequestIdRef.current = data.requestId ?? null;
pendingRequestIdRef.current = submitMessage.requestId ?? null;
handleSubmit(
{ text: submitText, files },
@@ -371,41 +387,59 @@ export default function IframeChatPage() {
const isLandingState = isNewThread && !hasStartedConversation;
const bottomBarHeightClass = "pb-24";
const modeButtons = [
{
key: "writing",
label: "写作",
icon: FileTextIcon,
active: !!settings.context.writing_mode,
onClick: toggleWritingMode,
activeClassName: "text-amber-600 hover:text-amber-700",
},
{
key: "memory",
label: "记忆",
icon: BrainCircuitIcon,
active: settings.context.memory_injection_enabled ?? true,
onClick: toggleMemoryInjection,
activeClassName: "text-blue-600 hover:text-blue-700",
},
{
key: "references",
label: "参考文献",
icon: BookMarkedIcon,
active: ragModeEnabled,
onClick: toggleRagMode,
disabled: ragModeLocked,
activeClassName: "text-emerald-600 hover:text-emerald-700",
},
{
key: "pro",
label: "专业问答",
icon: GraduationCapIcon,
active: proModeEnabled,
onClick: toggleProMode,
activeClassName: "text-violet-600 hover:text-violet-700",
},
] as const;
const modeButtons = buildIframeModeButtons({
agentSelected: !!selectedAgentId,
writingModeEnabled: !!settings.context.writing_mode,
memoryInjectionEnabled: Boolean(
settings.context.memory_injection_enabled ?? true,
),
ragModeEnabled,
ragModeLocked,
contextCompressionEnabled,
proModeEnabled,
}).map((button) => {
switch (button.key) {
case "agent":
return button;
case "writing":
return {
...button,
icon: FileTextIcon,
onClick: toggleWritingMode,
activeClassName: "text-amber-600 hover:text-amber-700",
};
case "memory":
return {
...button,
icon: BrainCircuitIcon,
onClick: toggleMemoryInjection,
activeClassName: "text-blue-600 hover:text-blue-700",
};
case "references":
return {
...button,
icon: BookMarkedIcon,
onClick: toggleRagMode,
activeClassName: "text-emerald-600 hover:text-emerald-700",
};
case "contextCompression":
return {
...button,
icon: ShrinkIcon,
onClick: toggleContextCompression,
activeClassName: "text-violet-600 hover:text-violet-700",
};
case "pro":
return {
...button,
icon: GraduationCapIcon,
onClick: toggleProMode,
activeClassName: "text-fuchsia-600 hover:text-fuchsia-700",
};
default:
return button;
}
});
return (
<ThreadContext.Provider value={{ thread, isMock }}>
@@ -496,6 +530,19 @@ export default function IframeChatPage() {
<TooltipProvider delayDuration={250}>
<div className="mx-auto flex max-w-(--container-width-lg) flex-wrap items-center justify-center gap-0 px-0 py-1">
{modeButtons.map((button) => {
if (button.key === "agent") {
return (
<AgentSelector
key={button.key}
selectedAgentId={selectedAgentId}
onAgentChange={handleAgentChange}
disabled={isUploading}
triggerVariant="icon"
iconButtonClassName="size-9 rounded-full text-muted-foreground shadow-none hover:bg-muted/60 hover:text-foreground"
iconActiveClassName="text-amber-600 hover:text-amber-700"
/>
);
}
const Icon = button.icon;
return (
<Tooltip key={button.key} content={button.label}>
+5
View File
@@ -88,6 +88,8 @@ export default function NewAgentPage() {
const [modelInput, setModelInput] = useState<string>("");
const [chatModelInput, setChatModelInput] = useState<string>("");
const [templateNameInput, setTemplateNameInput] = useState("");
// 会商席位「技能识别强化」开关(弱模型补偿)。默认关。
const [seatSkillDirectiveInput, setSeatSkillDirectiveInput] = useState(false);
const [formError, setFormError] = useState("");
const [agentId, setAgentId] = useState("");
const [agent, setAgent] = useState<Agent | null>(null);
@@ -240,6 +242,7 @@ export default function NewAgentPage() {
skills: selectedSkills,
model: modelOverride,
template_name: templateNameInput.trim(),
seat_skill_directive: seatSkillDirectiveInput,
});
setAgent(updated);
return updated;
@@ -261,6 +264,7 @@ export default function NewAgentPage() {
skills: selectedSkills,
model: modelOverride,
template_name: templateNameInput.trim(),
seat_skill_directive: seatSkillDirectiveInput,
});
setAgentId(created.id);
setAgent(created);
@@ -291,6 +295,7 @@ export default function NewAgentPage() {
selectedSkills,
soulInput,
templateNameInput,
seatSkillDirectiveInput,
t.agents.nameStepCheckError,
t.agents.nameStepNetworkError,
validateForm,
@@ -2,6 +2,9 @@ import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import AIWritingPage from '@/open-canvas/pages/AIWritingPage';
import { getNotebookApiBaseURL } from '@/core/config';
import { useTheme, type ThemeType } from '@/contexts/ThemeContext';
const VALID_THEMES: ThemeType[] = ['dark', 'light', 'lightblue'];
interface NotebookTokenData {
doc_ids: number[];
@@ -13,6 +16,17 @@ interface NotebookTokenData {
export default function NotebookAIWritingPage() {
const [searchParams] = useSearchParams();
const token = searchParams.get('token');
const themekey = searchParams.get('themekey');
const { setTheme } = useTheme();
// 跟随调用方传入的 themekey 切换主题;缺省或非法值兜底为 light
useEffect(() => {
const next = themekey && VALID_THEMES.includes(themekey as ThemeType)
? (themekey as ThemeType)
: 'light';
setTheme(next);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [themekey]);
const [data, setData] = useState<NotebookTokenData | null>(null);
const [spaceName, setSpaceName] = useState<string | null>(null);
+8 -1
View File
@@ -44,8 +44,15 @@ function PageLayout() {
() => isEmbedActive() || readEmbedParam(location.search) === "on",
[location.pathname, location.search],
);
// 「大屏绘制」独立页(/page/strategy/dashboard-agent)本就是「带导航栏 + 侧边栏」的独立页,
// 但它常被深链「上一步」从去 chrome 的工作区/新标签打开——那里 chromeByPreference 可能为 false
// (界面模式非全量、或会话级 sidebar 未置位),导致整页没有顶栏/侧栏。故对该路由**强制全局 chrome**
// (仍尊重 embed=1 嵌入态:外部 iframe 套用时仍隐藏)。
const forceChromeForDashboardAgent = location.pathname.includes("/strategy/dashboard-agent");
const pageSidebarAllowed =
chromeByPreference && !isChatsIframeWorkspacePath(location.pathname) && !embedActive;
(forceChromeForDashboardAgent || chromeByPreference) &&
!isChatsIframeWorkspacePath(location.pathname) &&
!embedActive;
// h-full(100%)而非 h-screen(100vh):配合 globals.css 的 html/body/#root height:100%
// 高度链,根布局跟随容器高度。全屏下 100% 解析到视口,与 h-screen 等价;无界等嵌套
@@ -0,0 +1,333 @@
"use client";
/**
* 会商诊断日志(仅 admin):展示多智能体会商全流程(第一步意图 / 第二步研讨 /
* 第三步报告 + 后台挂起执行器 / 进程内网关)各处的报错与关键事件,支持按
* scope(前台/后台)、阶段、级别、事件码、作业/任务/草稿 id、关键词筛选 + 分页。
*
* 数据源:`GET /api/roundtable-diagnostics`(admin-gated)。入口:多智能体会商页右上角
* 设置按钮(admin)。见 [[roundtable-diagnostics]]。
*/
import { useMemo, useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import { ArrowLeft, RefreshCw, Search } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Pagination } from "@/components/ui/pagination";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { getStoredAuth } from "@/core/auth";
import {
type DiagnosticFilters,
type DiagnosticItem,
useRoundtableDiagnosticFacets,
useRoundtableDiagnostics,
} from "@/strategy-components/api/roundtable-diagnostics";
const PAGE_SIZE = 50;
const ALL = "__all__";
// 阶段中文名(已知集合;未知阶段原样显示)。
const STAGE_LABELS: Record<string, string> = {
step1_intent: "第一步 · 意图",
step2_init: "第二步 · 初始化",
step2_leader: "第二步 · 总控",
step2_seat: "第二步 · 席位",
step2_recommend: "第二步 · 推荐",
step2_orchestration: "第二步 · 编排",
step3_summary: "第三步 · 总结报告",
step3_report: "第三步 · 结果绘制",
step3_dashboard: "第三步 · 大屏数据",
step3_structure: "第三步 · 数据入库",
upstream: "回环代理",
job: "后台作业",
};
const SCOPE_LABELS: Record<string, string> = {
background: "后台挂起",
foreground: "前台实时(服务端)",
client: "前端上报",
};
// 范围切换:后台挂起(background) / 前台调用(foreground 服务端观测 + client 前端上报)。
type ScopeCategory = "background" | "frontend";
// 每个范围下可选的阶段(按用户要求:后台挂起只到第二/三步;前台调用含第一步)。
const STAGE_OPTIONS: Record<ScopeCategory, string[]> = {
background: [
"step2_init",
"step2_leader",
"step2_seat",
"step2_orchestration",
"step3_summary",
"step3_report",
"step3_dashboard",
"step3_structure",
"job",
],
frontend: [
"step1_intent",
"step2_init",
"step2_leader",
"step2_seat",
"step2_recommend",
"step3_summary",
"step3_report",
"step3_dashboard",
"step3_structure",
],
};
const LEVEL_STYLES: Record<string, string> = {
error: "bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300",
warning: "bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300",
info: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300",
};
function stageLabel(stage: string): string {
return STAGE_LABELS[stage] ?? stage;
}
function fmtTime(iso: string | null): string {
if (!iso) return "";
try {
const d = new Date(iso);
return d.toLocaleString("zh-CN", { hour12: false });
} catch {
return iso;
}
}
function DiagnosticRow({ item }: { item: DiagnosticItem }) {
const [open, setOpen] = useState(false);
const hasDetail = item.detail != null && Object.keys(item.detail as object).length > 0;
return (
<div className="rounded-lg border border-slate-200 dark:border-border bg-white dark:bg-card px-3 py-2 text-sm">
<div className="flex items-start gap-2">
<span
className={cn(
"shrink-0 rounded px-1.5 py-0.5 text-xs font-medium uppercase",
LEVEL_STYLES[item.level] ?? LEVEL_STYLES.info,
)}
>
{item.level}
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<Badge variant="secondary" className="text-xs">
{stageLabel(item.stage)}
</Badge>
<code className="text-xs text-slate-500 dark:text-muted-foreground">{item.event}</code>
{item.agentName ? (
<span className="text-xs text-slate-500 dark:text-muted-foreground">· {item.agentName}</span>
) : null}
{item.userName ? (
<span className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300">
👤 {item.userName}
</span>
) : null}
<span className="ml-auto text-xs text-slate-400 dark:text-muted-foreground">{fmtTime(item.createdAt)}</span>
</div>
<p className="mt-1 whitespace-pre-wrap break-words text-slate-700 dark:text-foreground">
{item.message || <span className="text-slate-400">(无说明)</span>}
</p>
<div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-slate-400 dark:text-muted-foreground">
<span>{SCOPE_LABELS[item.scope] ?? item.scope}</span>
{item.jobId ? <span>job: {item.jobId.slice(0, 8)}</span> : null}
{item.taskId ? <span>task: {item.taskId}</span> : null}
{item.draftId ? <span>draft: {item.draftId.slice(0, 8)}</span> : null}
{item.cycle != null ? <span>cycle: {item.cycle}</span> : null}
{hasDetail ? (
<button type="button" className="text-blue-500 hover:underline" onClick={() => setOpen((v) => !v)}>
{open ? "收起详情" : "展开详情"}
</button>
) : null}
</div>
{open && hasDetail ? (
<pre className="mt-2 max-h-64 overflow-auto rounded bg-slate-50 dark:bg-muted p-2 text-xs text-slate-600 dark:text-muted-foreground">
{JSON.stringify(item.detail, null, 2)}
</pre>
) : null}
</div>
</div>
</div>
);
}
export default function RoundtableDiagnosticsPage() {
const isAdmin = getStoredAuth()?.system_role === "admin";
const navigate = useNavigate();
const [scopeCategory, setScopeCategory] = useState<ScopeCategory>("background");
const [stage, setStage] = useState<string>(ALL);
const [level, setLevel] = useState<string>(ALL);
const [event, setEvent] = useState<string>(ALL);
const [qInput, setQInput] = useState("");
const [q, setQ] = useState("");
const [page, setPage] = useState(1);
// 「前台调用」= 服务端观测(foreground) + 前端上报(client) 两种 scope 合并查(后端按逗号分隔多值)。
const scopeParam = scopeCategory === "background" ? "background" : "foreground,client";
const filters: DiagnosticFilters = useMemo(
() => ({
scope: scopeParam,
stage: stage === ALL ? undefined : stage,
level: level === ALL ? undefined : level,
event: event === ALL ? undefined : event,
q: q || undefined,
limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE,
}),
[scopeParam, stage, level, event, q, page],
);
const { data, isLoading, isFetching, refetch } = useRoundtableDiagnostics(filters, isAdmin);
const { data: facets } = useRoundtableDiagnosticFacets(isAdmin);
if (!isAdmin) {
return <Navigate to="/page/workspace/chats/new" replace />;
}
const items = data?.items ?? [];
const total = data?.total ?? 0;
const resetPageAnd = (fn: () => void) => {
fn();
setPage(1);
};
// 切换范围时清空阶段筛选(两种范围的阶段选项不同)+ 回到第一页。
const switchScope = (next: ScopeCategory) => {
setScopeCategory(next);
setStage(ALL);
setPage(1);
};
const applySearch = () => resetPageAnd(() => setQ(qInput.trim()));
return (
<div className="flex h-full flex-col bg-slate-50 dark:bg-background">
{/* Header */}
<header className="flex items-center gap-3 border-b border-slate-200 dark:border-border bg-white dark:bg-card px-4 py-3">
<Button variant="ghost" size="sm" onClick={() => navigate(-1)} className="gap-1">
<ArrowLeft className="h-4 w-4" />
返回
</Button>
<div>
<h1 className="text-base font-semibold text-slate-800 dark:text-foreground">会商报错日志</h1>
<p className="text-xs text-slate-400 dark:text-muted-foreground">
多智能体会商全流程报错日志(席位失败 / 空交付 / 超时 / 模型容错 / 产物缺失 / 崩溃等;运行进度类 info 不再收集)
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => refetch()}
className="ml-auto gap-1"
disabled={isFetching}
>
<RefreshCw className={cn("h-4 w-4", isFetching && "animate-spin")} />
刷新
</Button>
</header>
{/* Filters */}
<div className="flex flex-wrap items-center gap-2 border-b border-slate-200 dark:border-border bg-white dark:bg-card px-4 py-2">
{/* 范围切换:后台挂起 / 前台调用 */}
<div className="inline-flex rounded-lg border border-slate-200 dark:border-border p-0.5">
{(["background", "frontend"] as ScopeCategory[]).map((c) => (
<button
key={c}
type="button"
onClick={() => switchScope(c)}
className={cn(
"rounded-md px-3 py-1 text-xs font-medium transition-colors",
scopeCategory === c
? "bg-slate-800 text-white dark:bg-primary dark:text-primary-foreground"
: "text-slate-500 hover:text-slate-700 dark:text-muted-foreground dark:hover:text-foreground",
)}
>
{c === "background" ? "后台挂起" : "前台调用"}
</button>
))}
</div>
<FilterSelect label="阶段" value={stage} onChange={(v) => resetPageAnd(() => setStage(v))}
options={STAGE_OPTIONS[scopeCategory]} labels={STAGE_LABELS} />
<FilterSelect label="级别" value={level} onChange={(v) => resetPageAnd(() => setLevel(v))}
options={facets?.level ?? []} />
<FilterSelect label="事件" value={event} onChange={(v) => resetPageAnd(() => setEvent(v))}
options={facets?.event ?? []} />
<div className="flex items-center gap-1">
<Input
value={qInput}
onChange={(e) => setQInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && applySearch()}
placeholder="搜索报错说明…"
className="h-8 w-48"
/>
<Button variant="secondary" size="sm" onClick={applySearch} className="gap-1">
<Search className="h-4 w-4" />
</Button>
</div>
<span className="ml-auto text-xs text-slate-400 dark:text-muted-foreground">共 {total} 条</span>
</div>
{/* List */}
<div className="flex-1 overflow-auto px-4 py-3">
{isLoading ? (
<p className="py-10 text-center text-sm text-slate-400">加载中…</p>
) : items.length === 0 ? (
<p className="py-10 text-center text-sm text-slate-400">暂无诊断记录</p>
) : (
<div className="flex flex-col gap-2">
{items.map((it) => (
<DiagnosticRow key={it.id} item={it} />
))}
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} className="pt-2" />
</div>
)}
</div>
</div>
);
}
function FilterSelect({
label,
value,
onChange,
options,
labels,
}: {
label: string;
value: string;
onChange: (v: string) => void;
options: string[];
labels?: Record<string, string>;
}) {
return (
<Select value={value} onValueChange={onChange}>
<SelectTrigger className="h-8 w-auto min-w-[120px] text-xs">
<SelectValue placeholder={label} />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>{label}:全部</SelectItem>
{options.map((o) => (
<SelectItem key={o} value={o}>
{labels?.[o] ?? o}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
+169 -40
View File
@@ -1,6 +1,6 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { type ChangeEvent, useEffect, useMemo, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import {
AlertCircle,
@@ -21,6 +21,7 @@ import {
RefreshCw,
TagsIcon,
Trash2,
Upload,
X,
} from "lucide-react";
import { useSearchParams } from "react-router-dom";
@@ -54,6 +55,7 @@ import {
type ScheduledTaskExecutionContext,
useHtmlPageFavoriteActions,
useHtmlPageFavorites,
useHtmlTemplates,
useScheduledTaskActions,
useScheduledTaskDeliveryProfile,
useScheduledTaskRuns,
@@ -107,6 +109,9 @@ function displayUsername(value?: string | null): string {
return at === -1 ? raw : raw.slice(0, at);
}
/** 内置「模板数据转换器」agent 的稳定 id(后端 seed)。选中它时表单露出 HTML 模板下拉。 */
const TEMPLATE_BUILDER_AGENT_ID = "template-json-builder";
const emptyForm = {
name: "",
description: "",
@@ -114,6 +119,8 @@ const emptyForm = {
timezone: "Asia/Shanghai",
prompt: "",
execution_agent_name: "",
// 模板填充模式:选中「模板数据转换器」后要把源 JSON 填进哪个 HTML 模板。
template_id: "",
// Two independent output switches (may both be on): require a Markdown file
// and/or render an HTML page. The form no longer splits into "普通任务 / HTML
// 页面" tabs.
@@ -172,6 +179,25 @@ export default function ScheduledTasksPage() {
const [editing, setEditing] = useState<ScheduledTask | null>(null);
const [creating, setCreating] = useState(false);
const [form, setForm] = useState(emptyForm);
// 模板填充模式的 .json 上传:读入文件文本填进 prompt 框(不改后端契约)。
const jsonUploadRef = useRef<HTMLInputElement | null>(null);
const handleJsonUpload = async (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
event.target.value = ""; // 允许重复上传同名文件
if (!file) return;
try {
const text = await file.text();
// 校验是 JSON,给即时反馈;非法也照样填入让用户修正。
try {
JSON.parse(text);
} catch {
toast.error("文件不是合法 JSON,已填入文本框请检查", darkToastOpts.error);
}
setForm((value) => ({ ...value, prompt: text }));
} catch {
toast.error("读取文件失败", darkToastOpts.error);
}
};
const dialogOpen = creating || !!editing;
const { data: htmlFavorites = [] } = useHtmlPageFavorites(dialogOpen);
const htmlFavoriteActions = useHtmlPageFavoriteActions();
@@ -285,6 +311,7 @@ export default function ScheduledTasksPage() {
// stored that under ``html_config.page_prompt``, so prefer it on edit.
prompt: html.page_prompt || task.prompt,
execution_agent_name: task.execution_agent_name ?? "",
template_id: task.execution_context?.template_config?.template_id ?? "",
require_markdown: !!task.execution_context?.require_markdown,
// Backward compatible: legacy HTML tasks only carry ``task_kind``.
require_html:
@@ -311,7 +338,15 @@ export default function ScheduledTasksPage() {
setScheduleConfig(DEFAULT_SCHEDULE_CONFIG);
};
const isHtmlTask = form.require_html;
// 模板填充模式:选中内置「模板数据转换器」agent。此时表单露出 HTML 模板下拉,
// 并隐藏「必须生成 HTML/Markdown」开关(本模式必产出 HTML)。
const isTemplateAgent = form.execution_agent_name === TEMPLATE_BUILDER_AGENT_ID;
const { data: htmlTemplates = [] } = useHtmlTemplates(isTemplateAgent);
const selectedTemplate = htmlTemplates.find((t) => t.id === form.template_id);
// 选中的模板是「只展示」型(convertible===false)时,不需要源 JSON,隐藏上传/输入。
const templateDisplayOnly =
isTemplateAgent && selectedTemplate?.convertible === false;
const isHtmlTask = !isTemplateAgent && form.require_html;
// The model actually shown/used: the user's choice, else the first configured
// model. Never a hardcoded GLM-5 — it follows config order and the selection.
const effectiveHtmlModel = form.html_model_name || availableModels[0]?.name || "";
@@ -322,8 +357,22 @@ export default function ScheduledTasksPage() {
// as the page requirement; ``task_kind`` is kept in sync only for backward
// compatibility with older readers.
const buildExecutionContext = (): ScheduledTaskExecutionContext => {
// 模板填充模式:只带 template_config,后端据此走「转换 JSON → 填充模板」分支。
if (isTemplateAgent && form.template_id) {
return {
template_config: { template_id: form.template_id },
require_html: false,
task_kind: "agent",
html_config: undefined,
};
}
if (!isHtmlTask) {
return { require_html: false, task_kind: "agent", html_config: undefined };
return {
require_html: false,
task_kind: "agent",
html_config: undefined,
template_config: undefined,
};
}
return {
require_html: true,
@@ -1110,46 +1159,126 @@ export default function ScheduledTasksPage() {
))}
</SelectContent>
</Select>
<Textarea
className="min-h-40"
value={form.prompt}
onChange={(event) =>
setForm((value) => ({ ...value, prompt: event.target.value }))
}
placeholder={
isHtmlTask
? "任务 / 页面生成要求,例如:检索新能源车最新舆情,生成适合领导快速浏览的态势页"
: "任务 Prompt"
}
/>
<div className="flex items-center justify-between rounded-md border p-3">
<div className="min-w-0 pr-3">
<p className="text-sm font-medium">必须生成 Markdown 文件</p>
<p className="text-muted-foreground text-xs">
开启后会提示大模型生成 Markdown(.md) 文件;系统会校验本次是否生成了 .md 文件且文件正文超过 100 字,未达到则记为失败。
</p>
{isTemplateAgent && (
<div className="flex flex-col gap-2 rounded-md border border-primary/30 bg-primary/5 p-3">
<div className="flex flex-col gap-1">
<p className="text-sm font-medium">HTML 模板</p>
<p className="text-muted-foreground text-xs">
{templateDisplayOnly ? (
<>选择要展示的 HTML 模板。该模板暂为「直接展示已有数据」,执行时将原样输出其现有页面。</>
) : (
<>
选择要把源数据填充进去的 HTML 模板。执行时智能体会把下方源 JSON 转换成该模板所需的结构,校验后填充生成可预览的页面。
<span className="text-foreground/70">未提供源 JSON 时,将直接展示该模板的默认数据。</span>
</>
)}
</p>
</div>
<Select
value={form.template_id || undefined}
onValueChange={(v) =>
setForm((value) => ({ ...value, template_id: v }))
}
>
<SelectTrigger className="w-full min-w-0 max-w-full overflow-hidden [&>span]:min-w-0 [&>span]:flex-1 [&>span]:truncate">
<SelectValue placeholder="选择 HTML 模板" />
</SelectTrigger>
<SelectContent
position="popper"
className="max-h-[40vh] w-[max(var(--radix-select-trigger-width),28rem)] max-w-[min(90vw,40rem)]"
>
{htmlTemplates.map((tpl) => (
<SelectItem key={tpl.id} value={tpl.id}>
<span className="block whitespace-normal break-words">
{tpl.name}
{tpl.description ? ` — ${tpl.description}` : ""}
</span>
</SelectItem>
))}
{htmlTemplates.length === 0 && (
<div className="text-muted-foreground px-2 py-1.5 text-xs">
暂无可用模板
</div>
)}
</SelectContent>
</Select>
{templateDisplayOnly ? (
<p className="text-muted-foreground text-xs">
该模板暂为「直接展示已有数据」,无需填写源 JSON;执行时将原样输出模板的现有页面。
</p>
) : (
<div className="flex items-center gap-2">
<input
ref={jsonUploadRef}
type="file"
accept=".json,application/json"
className="hidden"
onChange={handleJsonUpload}
/>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => jsonUploadRef.current?.click()}
>
<Upload className="mr-1 size-4" />
上传 .json 文件
</Button>
<span className="text-muted-foreground text-xs">
也可直接在下方粘贴源 JSON(上传会填入下方文本框)
</span>
</div>
)}
</div>
<Switch
checked={form.require_markdown}
onCheckedChange={(v) =>
setForm((value) => ({ ...value, require_markdown: v }))
)}
{!templateDisplayOnly && (
<Textarea
className="min-h-40"
value={form.prompt}
onChange={(event) =>
setForm((value) => ({ ...value, prompt: event.target.value }))
}
placeholder={
isTemplateAgent
? "源 JSON 数据(粘贴或上传 .json),将被智能体转换并填充进所选 HTML 模板;留空则展示模板默认数据"
: isHtmlTask
? "任务 / 页面生成要求,例如:检索新能源车最新舆情,生成适合领导快速浏览的态势页"
: "任务 Prompt"
}
/>
</div>
<div className="flex items-center justify-between rounded-md border p-3">
<div className="min-w-0 pr-3">
<p className="text-sm font-medium">必须生成 HTML 页面</p>
<p className="text-muted-foreground text-xs">
开启后会先用智能体检索整理真实数据,再渲染为完整 HTML 页面(可在执行记录中预览)。可与“必须生成 Markdown”同时开启。
</p>
</div>
<Switch
checked={form.require_html}
onCheckedChange={(v) =>
setForm((value) => ({ ...value, require_html: v }))
}
/>
</div>
)}
{!isTemplateAgent && (
<>
<div className="flex items-center justify-between rounded-md border p-3">
<div className="min-w-0 pr-3">
<p className="text-sm font-medium">必须生成 Markdown 文件</p>
<p className="text-muted-foreground text-xs">
开启后会提示大模型生成 Markdown(.md) 文件;系统会校验本次是否生成了 .md 文件且文件正文超过 100 字,未达到则记为失败。
</p>
</div>
<Switch
checked={form.require_markdown}
onCheckedChange={(v) =>
setForm((value) => ({ ...value, require_markdown: v }))
}
/>
</div>
<div className="flex items-center justify-between rounded-md border p-3">
<div className="min-w-0 pr-3">
<p className="text-sm font-medium">必须生成 HTML 页面</p>
<p className="text-muted-foreground text-xs">
开启后会先用智能体检索整理真实数据,再渲染为完整 HTML 页面(可在执行记录中预览)。可与“必须生成 Markdown”同时开启。
</p>
</div>
<Switch
checked={form.require_html}
onCheckedChange={(v) =>
setForm((value) => ({ ...value, require_html: v }))
}
/>
</div>
</>
)}
{isHtmlTask && (
<>
+11
View File
@@ -42,6 +42,7 @@ import MenuManagementPage from "./MenuManagementPage";
import SensitiveWordsPage from "./SensitiveWordsPage";
import SkillAddressesPage from "./SkillAddressesPage";
import TaskButtonsPage from "./TaskButtonsPage";
import RoundtableDiagnosticsPage from "./RoundtableDiagnosticsPage";
import LightAppNewNotePage from "./LightAppNewNotePage";
import LightAppNoteListPage from "./LightAppNoteListPage";
import LightAppNoteQAPage from "./LightAppNoteQAPage";
@@ -394,6 +395,16 @@ export default function StrategyRoutes() {
)
}
/>
<Route
path="admin/roundtable-diagnostics"
element={
getStoredAuth()?.system_role === "admin" ? (
<RoundtableDiagnosticsPage />
) : (
<Navigate to="/page/workspace/chats/new" replace />
)
}
/>
<Route
path="admin/skill-addresses"
element={
@@ -6,11 +6,13 @@ import {
AlertCircle,
AlignLeft,
ArrowLeft,
ArrowUp,
BookOpen,
Files,
Globe,
Loader2,
Plus,
Square,
X,
} from "lucide-react";
@@ -27,6 +29,7 @@ import { fetchDocumentByChunk } from "@/core/studio/api";
import type { DocumentWithChunks } from "@/core/studio/api";
import type { SourceItem } from "@/core/studio/types";
import { getStoredAuth } from "@/core/auth";
import { useTheme } from "@/contexts/ThemeContext";
import { useModels } from "@/core/models/hooks";
import {
Select,
@@ -118,6 +121,20 @@ function SourceCard({
);
}
// ── 上传中占位卡片 ──────────────────────────────────────
function PendingSourceCard({ title }: { title: string }) {
return (
<div className="group relative flex h-32 w-full flex-col justify-between rounded-2xl p-4 ring-1 ring-border/50 bg-muted/40 cursor-default">
<div className="flex size-10 items-center justify-center rounded-xl bg-background">
<Loader2 className="size-5 animate-spin text-muted-foreground" />
</div>
<div className="min-w-0">
<p className="truncate text-xs font-medium text-foreground">{title}</p>
</div>
</div>
);
}
// ── 来源骨架屏 ──────────────────────────────────────────
function SourceCardSkeleton() {
return (
@@ -136,6 +153,7 @@ function SourcesDialog({
sources,
isLoadingSources,
selectedSourceIds,
pendingSources,
onToggle,
onDelete,
}: {
@@ -145,6 +163,7 @@ function SourcesDialog({
sources: SourceItem[];
isLoadingSources: boolean;
selectedSourceIds: number[];
pendingSources: Map<string, { id?: number; title: string }>;
onToggle: (id: number) => void;
onDelete: (id: number) => void;
}) {
@@ -188,15 +207,26 @@ function SourcesDialog({
<div className="grid grid-cols-4 gap-3">
{isLoadingSources
? Array.from({ length: 8 }).map((_, i) => <SourceCardSkeleton key={i} />)
: sources.map((src) => (
<SourceCard
key={src.id}
item={src}
selected={selectedSourceIds.includes(src.id)}
onToggle={onToggle}
onDelete={onDelete}
/>
))}
: <>
{Array.from(pendingSources.entries())
.filter(([, s]) => !sources.some((src) => {
const srcTitle = src.title ?? (src.document as { title?: string } | undefined)?.title ?? "";
return srcTitle === s.title;
}))
.map(([taskId, s]) => (
<PendingSourceCard key={taskId} title={s.title} />
))}
{sources.map((src) => (
<SourceCard
key={src.id}
item={src}
selected={selectedSourceIds.includes(src.id)}
onToggle={onToggle}
onDelete={onDelete}
/>
))}
</>
}
</div>
{!isLoadingSources && sources.length === 0 && (
<p className="text-sm text-muted-foreground">暂无来源,请添加文件。</p>
@@ -218,6 +248,7 @@ export default function StudioNotebookDetailPage({
const params = useParams<{ notebookId: string }>();
const notebookId =
notebookIdProp != null ? String(notebookIdProp) : params.notebookId;
const { theme } = useTheme(); // 跳转「我的空间」时带上当前主题 key
const { notebooks, isLoading, token: studioToken } = useStudioNotebooks(); // token 用于跳转 callback
const { models } = useModels();
const queryClient = useQueryClient();
@@ -229,6 +260,8 @@ export default function StudioNotebookDetailPage({
// null = 显示历史线程列表;string = 显示该线程的聊天
const [activeThreadId, setActiveThreadId] = useState<string | null>(null);
const [citationChunkId, setCitationChunkId] = useState<number | null>(null);
// 轮询成功后待选中的来源标题集合(后端上传时不返回 id,等 sources 刷新后按标题匹配)
const pendingSelectTitlesRef = useRef<Set<string>>(new Set());
const [threadsExpanded, setThreadsExpanded] = useState(false);
const THREADS_LIMIT = 5;
const [citationDoc, setCitationDoc] = useState<DocumentWithChunks | null>(null);
@@ -253,6 +286,22 @@ export default function StudioNotebookDetailPage({
setSelectedSourceIds(sources.map((s) => s.id));
}
}, [sources, notebook?.id, initializedForNotebook]);
// sources 刷新后,将轮询成功的来源(按标题匹配)自动选中
useEffect(() => {
if (pendingSelectTitlesRef.current.size === 0) return;
const matched = sources.filter((s) => {
const title = s.title ?? (s.document as { title?: string } | undefined)?.title ?? "";
return pendingSelectTitlesRef.current.has(title);
});
if (matched.length > 0) {
setSelectedSourceIds((prev) => [...new Set([...prev, ...matched.map((s) => s.id)])]);
matched.forEach((s) => {
const title = s.title ?? (s.document as { title?: string } | undefined)?.title ?? "";
pendingSelectTitlesRef.current.delete(title);
});
}
}, [sources]);
const citationRehypePlugins = useMemo(() => {
const mapped = sources.map((s) => ({
id: s.id,
@@ -297,6 +346,10 @@ export default function StudioNotebookDetailPage({
}
};
const handleStop = useCallback(() => {
void thread.stop();
}, [thread]);
const handleSend = async (e: React.SyntheticEvent) => {
e.preventDefault();
const text = input.trim();
@@ -358,20 +411,17 @@ export default function StudioNotebookDetailPage({
const data = await response.json() as { status: 'processing' | 'success' | 'failed' | 'error' };
const taskStatus = data.status === 'failed' ? 'error' : data.status;
if (taskStatus !== 'processing') {
// 任务完成,从轮询队列移除并刷新来源列表
// 先取出 source 信息,再从轮询队列移除
const source = pendingSources.get(taskId);
setPendingSources((prev) => {
const newMap = new Map(prev);
const source = newMap.get(taskId);
newMap.delete(taskId);
if (source) {
if (taskStatus === 'success') {
// toast.success(`来源 "${source.title}" 处理完成`);
} else {
// toast.error(`来源 "${source.title}" 处理失败`);
}
}
return newMap;
});
// 仅成功时记录标题,等 sources 刷新后按标题匹配 id 并选中
if (taskStatus === 'success' && source?.title) {
pendingSelectTitlesRef.current.add(source.title);
}
// 刷新来源列表
void queryClient.invalidateQueries({ queryKey: ["studio", "sources"] });
// 刷新 notebooks 数据以更新 source_count
@@ -381,7 +431,7 @@ export default function StudioNotebookDetailPage({
} catch (error) {
console.error(`轮询任务 ${taskId} 状态失败:`, error);
}
}, [notebook?.id, queryClient]);
}, [notebook?.id, pendingSources, queryClient]);
// 控制轮询 - 只在对话框打开时轮询
useEffect(() => {
@@ -508,7 +558,7 @@ export default function StudioNotebookDetailPage({
</div>
<div className="flex items-center gap-2">
<a
href={`${import.meta.env.VITE_AIPI_FRONTEND_URL}/auth/callback?token=${studioToken ?? ""}&redirect=/dashboard/${notebookId}/new-chat`}
href={`${import.meta.env.VITE_AIPI_FRONTEND_URL}/auth/callback?token=${studioToken ?? ""}&redirect=/dashboard/${notebookId}/new-chat&themekey=${theme}`}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1.5 rounded-full bg-muted px-3 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/70"
@@ -532,7 +582,7 @@ export default function StudioNotebookDetailPage({
<div className="relative z-10 flex flex-1 flex-col overflow-hidden">
{/* 右上角跳转按钮 */}
<a
href={`${import.meta.env.VITE_AIPI_FRONTEND_URL}/auth/callback?token=${studioToken ?? ""}&redirect=/dashboard/${notebookId}/new-chat`}
href={`${import.meta.env.VITE_AIPI_FRONTEND_URL}/auth/callback?token=${studioToken ?? ""}&redirect=/dashboard/${notebookId}/new-chat&themekey=${theme}`}
target="_blank"
rel="noreferrer"
className="absolute right-6 top-4 z-10 flex items-center gap-1.5 rounded-full bg-muted/70 px-3 py-1.5 text-xs text-muted-foreground backdrop-blur transition-colors hover:bg-muted"
@@ -583,7 +633,6 @@ export default function StudioNotebookDetailPage({
disabled={isStreaming}
className="flex-1 bg-transparent text-[15px] text-foreground placeholder:text-muted-foreground outline-none disabled:opacity-50"
/>
{isStreaming && <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" />}
{models.length > 0 && (
<Select value={selectedModel} onValueChange={setSelectedModel}>
<SelectTrigger className="h-7 w-auto shrink-0 gap-1 rounded-full border-0 bg-transparent px-2 text-sm text-muted-foreground shadow-none focus:ring-0 hover:bg-muted/60">
@@ -598,6 +647,24 @@ export default function StudioNotebookDetailPage({
</SelectContent>
</Select>
)}
{isStreaming ? (
<button
type="button"
onClick={handleStop}
className="shrink-0 rounded-full bg-muted p-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"
title="停止回答"
>
<Square className="size-3.5 fill-current" />
</button>
) : input.trim() ? (
<button
type="submit"
className="shrink-0 rounded-full bg-primary p-1.5 text-primary-foreground hover:bg-primary/90 transition-colors"
title="发送"
>
<ArrowUp className="size-3.5" />
</button>
) : null}
</form>
{/* 空状态提示 */}
@@ -711,7 +778,6 @@ export default function StudioNotebookDetailPage({
disabled={isStreaming}
className="flex-1 bg-transparent text-[15px] text-foreground placeholder:text-muted-foreground outline-none disabled:opacity-50"
/>
{isStreaming && <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" />}
{models.length > 0 && (
<Select value={selectedModel} onValueChange={setSelectedModel}>
<SelectTrigger className="h-7 w-auto shrink-0 gap-1 rounded-full border-0 bg-transparent px-2 text-sm text-muted-foreground shadow-none focus:ring-0 hover:bg-muted/60">
@@ -726,6 +792,24 @@ export default function StudioNotebookDetailPage({
</SelectContent>
</Select>
)}
{isStreaming ? (
<button
type="button"
onClick={handleStop}
className="shrink-0 rounded-full bg-muted p-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"
title="停止回答"
>
<Square className="size-3.5 fill-current" />
</button>
) : input.trim() ? (
<button
type="submit"
className="shrink-0 rounded-full bg-primary p-1.5 text-primary-foreground hover:bg-primary/90 transition-colors"
title="发送"
>
<ArrowUp className="size-3.5" />
</button>
) : null}
</form>
</div>
@@ -769,6 +853,7 @@ export default function StudioNotebookDetailPage({
sources={sources}
isLoadingSources={isLoadingSources}
selectedSourceIds={selectedSourceIds}
pendingSources={pendingSources}
onToggle={handleToggleSource}
onDelete={handleDeleteSource}
/>
+18 -9
View File
@@ -8,6 +8,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { useStudioNotebooks } from "@/core/studio/hooks";
import { createSearchSpace, deleteSearchSpace, renameSearchSpace } from "@/core/studio/api";
import { getStoredAuth } from "@/core/auth";
import { useTheme } from "@/contexts/ThemeContext";
import type { StudioNotebook } from "@/core/studio/types";
import {
Dialog,
@@ -23,13 +24,16 @@ import {
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
function NotebookCardSkeleton() {
function NotebookCardSkeleton({ isDark }: { isDark: boolean }) {
return (
<div className="flex flex-col rounded-[20px] bg-[#f2f2f2] p-5" style={{ minHeight: 180 }}>
<div className="size-10 animate-pulse rounded-xl bg-[#e0e0e0]" />
<div
className={`flex flex-col rounded-[20px] p-5 ${isDark ? "bg-[#1e2330]" : "bg-[#f2f2f2]"}`}
style={{ minHeight: 180 }}
>
<div className={`size-10 animate-pulse rounded-xl ${isDark ? "bg-[#2c3346]" : "bg-[#e0e0e0]"}`} />
<div className="mt-auto flex flex-col gap-1.5 pt-8">
<div className="h-4 w-3/4 animate-pulse rounded bg-[#e0e0e0]" />
<div className="h-3 w-1/3 animate-pulse rounded bg-[#e0e0e0]" />
<div className={`h-4 w-3/4 animate-pulse rounded ${isDark ? "bg-[#2c3346]" : "bg-[#e0e0e0]"}`} />
<div className={`h-3 w-1/3 animate-pulse rounded ${isDark ? "bg-[#2c3346]" : "bg-[#e0e0e0]"}`} />
</div>
</div>
);
@@ -37,11 +41,13 @@ function NotebookCardSkeleton() {
function NotebookCard({
nb,
isDark,
onRename,
onDelete,
onOpen,
}: {
nb: StudioNotebook;
isDark: boolean;
onRename: (nb: StudioNotebook) => void;
onDelete: (nb: StudioNotebook) => void;
/** 传入则点击卡片回调(内嵌打开),不再路由跳转。 */
@@ -61,16 +67,16 @@ function NotebookCard({
<div className="size-7" />
</div>
<div className="mt-auto flex flex-col gap-1 pt-8">
<span className="line-clamp-2 text-[15px] font-medium leading-snug text-[#1f1f1f]">
<span className={`line-clamp-2 text-[15px] font-medium leading-snug ${isDark ? "text-[#e8eaf0]" : "text-[#1f1f1f]"}`}>
{nb.name}
</span>
<span className="text-[13px] text-[#666]">{nb.source_count} 个来源</span>
<span className={`text-[13px] ${isDark ? "text-[#8b93a7]" : "text-[#666]"}`}>{nb.source_count} 个来源</span>
</div>
</>
);
return (
<div className="group relative flex flex-col rounded-[20px] bg-[#f2f2f2] transition-colors hover:bg-[#e8e8e8]" style={{ minHeight: 180 }}>
<div className={`group relative flex flex-col rounded-[20px] transition-colors ${isDark ? "bg-[#1e2330] hover:bg-[#262c3b]" : "bg-[#f2f2f2] hover:bg-[#e8e8e8]"}`} style={{ minHeight: 180 }}>
{onOpen ? (
<button
type="button"
@@ -125,6 +131,8 @@ export default function StudioNotebooksPage({
onOpenNotebook?: (id: number) => void;
} = {}) {
const { notebooks, isLoading, isError } = useStudioNotebooks();
const { theme } = useTheme();
const isDark = theme === "dark";
const queryClient = useQueryClient();
// ── 新建 ──
@@ -221,11 +229,12 @@ export default function StudioNotebooksPage({
{/* Grid */}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
{isLoading
? Array.from({ length: 8 }).map((_, i) => <NotebookCardSkeleton key={i} />)
? Array.from({ length: 8 }).map((_, i) => <NotebookCardSkeleton key={i} isDark={isDark} />)
: notebooks.map((nb) => (
<NotebookCard
key={nb.id}
nb={nb}
isDark={isDark}
onRename={(nb) => { setRenameTarget(nb); setRenameName(nb.name); setRenameError(""); }}
onDelete={(nb) => { setDeleteTarget(nb); setDeleteError(""); }}
onOpen={onOpenNotebook}
@@ -104,6 +104,7 @@ export default function TaskButtonsPage() {
appendTaskId: true,
idParam: "id",
idKind: "task",
openMode: "blank",
enabled: true,
sortOrder: maxSort + 1,
},
@@ -305,6 +306,19 @@ export default function TaskButtonsPage() {
)}
</div>
)}
<label className="text-muted-foreground ml-2 shrink-0 text-xs">打开方式</label>
<Select
value={r.openMode}
onValueChange={(v) => update(r.id, { openMode: v as TaskButton["openMode"] })}
>
<SelectTrigger className="h-8 w-32" title="外链打开方式">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="blank">新窗口</SelectItem>
<SelectItem value="self">当前窗口</SelectItem>
</SelectContent>
</Select>
</>
) : (
<Select value={r.target} onValueChange={(v) => update(r.id, { target: v })}>
@@ -0,0 +1,35 @@
import assert from "node:assert/strict";
import test from "node:test";
// @ts-ignore Node's test runner resolves the local .ts module directly.
import { resolveIframeAssistantId } from "./iframe-chat-agent.ts";
test("prefers the currently selected iframe agent", () => {
assert.equal(
resolveIframeAssistantId({
selectedAgentId: "roundtable-structure",
threadMetadataAgentId: "lead_agent",
}),
"roundtable-structure",
);
});
test("reuses the thread-bound agent when reopening an iframe thread", () => {
assert.equal(
resolveIframeAssistantId({
selectedAgentId: null,
threadMetadataAgentId: "roundtable-structure",
}),
"roundtable-structure",
);
});
test("falls back to lead-agent mode when no agent is selected or bound", () => {
assert.equal(
resolveIframeAssistantId({
selectedAgentId: null,
threadMetadataAgentId: null,
}),
undefined,
);
});
@@ -0,0 +1,19 @@
type ResolveIframeAssistantIdInput = {
selectedAgentId: string | null;
threadMetadataAgentId: string | null;
};
function normalizeAgentId(agentId: string | null | undefined): string | undefined {
const trimmed = agentId?.trim();
return trimmed ? trimmed : undefined;
}
export function resolveIframeAssistantId({
selectedAgentId,
threadMetadataAgentId,
}: ResolveIframeAssistantIdInput): string | undefined {
return (
normalizeAgentId(selectedAgentId) ??
normalizeAgentId(threadMetadataAgentId)
);
}
@@ -0,0 +1,43 @@
import assert from "node:assert/strict";
import test from "node:test";
// @ts-ignore Node's test runner resolves the local .ts module directly.
import { buildIframeModeButtons } from "./iframe-chat-mode-buttons.ts";
test("includes the context compression toggle in the iframe chat toolbar", () => {
const buttons = buildIframeModeButtons({
agentSelected: false,
writingModeEnabled: false,
memoryInjectionEnabled: true,
ragModeEnabled: false,
ragModeLocked: false,
contextCompressionEnabled: false,
proModeEnabled: false,
});
assert.deepEqual(
buttons.map((button) => button.key),
[
"writing",
"memory",
"references",
"contextCompression",
"pro",
"agent",
],
);
});
test("returns only concrete toolbar button configs", () => {
const buttons = buildIframeModeButtons({
agentSelected: true,
writingModeEnabled: false,
memoryInjectionEnabled: true,
ragModeEnabled: false,
ragModeLocked: false,
contextCompressionEnabled: false,
proModeEnabled: false,
});
assert.equal(buttons.every((button) => typeof button.key === "string"), true);
});
@@ -0,0 +1,66 @@
export type IframeModeButtonState = {
key:
| "agent"
| "writing"
| "memory"
| "references"
| "contextCompression"
| "pro";
label: string;
active: boolean;
disabled?: boolean;
};
type BuildIframeModeButtonsInput = {
agentSelected: boolean;
writingModeEnabled: boolean;
memoryInjectionEnabled: boolean;
ragModeEnabled: boolean;
ragModeLocked: boolean;
contextCompressionEnabled: boolean;
proModeEnabled: boolean;
};
export function buildIframeModeButtons({
agentSelected,
writingModeEnabled,
memoryInjectionEnabled,
ragModeEnabled,
ragModeLocked,
contextCompressionEnabled,
proModeEnabled,
}: BuildIframeModeButtonsInput): IframeModeButtonState[] {
return [
{
key: "writing",
label: "写作",
active: writingModeEnabled,
},
{
key: "memory",
label: "记忆",
active: memoryInjectionEnabled,
},
{
key: "references",
label: "参考文献",
active: ragModeEnabled,
disabled: ragModeLocked,
},
{
key: "contextCompression",
label: "上下文压缩",
active: contextCompressionEnabled,
},
{
key: "pro",
label: "专业问答",
active: proModeEnabled,
},
{
key: "agent",
label: "智能体",
active: agentSelected,
},
];
}
@@ -32,6 +32,8 @@ export interface ChainCreatePayload {
coordinatorPrompt?: string | null;
/** 默认席位执行模式(flash/thinking/pro/ultra);null = 未设。 */
seatMode?: SeatMode | null;
/** 研讨前并行取数开关(逐条 opt-in);缺省 false。 */
gatherFirst?: boolean;
}
/** Partial update — send only what changed. */
@@ -47,12 +49,19 @@ export interface ChainUpdatePayload {
coordinatorPrompt?: string | null;
/** 默认席位执行模式;send `null` to clear, omit to leave. */
seatMode?: SeatMode | null;
/** 研讨前并行取数开关;send true/false 改,omit 不改。 */
gatherFirst?: boolean;
/** 发布开关:true 发布为公共 / false 取消发布;omit 不改。仅 owner 生效。 */
isPublic?: boolean;
}
/** 列表筛选范围:`mine` = 我的;`public` = 所有已发布的公共链条。 */
export type ChainScope = "mine" | "public";
/**
* 列表筛选范围:
* - `mine` = 我的;
* - `public` = 所有已发布的公共链条;
* - `all` = 所有账号的全部链条(**仅管理员**;后端对非管理员请求 `all` 退化为 `mine`)。
*/
export type ChainScope = "mine" | "public" | "all";
const BASE = () => `${getBackendBaseURL()}/api/roundtable-chains`;
@@ -77,6 +86,7 @@ interface ServerChain {
stage_goals?: (string | null)[] | null;
coordinator_prompt?: string | null;
seat_mode?: string | null;
gather_first?: boolean;
is_public?: boolean;
is_mine?: boolean;
owner_name?: string | null;
@@ -94,6 +104,7 @@ function toChain(s: ServerChain): BusinessChain {
stageGoals: Array.isArray(s.stage_goals) ? s.stage_goals : null,
coordinatorPrompt: s.coordinator_prompt ?? null,
seatMode: (s.seat_mode as SeatMode | null) ?? undefined,
gatherFirst: s.gather_first ?? false,
isPublic: s.is_public ?? false,
// 后端缺省时按「我的」处理(向后兼容旧响应)。
isMine: s.is_mine ?? true,
@@ -113,6 +124,7 @@ function fromCreate(p: ChainCreatePayload) {
...(p.stageGoals !== undefined ? { stage_goals: p.stageGoals } : {}),
...(p.coordinatorPrompt !== undefined ? { coordinator_prompt: p.coordinatorPrompt } : {}),
...(p.seatMode !== undefined ? { seat_mode: p.seatMode } : {}),
...(p.gatherFirst !== undefined ? { gather_first: p.gatherFirst } : {}),
};
}
@@ -127,6 +139,7 @@ function fromUpdate(p: ChainUpdatePayload) {
if (p.stageGoals !== undefined) out.stage_goals = p.stageGoals;
if (p.coordinatorPrompt !== undefined) out.coordinator_prompt = p.coordinatorPrompt;
if (p.seatMode !== undefined) out.seat_mode = p.seatMode;
if (p.gatherFirst !== undefined) out.gather_first = p.gatherFirst;
if (p.isPublic !== undefined) out.is_public = p.isPublic;
return out;
}
@@ -139,7 +152,7 @@ function fromUpdate(p: ChainUpdatePayload) {
* - `"public"`:所有已发布的公共链条(任何账号可见 / 可选入研讨)。
*/
export async function listChains(scope: ChainScope = "mine"): Promise<BusinessChain[]> {
const url = scope === "public" ? `${BASE()}?scope=public` : BASE();
const url = scope === "mine" ? BASE() : `${BASE()}?scope=${scope}`;
const res = await apiFetch(url, { method: "GET" });
const data = await readJson<{ chains: ServerChain[] }>(res, "list chains");
const chains = (data.chains ?? []).map(toChain);
@@ -0,0 +1,90 @@
/**
* 会商「前端调用报错」上报器。
*
* 服务端诊断只能记到「处理函数跑起来后抛的错」;而用户实际遇到的很多报错(nginx/网关
* 返回 502、网络中断、fetch 直接失败、SSE 里收到的 error 帧)发生在**客户端**侧。这里把
* 这些前端可观测到的报错 best-effort 上报到 `POST /api/roundtable-diagnostics/report`
* (scope="client",非 admin 接口),便于管理员在诊断页统一筛选用户使用时的报错。
*
* 设计:fire-and-forget + `keepalive`(页面跳转也能发出去)+ 绝不抛错(上报失败就算了,
* 不能让「报错上报」本身再影响会商流程)。
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
export interface RoundtableErrorReport {
stage: string;
event: string;
message: string;
level?: "error" | "warning" | "info";
detail?: unknown;
agentId?: string;
agentName?: string;
cycle?: number;
draftId?: string;
taskId?: string;
jobId?: string;
httpStatus?: number;
}
// 页面级上下文(draftId / taskId),由会商页设置,使每条上报都能归属到草稿/任务,
// 而无需把它们穿进每个底层 api 调用。
let _ctx: { draftId?: string; taskId?: string } = {};
export function setRoundtableErrorContext(ctx: { draftId?: string; taskId?: string }): void {
_ctx = { ..._ctx, ...ctx };
}
/** 据 agentType + agentName 推断诊断 stage(与后端 `_stage_for_agent` 对齐)。 */
export function stageForRoundtableAgent(
agentType: string | undefined,
agentName: string | null | undefined,
): string {
switch (agentName) {
case "roundtable-report":
return "step3_report";
case "roundtable-summary":
return "step3_summary";
case "roundtable-dashboard":
return "step3_dashboard";
case "roundtable-structure":
return "step3_structure";
default:
return agentType === "leader" ? "step2_leader" : "step2_seat";
}
}
export function reportRoundtableError(input: RoundtableErrorReport): void {
try {
const detail =
input.httpStatus != null && typeof input.detail !== "object"
? { httpStatus: input.httpStatus, raw: input.detail }
: input.httpStatus != null
? { httpStatus: input.httpStatus, ...(input.detail as Record<string, unknown>) }
: input.detail;
const body = JSON.stringify({
stage: input.stage,
event: input.event,
level: input.level ?? "error",
message: (input.message ?? "").slice(0, 2000),
detail,
jobId: input.jobId,
draftId: input.draftId ?? _ctx.draftId,
taskId: input.taskId ?? _ctx.taskId,
agentId: input.agentId,
agentName: input.agentName,
cycle: input.cycle,
});
void apiFetch(`${getBackendBaseURL()}/api/roundtable-diagnostics/report`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
keepalive: true,
}).catch(() => {
/* 上报失败静默 */
});
} catch {
/* 绝不抛错 */
}
}
@@ -189,6 +189,11 @@ export interface DraftMeta {
/** Auto-derived task summary (objective → first user message → timestamp). */
title: string;
furthestStep: 1 | 2 | 3;
/**
* 本次会商所用业务链名(历史卡片展示)。无业务链(自由/recommend 模式)→ null/undefined,
* 由前端展示为「自由模式」。后端从 step2 快照里抽取(见 roundtable_drafts/sql.py)。
*/
chainTitle?: string | null;
createdAt: string;
updatedAt: string;
/**
@@ -251,6 +256,7 @@ export interface ServerDraftMeta {
task_id?: string | null;
title: string;
furthest_step: number;
chain_title?: string | null;
created_at: string | null;
updated_at: string | null;
status?: string | null;
@@ -270,6 +276,7 @@ export function toMeta(s: ServerDraftMeta): DraftMeta {
taskId: s.task_id ?? null,
title: s.title ?? "",
furthestStep: step,
chainTitle: s.chain_title ?? null,
createdAt: s.created_at ?? "",
updatedAt: s.updated_at ?? "",
status: (s.status as JobStatus | null | undefined) ?? null,
@@ -12,7 +12,7 @@ import { getBackendBaseURL } from "@/core/config";
import type { FlowGraphData } from "@/roundtable-planning/lib/flow-graph";
/** 第三步输入框意图分类结果(与后端 /intent 对应)。 */
export type FlowIntent = "regenerate_report" | "modify_flow" | "regenerate_flow" | "qa" | "unclear";
export type FlowIntent = "regenerate_report" | "modify_flow" | "regenerate_flow" | "ingest" | "qa" | "unclear";
/**
* 识别第三步输入框消息的意图(一次模型调用)。失败回退 "unclear"(前端发起澄清)。
@@ -22,6 +22,8 @@ export async function classifyFlowIntent(req: {
message: string;
hasReport: boolean;
hasFlow: boolean;
/** 当前是否可入库(入库按钮已出现、未入库);为真才允许识别出 ingest 意图。 */
canIngest?: boolean;
model?: string;
signal?: AbortSignal;
}): Promise<{ intent: FlowIntent; reason: string }> {
@@ -33,6 +35,7 @@ export async function classifyFlowIntent(req: {
message: req.message,
has_report: req.hasReport,
has_flow: req.hasFlow,
can_ingest: req.canIngest ?? false,
model: req.model,
}),
signal: req.signal,
@@ -82,6 +85,10 @@ export interface FlowExtractRequest {
chainLevels?: string[];
/** 业务链总控编排提示(写明层级时优先用它)。 */
coordinatorPrompt?: string | null;
/** 深链接业务码(rwfx→6BF 等)。非空 → 后端按业务链抽取规范强制注入完整层级。 */
businessCode?: string | null;
/** 根节点 label 强制值(xdfx:本次行动名称)。非空 → 根节点 n1 用它,不用任务名当根。 */
rootLabel?: string | null;
/** 推理模型名(沿用第三步所选)。 */
model?: string;
/** Phase 2 问答修改:当前流程图 + 指令 → 按指令改图(其余不变)。 */
@@ -94,6 +101,11 @@ export interface FlowExtractRequest {
onValidating?: () => void;
/** 校验/修复流式增量(同样含思考 + 正文,前端实时显示校验过程)。 */
onValidateDelta?: (text: string) => void;
/**
* 模型自动容错:后端某模型抽取失败,已切到下一个模型重抽。上层据此**清空已累计的抽取增量**
* (`onExtractDelta` 之前吐出的半截内容)并提示用户。`failedModel`/`nextModel`/`reason` 描述切换。
*/
onModelSwitch?: (info: { failedModel: string; nextModel: string; reason: string }) => void;
}
/**
@@ -109,6 +121,8 @@ export async function streamFlowExtract(req: FlowExtractRequest): Promise<FlowGr
seat_deliveries: (req.seatDeliveries ?? []).map((s) => ({ sender: s.sender, content: s.content })),
chain_levels: req.chainLevels ?? [],
coordinator_prompt: req.coordinatorPrompt ?? null,
business_code: req.businessCode ?? null,
root_label: req.rootLabel ?? null,
model: req.model,
current_graph: req.currentGraph ?? null,
instruction: req.instruction ?? null,
@@ -152,6 +166,12 @@ export async function streamFlowExtract(req: FlowExtractRequest): Promise<FlowGr
} else if (event === "validate_delta") {
const c = typeof frame.content === "string" ? frame.content : "";
if (c) req.onValidateDelta?.(c);
} else if (event === "model_switch") {
req.onModelSwitch?.({
failedModel: typeof frame.failed_model === "string" ? frame.failed_model : "",
nextModel: typeof frame.next_model === "string" ? frame.next_model : "",
reason: typeof frame.reason === "string" ? frame.reason : "",
});
} else if (event === "final") {
graph = (frame.graph as FlowGraphData) ?? null;
} else if (event === "error") {
@@ -1,38 +1,58 @@
/**
* 第三步「入库」功能门控。
* 第三步「入库」功能门控 + 入库执行客户端。
*
* 入库询问 / 意图识别 / 手动入库按钮只有在**入库技能存在且启用**时才出现
* (对应需求「如果有了调用技能入库的技能后…」)。当前是示例技能 `knowledge-base-ingest`
* (演示用);后续替换为真实入库技能时只要沿用同一个 name,本门控即继续生效。
* 入库不再由前端硬编码「有没有含『入库』关键字的技能」判定,而是让**结构化输出智能体**
* (`roundtable-structure`)读它挂载的入库技能 + 当前业务场景,**自行判断**是否有适合本
* 场景的入库技能(技能名可能含「六步法」等场景线索)。判定为可入库才显示「入库」按钮。
*
* 真正入库时,由结构化输出智能体走**完整 agent 运行时**(`POST /api/multi-agent/run/stream`,
* role=ingest)**自己挑技能、读 SKILL.md 并调用**完成入库——而不是前端代它调技能。
*/
import { loadSkills } from "@/core/skills/api";
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
/** 示例入库技能名(真实技能可改名;门控按「入库相关」关键字判断,不写死此名)。 */
export const INGEST_SKILL_NAME = "knowledge-base-ingest";
/**
* 是否为「入库相关」技能:按 name / name_zh / description 含 `ingest` 或「入库」判断。
* 这样示例技能(knowledge-base-ingest)与**后续改了名的真实入库技能**都能识别;
* 而知识库**检索**类技能(如 knowledge-base-search「知识库检索」)不含「入库」/`ingest`,不会误命中。
*/
export function isIngestRelatedSkill(s: {
name?: string;
name_zh?: string | null;
description?: string;
}): boolean {
const hay = `${s.name ?? ""} ${s.name_zh ?? ""} ${s.description ?? ""}`.toLowerCase();
return hay.includes("ingest") || hay.includes("入库");
/** `/ingest-eligibility` 返回:是否可入库 + 选中的技能名 + 一句话依据。 */
export interface IngestEligibility {
canIngest: boolean;
skill: string;
reason: string;
}
/**
* 是否**挂载了**可用的入库相关技能(存在且启用)。失败回退 false。
* 为 false 时第三步不显示入库按钮、不触发任何入库操作。
* 让结构化输出智能体判断「当前业务场景**是否有合适的入库技能**」(决定是否显示入库按钮)。
*
* 入参为业务场景线索(业务码 / 业务链名 / 总控编排提示 / 方案标题)+ taskId,由后端把挂在
* `roundtable-structure` 上、且已启用的技能交给模型对照判断。失败 / 未配置入库技能 → 不可入库。
*/
export async function isIngestSkillAvailable(): Promise<boolean> {
export async function checkIngestEligibility(req: {
taskId?: string | null;
businessCode?: string | null;
chainName?: string | null;
coordinatorPrompt?: string | null;
reportTitle?: string | null;
model?: string;
}): Promise<IngestEligibility> {
try {
const skills = await loadSkills();
return skills.some((s) => s.enabled && isIngestRelatedSkill(s));
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/ingest-eligibility`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
task_id: req.taskId ?? null,
business_code: req.businessCode ?? null,
chain_name: req.chainName ?? null,
coordinator_prompt: req.coordinatorPrompt ?? null,
report_title: req.reportTitle ?? null,
model: req.model,
}),
});
if (!res.ok) return { canIngest: false, skill: "", reason: "" };
const data = (await res.json()) as { can_ingest?: boolean; skill?: string; reason?: string };
return {
canIngest: !!data.can_ingest,
skill: data.skill ?? "",
reason: data.reason ?? "",
};
} catch {
return false;
return { canIngest: false, skill: "", reason: "" };
}
}
@@ -2,6 +2,7 @@ import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import type { ClarificationPayload } from "./multi-agent";
import { reportRoundtableError } from "./diagnostics-report";
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
export type { ClarificationPayload };
@@ -340,6 +341,11 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step1_intent", event: "intent_stream_http_error",
message: `第一步意图生成失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
});
throw new Error(`intent/stream failed (${res.status}): ${text}`);
}
@@ -425,6 +431,11 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
}
if (parsed.status === "error") {
result.errorDetail = parseIntentErrorDetail(parsed.error_detail);
reportRoundtableError({
stage: "step1_intent", event: "intent_error_frame",
message: `第一步意图生成报错:${(result.content || "").slice(0, 800)}`,
detail: result.errorDetail,
});
}
if (parsed.status === "clarification" && result.clarifications.length === 0) {
// Fallback path: no live `type:"tool"` clarification frames were seen
@@ -3,6 +3,7 @@ import { getBackendBaseURL } from "@/core/config";
import { OptType, writeYLog } from "@/core/log/y-log";
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
import { reportRoundtableError, stageForRoundtableAgent } from "@/roundtable-planning/api/diagnostics-report";
export type ThreadIdMap = Record<string, string>;
@@ -75,6 +76,12 @@ export async function initMultiAgent(
tlog(`fetch.headers status=${res.status}`);
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step2_init", event: "init_http_error",
message: `第二步会商初始化失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
detail: { agentNames: payload.agentNames, mainAgentName: payload.mainAgentName },
});
throw new Error(`init multi-agent failed (${res.status}): ${text}`);
}
@@ -151,18 +158,34 @@ export async function initMultiAgent(
}
} catch (err) {
aborted = (err as Error)?.name === "AbortError" || payload.signal?.aborted === true;
if (!aborted) throw err;
if (!aborted) {
reportRoundtableError({
stage: "step2_init", event: "init_stream_exception",
message: `第二步会商初始化中断(网络不可达 / 连接中断 / 超时):${(err as Error)?.message ?? String(err)}`,
detail: { seatCount },
});
throw err;
}
}
tlog(`total ${(performance.now() - t0).toFixed(0)}ms (seats=${seatCount})`);
if (errorDetail) {
reportRoundtableError({
stage: "step2_init", event: "init_error_frame",
message: `第二步会商初始化报错:${errorDetail.slice(0, 800)}`,
});
throw new Error(`init multi-agent failed: ${errorDetail}`);
}
if (aborted) {
throw new DOMException("init aborted", "AbortError");
}
if (!threadIds || !mainAgentName) {
reportRoundtableError({
stage: "step2_init", event: "init_incomplete",
message: "第二步会商初始化流提前结束(未收到 init_done,可能连接被中断)",
detail: { seatCount, hasThreadIds: !!threadIds, mainAgentName },
});
throw new Error("init multi-agent stream ended without init_done");
}
return {
@@ -212,6 +235,17 @@ export interface StreamMultiAgentRequest {
reasoningEffort?: "minimal" | "low" | "medium" | "high";
/** 仅 special 用;ultra 档置真,给席位解锁 `task` 子代理工具。 */
subagentEnabled?: boolean;
/**
* 仅 special 用。会商席位「技能识别强化」开关(沿用所选业务链条配置)。置 true 时后端把该
* 席位配置的技能(含 SKILL.md 路径 + 必须先 read_file 的硬指令)拼进本轮任务,补偿弱模型。
* 与该席位 agent 自身 config.yaml 的同名开关取 OR。省略 = false(关)。
*/
seatSkillDirective?: boolean;
/**
* 深链接业务码(rwfx→6BF 等)。**仅方案总结报告(summary)单例消费**:非空 → 后端按业务链抽取规范
* 强制注入「完整性核对」指令,让总结核对产出相对业务链完不完整。普通会商省略 = 不注入。
*/
businessCode?: string | null;
skillStopNames?: string[];
/**
* 仅 leader 用。置 true 表示这是「派活后让总控判断继续/综合」的轮次:后端会把各已交付
@@ -264,6 +298,27 @@ export interface StreamMultiAgentRequest {
name?: string,
args?: Record<string, unknown>,
) => void;
/**
* 模型自动容错:后端检测到当前模型出问题(兜底错误文案 / 交付为空等),已自动切到下一个
* 模型并即将重跑本轮时触发。上层据此把该角色「正在流式的失败气泡」重置(清空已累计的增量
* 文本)并给用户一条「『X』模型异常,已切换『Y』继续」的提示。此回调可能多次触发(连续多个
* 模型都失败时)。触发后,本次 streamMultiAgent 仍会继续用新模型流式,最终照常 resolve。
*/
onModelSwitch?: (info: ModelSwitchInfo) => void;
}
/** 模型自动容错通知(`streamMultiAgent` 的 `onModelSwitch` 回调入参)。 */
export interface ModelSwitchInfo {
/** 角色:leader / seat / seat_parallel / report / summary / dashboard / ingest。 */
role: string;
/** 出问题的智能体 agent_name。 */
agentName: string;
/** 失败的模型名。 */
failedModel: string;
/** 已切换到的下一个模型名。 */
nextModel: string;
/** 失败原因(已翻译成简短中文,如「服务繁忙」)。 */
reason: string;
}
export interface ClarificationPayload {
@@ -297,6 +352,8 @@ export interface StreamMultiAgentResult {
content: string;
/** Echoed agent_name of the agent that produced this run. */
agentName: string | null;
/** 实际产出本轮结果的模型(发生模型自动容错时即最终切换到的模型);后端未下发时为 null。 */
modelUsed?: string | null;
/**
* Populated when the leader called ask_clarification — the run ended without
* dispatching, and the model is asking the user a question instead. When
@@ -443,6 +500,11 @@ function extractAiTextDelta(parsed: unknown): { text: string; id: string } | nul
export async function streamMultiAgent(
req: StreamMultiAgentRequest,
): Promise<StreamMultiAgentResult> {
// 整段包一层兜底:除已在具体分支上报的(HTTP 错误 / error 帧 / worker error 事件)外,
// 再兜住 fetch 直接 reject(网络不可达 / 连接被拒)与流式中途中断(连接重置 / 超时),
// 做到「能收集到的报错越全越好」。`reported` 防止与具体分支重复上报。
let reported = false;
try {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/run/stream`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -458,6 +520,10 @@ export async function streamMultiAgent(
thinking_enabled: req.thinkingEnabled,
reasoning_effort: req.reasoningEffort,
subagent_enabled: req.subagentEnabled,
// 仅 special 用;会商技能识别强化(沿用所选业务链条开关)。省略 → 后端按 false(关)处理。
seat_skill_directive: req.seatSkillDirective ?? false,
// 仅 summary 单例用;深链接业务码 → 后端注入业务链完整性核对。省略/空 → 不注入。
business_code: req.businessCode ?? null,
skill_stop_names: req.skillStopNames ?? [],
// 仅 leader 用;综合轮让后端注入各席位完整交付正文。省略 → 后端按 false 处理。
synthesis_mode: req.synthesisMode ?? false,
@@ -475,6 +541,17 @@ export async function streamMultiAgent(
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
// 用户实际遇到的报错(含进第三步常见的 502):HTTP 层就失败、SSE 都没建起来。
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, req.agentName),
event: "run_stream_http_error",
message: `「${req.displayName || req.agentName}」调用失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
agentId: req.agentName,
agentName: req.displayName || req.agentName,
detail: { agentType: req.agentType },
});
reported = true;
throw new Error(`run/stream failed (${res.status}): ${text}`);
}
@@ -502,6 +579,7 @@ export async function streamMultiAgent(
content: "",
agentName: null,
clarification: null,
modelUsed: null,
};
// Inferred SSE phase + a tiny helper so we only fire onPhaseChange when the
@@ -612,6 +690,43 @@ export async function streamMultiAgent(
frameSeq += 1;
if (debugEnabled) console.debug(debugLabel, `frame#${frameSeq} event=${lastEvent}`, parsed);
// worker 把 run 内异常(常见:第二步席位/Step3 模型调用失败)发成 `event: error`
// SSE 帧 `{message,name}`——它既不是 HTTP 错误也不是 `{status:"error"}` 终帧,
// 单独在这里捕获上报,否则这类「模型没调用成功」的报错会漏收集。
if (lastEvent === "error") {
const obj = parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : { raw: parsed };
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, req.agentName),
event: "run_worker_error_event",
message: `「${req.displayName || req.agentName}」运行报错:${String(obj.message ?? obj.name ?? "").slice(0, 800)}`,
agentId: req.agentName,
agentName: req.displayName || req.agentName,
detail: { ...obj, agentType: req.agentType, framesBeforeError: frameSeq },
});
}
// 模型自动容错帧:后端检测到当前模型出问题,已切到下一个模型并即将重跑本轮。
// 不是终态帧(无 content)→ 不结束流。清空已累计的(失败尝试的)tool_call 增量,
// 把 phase 退回 connected,并通知上层重置该角色气泡 + 给用户提示。随后新模型的
// 流式增量会照常通过 onTextDelta 继续累计到(已被上层清空的)气泡。
if (
parsed &&
typeof parsed === "object" &&
(parsed as Record<string, unknown>).status === "model_switch"
) {
const obj = parsed as Record<string, unknown>;
toolCallAcc.clear();
currentPhase = "connected";
req.onModelSwitch?.({
role: typeof obj.role === "string" ? obj.role : "",
agentName: typeof obj.agent_name === "string" ? obj.agent_name : req.agentName,
failedModel: typeof obj.failed_model === "string" ? obj.failed_model : "",
nextModel: typeof obj.next_model === "string" ? obj.next_model : "",
reason: typeof obj.reason === "string" ? obj.reason : "",
});
continue;
}
// Phase inference from LangGraph messages-tuple frames. We only flip
// to tool_calling/tool_result on chunks that clearly indicate them;
// everything else with non-empty AI text means we're streaming.
@@ -712,6 +827,22 @@ export async function streamMultiAgent(
if (typeof parsed.agent_name === "string") {
result.agentName = parsed.agent_name;
}
{
const mu = (parsed as Record<string, unknown>).model_used;
if (typeof mu === "string" && mu) result.modelUsed = mu;
}
// SSE error 帧(后端 stream_generator 在席位/Step3 run 失败时下发
// `{status:"error", content, agent_name}`):上报,便于收集用户侧报错。
if (result.message === "error") {
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, result.agentName || req.agentName),
event: "run_stream_error_frame",
message: `「${req.displayName || req.agentName}」运行报错:${(result.content || "").slice(0, 800)}`,
agentId: result.agentName || req.agentName,
agentName: req.displayName || req.agentName,
detail: { agentType: req.agentType, framesBeforeError: frameSeq },
});
}
continue;
}
@@ -729,6 +860,19 @@ export async function streamMultiAgent(
console.debug(debugLabel, `stream ended after ${frameSeq} frames; final content length=${result.content.length}`);
}
return result;
} catch (err) {
if (!reported && req.signal?.aborted !== true && (err as Error)?.name !== "AbortError") {
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, req.agentName),
event: "run_stream_exception",
message: `「${req.displayName || req.agentName}」调用异常(网络不可达 / 连接中断 / 超时):${(err as Error)?.message ?? String(err)}`,
agentId: req.agentName,
agentName: req.displayName || req.agentName,
detail: { agentType: req.agentType },
});
}
throw err;
}
}
export interface SessionArtifactFile {
@@ -838,6 +982,11 @@ export async function initReportThread(
});
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step3_report", event: "init_thread_http_error",
message: `结果绘制线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status, agentId: "roundtable-report", agentName: "结果绘制",
});
throw new Error(`init report thread failed (${res.status}): ${text}`);
}
const json = (await res.json()) as { agent_name: string; thread_id: string };
@@ -864,6 +1013,11 @@ export async function initDashboardThread(
});
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step3_dashboard", event: "init_thread_http_error",
message: `大屏页面线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status, agentId: "roundtable-dashboard", agentName: "大屏页面",
});
throw new Error(`init dashboard thread failed (${res.status}): ${text}`);
}
const json = (await res.json()) as { agent_name: string; thread_id: string };
@@ -889,8 +1043,44 @@ export async function initSummaryThread(
});
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step3_summary", event: "init_thread_http_error",
message: `方案报告线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status, agentId: "roundtable-summary", agentName: "方案报告",
});
throw new Error(`init summary thread failed (${res.status}): ${text}`);
}
const json = (await res.json()) as { agent_name: string; thread_id: string };
return { agentName: json.agent_name, threadId: json.thread_id };
}
/**
* Create a thread for the Step 3「入库」structure agent (`roundtable-structure`,
* a built-in singleton — the same agent that extracts the flowchart, but this run
* uses the `ingest` run policy so its attached ingest skill actually executes).
* Run it afterwards with {@link streamMultiAgent} (`agentType: "special"`,
* `agentName: "roundtable-structure"`, `dAgentThreadId: { [agentName]: threadId }`):
* the agent picks the suitable ingest skill (its name may contain「六步法」), reads
* its SKILL.md and calls it — passing the taskId + summary report + structured flow.
*/
export async function initStructureThread(
options: { signal?: AbortSignal } = {},
): Promise<ReportThreadResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/structure/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
signal: options.signal,
});
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step3_structure", event: "init_thread_http_error",
message: `结构化输出线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status, agentId: "roundtable-structure", agentName: "结构化输出",
});
throw new Error(`init structure thread failed (${res.status}): ${text}`);
}
const json = (await res.json()) as { agent_name: string; thread_id: string };
return { agentName: json.agent_name, threadId: json.thread_id };
}
@@ -4,6 +4,7 @@ import { OptType, writeYLog } from "@/core/log/y-log";
import type { Agent } from "@/core/agents";
import type { IntentSummary } from "./intent";
import { reportRoundtableError } from "./diagnostics-report";
/**
* Agent-recommendation API. Sits between Step 1 (intent clarification) and
@@ -335,6 +336,11 @@ export async function streamRecommend(req: StreamRecommendRequest): Promise<Stre
if (!res.ok || !res.body) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "step2_recommend", event: "recommend_stream_http_error",
message: `智能体推荐失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
});
throw new Error(`recommend/stream failed (${res.status}): ${text}`);
}
@@ -390,6 +396,12 @@ export async function streamRecommend(req: StreamRecommendRequest): Promise<Stre
if (Array.isArray(parsed.picks)) {
result.picks = parsed.picks as RecommendPick[];
}
if (parsed.status === "error") {
reportRoundtableError({
stage: "step2_recommend", event: "recommend_error_frame",
message: `智能体推荐报错:${(result.content || "").slice(0, 800)}`,
});
}
continue;
}
@@ -16,6 +16,7 @@ import { getBackendBaseURL } from "@/core/config";
import { OptType, writeYLog } from "@/core/log/y-log";
import { getAvatarTypeFor } from "../lib/roundtable-constants";
import { reportRoundtableError } from "./diagnostics-report";
import { seatModeToRunParams } from "../lib/seat-mode";
import {
isTerminalJobStatus,
@@ -30,6 +31,11 @@ const BASE = () => `${getBackendBaseURL()}/api/roundtable-jobs`;
async function readJson<T>(res: Response, ctx: string): Promise<T> {
if (!res.ok) {
const text = await res.text().catch(() => "");
reportRoundtableError({
stage: "job", event: "job_api_http_error",
message: `后台作业接口「${ctx}」失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
});
throw new Error(`${ctx} failed (${res.status}): ${text}`);
}
return (await res.json()) as T;
@@ -93,6 +99,18 @@ function toStartBody(p: StartJobPayload) {
seedMessage: p.seedMessage,
threadIds: p.threadIds ?? null,
coordinatorName: p.coordinatorName ?? "roundtable-coordinator",
// 每席位技能识别强化映射 {agentId: bool}:沿用所选业务链条里各席位的开关;缺省 {}。
// 后端 run_seat 按 agentId 查表,与各席位 agent 自身开关取 OR。
seat_skill_directives: p.seatSkillDirectives ?? {},
// 每席位推理深度覆盖映射 {agentId: SeatMode|null}:沿用所选业务链条里各席位单独配的推理深度;
// 后端 run_seat 按 agentId 查表,覆盖优先、否则跟随作业级 seatMode(thinking/reasoning/subagent)。
seat_modes: Object.fromEntries(
Object.entries(p.seatModes ?? {}).filter(([, v]) => v != null) as [string, string][],
),
// 研讨前并行取数开关(来源链条 gatherFirst):true = 后台研讨前先并行取数再研讨。缺省 false。
gather_first: p.gatherFirst ?? false,
// 深链接业务码:后台总结报告据此做业务链完整性核对(写实业务如 rwfx 才生效)。空 → 不注入。
business_code: p.businessCode ?? null,
...(seat
? {
thinking_enabled: seat.thinking_enabled,
@@ -246,7 +264,13 @@ export function streamJob(jobId: string, handlers: StreamJobHandlers, taskId?: s
continue;
}
if (frame.event === "error") {
handlers.onError?.(String(frame.detail ?? "unknown stream error"));
const detail = String(frame.detail ?? "unknown stream error");
reportRoundtableError({
stage: "job", event: "job_stream_error_frame",
message: `后台作业进度流报错:${detail.slice(0, 500)}`,
jobId, detail: { taskId },
});
handlers.onError?.(detail);
continue;
}
const job = mapJob(frame);
@@ -1,4 +1,5 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import type { ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -214,7 +215,9 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
[content],
);
return (
// 经 portal 挂到 body:脱离会商页 <main>(`relative z-0`) 的层叠上下文,
// 否则 fixed 弹窗会被会商页头(z-40)/全局顶栏(z-45)盖住顶部。
return createPortal(
<div
className="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-6"
onMouseDown={(e) => {
@@ -287,6 +290,7 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
)}
</div>
</div>
</div>
</div>,
document.body,
);
};
@@ -31,6 +31,7 @@ import {
import { cn } from "@/lib/utils";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
import { getStoredAuth } from "@/core/auth";
import { listAgents } from "@/core/agents";
import { listChains, setChainPublic, type ChainScope } from "../api/chains";
@@ -71,7 +72,9 @@ export function BusinessChainListBody({
const [chains, setChains] = useState<BusinessChain[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// 筛选:我的 / 公共(已发布)。
// 管理员:额外多一个「全部」筛选,且可编辑 / 发布任意账号的链条。
const isAdmin = getStoredAuth()?.system_role === "admin";
// 筛选:我的 / 公共(已发布)/(管理员)全部。
const [scope, setScope] = useState<ChainScope>("mine");
const [publishingId, setPublishingId] = useState<string | null>(null);
// 实时名称表(id 小写 → 最新 name):用于把席位的落库快照名刷新成最新(agent 改名同步)。
@@ -147,9 +150,9 @@ export function BusinessChainListBody({
return (
<>
{/* 筛选:我的 / 公共 */}
{/* 筛选:我的 / 公共 /(管理员)全部 */}
<div className="shrink-0 flex items-center gap-1 rounded-lg border border-border bg-muted/40 p-0.5 self-start">
{(["mine", "public"] as const).map((s) => (
{((isAdmin ? ["mine", "public", "all"] : ["mine", "public"]) as ChainScope[]).map((s) => (
<button
key={s}
type="button"
@@ -161,7 +164,7 @@ export function BusinessChainListBody({
: "text-muted-foreground hover:text-foreground",
)}
>
{s === "mine" ? "我的" : "公共"}
{s === "mine" ? "我的" : s === "public" ? "公共" : "全部"}
</button>
))}
</div>
@@ -195,6 +198,7 @@ export function BusinessChainListBody({
<ChainRow
key={chain.id}
chain={chain}
canManage={isAdmin || chain.isMine !== false}
nameById={nameById}
publishing={publishingId === chain.id}
onSettings={() => onConfigure(chain.id)}
@@ -245,18 +249,20 @@ export function BusinessChainListDialog({
function ChainRow({
chain,
canManage,
nameById,
publishing,
onSettings,
onTogglePublic,
}: {
chain: BusinessChain;
/** 能否编辑 / 发布(本人链条 或 管理员)。 */
canManage: boolean;
nameById: Map<string, string>;
publishing: boolean;
onSettings: () => void;
onTogglePublic: () => void;
}) {
const isMine = chain.isMine !== false;
// 配置者用户名:后端返回 email,展示时取 @ 前的本地部分更像「用户名」。
const ownerName = chain.ownerName ? chain.ownerName.split("@")[0] : "";
return (
@@ -274,8 +280,8 @@ function ChainRow({
</span>
)}
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{/* 发布 / 取消发布:仅本人的链条可操作。 */}
{isMine && (
{/* 发布 / 取消发布:本人的链条或管理员可操作。 */}
{canManage && (
<Button
variant={chain.isPublic ? "secondary" : "outline"}
size="sm"
@@ -291,8 +297,8 @@ function ChainRow({
{chain.isPublic ? "取消发布" : "发布"}
</Button>
)}
{/* 设置(编辑):仅本人的链条;公共里别人的链条只读浏览。 */}
{isMine && (
{/* 设置(编辑):本人的链条或管理员;普通用户看别人的链条只读浏览。 */}
{canManage && (
<Button
variant="ghost"
size="sm"
@@ -147,19 +147,28 @@ export function BusinessChainPicker({
const chainMeta = { id: selectedChain.id, title: selectedChain.title };
const seatNameById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.name]));
const nameOf = (id: string) => nameById.get(id) ?? seatNameById.get(id) ?? id;
// 席位模型覆盖(链条配置):按 agent_id 取,空/缺省 = 跟随全局模型。
const modelById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.model ?? null]));
const modelOf = (id: string) => modelById.get(id) ?? null;
// 席位「会商技能识别强化」开关(链条配置):按 agent_id 取,缺省 = 关。
const skillById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.seat_skill_directive ?? false]));
const skillOf = (id: string) => skillById.get(id) ?? false;
// 席位「推理深度覆盖」(链条配置 seat_mode):按 agent_id 取,null/缺省 = 跟随链条级 seatMode。
const seatModeById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.seat_mode ?? null]));
const seatModeOf = (id: string) => seatModeById.get(id) ?? null;
// 链条带分层、过滤存活后仍并行 → dag 编排(携带快速/沙箱子模式);否则退回线性 chain。
if (dagPlan) {
// dag:席位顺序按 stage 展平(与 plan 一致)。
const agents = dagPlan.stages
.flatMap((st) => st.agentIds)
.map((id) => ({ agent_id: id, name: nameOf(id) }));
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode });
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), seatMode: seatModeOf(id) }));
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode, gatherFirst: selectedChain.gatherFirst ?? false });
return;
}
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id) }));
onConfirm({ agents, mode: "chain", chain: chainMeta });
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
onConfirm({ agents, mode: "chain", chain: chainMeta, gatherFirst: selectedChain.gatherFirst ?? false });
};
// 整片脱敏:链条卡片区(链条名/描述/席位智能体名)。输入框不受影响(Hook 跳过)。
@@ -156,7 +156,7 @@ export function DashboardChatPanel({
{/* 聊天记录 */}
<div className="relative flex-1 min-h-0 flex flex-col">
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto p-4 space-y-4 bg-white">
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-4 space-y-4 bg-white">
{phase === "creating" && dialogues.length === 0 && (
<div className="flex items-center gap-2 text-xs text-slate-500">
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary" />
@@ -181,7 +181,8 @@ export function Step1Panel(props: Step1PanelProps) {
<div className="relative flex-1 min-h-0 flex flex-col font-normal">
<div
ref={step1ScrollRef}
className="flex-1 min-h-0 overflow-y-auto p-6 space-y-4 bg-white"
// overflow-x-hidden:消息列表只竖向滚(见 Step2Panel 同处注释),避免误触横向拖动抢滑块。
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-6 space-y-4 bg-white"
>
{interactiveMessages.map((msg) => (
<Step1Message
@@ -551,7 +551,11 @@ export function Step2Panel(props: Step2PanelProps) {
)}
<div
ref={step2ScrollRef}
className="flex-1 min-h-0 overflow-y-auto p-6 space-y-4 bg-white border-t border-slate-150 border-b border-slate-150 shadow-inner"
// overflow-x-hidden:消息列表只竖向滚。否则 `overflow-y-auto` 单写时按 CSS 规范
// 另一轴会被计算成 auto,任何子元素溢出一两像素都会让整列横向可滚 → 鼠标移到右侧
// 竖滚条滑块时极易误触发横向拖动、抓不住滑块。宽内容(代码块/表格)在各自气泡内
// 已有 max-w-full + overflow-x-auto 自带横滚,故此处裁掉横向不影响查看。
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-6 space-y-4 bg-white border-t border-slate-150 border-b border-slate-150 shadow-inner"
>
{isInitializing && step2RoundtableDialogues.length === 0 && (
<div className="flex h-full flex-col items-center justify-center gap-3 py-12 text-slate-500">
@@ -592,7 +592,7 @@ function AgentProgressPanel({
<div className="relative flex-1 min-h-0 flex flex-col">
<div
ref={scrollRef}
className="flex-1 min-h-0 overflow-y-auto p-4 space-y-4 bg-white"
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-4 space-y-4 bg-white"
>
{phase === "creating" && dialogues.length === 0 && (
<div className="flex items-center gap-2 text-xs text-slate-500">
@@ -10,6 +10,7 @@
* 互不影响(report 画 HTML 看板,summary 写 Markdown 报告 + 问答)。
*/
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { createPortal } from "react-dom";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
@@ -420,6 +421,8 @@ export function Step3SummaryMode({
pendingIngestClarification={summary.pendingIngestClarification}
onResolveIngestChoice={summary.resolveIngestChoice}
onResolveIngestClarification={summary.resolveIngestClarification}
pendingFlowForIngest={summary.pendingFlowForIngest}
onResolveFlowForIngest={summary.resolveFlowForIngest}
onManualIngest={summary.runIngest}
onRetry={redraw}
onAsk={handleAsk}
@@ -572,6 +575,8 @@ function AgentProgressPanel({
pendingIngestClarification,
onResolveIngestChoice,
onResolveIngestClarification,
pendingFlowForIngest,
onResolveFlowForIngest,
onManualIngest,
onRetry,
onAsk,
@@ -602,6 +607,9 @@ function AgentProgressPanel({
pendingIngestClarification: string | null;
onResolveIngestChoice: UseStep3SummaryReturn["resolveIngestChoice"];
onResolveIngestClarification: UseStep3SummaryReturn["resolveIngestClarification"];
/** 入库时尚无流程图 → 展示「是否先生成流程图」协助。 */
pendingFlowForIngest: boolean;
onResolveFlowForIngest: UseStep3SummaryReturn["resolveFlowForIngest"];
onManualIngest: UseStep3SummaryReturn["runIngest"];
onRetry: () => void;
onAsk: (message: string, files?: File[]) => void;
@@ -699,7 +707,7 @@ function AgentProgressPanel({
{/* 消息列表 —— 与第 2 步同款气泡(流式正文 + 工具步骤卡 + 文件卡)。 */}
<div className="relative flex-1 min-h-0 flex flex-col">
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto p-4 space-y-4 bg-white">
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-4 space-y-4 bg-white">
{phase === "creating" && dialogues.length === 0 && (
<div className="flex items-center gap-2 text-xs text-slate-500">
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary" />
@@ -808,7 +816,7 @@ function AgentProgressPanel({
{ingestAvailable && ingestStatus === "asking" && (
<div className="shrink-0 border-t border-emerald-100 bg-emerald-50/60 px-3 py-2.5">
<div className="mb-1.5 text-[11px] font-bold text-emerald-800">
流程图已生成,是否把本方案入库到知识库?
流程图已生成,是否进行数据入库?
</div>
<div className="flex flex-wrap gap-1.5">
{(
@@ -831,6 +839,32 @@ function AgentProgressPanel({
</div>
)}
{/* 入库时尚无流程图 → 协助:数据入库以流程图为核心内容,先问是否生成流程图。 */}
{ingestAvailable && pendingFlowForIngest && (
<div className="shrink-0 border-t border-amber-100 bg-amber-50/70 px-3 py-2.5">
<div className="mb-1.5 text-[11px] font-bold text-amber-800">
当前还没有生成流程图,数据入库需要流程图。是否先生成流程图?
</div>
<div className="flex flex-wrap gap-1.5">
{(
[
{ k: "generate", t: "生成流程图" },
{ k: "cancel", t: "暂不入库" },
] as const
).map((o) => (
<button
key={o.k}
type="button"
onClick={() => onResolveFlowForIngest(o.k)}
className="rounded-lg border border-amber-300 bg-white px-2.5 py-1.5 text-[11px] font-bold text-amber-800 transition hover:bg-amber-100"
>
{o.t}
</button>
))}
</div>
</div>
)}
{/* 「稍后入库」自由文字意图模糊 → 让用户在入库语境下自己定。 */}
{ingestAvailable && pendingIngestClarification && (
<div className="shrink-0 border-t border-emerald-100 bg-emerald-50/60 px-3 py-2.5">
@@ -912,11 +946,11 @@ function AgentProgressPanel({
<button
type="button"
onClick={() => onManualIngest()}
title="把本方案入库到知识库(调用入库技能,过程见消息列表步骤条)"
title="进行数据入库(由结构化输出智能体调用入库技能,过程见消息列表步骤条)"
className="mb-0.5 flex h-8 shrink-0 items-center gap-1 rounded-xl border border-emerald-200 bg-emerald-50 px-2.5 text-[11px] font-bold text-emerald-700 transition hover:bg-emerald-100 active:scale-95"
>
<Database className="h-3.5 w-3.5" />
入库
数据入库
</button>
)}
@@ -972,7 +1006,10 @@ function ContentModal({
onClose: () => void;
headerAction?: React.ReactNode;
}) {
return (
// 经 portal 挂到 body:页面 <main> 是 `relative z-0`(浅蓝主题层叠基线),会把
// 内部 fixed 弹窗困在 z-0 层叠上下文里,被会商页头(z-40)/全局顶栏(z-45)盖住顶部。
// 挂到 body 后脱离该上下文,z-50 才真正盖在顶栏之上,弹窗标题栏正常显示。
return createPortal(
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[1px] p-4"
onClick={onClose}
@@ -996,7 +1033,8 @@ function ContentModal({
</div>
<div className="flex-1 overflow-y-auto p-5">{children}</div>
</div>
</div>
</div>,
document.body,
);
}
@@ -0,0 +1,319 @@
/**
* 「大屏绘制智能体」决心建议页 —— 任务信息 / 作战主张 / 打击目标 / 实施要点 / 决心总结
* (按设计图 dp-6.png 一比一实现)。
*
* **dashboard-agent 独占**:作为 DashboardApp `pages` 插槽里「决心建议」Tab 的内容,
* 不影响多智能体会商(Step3)大屏多页的样式。当前为「静态页面」,文案为占位内容,
* 动态数据后续接入。版式包含:
* 1. 任务信息 + 任务行动方向 / 作战主张(3 个编号方案)
* 2. 打击目标 / 目标建议(表)+ 实施要点
* 3. 决心建议总结(总结段 + 统计块)
*/
import { ClipboardList, Crosshair, Target, ListChecks, Flag, Clock, ShieldCheck, AlertTriangle, type LucideIcon } from "lucide-react";
import { Card, CardTitle, Table, Td, Tag, NoData, useDesensitize, type Tone } from "@/roundtable-planning/dashboard-agent/ui";
import type { DecisionData } from "@/roundtable-planning/dashboard-agent/sq-report";
// ── 占位数据 ──────────────────────────────────────────────────────────────────
const TASK_META: Array<{ label: string; value: string }> = [
{ label: "任务标题", value: "夺控 XX 关键地域,压制敌防御体系" },
{ label: "任务类型", value: "进攻作战" },
{ label: "任务时限", value: "5 小时内" },
{ label: "任务方向", value: "XX 方向" },
];
const TASK_INTRO =
"根据上级指示,我方对敌防御体系实施进攻,夺控 XX 关键地域,破坏敌指挥控制能力与防御部署,压制敌纵深支援能力,为后续行动创造有利条件。";
interface Proposal {
no: number;
title: string;
bullets: string[];
rec: string;
recTone: Tone;
}
const PROPOSALS: Proposal[] = [
{
no: 1,
title: "主攻突破,速战速决",
bullets: ["集中优势兵力突击敌防御薄弱点", "快速突破并夺控要点", "压制敌纵深火力支援能力"],
rec: "高",
recTone: "red",
},
{
no: 2,
title: "稳固推进,逐步压制",
bullets: ["先期压制敌火力与指挥体系", "分段推进,扩大战果", "稳固圈占,巩固防御"],
rec: "中",
recTone: "amber",
},
{
no: 3,
title: "迂回包抄,分割合围",
bullets: ["迂回敌防御侧翼实施包抄", "切割敌防御部署", "围点打援,歼敌纵深兵力"],
rec: "中",
recTone: "amber",
},
];
interface TargetRow {
no: number;
name: string;
type: string;
importance: string;
impTone: Tone;
priority: string;
priTone: Tone;
effect: string;
method: string;
timing: string;
}
const TARGETS: TargetRow[] = [
{ no: 1, name: "敌前沿防御阵地", type: "防御工事", importance: "高", impTone: "red", priority: "高", priTone: "red", effect: "摧毁瘫痪,降低防御能力", method: "精确打击", timing: "D+0~0+3h" },
{ no: 2, name: "敌指挥控制节点", type: "指挥所", importance: "高", impTone: "red", priority: "高", priTone: "red", effect: "压制致瘫", method: "火力打击", timing: "D+0~0+5h" },
{ no: 3, name: "敌炮兵阵地", type: "火力群", importance: "高", impTone: "red", priority: "中", priTone: "amber", effect: "压制摧毁", method: "远程火力", timing: "D+0~0+4h" },
{ no: 4, name: "敌防空火力点", type: "防空阵地", importance: "中", impTone: "amber", priority: "高", priTone: "red", effect: "前期压制夺取制空", method: "电子+火力", timing: "D+0~0+2h" },
{ no: 5, name: "敌纵深兵力", type: "增援部队", importance: "中", impTone: "amber", priority: "中", priTone: "amber", effect: "迟滞阻断", method: "火力封锁", timing: "D+0~0+18h" },
];
const KEY_POINTS = [
"集中优势兵力与火力,确保主攻方向突破能力。",
"先期制电、压制网络,为突击与夺控创造信息优势。",
"强化诸军兵种协同,提升整体作战效能。",
"严格协同空地火力与地面行动,形成体系打击合力。",
"做好预备兵力与增援应对预案,保持持续作战能力。",
"注重战场舆情与目标善后,及时修订完善方案。",
];
const SUMMARY =
"建议采取「主攻突破,速战速决」的作战行动方向,集中优势兵力与火力,优先打击敌防御阵地、敌指挥控制节点与敌纵深兵力,迅速压制敌防御体系,夺控 XX 关键地域,并同步破坏敌纵深支援能力,形成战役全局有利态势。";
interface SummaryStat {
icon: LucideIcon;
label: string;
value: string;
}
const SUMMARY_STATS: SummaryStat[] = [
{ icon: Crosshair, label: "推荐行动方向", value: "主攻突破,速战速决" },
{ icon: Clock, label: "建议处置时机", value: "D+0 ~ D+6h" },
{ icon: Target, label: "关键目标数量", value: "5 个" },
{ icon: ShieldCheck, label: "重点保障", value: "火力压制 / 空中协同 / 机动补给" },
{ icon: AlertTriangle, label: "风险提示", value: "敌防空反制 / 增援压力 / 地形限制" },
];
// ── 主组件(有真实数据走真实渲染,否则回退静态占位) ─────────────────────────────
export function Decision({ data }: { data?: DecisionData | null }) {
return data ? <DecisionReal data={data} /> : <NoData />;
}
function DecisionPlaceholder() {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 1. 任务信息 + 作战主张 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
<Card className="flex flex-col lg:col-span-4">
<CardTitle icon={ClipboardList} title="任务信息" />
<div className="flex-1 px-4 py-3.5">
<dl className="space-y-2">
{TASK_META.map((m) => (
<div key={m.label} className="flex gap-2 text-xs">
<dt className="w-16 shrink-0 text-slate-400 dark:text-[var(--dash-text-dim)]">{m.label}</dt>
<dd className="font-medium text-slate-700 dark:text-[var(--dash-text-strong)]">{m.value}</dd>
</div>
))}
</dl>
<div className="mt-3 border-t border-slate-100 pt-3 dark:border-[var(--dash-border)]">
<div className="mb-1 text-[11px] text-slate-400 dark:text-[var(--dash-text-dim)]">任务简介</div>
<p className="text-xs leading-relaxed text-slate-600 dark:text-[var(--dash-text)]">{TASK_INTRO}</p>
</div>
</div>
</Card>
<Card className="flex flex-col lg:col-span-8">
<CardTitle icon={Flag} title="任务行动方向 / 作战主张" />
<div className="grid flex-1 grid-cols-1 gap-3 px-4 py-3.5 sm:grid-cols-3">
{PROPOSALS.map((p) => (
<div
key={p.no}
className="flex flex-col rounded-md border border-slate-200 p-3 dark:border-[var(--dash-border)]"
>
<div className="mb-2 flex items-center gap-2">
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-600 text-[11px] font-bold text-white">
{p.no}
</span>
<h4 className="text-xs font-bold text-slate-900 dark:text-[var(--dash-text-strong)]">{p.title}</h4>
</div>
<ul className="flex-1 space-y-1.5">
{p.bullets.map((b) => (
<li key={b} className="flex gap-1.5 text-[11px] leading-snug text-slate-600 dark:text-[var(--dash-text)]">
<span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-red-500" />
{b}
</li>
))}
</ul>
<div className="mt-2 flex items-center gap-1.5 border-t border-slate-100 pt-2 text-[11px] text-slate-400 dark:border-[var(--dash-border)]">
推荐程度
<Tag tone={p.recTone}>{p.rec}</Tag>
</div>
</div>
))}
</div>
</Card>
</div>
{/* 2. 打击目标 + 实施要点 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
<Card className="flex flex-col lg:col-span-8">
<CardTitle icon={Target} title="打击目标 / 目标建议" />
<div className="flex-1 px-4 py-3.5">
<Table head={["序号", "目标名称", "类型", "重要性", "优先级", "达成效果", "建议方式", "建议时机"]}>
{TARGETS.map((t) => (
<tr key={t.no}>
<Td className="font-mono text-slate-400">{t.no}</Td>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{t.name}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.type}</Td>
<Td>
<Tag tone={t.impTone}>{t.importance}</Tag>
</Td>
<Td>
<Tag tone={t.priTone}>{t.priority}</Tag>
</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.effect}</Td>
<Td className="whitespace-nowrap text-slate-500 dark:text-[var(--dash-text-sec)]">{t.method}</Td>
<Td className="whitespace-nowrap font-mono text-slate-400">{t.timing}</Td>
</tr>
))}
</Table>
</div>
</Card>
<Card className="flex flex-col lg:col-span-4">
<CardTitle icon={ListChecks} title="实施要点" />
<ol className="flex-1 space-y-2.5 px-4 py-3.5">
{KEY_POINTS.map((p, i) => (
<li key={p} className="flex gap-2 text-xs leading-relaxed">
<span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-red-600 text-[10px] font-bold text-white">
{i + 1}
</span>
<span className="text-slate-600 dark:text-[var(--dash-text)]">{p}</span>
</li>
))}
</ol>
</Card>
</div>
{/* 3. 决心建议总结 */}
<Card>
<CardTitle icon={Flag} title="决心建议总结" />
<div className="px-4 py-3.5">
<p className="rounded border-l-2 border-red-500 bg-red-50 px-3 py-2.5 text-[13px] leading-relaxed text-slate-700 dark:bg-red-500/10 dark:text-[var(--dash-text)]">
{SUMMARY}
</p>
<div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
{SUMMARY_STATS.map((s) => (
<div key={s.label} className="rounded-md bg-slate-50 px-3 py-3 dark:bg-white/5">
<div className="mb-1.5 flex items-center gap-1.5 text-[11px] text-slate-500 dark:text-[var(--dash-text-sec)]">
<s.icon className="h-3.5 w-3.5 text-red-600" />
{s.label}
</div>
<div className="text-xs font-bold text-slate-900 dark:text-[var(--dash-text-strong)]">{s.value}</div>
</div>
))}
</div>
</div>
</Card>
</div>
);
}
// ── 真实数据渲染 ──────────────────────────────────────────────────────────────
function DecisionReal({ data }: { data: DecisionData }) {
const ds = useDesensitize();
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 任务信息 + 作战目的 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
<Card className="flex flex-col lg:col-span-5">
<CardTitle icon={ClipboardList} title="任务信息" />
<div className="flex-1 px-4 py-3.5">
{data.taskTitle && (
<div className="mb-2">
<div className="mb-1 text-[11px] text-slate-400 dark:text-[var(--dash-text-dim)]">{ds("任务标题")}</div>
<p className="text-sm font-bold text-slate-800 dark:text-[var(--dash-text-strong)]">{data.taskTitle}</p>
</div>
)}
{data.taskIntro && (
<div className="border-t border-slate-100 pt-2.5 dark:border-[var(--dash-border)]">
<div className="mb-1 text-[11px] text-slate-400 dark:text-[var(--dash-text-dim)]">{ds("任务简介")}</div>
<p className="text-xs leading-relaxed text-slate-600 dark:text-[var(--dash-text)]">{data.taskIntro}</p>
</div>
)}
</div>
</Card>
{data.objectives.length > 0 && (
<Card className="flex flex-col lg:col-span-7">
<CardTitle icon={Crosshair} title="作战目的" />
<ol className="flex-1 space-y-2.5 px-4 py-3.5">
{data.objectives.map((o, i) => (
<li key={i} className="flex gap-2 text-xs leading-relaxed">
<span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-red-600 text-[10px] font-bold text-white">{i + 1}</span>
<span className="text-slate-600 dark:text-[var(--dash-text)]">{o}</span>
</li>
))}
</ol>
</Card>
)}
</div>
{/* 打击目标 + 实施要点 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
{data.targets.length > 0 && (
<Card className="flex flex-col lg:col-span-8">
<CardTitle icon={Target} title="打击目标 / 目标建议" />
<div className="flex-1 px-4 py-3.5">
<Table head={["目标名称", "目标描述", "选择理由", "潜在影响", "推荐依据"]}>
{data.targets.map((t, i) => (
<tr key={i}>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{t.name || "—"}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.desc || "—"}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.reason || "—"}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.impact || "—"}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.basis || "—"}</Td>
</tr>
))}
</Table>
</div>
</Card>
)}
{data.keyPoints.length > 0 && (
<Card className="flex flex-col lg:col-span-4">
<CardTitle icon={ListChecks} title="实施要点" />
<ol className="flex-1 space-y-2.5 px-4 py-3.5">
{data.keyPoints.map((p, i) => (
<li key={i} className="flex gap-2 text-xs leading-relaxed">
<span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-red-600 text-[10px] font-bold text-white">{i + 1}</span>
<span className="text-slate-600 dark:text-[var(--dash-text)]">{p}</span>
</li>
))}
</ol>
</Card>
)}
</div>
{/* 决心建议总结 */}
{data.summary && (
<Card>
<CardTitle icon={Flag} title="决心建议总结" />
<div className="px-4 py-3.5">
<p className="rounded border-l-2 border-red-500 bg-red-50 px-3 py-2.5 text-[13px] leading-relaxed text-slate-700 dark:bg-red-500/10 dark:text-[var(--dash-text)]">
{data.summary}
</p>
</div>
</Card>
)}
</div>
);
}
@@ -0,0 +1,274 @@
/**
* 「大屏绘制智能体」处置建议页 —— 处置总结 / 目标 / 处置建议表 / 关键事态
* (按设计图 dp-7.png 一比一实现)。
*
* **dashboard-agent 独占**:作为 DashboardApp `pages` 插槽里「处置建议」Tab 的内容,
* 不影响多智能体会商(Step3)大屏多页的样式。当前为「静态页面」,文案为占位内容,
* 动态数据后续接入。版式包含:
* 1. 处置建议总结 + 目标(5 个处置目标卡)
* 2. 处置建议(大表)+ 关键事态(编号事件列表)
*/
import {
ClipboardCheck,
ClipboardList,
Flag,
ShieldAlert,
Megaphone,
Users,
Gavel,
Handshake,
AlertTriangle,
Star,
type LucideIcon,
} from "lucide-react";
import { Card, CardTitle, FooterNote, Table, Td, Tag, NoData, useDesensitize, type Tone } from "@/roundtable-planning/dashboard-agent/ui";
import type { DisposalData } from "@/roundtable-planning/dashboard-agent/sq-report";
// ── 占位数据 ──────────────────────────────────────────────────────────────────
const SUMMARY_ITEMS: Array<{ label: string; text: string }> = [
{ label: "总体判断", text: "当前事件可控但需密切关注,舆情存在扩散与升级风险,需快速反应、综合施策。" },
{ label: "主体策略", text: "以澄清事实、权威发声为主,依法依规处置,统筹线上线下,压缩谣言空间。" },
{ label: "处置重点", text: "统一对外口径,加强舆论引导,强化协同联动,做好重点群体与重点平台工作。" },
{ label: "风险防控", text: "警惕谣言扩散、情绪对立与境外炒作,防范局部聚集与事态升级,守牢安全底线。" },
];
interface GoalCard {
icon: LucideIcon;
title: string;
text: string;
}
const GOALS: GoalCard[] = [
{ icon: ShieldAlert, title: "阻止威胁扩张", text: "及时防御与压制扩张,减少不实信息蔓延与影响扩散。" },
{ icon: Megaphone, title: "澄清事实,统一口径", text: "权威发布、统一口径,及时回应社会关切。" },
{ icon: Users, title: "维护社会稳定", text: "引导社会情绪,防范对立与局部聚集,维护大局稳定。" },
{ icon: Gavel, title: "依法严正应对", text: "对违法违规行为依法处置,严正立场、坚守底线。" },
{ icon: Handshake, title: "提升协同效能", text: "强化多部门协同联动,形成处置合力与快速反应能力。" },
];
interface DisposalRow {
no: number;
content: string;
timing: string;
subject: string;
caliber: string;
method: string;
effect: string;
basis: string;
}
const DISPOSALS: DisposalRow[] = [
{ no: 1, content: "澄清事实,发布权威信息", timing: "立即", subject: "宣传部门 / 权威发布机构", caliber: "事实 / 立场", method: "权威发布、多渠道同步", effect: "统一口径,稳定舆论", basis: "公开透明" },
{ no: 2, content: "管控舆情,做强引导", timing: "持续", subject: "网信部门 / 平台", caliber: "引导 / 疏导", method: "加强议题设置与正向引导", effect: "压制负面,提升正能量", basis: "依法管理" },
{ no: 3, content: "防范网络,加强溯源处置", timing: "快速", subject: "公安部门 / 平台", caliber: "溯源 / 处置", method: "监测溯源、依法处置", effect: "切断扩散链条", basis: "合法合规" },
{ no: 4, content: "协同处置,打击违法行为", timing: "视情", subject: "多部门联动", caliber: "联动 / 执法", method: "联合执法、分级处置", effect: "形成有效震慑", basis: "严正应对" },
{ no: 5, content: "防范升级,维护稳定", timing: "持续", subject: "综合部门", caliber: "稳控 / 防控", method: "重点防控、预案处置", effect: "守牢稳定底线", basis: "安全第一" },
];
interface KeyEvent {
no: number;
title: string;
time: string;
impact: string;
impactTone: Tone;
}
const EVENTS: KeyEvent[] = [
{ no: 1, title: "不实信息在社交平台扩散", time: "05-16 09:30", impact: "高", impactTone: "red" },
{ no: 2, title: "部分舆情持续发酵引发讨论", time: "05-16 08:40", impact: "中", impactTone: "amber" },
{ no: 3, title: "相关话题持续热度上升", time: "05-16 10:05", impact: "中", impactTone: "amber" },
{ no: 4, title: "线下出现小范围聚集活动", time: "05-16 10:20", impact: "高", impactTone: "red" },
{ no: 5, title: "涉事相关单位回应迟缓", time: "05-16 09:50", impact: "中", impactTone: "amber" },
];
// ── 主组件(有真实数据走真实渲染,否则回退静态占位) ─────────────────────────────
export function Disposal({ data }: { data?: DisposalData | null }) {
return data ? <DisposalReal data={data} /> : <NoData />;
}
function DisposalPlaceholder() {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 1. 处置建议总结 + 目标 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
{/* 处置建议总结 */}
<Card className="flex flex-col lg:col-span-4">
<CardTitle icon={ClipboardCheck} title="处置建议总结" />
<ul className="flex-1 space-y-3 px-4 py-3.5">
{SUMMARY_ITEMS.map((s) => (
<li key={s.label} className="flex gap-2.5 text-xs leading-relaxed">
<span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-red-600" />
<p className="text-slate-600 dark:text-[var(--dash-text)]">
<span className="font-bold text-red-600">{s.label}:</span>
{s.text}
</p>
</li>
))}
</ul>
<div className="mx-4 mb-3.5 flex flex-wrap items-center gap-x-4 gap-y-2 rounded bg-slate-50 px-3 py-2.5 dark:bg-white/5">
<div className="flex items-center gap-1.5 text-[11px] text-slate-500 dark:text-[var(--dash-text-sec)]">
综合处置建议
<Tag tone="red">稳健(取义)</Tag>
</div>
<div className="flex items-center gap-1.5 text-[11px] text-slate-500 dark:text-[var(--dash-text-sec)]">
建议执行优先级
<span className="flex items-center gap-0.5 text-red-600">
{Array.from({ length: 5 }).map((_, i) => (
<Star key={i} className="h-3.5 w-3.5 fill-current" />
))}
</span>
</div>
</div>
</Card>
{/* 目标 */}
<Card className="flex flex-col lg:col-span-8">
<CardTitle icon={Flag} title="目标" />
<div className="grid flex-1 grid-cols-1 gap-3 px-4 py-3.5 sm:grid-cols-2 lg:grid-cols-5">
{GOALS.map((g) => (
<div key={g.title} className="flex flex-col rounded-md border border-slate-200 p-3 dark:border-[var(--dash-border)]">
<span className="mb-2 flex h-8 w-8 items-center justify-center rounded-md bg-red-50 text-red-600 dark:bg-red-500/15">
<g.icon className="h-4 w-4" />
</span>
<h4 className="mb-1.5 text-xs font-bold text-slate-900 dark:text-[var(--dash-text-strong)]">{g.title}</h4>
<p className="text-[11px] leading-snug text-slate-500 dark:text-[var(--dash-text-sec)]">{g.text}</p>
</div>
))}
</div>
</Card>
</div>
{/* 2. 处置建议表 + 关键事态 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
{/* 处置建议 */}
<Card className="flex flex-col lg:col-span-8">
<CardTitle icon={ClipboardList} title="处置建议" />
<div className="flex-1 px-4 py-3.5">
<Table head={["序号", "建议内容", "时序", "处置主体", "口径要素", "处置方式", "预期效果", "立场依据"]}>
{DISPOSALS.map((d) => (
<tr key={d.no}>
<Td className="font-mono text-slate-400">{d.no}</Td>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{d.content}</Td>
<Td className="whitespace-nowrap text-slate-500 dark:text-[var(--dash-text-sec)]">{d.timing}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{d.subject}</Td>
<Td className="whitespace-nowrap text-slate-500 dark:text-[var(--dash-text-sec)]">{d.caliber}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{d.method}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{d.effect}</Td>
<Td className="whitespace-nowrap text-slate-500 dark:text-[var(--dash-text-sec)]">{d.basis}</Td>
</tr>
))}
</Table>
</div>
<FooterNote label="说明">
上述处置应在法治框架内规范实施,统筹线上线下,确保快速反应、综合施策。
</FooterNote>
</Card>
{/* 关键事态 */}
<Card className="flex flex-col lg:col-span-4">
<CardTitle icon={AlertTriangle} title="关键事态" />
<ul className="flex-1 space-y-3 px-4 py-3.5">
{EVENTS.map((e) => (
<li key={e.no} className="flex gap-2.5">
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-600 text-[11px] font-bold text-white">
{e.no}
</span>
<div className="min-w-0 flex-1">
<div className="text-xs font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{e.title}</div>
<div className="mt-1 flex items-center gap-2 text-[11px] text-slate-400 dark:text-[var(--dash-text-dim)]">
<span className="font-mono">{e.time}</span>
<span>影响</span>
<Tag tone={e.impactTone}>{e.impact}</Tag>
</div>
</div>
</li>
))}
</ul>
<FooterNote label="提示">关键事态需密切跟踪,及时研判处置。</FooterNote>
</Card>
</div>
</div>
);
}
// ── 真实数据渲染 ──────────────────────────────────────────────────────────────
function DisposalReal({ data }: { data: DisposalData }) {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 目标 + 处置总结 */}
{(data.goal || data.summary) && (
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
{data.goal && (
<Card className="flex flex-col">
<CardTitle icon={Flag} title="目标" />
<div className="flex-1 px-4 py-3.5">
<p className="text-xs leading-relaxed text-slate-600 dark:text-[var(--dash-text)]">{data.goal}</p>
</div>
</Card>
)}
{data.summary && (
<Card className="flex flex-col">
<CardTitle icon={ClipboardCheck} title="处置建议总结" />
<div className="flex-1 px-4 py-3.5">
<p className="rounded border-l-2 border-red-500 bg-red-50 px-3 py-2.5 text-xs leading-relaxed text-slate-700 dark:bg-red-500/10 dark:text-[var(--dash-text)]">
{data.summary}
</p>
</div>
</Card>
)}
</div>
)}
{/* 处置建议:每条建议一张卡片(建议内容作标题 + 其余字段做带标签的两列网格),
替代原 7 列大表——内容多时更易读、不再拥挤。 */}
{data.items.length > 0 && (
<Card>
<CardTitle icon={ClipboardList} title="处置建议" />
<div className="space-y-3 px-4 py-3.5">
{data.items.map((d, i) => (
<div
key={i}
className="rounded-md border border-slate-200 bg-slate-50/60 p-4 dark:border-[var(--dash-border)] dark:bg-[var(--dash-elev)]"
>
{/* 标题行:序号 + 建议内容 + 口径基调 */}
<div className="mb-3 flex items-start gap-2.5">
<span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-600 text-[11px] font-bold text-white">
{i + 1}
</span>
<div className="min-w-0 flex-1 text-xs font-semibold leading-relaxed text-slate-800 dark:text-[var(--dash-text-strong)]">
{d.content || "—"}
</div>
{d.tone && (
<span className="shrink-0">
<Tag tone="amber">{d.tone}</Tag>
</span>
)}
</div>
{/* 其余字段:带标签两列网格 */}
{(d.method || d.effect || d.subject || d.basis) && (
<dl className="grid grid-cols-1 gap-x-6 gap-y-2.5 border-t border-dashed border-slate-200 pt-3 dark:border-[var(--dash-border)] sm:grid-cols-2">
{d.method && <Field label="处置方式与步骤" value={d.method} />}
{d.effect && <Field label="预期效果" value={d.effect} />}
{d.subject && <Field label="主责单位" value={d.subject} />}
{d.basis && <Field label="立场与原则" value={d.basis} />}
</dl>
)}
</div>
))}
</div>
</Card>
)}
</div>
);
}
/** 处置建议卡片里的「标签 + 值」字段(标签红色小字,值正文)。 */
function Field({ label, value }: { label: string; value: string }) {
const ds = useDesensitize();
return (
<div className="text-xs">
<dt className="mb-0.5 font-semibold text-[#222222] dark:text-[var(--dash-text-strong)]">{ds(label)}</dt>
<dd className="leading-relaxed text-slate-600 dark:text-[var(--dash-text)]">{value}</dd>
</div>
);
}
@@ -0,0 +1,334 @@
/**
* 「大屏绘制智能体」敌情页 —— 敌情详情版式(按设计图 dp-2.png 一比一实现)。
*
* **dashboard-agent 独占**:作为 DashboardApp `pages` 插槽里「敌情」Tab 的内容,
* 不影响多智能体会商(Step3)大屏多页的样式。当前为「静态页面」,文案为占位内容,
* 动态数据后续接入。版式包含:
* 1. 敌方目标表 + 关键事件表(上排两栏)
* 2. 对手叙事表(整行)
* 3. 重点关注对象表 + 传播渠道分析 + 风险热度研判(下排三栏)
*/
import { Target, CalendarClock, Users, Crosshair, Share2, Activity, ArrowUp } from "lucide-react";
import { Card, CardTitle, HeadBadge, Tag, Table, Td, FooterNote, NoData, type Tone } from "@/roundtable-planning/dashboard-agent/ui";
import type { EnemyData } from "@/roundtable-planning/dashboard-agent/sq-report";
// ── 占位数据 ──────────────────────────────────────────────────────────────────
interface EnemyTarget {
no: number;
name: string;
count: string;
gap: string;
gapTone: Tone;
note: string;
}
const TARGETS: EnemyTarget[] = [
{ no: 1, name: "战略级", count: "2 个", gap: "+2", gapTone: "red", note: "查实战略意义重大的目标节点" },
{ no: 2, name: "战役级", count: "3 个", gap: "+1", gapTone: "red", note: "重要枢纽与指挥控制节点" },
{ no: 3, name: "战术级", count: "5 个", gap: "-2", gapTone: "green", note: "前沿火力点 / 机动单元" },
{ no: 4, name: "支援级", count: "4 个", gap: "持平", gapTone: "slate", note: "后勤与通信保障目标" },
{ no: 5, name: "关键人员", count: "78 人", gap: "+3", gapTone: "red", note: "专家与高级指挥人员,重点关注" },
];
interface KeyEvent {
time: string;
title: string;
brief: string;
impact: string;
impactTone: Tone;
}
const EVENTS: KeyEvent[] = [
{ time: "05-16 09:30", title: "对我方侦察活动加强", brief: "敌多个 APT 组织对我重点系统进行扫描探测", impact: "高", impactTone: "red" },
{ time: "05-16 08:45", title: "北部方向兵力调动", brief: "北部出现兵力机动迹象,向前沿地域集结", impact: "高", impactTone: "red" },
{ time: "05-15 21:10", title: "增设通信节点", brief: "增设若干临时通信节点,提升指挥保障", impact: "中", impactTone: "amber" },
{ time: "05-15 13:05", title: "网络渗透扫描", brief: "针对我政务与能源系统的渗透扫描频度上升", impact: "高", impactTone: "red" },
];
interface Narrative {
name: string;
view: string;
intent: string;
channel: string;
audience: string;
heat: string;
trend: string;
trendTone: Tone;
}
const NARRATIVES: Narrative[] = [
{ name: "主导叙事", view: "渲染我方为地区紧张根源", intent: "争夺道义高地、动员国际舆论", channel: "境外主流媒体 / 社交平台", audience: "国际受众 / 中立国家", heat: "高", trend: "上升", trendTone: "red" },
{ name: "配套舆论", view: "夸大我方军事活动威胁", intent: "制造焦虑、离间区域关系", channel: "本地社交媒体矩阵", audience: "周边民众", heat: "中", trend: "上升", trendTone: "red" },
{ name: "情绪动员", view: "煽动对立与不满情绪", intent: "削弱我方内部凝聚力", channel: "短视频 / 论坛", audience: "青年群体", heat: "中", trend: "持平", trendTone: "slate" },
];
interface FocusObject {
no: number;
name: string;
category: string;
relevance: number;
relTone: Tone;
status: string;
statusTone: Tone;
}
const FOCUS: FocusObject[] = [
{ no: 1, name: "红方网络安全组织", category: "组织", relevance: 88, relTone: "red", status: "高度活跃", statusTone: "red" },
{ no: 2, name: "东方某无人机部队", category: "部队", relevance: 82, relTone: "red", status: "活跃", statusTone: "amber" },
{ no: 3, name: "北部战区通信枢纽", category: "设施", relevance: 76, relTone: "amber", status: "监控中", statusTone: "amber" },
{ no: 4, name: "某舆论账号矩阵", category: "媒体", relevance: 70, relTone: "amber", status: "活跃", statusTone: "amber" },
{ no: 5, name: "海外某情报机构", category: "机构", relevance: 65, relTone: "slate", status: "持续观察", statusTone: "slate" },
];
interface Channel {
name: string;
pct: number;
desc: string;
}
const CHANNELS: Channel[] = [
{ name: "即时通讯类", pct: 38, desc: "封闭式扩散,溯源难度大" },
{ name: "社交媒体类", pct: 27, desc: "扩散速度快、覆盖面广" },
{ name: "论坛 / 贴吧", pct: 16, desc: "话题沉淀、舆论发酵" },
{ name: "视频平台", pct: 12, desc: "情绪煽动性强" },
{ name: "其他渠道", pct: 7, desc: "小范围定向传播" },
];
const RISK_POINTS = [
"网络攻击与渗透风险偏高,关键系统面临持续探测。",
"信息渗透与认知作战风险上升,舆论环境复杂。",
"前沿方向摩擦风险存在,需防范局部突发事件。",
];
const RISK_CONCLUSION = "当前风险整体呈上升态势,须重点防范网络与认知域,强化预警与协同处置。";
// ── 主组件(有真实数据走真实渲染,否则回退静态占位) ─────────────────────────────
export function EnemyDetail({ data }: { data?: EnemyData | null }) {
return data ? <EnemyReal data={data} /> : <NoData />;
}
function EnemyPlaceholder() {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 1. 上排:敌方目标 + 关键事件 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
{/* 敌方目标 */}
<Card className="flex flex-col lg:col-span-5">
<CardTitle
icon={Target}
title="敌方目标"
badges={
<>
<HeadBadge label="组织目标" value="12 个" />
<HeadBadge label="人员目标" value="78 人" />
</>
}
/>
<div className="flex-1 px-4 py-3.5">
<Table head={["编号", "名称", "数量", "缺口", "状态说明"]}>
{TARGETS.map((t) => (
<tr key={t.no}>
<Td className="font-mono text-slate-400">{t.no}</Td>
<Td className="font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{t.name}</Td>
<Td className="font-mono">{t.count}</Td>
<Td>
<Tag tone={t.gapTone}>{t.gap}</Tag>
</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.note}</Td>
</tr>
))}
</Table>
</div>
</Card>
{/* 关键事件 */}
<Card className="flex flex-col lg:col-span-7">
<CardTitle icon={CalendarClock} title="关键事件" />
<div className="flex-1 px-4 py-3.5">
<Table head={["时间", "标题", "内容摘要", "影响评估"]}>
{EVENTS.map((e) => (
<tr key={e.time}>
<Td className="whitespace-nowrap font-mono text-slate-400">{e.time}</Td>
<Td className="font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{e.title}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{e.brief}</Td>
<Td>
<Tag tone={e.impactTone}>{e.impact}</Tag>
</Td>
</tr>
))}
</Table>
</div>
<FooterNote label="事件说明">
近期事件以网络空间动作与军事活动配合为主,整体风险趋升,需持续跟踪重点节点。
</FooterNote>
</Card>
</div>
{/* 2. 对手叙事(整行) */}
<Card>
<CardTitle icon={Users} title="对手叙事" />
<div className="px-4 py-3.5">
<Table head={["名称", "主要观点", "叙事意图", "使用渠道", "受众群体", "热度", "影响烈度"]}>
{NARRATIVES.map((n) => (
<tr key={n.name}>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{n.name}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{n.view}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{n.intent}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{n.channel}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{n.audience}</Td>
<Td>
<Tag tone={n.heat === "高" ? "red" : n.heat === "中" ? "amber" : "slate"}>{n.heat}</Tag>
</Td>
<Td>
<Tag tone={n.trendTone}>{n.trend}</Tag>
</Td>
</tr>
))}
</Table>
</div>
<FooterNote label="叙事说明">
对手叙事以「去式化行动」「外部归因」为核心,须以精准事实与权威信息及时反制,压缩其传播空间。
</FooterNote>
</Card>
{/* 3. 下排:重点关注对象 + 传播渠道分析 + 风险热度研判 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
{/* 重点关注对象 */}
<Card className="flex flex-col">
<CardTitle icon={Crosshair} title="重点关注对象" />
<div className="flex-1 px-4 py-3.5">
<Table head={["编号", "名称", "类别", "相关度", "状态"]}>
{FOCUS.map((f) => (
<tr key={f.no}>
<Td className="font-mono text-slate-400">{f.no}</Td>
<Td className="font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{f.name}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{f.category}</Td>
<Td>
<span className={`font-mono font-bold ${f.relTone === "red" ? "text-red-600" : f.relTone === "amber" ? "text-amber-600" : "text-slate-500"}`}>
{f.relevance}%
</span>
</Td>
<Td>
<Tag tone={f.statusTone}>{f.status}</Tag>
</Td>
</tr>
))}
</Table>
</div>
</Card>
{/* 传播渠道分析 */}
<Card className="flex flex-col">
<CardTitle icon={Share2} title="传播渠道分析(文字化)" />
<ul className="flex-1 space-y-3 px-4 py-3.5">
{CHANNELS.map((c) => (
<li key={c.name}>
<div className="mb-1 flex items-baseline justify-between gap-2 text-xs">
<span className="font-semibold text-slate-700 dark:text-[var(--dash-text-strong)]">{c.name}</span>
<span className="font-mono font-bold text-red-600">{c.pct}%</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-slate-100 dark:bg-white/10">
<div className="h-full rounded-full bg-red-500" style={{ width: `${c.pct}%` }} />
</div>
<div className="mt-1 text-[11px] leading-snug text-slate-400 dark:text-[var(--dash-text-dim)]">{c.desc}</div>
</li>
))}
</ul>
</Card>
{/* 风险热度研判 */}
<Card className="flex flex-col">
<CardTitle icon={Activity} title="风险热度研判(文字化)" />
<div className="flex-1 px-4 py-3.5">
<div className="mb-3 flex items-center justify-between rounded-md bg-red-50 px-3 py-2.5 dark:bg-red-500/10">
<span className="text-xs font-semibold text-slate-700 dark:text-[var(--dash-text-strong)]">总体风险等级</span>
<span className="inline-flex items-center gap-1 text-sm font-bold text-red-600">
<ArrowUp className="h-4 w-4" />
上升 1 级
</span>
</div>
<div className="mb-2 text-[11px] font-semibold text-red-600">主要风险点</div>
<ul className="space-y-2">
{RISK_POINTS.map((p) => (
<li key={p} className="flex gap-1.5 text-xs leading-snug text-slate-600 dark:text-[var(--dash-text)]">
<span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-red-500" />
{p}
</li>
))}
</ul>
</div>
<FooterNote label="研判结论">{RISK_CONCLUSION}</FooterNote>
</Card>
</div>
</div>
);
}
// ── 真实数据渲染 ──────────────────────────────────────────────────────────────
function EnemyReal({ data }: { data: EnemyData }) {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{data.targets.length > 0 && (
<Card>
<CardTitle icon={Target} title="敌方目标" badges={<HeadBadge label="目标数" value={`${data.targets.length}`} />} />
<div className="flex-1 px-4 py-3.5">
<Table head={["名称", "类别", "说明"]}>
{data.targets.map((t, i) => (
<tr key={i}>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{t.name}</Td>
<Td className="whitespace-nowrap text-slate-500 dark:text-[var(--dash-text-sec)]">{t.category || "—"}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.note || "—"}</Td>
</tr>
))}
</Table>
</div>
</Card>
)}
{data.narratives.length > 0 && (
<Card>
<CardTitle icon={Users} title="对手叙事" />
<div className="flex-1 px-4 py-3.5">
<Table head={["主题", "叙事方", "叙事意图", "类型", "概述"]}>
{data.narratives.map((n, i) => (
<tr key={i}>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{n.topic || "—"}</Td>
<Td className="whitespace-nowrap text-slate-500 dark:text-[var(--dash-text-sec)]">{n.narrator || "—"}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{n.intention || "—"}</Td>
<Td className="whitespace-nowrap text-slate-500 dark:text-[var(--dash-text-sec)]">{n.type || "—"}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{n.summary || "—"}</Td>
</tr>
))}
</Table>
</div>
</Card>
)}
{data.events.length > 0 && (
<Card>
<CardTitle icon={CalendarClock} title="关键事件" />
{/* 时间线样式(参考示例图):左侧一条竖线,每个事件一个红点节点;时间在节点旁,
标题/摘要放进右侧浅底小卡。仅用已有字段(时间/标题/摘要),不加图片等无数据元素。 */}
<div className="space-y-5 px-4 py-3.5">
{data.events.map((g, i) => (
<div key={i}>
<div className="mb-3 text-xs font-bold text-slate-800 dark:text-[var(--dash-text-strong)]">{g.topic || "事件"}</div>
<ol className="relative ml-2 border-l-2 border-dashed border-slate-300 text-xs dark:border-[var(--dash-border)]">
{g.items.map((e, j) => (
<li key={j} className="mb-5 ml-5 last:mb-0">
<span className="absolute -left-[7px] mt-1 h-3 w-3 rounded-full border-2 border-red-400 bg-red-50 dark:bg-[var(--dash-card)]" />
{e.time && (
<div className="mb-1 font-mono text-[11px] text-slate-400 dark:text-[var(--dash-text-dim)]">{e.time}</div>
)}
<div className="rounded-md border border-slate-200 bg-slate-50 px-3 py-2.5 dark:border-[var(--dash-border)] dark:bg-[var(--dash-elev)]">
<div className="font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{e.title}</div>
{e.brief && <div className="mt-1 leading-relaxed text-slate-500 dark:text-[var(--dash-text-sec)]">{e.brief}</div>}
</div>
</li>
))}
</ol>
</div>
))}
</div>
</Card>
)}
</div>
);
}
@@ -0,0 +1,384 @@
/**
* 「大屏绘制智能体」战场环境页 —— 信息环境 / 人文环境 / 综合研判(按设计图 dp-4.png 一比一实现)。
*
* **dashboard-agent 独占**:作为 DashboardApp `pages` 插槽里「战场环境」Tab 的内容,
* 不影响多智能体会商(Step3)大屏多页的样式。当前为「静态页面」,文案为占位内容,
* 动态数据后续接入。版式包含:
* 1. 顶部 5 个环境指数卡
* 2. 信息环境(5 栏维度卡:媒体生态 / 平台分布 / 基础设施 / 监管治理 / 受众习惯)
* 3. 人文环境(4 栏维度卡:社会 / 经济 / 舆论 / 文化)
* 4. 环境综合研判 + 信息来源与参考
*/
import {
Activity,
AlertTriangle,
Network,
AlertOctagon,
BarChart3,
Tv,
LayoutGrid,
Server,
ShieldCheck,
Users,
Building2,
Coins,
MessageSquare,
BookOpen,
Lightbulb,
FileText,
TrendingUp,
TrendingDown,
Minus,
type LucideIcon,
} from "lucide-react";
import { Card, CardTitle, FooterNote, Table, Td, Tag, NoData, useDesensitize, type Tone } from "@/roundtable-planning/dashboard-agent/ui";
import type { EnvData, EnvSection } from "@/roundtable-planning/dashboard-agent/sq-report";
// ── 占位数据 ──────────────────────────────────────────────────────────────────
type Trend = "up" | "down" | "flat";
interface Kpi {
label: string;
value: string;
icon: LucideIcon;
delta: string;
trend: Trend;
}
const KPIS: Kpi[] = [
{ label: "信息活跃度指数", value: "78.6", icon: Activity, delta: "+3.4", trend: "up" },
{ label: "舆论风险指数", value: "64.2", icon: AlertTriangle, delta: "+5.1", trend: "up" },
{ label: "网络连接通畅率", value: "58.7%", icon: Network, delta: "+2.3", trend: "up" },
{ label: "虚假信息占比", value: "23.6%", icon: AlertOctagon, delta: "-1.8", trend: "down" },
{ label: "关键平台覆盖率", value: "92.4%", icon: BarChart3, delta: "+0.6", trend: "up" },
];
interface EnvRow {
label: string;
value: string;
tone: Tone;
}
interface EnvField {
icon: LucideIcon;
title: string;
rows: EnvRow[];
assessLabel: string;
assessment: string;
}
const INFO_ENV: EnvField[] = [
{
icon: Tv,
title: "媒体生态分布",
rows: [
{ label: "主流媒体", value: "高", tone: "red" },
{ label: "自媒体", value: "高", tone: "red" },
{ label: "社交平台", value: "高", tone: "red" },
{ label: "境外媒体", value: "中", tone: "amber" },
{ label: "传统媒体", value: "中", tone: "amber" },
],
assessLabel: "总体评估",
assessment: "媒体生态多元,信息传播活跃。",
},
{
icon: LayoutGrid,
title: "平台分布",
rows: [
{ label: "即时通讯", value: "高", tone: "red" },
{ label: "社交媒体", value: "高", tone: "red" },
{ label: "视频平台", value: "高", tone: "red" },
{ label: "论坛社区", value: "中", tone: "amber" },
{ label: "新闻门户", value: "中", tone: "amber" },
],
assessLabel: "总体评估",
assessment: "平台覆盖广泛,传播路径多样。",
},
{
icon: Server,
title: "基础设施状况",
rows: [
{ label: "网络覆盖", value: "良好", tone: "green" },
{ label: "带宽容量", value: "充足", tone: "green" },
{ label: "移动网络", value: "良好", tone: "green" },
{ label: "数据中心", value: "稳定", tone: "green" },
{ label: "电力保障", value: "稳定", tone: "green" },
],
assessLabel: "总体评估",
assessment: "基础设施完备,保障能力强。",
},
{
icon: ShieldCheck,
title: "信息监管与治理",
rows: [
{ label: "内容审核", value: "较强", tone: "green" },
{ label: "谣言治理", value: "较强", tone: "green" },
{ label: "平台自律", value: "一般", tone: "slate" },
{ label: "跨境监管", value: "较弱", tone: "amber" },
],
assessLabel: "总体评估",
assessment: "治理体系较完善,执行力度持续提升。",
},
{
icon: Users,
title: "受众信息接触习惯",
rows: [
{ label: "移动端为主", value: "高", tone: "red" },
{ label: "短视频主导", value: "高", tone: "red" },
{ label: "信息甄别能力", value: "中", tone: "amber" },
{ label: "权威信息依赖", value: "中", tone: "amber" },
],
assessLabel: "总体评估",
assessment: "触达渠道广泛,注意力相对分散。",
},
];
const HUMAN_ENV: EnvField[] = [
{
icon: Building2,
title: "社会环境",
rows: [
{ label: "社会稳定度", value: "良好", tone: "green" },
{ label: "社会矛盾", value: "可控", tone: "amber" },
{ label: "民族宗教", value: "稳定", tone: "green" },
{ label: "城乡发展", value: "一般", tone: "slate" },
],
assessLabel: "评估结论",
assessment: "社会大局稳定,整体可控。",
},
{
icon: Coins,
title: "经济基础",
rows: [
{ label: "经济发展水平", value: "良好", tone: "green" },
{ label: "产业结构", value: "一般", tone: "slate" },
{ label: "就业形势", value: "一般", tone: "slate" },
{ label: "居民收入", value: "一般", tone: "slate" },
],
assessLabel: "评估结论",
assessment: "经济运行平稳,韧性较强。",
},
{
icon: MessageSquare,
title: "社会舆论",
rows: [
{ label: "主流舆论引导", value: "有效", tone: "green" },
{ label: "网络情绪", value: "一般", tone: "amber" },
{ label: "热点话题", value: "活跃", tone: "red" },
{ label: "意见多样性", value: "较强", tone: "amber" },
],
assessLabel: "评估结论",
assessment: "舆论总体平稳,热点多发。",
},
{
icon: BookOpen,
title: "文化环境",
rows: [
{ label: "文化认同", value: "较强", tone: "green" },
{ label: "价值观主流", value: "稳定", tone: "green" },
{ label: "文化多元", value: "一般", tone: "slate" },
{ label: "文化渗透风险", value: "中", tone: "amber" },
],
assessLabel: "评估结论",
assessment: "文化主流稳定,需防外来渗透。",
},
];
const REVIEW = [
"信息环境高度活跃,传播速度快、覆盖面广,主流舆论引导总体有效,但虚假信息与噪声并存。",
"网络基础设施完备、平台多元,为信息传播与舆论引导提供良好支撑,需防范境外渗透。",
"社会大局稳定,经济运行平稳,人文环境总体向好,为我方舆论工作提供有利条件。",
"综合研判:当前战场信息环境总体有利,须强化内容供给与精准引导,压缩虚假信息空间。",
];
interface SourceRow {
name: string;
type: string;
trust: string;
trustTone: Tone;
updated: string;
}
const SOURCES: SourceRow[] = [
{ name: "全网舆情监测平台", type: "舆情", trust: "高", trustTone: "green", updated: "2025-05-16 10:20" },
{ name: "媒体监测系统", type: "媒体", trust: "高", trustTone: "green", updated: "2025-05-16 10:00" },
{ name: "社交平台数据接口", type: "社交", trust: "中", trustTone: "amber", updated: "2025-05-16 09:40" },
{ name: "行业研究报告", type: "第三方", trust: "中", trustTone: "amber", updated: "2025-05-15 18:00" },
{ name: "公开统计数据", type: "官方", trust: "高", trustTone: "green", updated: "2025-05-14 16:00" },
];
const TREND_ICON: Record<Trend, LucideIcon> = { up: TrendingUp, down: TrendingDown, flat: Minus };
const TREND_COLOR: Record<Trend, string> = { up: "text-red-600", down: "text-emerald-600", flat: "text-slate-400" };
const VAL_COLOR: Record<Tone, string> = {
red: "text-red-600",
amber: "text-amber-600",
green: "text-emerald-600",
blue: "text-sky-600",
slate: "text-slate-400 dark:text-[var(--dash-text-dim)]",
};
// ── 主组件(有真实数据走真实渲染,否则回退静态占位) ─────────────────────────────
export function EnvironmentDetail({ data }: { data?: EnvData | null }) {
return data ? <EnvReal data={data} /> : <NoData />;
}
function EnvPlaceholder() {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 1. 顶部 5 个环境指数卡 */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
{KPIS.map((k) => {
const TrendIco = TREND_ICON[k.trend];
return (
<Card key={k.label} className="p-4">
<div className="mb-3 flex items-center gap-2">
<span className="flex h-8 w-8 items-center justify-center rounded-md bg-red-50 text-red-600 dark:bg-red-500/15">
<k.icon className="h-4 w-4" />
</span>
<span className="text-xs font-medium text-slate-500 dark:text-[var(--dash-text-sec)]">{k.label}</span>
</div>
<div className="font-mono text-3xl font-black leading-none text-slate-900 dark:text-[var(--dash-text-strong)]">
{k.value}
</div>
<div className="mt-2 flex items-center gap-1 text-[11px] text-slate-400 dark:text-[var(--dash-text-dim)]">
<span>较昨日</span>
<span className={`inline-flex items-center gap-0.5 font-semibold ${TREND_COLOR[k.trend]}`}>
<TrendIco className="h-3 w-3" />
{k.delta}
</span>
</div>
</Card>
);
})}
</div>
{/* 2. 信息环境(5 栏) */}
<SectionLabel>信息环境</SectionLabel>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-5">
{INFO_ENV.map((f) => (
<EnvCard key={f.title} field={f} />
))}
</div>
{/* 3. 人文环境(4 栏) */}
<SectionLabel>人文环境</SectionLabel>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
{HUMAN_ENV.map((f) => (
<EnvCard key={f.title} field={f} />
))}
</div>
{/* 4. 环境综合研判 + 信息来源与参考 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
<Card className="flex flex-col lg:col-span-7">
<CardTitle icon={Lightbulb} title="环境综合研判" />
<ol className="flex-1 space-y-3 px-4 py-3.5">
{REVIEW.map((r, i) => (
<li key={r} className="flex gap-2.5 text-[13px] leading-relaxed">
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-600 text-[11px] font-bold text-white">
{i + 1}
</span>
<span className="text-slate-600 dark:text-[var(--dash-text)]">{r}</span>
</li>
))}
</ol>
</Card>
<Card className="flex flex-col lg:col-span-5">
<CardTitle icon={FileText} title="信息来源与参考" />
<div className="flex-1 px-4 py-3.5">
<Table head={["来源名称", "类型", "可信度", "更新时间"]}>
{SOURCES.map((s) => (
<tr key={s.name}>
<Td className="font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{s.name}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{s.type}</Td>
<Td>
<Tag tone={s.trustTone}>{s.trust}</Tag>
</Td>
<Td className="whitespace-nowrap font-mono text-slate-400">{s.updated}</Td>
</tr>
))}
</Table>
</div>
<FooterNote label="说明">可信度分为高 / 中 / 低,时效性以最新更新时间为准,综合研判时按权重折算。</FooterNote>
</Card>
</div>
</div>
);
}
/** 环境维度卡(红色标题 + 键值行 + 评估脚注)。 */
function EnvCard({ field }: { field: EnvField }) {
return (
<Card className="flex flex-col">
<CardTitle icon={field.icon} title={field.title} />
<div className="flex-1 px-4 py-3.5">
<dl className="space-y-2">
{field.rows.map((r) => (
<div key={r.label} className="flex items-center justify-between gap-2 text-xs">
<dt className="text-slate-400 dark:text-[var(--dash-text-dim)]">{r.label}</dt>
<dd className={`font-semibold ${VAL_COLOR[r.tone]}`}>{r.value}</dd>
</div>
))}
</dl>
</div>
<FooterNote label={field.assessLabel}>{field.assessment}</FooterNote>
</Card>
);
}
/** 行级区段标题(红色竖条 + 文字)。 */
function SectionLabel({ children }: { children: React.ReactNode }) {
const ds = useDesensitize();
return (
<div className="flex items-center gap-2 pt-1 text-sm font-bold text-slate-900 dark:text-[var(--dash-text-strong)]">
<span className="h-3.5 w-1 rounded-full bg-red-600" />
{typeof children === "string" ? ds(children) : children}
</div>
);
}
// ── 真实数据渲染 ──────────────────────────────────────────────────────────────
function EnvReal({ data }: { data: EnvData }) {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{data.info.length > 0 && (
<>
<SectionLabel>信息环境</SectionLabel>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{data.info.map((s, i) => (
<EnvTextCard key={i} section={s} />
))}
</div>
</>
)}
{data.human.length > 0 && (
<>
<SectionLabel>人文环境</SectionLabel>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{data.human.map((s, i) => (
<EnvTextCard key={i} section={s} />
))}
</div>
</>
)}
</div>
);
}
/** 环境文本维度卡(标题 + 段落要点)。 */
function EnvTextCard({ section }: { section: EnvSection }) {
return (
<Card className="flex flex-col">
<CardTitle icon={FileText} title={section.title} />
<ul className="flex-1 space-y-2 px-4 py-3.5">
{section.paragraphs.map((p, i) => (
<li key={i} className="flex gap-2 text-xs leading-relaxed">
<span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-red-500" />
<span className="text-slate-600 dark:text-[var(--dash-text)]">{p}</span>
</li>
))}
</ul>
</Card>
);
}
@@ -0,0 +1,365 @@
/**
* 「大屏绘制智能体」情况判断页 —— 敌我优劣 / 条件限制 / 风险应对 / 综合研判
* (按设计图 dp-5.png 一比一实现)。
*
* **dashboard-agent 独占**:作为 DashboardApp `pages` 插槽里「情况判断」Tab 的内容,
* 不影响多智能体会商(Step3)大屏多页的样式。当前为「静态页面」,文案为占位内容,
* 动态数据后续接入。版式包含:
* 1. 敌我优劣势分析(敌方优势/劣势 + 我方优势/劣势 四张要点卡)
* 2. 条件与限制(资源/法理/政治/时间 四张约束键值卡)
* 3. 风险与应对(风险表)+ 判断结论(综合研判)
*/
import { Swords, ShieldX, ShieldCheck, ShieldAlert, Package, Scale, Landmark, Clock, AlertTriangle, Gavel, type LucideIcon } from "lucide-react";
import { Card, CardTitle, FooterNote, Table, Td, Tag, Val, NoData, MarkdownText, useDesensitize, type Tone } from "@/roundtable-planning/dashboard-agent/ui";
import type { JudgeData } from "@/roundtable-planning/dashboard-agent/sq-report";
// ── 占位数据 ──────────────────────────────────────────────────────────────────
interface BulletCardData {
icon: LucideIcon;
title: string;
items: string[];
}
const SWOT: BulletCardData[] = [
{
icon: Swords,
title: "敌方优势",
items: [
"火力密度大,远程打击能力强",
"信息系统较完善,情报获取渠道多",
"机动能力强,可快速集结兵力",
"体系作战能力较强,协同较成熟",
],
},
{
icon: ShieldX,
title: "敌方劣势",
items: [
"地形适应性差,山地作战能力不足",
"部队协同较弱,指挥链路较长",
"兵力部署分散,防御纵深不足",
"后勤补给线长,维护保障压力大",
],
},
{
icon: ShieldCheck,
title: "我方优势",
items: [
"占据有利地形,防御体系完备",
"群众基础好,保障支援能力强",
"部队士气高昂,战斗意志坚定",
"熟悉地形地貌,机动灵活",
],
},
{
icon: ShieldAlert,
title: "我方劣势",
items: [
"远程火力相对不足,打击体系待完善",
"部分装备老化,信息化程度待提升",
"防空反导能力有限,制空压力较大",
"特定方向兵力薄弱,需重点加强",
],
},
];
interface KvRow {
label: string;
value: string;
tone: Tone;
}
interface ConstraintData {
icon: LucideIcon;
title: string;
rows: KvRow[];
footer: string;
}
const CONSTRAINTS: ConstraintData[] = [
{
icon: Package,
title: "资源约束",
rows: [
{ label: "弹药储备", value: "充足", tone: "green" },
{ label: "燃油保障", value: "适中", tone: "amber" },
{ label: "医疗资源", value: "紧张", tone: "red" },
{ label: "兵员补充", value: "适中", tone: "amber" },
{ label: "通信物资", value: "适中", tone: "amber" },
],
footer: "资源总体可支撑当前作战,医疗与持续保障需重点关注。",
},
{
icon: Scale,
title: "法理约束",
rows: [
{ label: "作战法理依据", value: "符合", tone: "green" },
{ label: "国际人道法", value: "合规", tone: "green" },
{ label: "平民保护责任", value: "严格", tone: "red" },
{ label: "舆论道义争取", value: "有利", tone: "green" },
],
footer: "行动总体合法合规,应在法理框架内规范实施。",
},
{
icon: Landmark,
title: "政治约束",
rows: [
{ label: "政治敏感度", value: "高", tone: "red" },
{ label: "对外关系影响", value: "中", tone: "amber" },
{ label: "国内舆论支持", value: "较高", tone: "green" },
{ label: "国际舆论环境", value: "一般", tone: "slate" },
],
footer: "政治考量需贯穿全程,注重舆论与外交配合。",
},
{
icon: Clock,
title: "时间约束",
rows: [
{ label: "现有作战窗口", value: "36 小时内", tone: "red" },
{ label: "兵力集结时限", value: "48 小时内", tone: "amber" },
{ label: "后勤展开时间", value: "72 小时内", tone: "amber" },
{ label: "上级决心时限", value: "60 小时内", tone: "amber" },
],
footer: "时间窗口偏紧,须加快决策与力量展开。",
},
];
interface RiskRow {
item: string;
level: string;
levelTone: Tone;
impact: string;
plan: string;
}
const RISKS: RiskRow[] = [
{ item: "敌火力突袭风险", level: "高", levelTone: "red", impact: "前沿阵地与人员装备损失", plan: "强化伪装防护与机动疏散" },
{ item: "敌增援兵力介入", level: "中", levelTone: "amber", impact: "局部兵力对比变化", plan: "预置阻援力量,封控通道" },
{ item: "通信干扰破坏", level: "中", levelTone: "amber", impact: "指挥效率下降", plan: "启用备份链路与抗扰手段" },
{ item: "网络攻击渗透", level: "高", levelTone: "red", impact: "信息系统受损", plan: "加固防护,分区隔离" },
{ item: "舆论造谣攻击", level: "低", levelTone: "green", impact: "局部认知影响", plan: "及时澄清,权威发声" },
];
interface StatBlock {
value: string;
caption: string;
}
const CONCLUSION_STATS: StatBlock[] = [
{ value: "我方占优", caption: "敌我对比" },
{ value: "中高", caption: "整体风险" },
{ value: "积极进取", caption: "决策倾向" },
];
const CONCLUSION_POINTS = [
"当前总体态势有利,敌方兵力行动受牵制。",
"我方占据地利与人和,具备掌握主动的条件。",
];
const CONCLUSION = "总体态势有利,敌方行动受牵制;建议积极把握主动,稳中求进、择机而动。";
// ── 主组件(有真实数据走真实渲染,否则回退静态占位) ─────────────────────────────
export function Judgement({ data }: { data?: JudgeData | null }) {
return data ? <JudgeReal data={data} /> : <NoData />;
}
function JudgePlaceholder() {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 1. 敌我优劣势分析 */}
<NumberedHeading n={1}>敌我优劣势分析</NumberedHeading>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
{SWOT.map((c) => (
<Card key={c.title} className="flex flex-col">
<CardTitle icon={c.icon} title={c.title} />
<ul className="flex-1 space-y-2 px-4 py-3.5">
{c.items.map((it) => (
<li key={it} className="flex gap-2 text-xs leading-relaxed">
<span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-red-600" />
<span className="text-slate-600 dark:text-[var(--dash-text)]">{it}</span>
</li>
))}
</ul>
</Card>
))}
</div>
{/* 2. 条件与限制 */}
<NumberedHeading n={2}>条件与限制</NumberedHeading>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
{CONSTRAINTS.map((c) => (
<Card key={c.title} className="flex flex-col">
<CardTitle icon={c.icon} title={c.title} />
<div className="flex-1 px-4 py-3.5">
<dl className="space-y-2">
{c.rows.map((r) => (
<div key={r.label} className="flex items-center justify-between gap-2 text-xs">
<dt className="text-slate-400 dark:text-[var(--dash-text-dim)]">{r.label}</dt>
<dd>
<Val tone={r.tone}>{r.value}</Val>
</dd>
</div>
))}
</dl>
</div>
<FooterNote label="评估">{c.footer}</FooterNote>
</Card>
))}
</div>
{/* 3. 风险与应对 + 判断结论 */}
<NumberedHeading n={3}>风险与应对</NumberedHeading>
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
{/* 风险与应对表 */}
<Card className="flex flex-col lg:col-span-7">
<CardTitle icon={AlertTriangle} title="风险与应对" />
<div className="flex-1 px-4 py-3.5">
<Table head={["风险事项", "等级", "可能影响", "应对计划"]}>
{RISKS.map((r) => (
<tr key={r.item}>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{r.item}</Td>
<Td>
<Tag tone={r.levelTone}>{r.level}</Tag>
</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{r.impact}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{r.plan}</Td>
</tr>
))}
</Table>
</div>
</Card>
{/* 判断结论(综合研判) */}
<Card className="flex flex-col lg:col-span-5">
<CardTitle icon={Gavel} title="判断结论(综合研判)" />
<div className="flex-1 px-4 py-3.5">
<div className="mb-3 grid grid-cols-3 gap-2">
{CONCLUSION_STATS.map((s) => (
<div key={s.caption} className="rounded-md bg-red-50 px-2 py-3 text-center dark:bg-red-500/10">
<div className="text-sm font-black text-red-600">{s.value}</div>
<div className="mt-1 text-[10px] text-slate-400 dark:text-[var(--dash-text-dim)]">{s.caption}</div>
</div>
))}
</div>
<ul className="space-y-2">
{CONCLUSION_POINTS.map((p) => (
<li key={p} className="flex gap-2 text-xs leading-relaxed">
<span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-red-600" />
<span className="text-slate-600 dark:text-[var(--dash-text)]">{p}</span>
</li>
))}
</ul>
</div>
<FooterNote label="结论">{CONCLUSION}</FooterNote>
</Card>
</div>
</div>
);
}
/** 红色编号区段标题(① 敌我优劣势分析 …)。 */
function NumberedHeading({ n, children }: { n: number; children: React.ReactNode }) {
const ds = useDesensitize();
return (
<div className="flex items-center gap-2 pt-1">
<span className="flex h-5 w-5 items-center justify-center rounded-full bg-red-600 text-[11px] font-bold text-white">
{n}
</span>
<h2 className="text-sm font-bold text-slate-900 dark:text-[var(--dash-text-strong)]">
{typeof children === "string" ? ds(children) : children}
</h2>
</div>
);
}
// ── 真实数据渲染 ──────────────────────────────────────────────────────────────
function SwotCard({ title, icon, items, dot }: { title: string; icon: LucideIcon; items: Array<{ title: string; content: string }>; dot: Tone }) {
const dotColor = dot === "green" ? "bg-emerald-500" : "bg-red-600";
return (
<Card className="flex flex-col">
<CardTitle icon={icon} title={title} />
<ul className="flex-1 space-y-2.5 px-4 py-3.5">
{items.map((it, i) => (
<li key={i} className="flex gap-2 text-xs leading-relaxed">
<span className={`mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full ${dotColor}`} />
<span className="text-slate-600 dark:text-[var(--dash-text)]">
{it.title && <span className="font-bold text-slate-800 dark:text-[var(--dash-text-strong)]">{it.title}:</span>}
{it.content}
</span>
</li>
))}
</ul>
</Card>
);
}
function JudgeReal({ data }: { data: JudgeData }) {
const hasSwot = data.strengths.length > 0 || data.weaknesses.length > 0;
const hasRisk = data.risks.length > 0 || data.responses.length > 0;
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{hasSwot && (
<>
<NumberedHeading n={1}>优劣势分析</NumberedHeading>
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
{data.strengths.length > 0 && <SwotCard title="优势" icon={ShieldCheck} items={data.strengths} dot="green" />}
{data.weaknesses.length > 0 && <SwotCard title="劣势" icon={ShieldAlert} items={data.weaknesses} dot="red" />}
</div>
</>
)}
{data.constraints.length > 0 && (
<>
<NumberedHeading n={2}>条件与限制</NumberedHeading>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
{data.constraints.map((c, i) => (
<Card key={i} className="flex flex-col">
<CardTitle icon={Scale} title={c.title} />
<ul className="flex-1 space-y-2 px-4 py-3.5">
{c.items.map((it, j) => (
<li key={j} className="flex gap-2 text-xs leading-relaxed">
<span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-red-500" />
<span className="text-slate-600 dark:text-[var(--dash-text)]">{it}</span>
</li>
))}
</ul>
</Card>
))}
</div>
</>
)}
{hasRisk && (
<>
<NumberedHeading n={3}>风险与应对</NumberedHeading>
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
{data.risks.length > 0 && (
<Card className="flex flex-col">
<CardTitle icon={AlertTriangle} title="风险分析" />
<ul className="flex-1 space-y-2.5 px-4 py-3.5">
{data.risks.map((r, i) => (
<li key={i} className="flex gap-2 text-xs leading-relaxed">
<span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-red-600" />
<span className="text-slate-600 dark:text-[var(--dash-text)]">{r}</span>
</li>
))}
</ul>
</Card>
)}
{data.responses.length > 0 && (
<Card className="flex flex-col">
<CardTitle icon={Gavel} title="应对方案" />
<ol className="flex-1 space-y-2.5 px-4 py-3.5">
{data.responses.map((r, i) => (
<li key={i} className="flex gap-2 text-xs leading-relaxed">
<span className="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-red-600 text-[10px] font-bold text-white">{i + 1}</span>
<div className="min-w-0 flex-1 text-slate-600 dark:text-[var(--dash-text)]">
<MarkdownText>{r}</MarkdownText>
</div>
</li>
))}
</ol>
</Card>
)}
</div>
</>
)}
</div>
);
}
@@ -0,0 +1,332 @@
/**
* 「大屏绘制智能体」我情页 —— 我方口径 / 叙事 / 任务版式(按设计图 dp-3.png 一比一实现)。
*
* **dashboard-agent 独占**:作为 DashboardApp `pages` 插槽里「我情」Tab 的内容,
* 不影响多智能体会商(Step3)大屏多页的样式。当前为「静态页面」,文案为占位内容,
* 动态数据后续接入。版式包含:
* 1. 口径 + 叙事 + 上级要求(上排三栏)
* 2. 重点发布日历 + 口径关键词 + 传播任务分工速览(下排三栏)
*/
import { MessageSquareQuote, BookText, Star, CalendarDays, Tags, Megaphone } from "lucide-react";
import {
Card,
CardTitle,
CardFooterLink,
Tag,
Table,
Td,
NoData,
useDesensitize,
type Tone,
} from "@/roundtable-planning/dashboard-agent/ui";
import type { OursData } from "@/roundtable-planning/dashboard-agent/sq-report";
// ── 占位数据 ──────────────────────────────────────────────────────────────────
const TONE_META: Array<{ label: string; value: string }> = [
{ label: "创建时间", value: "2025-05-16 10:00" },
{ label: "适用范围", value: "对外宣传、媒体回应、公开发布" },
{ label: "发布层级", value: "公开" },
];
const TONE_POINTS = [
"坚定维护国家主权、安全与领土完整,立场坚定不移。",
"我方始终致力于维护地区和平稳定与共同发展。",
"任何外部势力干涉地区事务的行径都不得人心。",
"呼吁有关各方保持克制,通过对话协商解决分歧。",
];
interface NarrativeRow {
no: number;
title: string;
point: string;
time: string;
}
const NARRATIVES: NarrativeRow[] = [
{ no: 1, title: "维护正当权益", point: "正当维权行为合法合理", time: "05-16 10:00" },
{ no: 2, title: "致力地区和平", point: "始终是和平稳定的建设者", time: "05-16 09:00" },
{ no: 3, title: "倡导对话合作", point: "反对集团对抗与零和博弈", time: "05-15 18:30" },
{ no: 4, title: "揭批外部干涉", point: "外部势力是紧张根源", time: "05-15 14:00" },
];
const ORDERS = [
"坚定政治方向,主动发声,紧贴宣传节奏。",
"强化媒体引导,及时回应社会关切。",
"严守宣传纪律,确保信息口径统一。",
"加强协同联动,形成对外宣传合力。",
];
const ORDER_META: Array<{ label: string; value: string }> = [
{ label: "下发时间", value: "2025-05-16 08:00" },
{ label: "下发单位", value: "联合作战指挥部宣传工作组" },
];
interface CalendarItem {
time: string;
event: string;
status: string;
tone: Tone;
}
const TODAY_PLAN: CalendarItem[] = [
{ time: "09:00", event: "例行新闻发布会", status: "已发布", tone: "green" },
{ time: "14:00", event: "重点新闻通稿", status: "待发布", tone: "amber" },
{ time: "18:00", event: "对外答问口径", status: "待发布", tone: "amber" },
];
const UPCOMING: CalendarItem[] = [
{ time: "05-17 09:00", event: "专题新闻发布会", status: "待发布", tone: "amber" },
{ time: "05-18 10:00", event: "白皮书发布", status: "筹备中", tone: "slate" },
];
interface KeywordGroup {
name: string;
tone: Tone;
words: string[];
}
const KEYWORDS: KeywordGroup[] = [
{ name: "主权安全", tone: "red", words: ["主权", "领土完整", "国家安全", "核心利益"] },
{ name: "和平发展", tone: "green", words: ["和平", "稳定", "合作", "共同发展"] },
{ name: "立场态度", tone: "blue", words: ["坚决", "克制", "正当", "合法合理"] },
];
interface TaskRow {
dept: string;
task: string;
deadline: string;
}
const TASKS: TaskRow[] = [
{ dept: "新闻发布组", task: "组织发布会与新闻通稿", deadline: "当日" },
{ dept: "媒体协调组", task: "协调媒体报道口径", deadline: "持续" },
{ dept: "网络宣传组", task: "网络平台内容推送与监看", deadline: "实时" },
{ dept: "对外传播组", task: "多语种对外发声", deadline: "当日" },
];
// ── 主组件(有真实数据走真实渲染,否则回退静态占位) ─────────────────────────────
export function OurSituation({ data }: { data?: OursData | null }) {
return data ? <OursReal data={data} /> : <NoData />;
}
function OursPlaceholder() {
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 1. 上排:口径 + 叙事 + 上级要求 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
{/* 口径 */}
<Card className="flex flex-col">
<CardTitle icon={MessageSquareQuote} title="口径" />
<div className="flex-1 px-4 py-3.5">
<dl className="mb-3 space-y-1.5">
{TONE_META.map((m) => (
<div key={m.label} className="flex gap-2 text-[11px]">
<dt className="shrink-0 text-slate-400 dark:text-[var(--dash-text-dim)]">{m.label}</dt>
<dd className="text-slate-600 dark:text-[var(--dash-text)]">{m.value}</dd>
</div>
))}
</dl>
<ul className="space-y-2 border-t border-slate-100 pt-3 dark:border-[var(--dash-border)]">
{TONE_POINTS.map((p) => (
<li key={p} className="flex gap-2 text-xs leading-relaxed">
<span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-red-600" />
<span className="text-slate-600 dark:text-[var(--dash-text)]">{p}</span>
</li>
))}
</ul>
</div>
<CardFooterLink>查看完整口径</CardFooterLink>
</Card>
{/* 叙事 */}
<Card className="flex flex-col">
<CardTitle icon={BookText} title="叙事" />
<div className="flex-1 px-4 py-3.5">
<Table head={["编号", "标题", "核心要点", "更新时间"]}>
{NARRATIVES.map((n) => (
<tr key={n.no}>
<Td className="font-mono text-slate-400">{n.no}</Td>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{n.title}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{n.point}</Td>
<Td className="whitespace-nowrap font-mono text-slate-400">{n.time}</Td>
</tr>
))}
</Table>
</div>
<CardFooterLink>查看更多叙事</CardFooterLink>
</Card>
{/* 上级要求 */}
<Card className="flex flex-col">
<CardTitle icon={Star} title="上级要求" />
<ol className="flex-1 space-y-2.5 px-4 py-3.5">
{ORDERS.map((o, i) => (
<li key={o} className="flex gap-2 text-xs leading-relaxed">
<span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-red-600 text-[10px] font-bold text-white">
{i + 1}
</span>
<span className="text-slate-600 dark:text-[var(--dash-text)]">{o}</span>
</li>
))}
</ol>
<dl className="mx-4 mb-3.5 space-y-1.5 rounded bg-slate-50 px-3 py-2.5 dark:bg-white/5">
{ORDER_META.map((m) => (
<div key={m.label} className="flex gap-2 text-[11px]">
<dt className="shrink-0 text-slate-400 dark:text-[var(--dash-text-dim)]">{m.label}</dt>
<dd className="text-slate-600 dark:text-[var(--dash-text)]">{m.value}</dd>
</div>
))}
</dl>
</Card>
</div>
{/* 2. 下排:重点发布日历 + 口径关键词 + 传播任务分工速览 */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
{/* 重点发布日历 */}
<Card className="flex flex-col">
<CardTitle icon={CalendarDays} title="重点发布日历(05-16)" />
<div className="flex-1 space-y-3 px-4 py-3.5">
<CalendarSection title="今日重点发布安排" items={TODAY_PLAN} />
<CalendarSection title="近期重要安排" items={UPCOMING} />
</div>
<CardFooterLink>查看完整日历</CardFooterLink>
</Card>
{/* 口径关键词 */}
<Card className="flex flex-col">
<CardTitle icon={Tags} title="口径关键词" />
<div className="flex-1 space-y-3 px-4 py-3.5">
{KEYWORDS.map((g) => (
<div key={g.name}>
<div className="mb-1.5 text-[11px] font-semibold text-slate-400 dark:text-[var(--dash-text-dim)]">
{g.name}
</div>
<div className="flex flex-wrap gap-1.5">
{g.words.map((w) => (
<Tag key={w} tone={g.tone}>
{w}
</Tag>
))}
</div>
</div>
))}
</div>
<CardFooterLink>查看更多关键词</CardFooterLink>
</Card>
{/* 传播任务分工速览 */}
<Card className="flex flex-col">
<CardTitle icon={Megaphone} title="传播任务分工速览" />
<div className="flex-1 px-4 py-3.5">
<Table head={["部门", "主要任务", "完成时限"]}>
{TASKS.map((t) => (
<tr key={t.dept}>
<Td className="whitespace-nowrap font-semibold text-slate-800 dark:text-[var(--dash-text-strong)]">{t.dept}</Td>
<Td className="text-slate-500 dark:text-[var(--dash-text-sec)]">{t.task}</Td>
<Td className="whitespace-nowrap text-slate-500 dark:text-[var(--dash-text-sec)]">{t.deadline}</Td>
</tr>
))}
</Table>
</div>
<CardFooterLink>查看完整分工</CardFooterLink>
</Card>
</div>
</div>
);
}
/** 发布日历小节(标题 + 时间/事件/状态行)。 */
function CalendarSection({ title, items }: { title: string; items: CalendarItem[] }) {
return (
<div>
<div className="mb-1.5 text-[11px] font-semibold text-red-600">{title}</div>
<ul className="space-y-1.5">
{items.map((it) => (
<li key={`${it.time}-${it.event}`} className="flex items-center gap-2 text-xs">
<span className="w-20 shrink-0 font-mono text-slate-400 dark:text-[var(--dash-text-dim)]">{it.time}</span>
<span className="flex-1 truncate text-slate-600 dark:text-[var(--dash-text)]">{it.event}</span>
<Tag tone={it.tone}>{it.status}</Tag>
</li>
))}
</ul>
</div>
);
}
// ── 真实数据渲染 ──────────────────────────────────────────────────────────────
function OursReal({ data }: { data: OursData }) {
const ds = useDesensitize();
const keywords = Array.from(new Set(data.narratives.flatMap((n) => n.tags))).slice(0, 24);
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
<div className="grid grid-cols-1 gap-3 lg:grid-cols-12">
{/* 口径 */}
{data.speeches.length > 0 && (
<Card className="flex flex-col lg:col-span-8">
<CardTitle icon={MessageSquareQuote} title="口径" />
<ul className="flex-1 space-y-3 px-4 py-3.5">
{data.speeches.map((s, i) => (
<li key={i} className="border-b border-slate-50 pb-3 last:border-0 last:pb-0 dark:border-[var(--dash-border)]">
<div className="mb-1 flex items-start justify-between gap-2">
<span className="text-xs font-bold text-slate-800 dark:text-[var(--dash-text-strong)]">{s.title || "口径"}</span>
{s.time && <span className="shrink-0 whitespace-nowrap font-mono text-[10px] text-slate-400 dark:text-[var(--dash-text-dim)]">{s.time}</span>}
</div>
{s.summary && <p className="line-clamp-3 text-xs leading-relaxed text-slate-600 dark:text-[var(--dash-text)]">{s.summary}</p>}
{s.direction && (
<p className="mt-1 line-clamp-2 text-[11px] leading-snug text-slate-400 dark:text-[var(--dash-text-dim)]">
<span className="font-semibold text-red-600">{ds("导向")}:</span>
{s.direction}
</p>
)}
</li>
))}
</ul>
</Card>
)}
{/* 上级要求 */}
{data.orders.length > 0 && (
<Card className="flex flex-col lg:col-span-4">
<CardTitle icon={Star} title="上级要求" />
<ol className="flex-1 space-y-2.5 px-4 py-3.5">
{data.orders.map((o, i) => (
<li key={i} className="flex gap-2 text-xs leading-relaxed">
<span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-red-600 text-[10px] font-bold text-white">{i + 1}</span>
<span className="text-slate-600 dark:text-[var(--dash-text)]">{o}</span>
</li>
))}
</ol>
</Card>
)}
</div>
{/* 叙事 */}
{data.narratives.length > 0 && (
<Card>
<CardTitle icon={BookText} title="叙事" />
<ul className="space-y-3 px-4 py-3.5">
{data.narratives.map((n, i) => (
<li key={i} className="border-b border-slate-50 pb-3 last:border-0 last:pb-0 dark:border-[var(--dash-border)]">
<div className="mb-1 flex flex-wrap items-center gap-1.5">
<span className="text-xs font-bold text-slate-800 dark:text-[var(--dash-text-strong)]">{n.title || "叙事"}</span>
{n.tags.map((t) => (
<Tag key={t} tone="blue">{t}</Tag>
))}
</div>
{n.content && <p className="text-xs leading-relaxed text-slate-600 dark:text-[var(--dash-text)]">{n.content}</p>}
</li>
))}
</ul>
</Card>
)}
{/* 口径关键词(取自叙事标签) */}
{keywords.length > 0 && (
<Card>
<CardTitle icon={Tags} title="口径关键词" />
<div className="flex flex-wrap gap-1.5 px-4 py-3.5">
{keywords.map((w) => (
<Tag key={w} tone="red">{w}</Tag>
))}
</div>
</Card>
)}
</div>
);
}
@@ -0,0 +1,232 @@
/**
* 「大屏绘制智能体」总览页 —— **由六类战情数据聚合**而成(敌情/我情/战场环境/
* 情况判断/决心建议/处置建议),版式参考设计图 dp-1.png。
*
* **dashboard-agent 独占组件**:作为 DashboardApp `pages` 插槽里「总览」Tab 的内容,
* **不影响多智能体会商(Step3)大屏多页的样式**。
*
* 数据来自 `parseSqReport` 的整份 `SqReport`:
* - 顶部指标 = 各类目数量;关键战情摘要 / 三栏概览 / 判断·决策·处置 = 各类目要点提炼。
* - 接口返回为空(无任何类目)→ 显示「暂无数据」。
*/
import {
Target,
Zap,
Megaphone,
BookText,
ShieldAlert,
FileText,
Crosshair,
Shield,
Mountain,
Lightbulb,
Flag,
type LucideIcon,
} from "lucide-react";
import { Card, CardTitle, FooterNote, NoData, useDesensitize } from "@/roundtable-planning/dashboard-agent/ui";
import type { SqReport } from "@/roundtable-planning/dashboard-agent/sq-report";
// ── 聚合 ──────────────────────────────────────────────────────────────────────
function eventCount(r: SqReport): number {
return (r.enemy?.events ?? []).reduce((s, g) => s + (g.count || g.items.length || 0), 0);
}
interface OverviewColumn {
title: string;
icon: LucideIcon;
rows: Array<{ label: string; value: string }>;
focusTitle: string;
focus: string[];
}
// ── 主组件 ────────────────────────────────────────────────────────────────────
export function SituationOverview({ data }: { data?: SqReport | null }) {
const ds = useDesensitize();
const r = data;
const hasAny =
!!r && (!!r.enemy || !!r.ours || !!r.environment || !!r.judgement || !!r.decision || !!r.disposal);
if (!hasAny) return <NoData />;
// 顶部指标(各类目数量)
const metrics: Array<{ label: string; value: number; icon: LucideIcon }> = [
{ label: "敌方目标", value: r!.enemy?.targets.length ?? 0, icon: Target },
{ label: "关键事件", value: eventCount(r!), icon: Zap },
{ label: "对手叙事", value: r!.enemy?.narratives.length ?? 0, icon: Megaphone },
{ label: "我方口径", value: r!.ours?.speeches.length ?? 0, icon: BookText },
{ label: "风险项", value: r!.judgement?.risks.length ?? 0, icon: ShieldAlert },
{ label: "处置建议", value: r!.disposal?.items.length ?? 0, icon: FileText },
];
// 关键战情摘要(取各类目最有代表性的一句)
const summary: Array<{ label: string; text: string }> = [
r!.decision?.summary && { label: "决心研判", text: r!.decision.summary },
r!.disposal?.summary && { label: "处置研判", text: r!.disposal.summary },
r!.enemy?.narratives[0]?.summary && { label: "对手叙事", text: r!.enemy!.narratives[0].summary },
r!.judgement?.risks[0] && { label: "主要风险", text: r!.judgement!.risks[0] },
r!.ours?.speeches[0]?.summary && { label: "我方口径", text: r!.ours!.speeches[0].summary },
].filter(Boolean) as Array<{ label: string; text: string }>;
// 三栏概览
const columns: OverviewColumn[] = [];
if (r!.enemy) {
columns.push({
title: "敌情概览",
icon: Crosshair,
rows: [
{ label: "敌方目标", value: `${r!.enemy.targets.length} 个` },
{ label: "关键事件", value: `${eventCount(r!)} 起` },
{ label: "对手叙事", value: `${r!.enemy.narratives.length} 条` },
],
focusTitle: "重点事件",
focus: r!.enemy.events.map((e) => e.topic).filter(Boolean).slice(0, 3),
});
}
if (r!.ours) {
columns.push({
title: "我情概览",
icon: Shield,
rows: [
{ label: "口径", value: `${r!.ours.speeches.length} 条` },
{ label: "叙事", value: `${r!.ours.narratives.length} 条` },
{ label: "上级要求", value: `${r!.ours.orders.length} 项` },
],
focusTitle: "口径要点",
focus: r!.ours.speeches.map((s) => s.title).filter(Boolean).slice(0, 3),
});
}
if (r!.environment) {
columns.push({
title: "战场环境概览",
icon: Mountain,
rows: [
{ label: "信息环境", value: `${r!.environment.info.length} 维度` },
{ label: "人文环境", value: `${r!.environment.human.length} 维度` },
],
focusTitle: "环境维度",
focus: [...r!.environment.info, ...r!.environment.human].map((s) => s.title).slice(0, 4),
});
}
const judgePoints = (r!.judgement?.risks ?? []).slice(0, 3);
const decisionPoints = (r!.decision?.objectives ?? []).slice(0, 3);
const disposalPoints = (r!.disposal?.items ?? []).map((i) => i.content).filter(Boolean).slice(0, 3);
return (
<div className="space-y-4 text-slate-700 dark:text-[var(--dash-text)]">
{/* 1. 顶部指标 */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
{metrics.map((m) => (
<Card key={m.label} className="p-4">
<div className="mb-3 flex items-center gap-2">
<span className="flex h-8 w-8 items-center justify-center rounded-md bg-red-50 text-red-600 dark:bg-red-500/15">
<m.icon className="h-4 w-4" />
</span>
<span className="text-xs font-medium text-slate-500 dark:text-[var(--dash-text-sec)]">{ds(m.label)}</span>
</div>
<div className="font-mono text-3xl font-black leading-none text-slate-900 dark:text-[var(--dash-text-strong)]">{m.value}</div>
</Card>
))}
</div>
{/* 2. 关键战情摘要 */}
{summary.length > 0 && (
<Card>
<CardTitle icon={Megaphone} title="关键战情摘要" />
<ul className="space-y-3 px-4 py-3.5">
{summary.map((s) => (
<li key={s.label} className="flex gap-2.5 text-[13px] leading-relaxed">
<span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-red-600" />
<p className="text-slate-600 dark:text-[var(--dash-text)]">
<span className="font-bold text-red-600">{ds(s.label)}:</span>
{s.text}
</p>
</li>
))}
</ul>
</Card>
)}
{/* 3. 三栏概览 */}
{columns.length > 0 && (
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
{columns.map((col) => (
<Card key={col.title} className="flex flex-col">
<CardTitle icon={col.icon} title={col.title} />
<div className="grid flex-1 grid-cols-1 gap-x-4 gap-y-3 px-4 py-3.5 sm:grid-cols-2">
<dl className="space-y-2">
{col.rows.map((row) => (
<div key={row.label} className="flex items-baseline justify-between gap-2 text-xs">
<dt className="shrink-0 text-slate-400 dark:text-[var(--dash-text-dim)]">{ds(row.label)}</dt>
<dd className="text-right font-medium text-slate-800 dark:text-[var(--dash-text-strong)]">{row.value}</dd>
</div>
))}
</dl>
{col.focus.length > 0 && (
<div className="border-t border-dashed border-slate-100 pt-3 dark:border-[var(--dash-border)] sm:border-l sm:border-t-0 sm:pl-4 sm:pt-0">
<div className="mb-2 text-[11px] font-semibold text-red-600">{ds(col.focusTitle)}</div>
<ul className="space-y-1.5">
{col.focus.map((f, i) => (
<li key={i} className="flex gap-1.5 text-xs leading-snug text-slate-600 dark:text-[var(--dash-text)]">
<span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-red-500" />
{f}
</li>
))}
</ul>
</div>
)}
</div>
</Card>
))}
</div>
)}
{/* 4. 情况判断 / 决策建议 / 处置建议 */}
{(judgePoints.length > 0 || decisionPoints.length > 0 || disposalPoints.length > 0) && (
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
{judgePoints.length > 0 && (
<SummaryCard icon={Lightbulb} title="情况判断" points={judgePoints} footerLabel="风险研判" footer={r!.judgement?.responses[0]} />
)}
{decisionPoints.length > 0 && (
<SummaryCard icon={Flag} title="决策建议" points={decisionPoints} footerLabel="决心重点" footer={r!.decision?.taskTitle} />
)}
{disposalPoints.length > 0 && (
<SummaryCard icon={FileText} title="处置建议" points={disposalPoints} footerLabel="处置目标" footer={r!.disposal?.goal} />
)}
</div>
)}
</div>
);
}
/** 底部要点卡(编号要点 + 可选脚注)。 */
function SummaryCard({
icon,
title,
points,
footerLabel,
footer,
}: {
icon: LucideIcon;
title: string;
points: string[];
footerLabel: string;
footer?: string;
}) {
return (
<Card className="flex flex-col">
<CardTitle icon={icon} title={title} />
<ol className="flex-1 space-y-2.5 px-4 py-3.5">
{points.map((p, i) => (
<li key={i} className="flex gap-2 text-xs leading-relaxed">
<span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-red-600 text-[10px] font-bold text-white">{i + 1}</span>
<span className="text-slate-600 dark:text-[var(--dash-text)]">{p}</span>
</li>
))}
</ol>
{footer && <FooterNote label={footerLabel}>{footer}</FooterNote>}
</Card>
);
}
@@ -0,0 +1,326 @@
/**
* 「大屏绘制智能体」战情报告(selectSqReport)→ 各页面展示模型 的适配器。
*
* 接口经 `fetchDashboardInputJson` → `extractSqReport` 后得到:
* `{ taskId, source, categories: { [类目]: 反序列化内容 } }`
* 类目键(categoryType 去掉「 JSON」后缀):敌情目标 / 敌情关键事件 / 敌情对手叙事 /
* 我情口径 / 我情叙事 / 我情上级要求 / 信息环境 / 人文环境 / 优劣势分析 /
* 条件与限制 / 风险及应对 / 决心建议 / 处置建议 / 行动方案。
*
* 本模块把这些**异构、自由文本**的内容防御式地适配成每个页面要用的结构化模型;
* 任一类目缺失/为空 → 对应页面 data 为 null,页面回退到静态占位(先做对接,编辑后续再说)。
*/
// ── 防御式取值 ────────────────────────────────────────────────────────────────
function asArray(v: unknown): unknown[] {
return Array.isArray(v) ? v : [];
}
function asObj(v: unknown): Record<string, unknown> {
return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
}
function asStr(v: unknown): string {
if (typeof v === "string") return v;
if (v == null) return "";
if (typeof v === "number" || typeof v === "boolean") return String(v);
return "";
}
function strArr(v: unknown): string[] {
return asArray(v).map(asStr).filter((s) => s.trim().length > 0);
}
/**
* 过滤掉自由文本里的「引用角标」标记,做得**通用**:
* - 独立角标:`[[1]]`、`[[12]]`、`[[1,3]]` 等(方括号里任意非括号内容);
* - 带中文标签:`资料[[1]]`、`来源[[2]]`、`参考[[3]]` …;
* - 括号包裹:`(资料[[1]])`、`(来源[[12]])`、`([[3]])` …(中英文括号)。
* 删除后再清理残留的空括号与多余空白。用于所有展示文本(解析末尾整树清洗)。
*/
function stripCitations(s: string): string {
if (!s) return s;
return s
// 1) 括号包裹且内部含 [[..]] 的整体删除(不跨越其它括号)
.replace(/[((][^(())]*?\[\[[^[\]]+\]\][^(())]*?[))]/g, "")
// 2) 可选中文标签 + [[..]],或独立 [[..]]
.replace(/(?:资料|来源|参考|出处|引用|文献|注|脚注)?\s*\[\[[^[\]]+\]\]/g, "")
// 3) 残留空括号 + 多余空白
.replace(/[((]\s*[))]/g, "")
.replace(/[ \t]{2,}/g, " ")
.trim();
}
/** 深度清洗:递归把对象/数组里所有字符串过一遍 {@link stripCitations},返回新值。 */
function deepStripCitations<T>(value: T): T {
if (typeof value === "string") return stripCitations(value) as unknown as T;
if (Array.isArray(value)) return value.map(deepStripCitations) as unknown as T;
if (value && typeof value === "object") {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = deepStripCitations(v);
return out as T;
}
return value;
}
/** 取 categories 容器(输入即 fetchDashboardInputJson 的返回)。 */
export function getSqCategories(input: unknown): Record<string, unknown> | null {
const o = asObj(input);
const cats = asObj(o.categories);
return Object.keys(cats).length > 0 ? cats : null;
}
// ── 各页面展示模型 ────────────────────────────────────────────────────────────
export interface EnemyData {
targets: Array<{ name: string; category: string; note: string }>;
events: Array<{ topic: string; count: number; items: Array<{ time: string; title: string; brief: string }> }>;
narratives: Array<{ topic: string; narrator: string; intention: string; type: string; summary: string }>;
}
export interface OursData {
speeches: Array<{ title: string; summary: string; direction: string; time: string }>;
narratives: Array<{ title: string; intent: string; tags: string[]; content: string }>;
orders: string[];
}
export interface EnvSection {
title: string;
paragraphs: string[];
}
export interface EnvData {
info: EnvSection[];
human: EnvSection[];
}
export interface JudgeData {
strengths: Array<{ title: string; content: string }>;
weaknesses: Array<{ title: string; content: string }>;
constraints: Array<{ title: string; items: string[] }>;
risks: string[];
responses: string[];
}
export interface DecisionData {
taskTitle: string;
taskIntro: string;
objectives: string[];
targets: Array<{ name: string; desc: string; reason: string; impact: string; basis: string }>;
keyPoints: string[];
summary: string;
}
export interface DisposalData {
goal: string;
summary: string;
items: Array<{ content: string; method: string; tone: string; effect: string; subject: string; basis: string }>;
}
export interface SqReport {
enemy: EnemyData | null;
ours: OursData | null;
environment: EnvData | null;
judgement: JudgeData | null;
decision: DecisionData | null;
disposal: DisposalData | null;
}
// ── 适配函数(每个返回 null 表示该类目无可用数据) ─────────────────────────────
function adaptEnemy(cats: Record<string, unknown>): EnemyData | null {
// 敌方目标:组织 + 人物实体
const tgt = asObj(cats["敌情目标"]);
const targets = [...asArray(tgt.organization), ...asArray(tgt.human)]
.map((e) => {
const o = asObj(e);
return { name: asStr(o.name), category: asStr(o.text) || asStr(o.etype), note: asStr(o.reason) };
})
.filter((t) => t.name);
// 关键事件:按 topic 分组
const events = asArray(cats["敌情关键事件"])
.map((g) => {
const o = asObj(g);
const items = asArray(o.events)
.map((ev) => {
const e = asObj(ev);
return { time: asStr(e.date) || asStr(e.publish_time), title: asStr(e.title), brief: asStr(e.content) };
})
.filter((i) => i.title);
return { topic: asStr(o.topic), count: typeof o.count === "number" ? o.count : items.length, items };
})
.filter((g) => g.topic || g.items.length > 0);
// 对手叙事
const narratives = asArray(cats["敌情对手叙事"])
.map((n) => {
const o = asObj(n);
return {
topic: asStr(o.topic) || asStr(o.event_name),
narrator: asStr(o.narrator) || asStr(o.entity),
intention: asStr(o.intention) || asStr(o.intent_of_the_opponent),
type: asStr(o.topicType) || asStr(o.narrative_topic_types),
summary: asStr(o.summary) || asStr(o.event_summary),
};
})
.filter((n) => n.topic || n.summary);
if (targets.length === 0 && events.length === 0 && narratives.length === 0) return null;
return { targets, events, narratives };
}
function adaptOurs(cats: Record<string, unknown>): OursData | null {
const speech = asObj(cats["我情口径"]);
const speeches = [
...asArray(speech.selfSpeech).map((s) => {
const o = asObj(s);
return {
title: asStr(o.trendSpeechTitle) || asStr(o.trendSpeechTitleMini),
summary: asStr(o.trendSpeechLike) || asStr(o.trendSpeechContent),
direction: asStr(o.narrativeDirection),
time: asStr(o.trendSpeechTime),
};
}),
...asArray(speech.selfConsistents).map((s) => {
const o = asObj(s);
return {
title: asStr(o.trendConsistentTitleMini) || asStr(o.trendConsistentTitle),
summary: asStr(o.trendConsistentLike) || asStr(o.trendConsistentContent),
direction: asStr(o.narrativeDirection),
time: asStr(o.trendConsistentTime),
};
}),
].filter((s) => s.title || s.summary);
const narratives = asArray(cats["我情叙事"])
.map((n) => {
const o = asObj(n);
return {
title: asStr(o["标题"]),
intent: asStr(o["意图"]),
tags: strArr(o["标签"]),
content: asStr(o["内容"]),
};
})
.filter((n) => n.title || n.content);
// 上级要求:字符串(含编号),按行拆分、去掉行首编号
const orderRaw = cats["我情上级要求"];
const orderText = typeof orderRaw === "string" ? orderRaw : asStr(orderRaw);
const orders = orderText
.split(/\r?\n/)
.map((l) => l.trim().replace(/^[0-9]+[.、)]\s*/, ""))
.filter((l) => l.length > 0);
if (speeches.length === 0 && narratives.length === 0 && orders.length === 0) return null;
return { speeches, narratives, orders };
}
function adaptEnv(cats: Record<string, unknown>): EnvData | null {
const toSections = (raw: unknown): EnvSection[] =>
Object.entries(asObj(raw))
.filter(([k]) => k !== "type")
// 段落里过滤掉「引用角标」([[1]] / 资料[[1]] / (资料[[1]]) 等),过滤后为空的段落丢弃
.map(([title, v]) => ({
title: stripCitations(title),
paragraphs: strArr(v).map(stripCitations).filter((p) => p.length > 0),
}))
.filter((s) => s.paragraphs.length > 0);
const info = toSections(cats["信息环境"]);
const human = toSections(cats["人文环境"]);
if (info.length === 0 && human.length === 0) return null;
return { info, human };
}
function adaptJudge(cats: Record<string, unknown>): JudgeData | null {
const sw = asObj(cats["优劣势分析"]);
const mapTC = (v: unknown) =>
asArray(v)
.map((x) => {
const o = asObj(x);
return { title: asStr(o["title"]), content: asStr(o["content"]) };
})
.filter((x) => x.title || x.content);
const strengths = mapTC(sw["优势"]);
const weaknesses = mapTC(sw["劣势"]);
const con = asObj(cats["条件与限制"]);
const constraints = Object.entries(con)
.map(([title, v]) => ({ title: title.replace(/分析与?/, ""), items: strArr(v) }))
.filter((c) => c.items.length > 0);
const risk = asObj(cats["风险及应对"]);
const risks = strArr(risk["风险分析"]);
const responses = strArr(risk["应对方案"]);
if (strengths.length === 0 && weaknesses.length === 0 && constraints.length === 0 && risks.length === 0 && responses.length === 0)
return null;
return { strengths, weaknesses, constraints, risks, responses };
}
function adaptDecision(cats: Record<string, unknown>): DecisionData | null {
const root = asObj(cats["决心建议"]);
const core = asObj(root["决心建议"]);
const targets = asArray(core["打击目标"])
.map((t) => {
const o = asObj(t);
return {
name: asStr(o["目标名称"]),
desc: asStr(o["目标描述"]),
reason: asStr(o["选择理由"]),
impact: asStr(o["潜在影响"]),
basis: asStr(o["推荐依据"]),
};
})
.filter((t) => t.name || t.desc);
const data: DecisionData = {
taskTitle: asStr(core["任务标题"]),
taskIntro: asStr(core["任务简介"]),
objectives: strArr(core["作战目的"]),
targets,
keyPoints: strArr(root["实施要点"]),
summary: asStr(root["决心建议总结"]),
};
if (!data.taskTitle && !data.taskIntro && data.objectives.length === 0 && targets.length === 0 && data.keyPoints.length === 0 && !data.summary)
return null;
return data;
}
function adaptDisposal(cats: Record<string, unknown>): DisposalData | null {
const root = asObj(cats["处置建议"]);
const items = asArray(root["处置建议"])
.map((it) => {
const o = asObj(it);
const subj = asObj(o["处置主体"]);
return {
content: asStr(o["建议内容"]),
method: asStr(o["处置方式与步骤"]),
tone: asStr(o["口径基调"]),
effect: asStr(o["预期效果"]),
subject: asStr(subj["主责单位"]),
basis: asStr(o["立场与原则"]),
};
})
.filter((i) => i.content || i.method);
const data: DisposalData = {
goal: asStr(root["目标"]),
summary: asStr(root["处置建议总结"]),
items,
};
if (!data.goal && !data.summary && items.length === 0) return null;
return data;
}
/** 把 fetchDashboardInputJson 的返回解析成各页面展示模型(无 categories → 全 null)。 */
export function parseSqReport(input: unknown): SqReport {
const cats = getSqCategories(input);
if (!cats) {
return { enemy: null, ours: null, environment: null, judgement: null, decision: null, disposal: null };
}
// 整树清洗:所有类目的所有字符串字段统一过滤引用角标(通用,不止战场环境)。
return deepStripCitations({
enemy: adaptEnemy(cats),
ours: adaptOurs(cats),
environment: adaptEnv(cats),
judgement: adaptJudge(cats),
decision: adaptDecision(cats),
disposal: adaptDisposal(cats),
});
}
@@ -0,0 +1,242 @@
/**
* 「大屏绘制智能体」战情页公共 UI 片段(卡片 / 标题 / 更多按钮 / 色块徽标 / 表格)。
*
* **dashboard-agent 独占**:仅供战情系列静态页(SituationOverview / EnemyDetail / …)
* 复用,不影响会商共享的 DashboardApp / dashboard 组件群。配色对齐设计图(白底 + 红色强调)。
*/
import { createContext, useContext, type ReactNode } from "react";
import { ChevronRight, Inbox, type LucideIcon } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { desensitize } from "@/lib/desensitize";
import { markdownComponents } from "@/roundtable-planning/components/markdown-components";
/**
* 战情页**展示层脱敏函数**的 Context。
*
* 由 `DashboardAgentPage` 注入「后台敏感词(/api/sensitive-words)」版本(与「敏感词管理」
* 配置页同源),让本文件所有公共 UI 片段渲染的**静态文案**(卡片标题 / 表头 / 徽标 / 脚注 等,
* 内含 目标→MB、叙事→XS 这类映射词)也统一脱敏;缺省回退全局种子 {@link desensitize}。
* 数据文本已在数据层脱敏,这里再过一遍是幂等的(替换词为拉丁码,不会二次命中中文原词)。
*/
const DesensitizeContext = createContext<(s: string) => string>(desensitize);
export const DesensitizeProvider = DesensitizeContext.Provider;
export function useDesensitize() {
return useContext(DesensitizeContext);
}
/** children 若是纯字符串则脱敏,否则原样返回(元素/数字等不动)。 */
function dsNode(fn: (s: string) => string, node: ReactNode): ReactNode {
return typeof node === "string" ? fn(node) : node;
}
/** 空数据占位(接口返回为空 / 该类目缺失时显示)。 */
export function NoData({ label = "暂无数据" }: { label?: string }) {
const ds = useDesensitize();
return (
<div className="flex min-h-[320px] flex-1 flex-col items-center justify-center gap-2 py-20 text-slate-400 dark:text-[var(--dash-text-dim)]">
<Inbox className="h-10 w-10 opacity-40" />
<span className="text-sm">{ds(label)}</span>
</div>
);
}
/** 卡片外框(白底 + slate 细边 + 轻阴影)。 */
export function Card({ className = "", children }: { className?: string; children: React.ReactNode }) {
return (
<div
className={`rounded-md border border-slate-200 bg-white shadow-sm dark:border-[var(--dash-border)] dark:bg-[var(--dash-card)] ${className}`}
>
{children}
</div>
);
}
/** 卡片标题(红色图标 + 标题 + 可选徽标 + 可选右侧操作 + 底部分隔线)。 */
export function CardTitle({
icon: Icon,
title,
badges,
action,
}: {
icon: LucideIcon;
title: string;
badges?: React.ReactNode;
action?: React.ReactNode;
}) {
const ds = useDesensitize();
return (
<div className="flex items-center justify-between gap-2 border-b border-slate-100 px-4 py-2.5 dark:border-[var(--dash-border)]">
<div className="flex min-w-0 items-center gap-2">
<span className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-red-50 text-red-600 dark:bg-red-500/15">
<Icon className="h-3.5 w-3.5" />
</span>
<h3 className="shrink-0 text-sm font-bold tracking-tight text-slate-900 dark:text-[var(--dash-text-strong)]">
{ds(title)}
</h3>
{badges && <div className="flex min-w-0 flex-wrap items-center gap-1.5">{badges}</div>}
</div>
{action}
</div>
);
}
/** 标题徽标药丸(如「组织目标 12 个」,数字红色高亮)。 */
export function HeadBadge({ label, value }: { label: string; value: string }) {
const ds = useDesensitize();
return (
<span className="inline-flex items-center gap-1 rounded bg-slate-50 px-1.5 py-0.5 text-[11px] text-slate-500 dark:bg-white/5 dark:text-[var(--dash-text-sec)]">
{ds(label)}
<b className="font-bold text-red-600">{ds(value)}</b>
</span>
);
}
/** 「更多 >」操作按钮(标题右侧,可自定义文案)。 */
export function MoreLink({ label = "更多", onClick }: { label?: string; onClick?: () => void }) {
const ds = useDesensitize();
return (
<button
type="button"
onClick={onClick}
className="inline-flex shrink-0 items-center gap-0.5 text-xs font-medium text-red-600 hover:underline"
>
{ds(label)}
<ChevronRight className="h-3.5 w-3.5" />
</button>
);
}
/** 卡片底部「查看完整… >」链接条(顶部分隔线 + 红色链接)。 */
export function CardFooterLink({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) {
const ds = useDesensitize();
return (
<div className="mt-auto border-t border-slate-100 px-4 py-2.5 dark:border-[var(--dash-border)]">
<button
type="button"
onClick={onClick}
className="inline-flex items-center gap-0.5 text-xs font-medium text-red-600 hover:underline"
>
{dsNode(ds, children)}
<ChevronRight className="h-3.5 w-3.5" />
</button>
</div>
);
}
export type Tone = "red" | "amber" | "green" | "blue" | "slate";
const TONE_CLASS: Record<Tone, string> = {
red: "bg-red-50 text-red-600 dark:bg-red-500/15",
amber: "bg-amber-50 text-amber-600 dark:bg-amber-500/15",
green: "bg-emerald-50 text-emerald-600 dark:bg-emerald-500/15",
blue: "bg-sky-50 text-sky-600 dark:bg-sky-500/15",
slate: "bg-slate-100 text-slate-500 dark:bg-white/10 dark:text-[var(--dash-text-sec)]",
};
/** 语义色块徽标(高/中/低、上升/持平/下降、偏高 等)。 */
export function Tag({ tone, children }: { tone: Tone; children: React.ReactNode }) {
const ds = useDesensitize();
return (
<span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[11px] font-semibold ${TONE_CLASS[tone]}`}>
{dsNode(ds, children)}
</span>
);
}
const VAL_TEXT: Record<Tone, string> = {
red: "text-red-600",
amber: "text-amber-600",
green: "text-emerald-600",
blue: "text-sky-600",
slate: "text-slate-400 dark:text-[var(--dash-text-dim)]",
};
/** 语义色取值文字(键值行右侧的 高/中/充足/紧张 等,以颜色表强弱)。 */
export function Val({ tone, children }: { tone: Tone; children: React.ReactNode }) {
const ds = useDesensitize();
return <span className={`font-semibold ${VAL_TEXT[tone]}`}>{dsNode(ds, children)}</span>;
}
/** 紧凑表格(表头灰字 + 行细分隔线,对齐设计图密集表格)。 */
export function Table({ head, children }: { head: string[]; children: React.ReactNode }) {
const ds = useDesensitize();
// 外层 overflow-x-auto:字号抬到 16px 后,多列密集表(如 8 列)超宽时横向滚动而非撑破卡片,保证布局不错乱。
// 不加负 margin:表格左右须与卡片标题/正文同在 px-4 基线上,否则整张表相对标题左移看着错位。
return (
<div className="overflow-x-auto">
<table className="w-full border-collapse text-xs">
<thead>
<tr className="text-left text-[11px] text-slate-400 dark:text-[var(--dash-text-dim)]">
{head.map((h) => (
<th
key={h}
className="border-b border-slate-100 px-1.5 pb-2 font-semibold first:pl-0 last:pr-0 dark:border-[var(--dash-border)]"
>
{ds(h)}
</th>
))}
</tr>
</thead>
<tbody>{children}</tbody>
</table>
</div>
);
}
/** 表格数据单元(统一内边距 + 细分隔线 + 顶对齐)。 */
export function Td({ className = "", children }: { className?: string; children?: React.ReactNode }) {
const ds = useDesensitize();
return (
<td
className={`border-b border-slate-50 px-1.5 py-2 align-top leading-relaxed first:pl-0 last:pr-0 dark:border-[var(--dash-border)] ${className}`}
>
{dsNode(ds, children)}
</td>
);
}
/** 卡片底部「说明 / 动态」提示条(左侧色条 + 浅底)。 */
export function FooterNote({
label,
tone = "red",
children,
}: {
label: string;
tone?: Tone;
children: React.ReactNode;
}) {
const border = tone === "green" ? "border-emerald-500" : tone === "blue" ? "border-sky-500" : "border-red-500";
const labelColor =
tone === "green"
? "text-emerald-700 dark:text-emerald-400"
: tone === "blue"
? "text-sky-700 dark:text-sky-400"
: "text-red-600";
const bg =
tone === "green" ? "bg-emerald-50 dark:bg-emerald-500/10" : tone === "blue" ? "bg-sky-50 dark:bg-sky-500/10" : "bg-red-50 dark:bg-red-500/10";
const ds = useDesensitize();
return (
<div className={`mx-4 mb-3.5 rounded border-l-2 ${border} ${bg} px-3 py-2 text-[11px] leading-relaxed`}>
<span className={`font-semibold ${labelColor}`}>{ds(label)}:</span>
<span className="text-slate-600 dark:text-[var(--dash-text)]">{dsNode(ds, children)}</span>
</div>
);
}
/**
* 富文本(Markdown)渲染——战情数据里部分字段(如「应对方案」)带 Markdown 标记,
* 直接当纯文本渲染会露出 `**`/`-`/`#` 等源码。这里用与圆桌报告同一套
* {@link markdownComponents}(react-markdown + remark-gfm)渲染,并先脱敏。
* 纯文本传入也能正常渲染(按段落输出),可安全套用。
*/
export function MarkdownText({ children }: { children: string }) {
const ds = useDesensitize();
return (
<div className="dash-md">
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
{ds(children ?? "")}
</ReactMarkdown>
</div>
);
}
@@ -8,7 +8,7 @@
* - 不传 data 时回落参考 demo(DEMO_DATA)。
*/
import './dashboard.css';
import { useEffect, useState } from 'react';
import { useEffect, useState, type ReactNode } from 'react';
import { TabType } from './types';
import {
DashboardDataProvider,
@@ -31,23 +31,48 @@ import {
const TAB_ICONS = [LayoutGrid, Users, Megaphone, ShieldAlert, FileText, Activity];
export function DashboardApp({ data = DEMO_DATA }: { data?: DashboardDataValue }) {
const [activeTab, setActiveTab] = useState<TabType>('overview');
/** 自定义页(dashboard-agent 战情多页用):一个 Tab = id + 标签 + 图标 + 正文。 */
export interface DashboardPage {
id: string;
label: string;
icon?: ReactNode;
content: ReactNode;
}
// 数据切换(切历史记录/重绘 → data 引用变化)时复位到总览:避免停留在上一份数据
// 钻入的某个席位详情页,而新数据里无同名席位导致「加载席位数据失败」。
export function DashboardApp({
data = DEMO_DATA,
pages,
}: {
data?: DashboardDataValue;
/**
* 可选自定义页集:传入时整套 Tab(标签/图标)与正文都由它驱动,替换默认的
* 「总览 + 各席位」(dashboard-agent 用它注入战情多页)。会商 Step3 不传 → 行为零变化。
*/
pages?: DashboardPage[];
}) {
const usingPages = !!pages && pages.length > 0;
const firstTab: TabType = usingPages ? pages![0].id : 'overview';
const [activeTab, setActiveTab] = useState<TabType>(firstTab);
// 数据/页集切换(切历史记录/重绘 → data 引用变化)时复位到首个 Tab:避免停留在上一份
// 数据钻入的某个席位详情页,而新数据里无同名席位导致「加载席位数据失败」。
useEffect(() => {
setActiveTab('overview');
}, [data]);
setActiveTab(firstTab);
}, [data, firstTab]);
// 导航 Tab:总览 + 各席位(由数据动态生成,原参考为写死的固定 6 项)。
const tabs: TabType[] = ['overview', ...data.SEAT_CARDS.map((s) => s.id)];
// 导航 Tab:自定义页集 → 各页 id;否则总览 + 各席位(由数据动态生成)。
const tabs: TabType[] = usingPages
? pages!.map((p) => p.id)
: ['overview', ...data.SEAT_CARDS.map((s) => s.id)];
const getTabLabel = (tab: TabType) =>
tab === 'overview' ? '总览' : data.SEAT_CARDS.find((c) => c.id === tab)?.title ?? tab;
const getTabLabel = (tab: TabType) => {
if (usingPages) return pages!.find((p) => p.id === tab)?.label ?? tab;
return tab === 'overview' ? '总览' : data.SEAT_CARDS.find((c) => c.id === tab)?.title ?? tab;
};
const getTabIcon = (tab: TabType) => {
const cls = 'w-4 h-4';
if (usingPages) return pages!.find((p) => p.id === tab)?.icon ?? <Compass className={cls} />;
if (tab === 'overview') return <Compass className={cls} />;
const idx = data.SEAT_CARDS.findIndex((c) => c.id === tab);
const Ico = TAB_ICONS[(idx >= 0 ? idx : 0) % TAB_ICONS.length];
@@ -76,12 +101,15 @@ export function DashboardApp({ data = DEMO_DATA }: { data?: DashboardDataValue }
)}
</div>
<div className="flex flex-wrap items-center gap-2.5 self-start lg:self-center text-xs text-slate-500 dark:text-[var(--dash-text-sec)]">
<div className="flex items-center gap-1.5 font-mono px-3 py-1.5 bg-white dark:bg-[var(--dash-card)] border border-slate-200 dark:border-[var(--dash-border)] shadow-sm rounded-sm">
<Clock className="w-3.5 h-3.5 text-rose-600 dark:text-[var(--dash-primary)] animate-pulse" />
<span>生成于 {data.meta.generatedAt}</span>
{/* 战情多页(dashboard-agent)不展示「生成于」时间标签;会商 Step3 大屏保留。 */}
{!usingPages && (
<div className="flex flex-wrap items-center gap-2.5 self-start lg:self-center text-xs text-slate-500 dark:text-[var(--dash-text-sec)]">
<div className="flex items-center gap-1.5 font-mono px-3 py-1.5 bg-white dark:bg-[var(--dash-card)] border border-slate-200 dark:border-[var(--dash-border)] shadow-sm rounded-sm">
<Clock className="w-3.5 h-3.5 text-rose-600 dark:text-[var(--dash-primary)] animate-pulse" />
<span>生成于 {data.meta.generatedAt}</span>
</div>
</div>
</div>
)}
</header>
{/* 导航 Tab */}
@@ -109,7 +137,18 @@ export function DashboardApp({ data = DEMO_DATA }: { data?: DashboardDataValue }
{/* Body */}
<AnimatePresence mode="wait">
{activeTab === 'overview' ? (
{usingPages ? (
<motion.div
key={activeTab}
initial={{ opacity: 0, y: 5 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -5 }}
transition={{ duration: 0.25 }}
className="space-y-6"
>
{pages!.find((p) => p.id === activeTab)?.content}
</motion.div>
) : activeTab === 'overview' ? (
<motion.div
key="overview-dashboard"
initial={{ opacity: 0, y: 5 }}
@@ -20,6 +20,7 @@ import { useArtifacts } from "@/components/workspace/artifacts";
import {
initMultiAgent,
streamMultiAgent,
type ModelSwitchInfo,
type ClarificationPayload,
type LeaderDispatch,
type StreamPhase,
@@ -279,6 +280,26 @@ export interface UseStep2OrchestrationOptions {
* 智能体」弹窗确认时的 `SeatSelectionResult.seatMode` 决定。缺省 `pro`。
*/
selectedMode: SeatMode;
/**
* 每席位「技能识别强化」开关映射 {agentId: bool}(沿用所选业务链条里每个席位的配置)。
* 按 agentId 查表后透传给该 special 席位 run,与该席位 agent 自身 config.yaml 的同名开关取
* OR。recommend / 未选链条 → 空 {}(各席位仅靠其自身开关)。
*/
seatSkillDirectives?: Record<string, boolean>;
/**
* 每席位「推理深度覆盖」映射 {agentId: SeatMode | null}(沿用所选业务链条里每个席位的配置)。
* 派活该 special 席位时按 agentId 查表,**席位覆盖优先、否则跟随链条级 `selectedMode`**:
* `seatModeToRequestFields(seatModes[agentId] ?? selectedMode)`。模型卡顿时把次要席位降到
* `flash` 即可大幅提速。recommend / 未选链条 / 未覆盖 → 跟随 `selectedMode`。
*/
seatModes?: Record<string, SeatMode | null>;
/**
* 「研讨前并行取数」开关(来源业务链条的 gatherFirst,逐条 opt-in,缺省 false)。true = 正式研讨
* 前先对**全席位并行**跑一轮「只取数」(各席位只调技能取数、不研讨),产出作为共享资料(peerDeliveries)
* 注入后续研讨轮,把最慢的技能检索前置并行、给(尤其 chain 串行的)研讨段提速。每轮研讨只在**本轮
* 研讨真正启动时**取数一次(resetInitGate 复位后下一轮再取),澄清续跑/干预不重复取数。
*/
gatherFirst?: boolean;
/**
* 编排模式:
* - `recommend`(默认)—— 总控自由派活循环(`runOrchestration`);
@@ -434,6 +455,9 @@ export function useStep2Orchestration(
currentStep,
selectedModel,
selectedMode,
seatSkillDirectives = {},
seatModes = {},
gatherFirst = false,
orchestrationMode,
orchestrationPlan,
dagExecMode = "fast",
@@ -567,6 +591,16 @@ export function useStep2Orchestration(
const selectedModelRef = useRef<string>(selectedModel);
// 席位执行模式同样打到 ref,让席位调用在编排循环里读到最新值而不重建回调。
const selectedModeRef = useRef<SeatMode>(selectedMode);
// 每席位技能识别强化映射(所选业务链条各席位开关)同样打到 ref,席位调用按 agentId 读最新值。
const seatSkillDirectivesRef = useRef<Record<string, boolean>>(seatSkillDirectives);
// 每席位推理深度覆盖映射(所选业务链条各席位 seatMode)打到 ref,席位调用按 agentId 读最新值;
// 覆盖优先、否则跟随 selectedModeRef。
const seatModesRef = useRef<Record<string, SeatMode | null>>(seatModes);
// 「研讨前并行取数」开关 + 本轮取数产物({name,content}[])+ 本轮是否已取过的闸门。取数产物作为
// peerDeliveries 注入研讨轮席位;闸门保证一轮研讨只取一次(resetInitGate / resetStep2State 复位)。
const gatherFirstRef = useRef<boolean>(gatherFirst);
const gatheredDeliveriesRef = useRef<Array<{ name: string; content: string }>>([]);
const gatherPhaseDoneRef = useRef<boolean>(false);
const agentConfigsRef = useRef<Record<number, AgentConfig>>(agentConfigs);
const agentNameToRoleRef = useRef(agentNameToRole);
const threadIdsRef = useRef<ThreadIdMap | null>(threadIds);
@@ -606,6 +640,15 @@ export function useStep2Orchestration(
useEffect(() => {
selectedModeRef.current = selectedMode;
}, [selectedMode]);
useEffect(() => {
seatSkillDirectivesRef.current = seatSkillDirectives;
}, [seatSkillDirectives]);
useEffect(() => {
seatModesRef.current = seatModes;
}, [seatModes]);
useEffect(() => {
gatherFirstRef.current = gatherFirst;
}, [gatherFirst]);
useEffect(() => {
agentConfigsRef.current = agentConfigs;
}, [agentConfigs]);
@@ -1277,6 +1320,41 @@ export function useStep2Orchestration(
);
}, []);
/**
* 生成某气泡的 onModelSwitch 处理器:弹提示 + 在该失败气泡**正前方**插入一条「系统提示」
* 气泡(「『X』模型异常 → 已切换『Y』继续」),同时把失败气泡里「已累计的半截内容」清空
* (随后新模型的流式增量会重新填进同一气泡)并标为「模型切换中…」。
*
* 顺序很关键:系统提示插在失败气泡之前 → 用户**先**看到「已切换其他模型」、**再**看到新
* 模型重答的过程(旧实现把提示气泡追加到列表末尾,反而排在新模型答案之后,顺序颠倒)。
* 插「之前」而非「移到末尾」也保住并行批次里各席位气泡的相对次序。
*/
const makeModelSwitchHandler = useCallback(
(bubbleId: number, isParallel: boolean) => (info: ModelSwitchInfo) => {
const who = info.agentName || "智能体";
triggerToast(`⚠️「${info.failedModel}」模型${info.reason},已自动切换「${info.nextModel}」继续`);
if (isParallel) parallelStreamRef.current.delete(bubbleId);
const systemBubble: Step2Dialogue = {
id: Date.now() + Math.random(),
sender: "系统提示",
avatarType: "amber",
content: `⚠️ 模型容错:「${who}」所用模型「${info.failedModel}」${info.reason},已自动切换到「${info.nextModel}」继续。`,
time: nowTime(),
confidence: "模型容错",
};
setStep2RoundtableDialogues((prev) => {
const idx = prev.findIndex((d) => d.id === bubbleId);
// 失败气泡找不到(异常兜底):仍按旧行为在末尾追加系统提示。
if (idx < 0) return [...prev, systemBubble];
const cleared = { ...prev[idx], content: "", confidence: "模型切换中…" };
const next = [...prev];
next.splice(idx, 1, systemBubble, cleared);
return next;
});
},
[triggerToast],
);
// ─── §6 并行流式:全接收 / 惰性渲染 / 节流 ───────────────────────────────
/**
* 节流 flush(~80ms 一拍,约 12fps):**仅被选中**的席位把 ref 累积的全文挂到
@@ -1573,7 +1651,8 @@ export function useStep2Orchestration(
"③ 风险 / 注意事项(如有);④ 与其它席位的依赖 / 承接关系(如有)。";
// 优化4:跨轮累积各席位**完整交付**,作为 peerDeliveries 传给后续席位的 run
// (后端注入 context,席位用 read_peer_delivery 按需取全文,不进 prompt 不耗 token)。
const priorDeliveries: Array<{ name: string; content: string }> = [];
// 研讨前并行取数(gatherFirst)的产物作为初始 peerDeliveries 注入:研讨席位开局即带共享资料。
const priorDeliveries: Array<{ name: string; content: string }> = [...gatheredDeliveriesRef.current];
// 共享的「单席位交付执行」——串行/并行分支共用。含**失败自动重试一次**(优化5,
// 对齐 Step3 自愈:网络错误 / 502 重试,abort 不重试)。返回交付正文(aborted → 空)。
@@ -1601,8 +1680,13 @@ export function useStep2Orchestration(
peerDeliveries: priorDeliveries,
model: perSeatModel || selectedModelRef.current || undefined,
// 席位执行模式(快速/思考/专业问答/多智能体问答)→ thinking/reasoning/subagent。
...seatModeToRequestFields(selectedModeRef.current),
// 席位覆盖优先(业务链条里给该席位单独配的推理深度),否则跟随链条级 selectedMode。
...seatModeToRequestFields(seatModesRef.current[a.agentId] ?? selectedModeRef.current),
// 会商技能识别强化(该席位在所选业务链条里的开关,按 agentId 查表);与该席位
// agent 自身开关取 OR。
seatSkillDirective: seatSkillDirectivesRef.current[a.agentId] ?? false,
signal: subAborter.signal,
onModelSwitch: makeModelSwitchHandler(a.bubbleId, a.isParallel),
onTextDelta: (text) =>
a.isParallel ? ingestParallelDelta(a.bubbleId, text) : appendToDialogue(a.bubbleId, text),
onPhaseChange: (phase, toolName, args) => {
@@ -1683,10 +1767,16 @@ export function useStep2Orchestration(
// 第 2 轮起(已有席位交付)才是「综合轮」:让后端注入各席位完整交付供总控收口。
// 首轮纯派活、无交付,传 false 保持上下文精简。
synthesisMode: safetyCounter > 1,
// 削减重复广播(2026-06-20):首轮(safetyCounter==1)保留预广播——它把任务背景播进各席位
// thread,为席位打底;第 2 轮起的续轮/综合广播是「总控收到:<续轮 prompt>」纯噪声 + N 次
// 读写巨大席位 thread 的纯浪费(还会让弱模型从历史模仿派活),故 suppress。席位的前序交付
// 另经「席位交付广播」(broadcastSeatDeliveryToOthers)送达,不受影响。
suppressPreBroadcast: safetyCounter > 1,
// 用户随干预上传的参考文件(consume-once:仅首轮 leader 带,之后清空)。
files: takeOnce(pendingInjectFilesRef),
model: selectedModelRef.current || undefined,
signal: leaderAborter.signal,
onModelSwitch: makeModelSwitchHandler(leaderBubbleId, false),
onTextDelta: (text) => appendToDialogue(leaderBubbleId, text),
onPhaseChange: (phase, toolName, args) => {
const label = phaseLabel(phase, "leader", toolName);
@@ -1954,10 +2044,15 @@ export function useStep2Orchestration(
dAgentThreadId: ids,
agentName: coord,
newMessage: leaderTask,
// 削减重复广播(2026-06-20):首个席位(i===0)保留预广播为其打底任务背景;从第 2 个席位起
// suppress——后续席位的前序交付已由「席位交付广播」送达其 thread,总控派活 prompt 再播一遍
// 是 N 次读写巨大 thread 的纯浪费(还会让弱模型模仿派活)。
suppressPreBroadcast: i > 0,
// 用户随干预上传的参考文件(consume-once:仅首轮 leader 带,之后清空)。
files: takeOnce(pendingInjectFilesRef),
model: selectedModelRef.current || undefined,
signal: leaderAborter.signal,
onModelSwitch: makeModelSwitchHandler(leaderBubbleId, false),
onTextDelta: (text) => appendToDialogue(leaderBubbleId, text),
onPhaseChange: (phase, toolName, args) => {
const label = phaseLabel(phase, "leader", toolName);
@@ -2028,10 +2123,18 @@ export function useStep2Orchestration(
agentName: seat.agent_id,
displayName: seatName,
newMessage: task,
// 研讨前并行取数(gatherFirst)的产物作为共享资料注入:chain 席位也能直接引用、少重复检索。
// chain 串行靠 thread 广播看前序交付;取数资料这里另经 peerDeliveries 一并带上。
peerDeliveries: gatheredDeliveriesRef.current,
model: perSeatModel || selectedModelRef.current || undefined,
// 席位执行模式 → thinking/reasoning/subagent(与推荐/DAG 路径一致)。
...seatModeToRequestFields(selectedModeRef.current),
// 席位覆盖优先(业务链条里给该席位单独配的推理深度),否则跟随链条级 selectedMode。
...seatModeToRequestFields(seatModesRef.current[seat.agent_id] ?? selectedModeRef.current),
// 会商技能识别强化(该席位在所选业务链条里的开关,按 agentId 查表);与该席位
// agent 自身开关取 OR。
seatSkillDirective: seatSkillDirectivesRef.current[seat.agent_id] ?? false,
signal: subAborter.signal,
onModelSwitch: makeModelSwitchHandler(subBubbleId, false),
onTextDelta: (text) => appendToDialogue(subBubbleId, text),
onPhaseChange: (phase, toolName, args) => {
const label = phaseLabel(phase, "special", toolName);
@@ -2091,8 +2194,11 @@ export function useStep2Orchestration(
"各链条席位已按顺序完成发言,请你综合所有席位的交付,输出最终方案与结论。不要再派活、不要再向任何席位分配任务。",
// 链条收口就是综合轮:让后端注入各席位完整交付正文。
synthesisMode: true,
// 削减重复广播:收口轮不派活、研讨已结束,把总控收口 prompt 播进席位 thread 纯浪费,suppress。
suppressPreBroadcast: true,
model: selectedModelRef.current || undefined,
signal: closeoutAborter.signal,
onModelSwitch: makeModelSwitchHandler(closeoutBubbleId, false),
onTextDelta: (text) => appendToDialogue(closeoutBubbleId, text),
onPhaseChange: (phase, toolName, args) => {
const label = phaseLabel(phase, "leader", toolName);
@@ -2189,7 +2295,8 @@ export function useStep2Orchestration(
let finishedAllStages = true;
// 跨 stage 累积的**完整交付** {name, content}[] —— 注入下一 stage 席位的 run context
// (peerDeliveries),供 read_peer_delivery 工具按需取全文(§12.9 传摘要按需传全文)。
const priorDeliveries: Array<{ name: string; content: string }> = [];
// 研讨前并行取数(gatherFirst)的产物作为初始注入:首个 stage 席位开局即带共享资料。
const priorDeliveries: Array<{ name: string; content: string }> = [...gatheredDeliveriesRef.current];
// Phase 7:初始化 DAG 流程图节点状态 —— 计划内所有席位置 pending,执行过程中逐个点亮。
const markDagNode = (agentId: string, state: ChainNodeState) =>
@@ -2253,6 +2360,7 @@ export function useStep2Orchestration(
files: takeOnce(pendingInjectFilesRef),
model: selectedModelRef.current || undefined,
signal: leaderAborter.signal,
onModelSwitch: makeModelSwitchHandler(leaderBubbleId, false),
onTextDelta: (text) => appendToDialogue(leaderBubbleId, text),
onPhaseChange: (phase, toolName, args) => {
const label = phaseLabel(phase, "leader", toolName);
@@ -2370,10 +2478,15 @@ export function useStep2Orchestration(
peerDeliveries: priorDeliveries,
model: perSeatModel || selectedModelRef.current || undefined,
// 席位执行模式 → thinking/reasoning/subagent(与推荐/链条路径一致)。
...seatModeToRequestFields(selectedModeRef.current),
// 席位覆盖优先(业务链条里给该席位单独配的推理深度),否则跟随链条级 selectedMode。
...seatModeToRequestFields(seatModesRef.current[agentId] ?? selectedModeRef.current),
// 会商技能识别强化(该席位在所选业务链条里的开关,按 agentId 查表);与该
// 席位 agent 自身开关取 OR。
seatSkillDirective: seatSkillDirectivesRef.current[agentId] ?? false,
signal: subAborter.signal,
// §6:并行席位走 ref 全量累积 + 节流 flush(只渲染选中的);单节点
// stage 实际串行,1 路流直接 setState 不卡,沿用 appendToDialogue。
onModelSwitch: makeModelSwitchHandler(bubbleId, isParallel),
onTextDelta: (text) =>
isParallel ? ingestParallelDelta(bubbleId, text) : appendToDialogue(bubbleId, text),
onPhaseChange: (phase, toolName, args) => {
@@ -2495,10 +2608,132 @@ export function useStep2Orchestration(
],
);
// 研讨前「并行取数」阶段:对**全席位并行**跑一轮「只取数、不研讨」,产出存进 gatheredDeliveriesRef
// 作为共享资料注入后续研讨轮(recommend/dag 经 priorDeliveries、chain 经 peerDeliveries)。复用
// recommend 同款并行批显示。每轮研讨只取一次(由 runActiveOrchestration 的 gatherPhaseDoneRef 闸门控制)。
const runGatherPhase = useCallback(
async (ids: ThreadIdMap): Promise<void> => {
const agents = selectedAgentsRef.current;
if (agents.length === 0) return;
// 与后端 engine._GATHER_TASK 同义:只取数、不研讨、不下结论。
const GATHER_TASK =
"【资料收集阶段——只取数、不研讨】\n现在是正式研讨**之前**的并行资料收集阶段。请你**只负责把与本次任务、" +
"与你这个席位职责相关的真实信息/数据收集、整理出来**(优先用你配置的技能去检索/获取真实信息,没有技能可凭专业知识梳理)," +
"为后续正式研讨打底。\n**这一步不要做分析评估、不要给方案、不要下结论**——把判断与方案留到研讨阶段。" +
"请把你收集到的关键信息整理成条理清晰的事实/要点清单输出,**不要向用户提问或等待确认**。";
const seatPrep = agents.map((a) => {
const meta = agentNameToRoleRef.current[a.agent_id.toLowerCase()];
const seatName = meta?.displayName ?? a.name;
const avatarType = meta?.avatarType ?? "blue";
const seatThreadId = resolveSeatThreadId(ids, a.agent_id);
const bubbleId = appendStreamingDialogue({
sender: seatName,
avatarType,
initialContent: "",
confidence: "并行取数中",
agentThreadId: seatThreadId,
});
return { agentId: a.agent_id, seatName, avatarType, seatThreadId, bubbleId, meta };
});
markParallelSpeakers(
seatPrep.map((p) => p.meta?.speakerId).filter((v): v is number => typeof v === "number"),
);
setParallelBatch(
seatPrep.map((p) => ({
agentId: p.agentId,
displayName: p.seatName,
avatarType: p.avatarType,
status: "running" as const,
bubbleId: p.bubbleId,
})),
);
setSelectedParallelSeats(seatPrep.slice(0, 1).map((p) => p.agentId));
const markBatchStatus = (agentId: string, status: ParallelSeatView["status"]) =>
setParallelBatch((prev) => prev.map((p) => (p.agentId === agentId ? { ...p, status } : p)));
const results = await Promise.all(
seatPrep.map(async ({ agentId, seatName, seatThreadId, bubbleId, meta }) => {
const perSeatModel = meta ? agentConfigsRef.current[meta.speakerId]?.model : undefined;
const subAborter = new AbortController();
activeAbortersRef.current.add(subAborter);
try {
const specRes = await streamMultiAgent({
agentType: "special",
dAgentThreadId: ids,
agentName: agentId,
displayName: seatName,
newMessage: GATHER_TASK,
model: perSeatModel || selectedModelRef.current || undefined,
...seatModeToRequestFields(seatModesRef.current[agentId] ?? selectedModeRef.current),
seatSkillDirective: seatSkillDirectivesRef.current[agentId] ?? false,
signal: subAborter.signal,
onModelSwitch: makeModelSwitchHandler(bubbleId, true),
onTextDelta: (text) => ingestParallelDelta(bubbleId, text),
onPhaseChange: (phase, toolName, args) => {
const label = phaseLabel(phase, "special", toolName);
setDialogueConfidence(bubbleId, label);
appendStepIfNew(bubbleId, label, `${phase}:${toolName ?? ""}`, args);
handleArtifactToolPhase(phase, toolName, args, seatThreadId);
},
onUpstreamFrame: (frame) => {
handleUpstreamFrame(frame, seatThreadId);
ingestSubagentTaskFrame(frame, bubbleId);
},
});
activeAbortersRef.current.delete(subAborter);
finalizeDialogue(bubbleId, specRes.content, "资料收集");
markBatchStatus(agentId, "done");
if (meta) markSpeakerIdle(meta.speakerId);
parallelStreamRef.current.delete(bubbleId);
return specRes.content?.trim() ? { name: seatName, content: specRes.content } : null;
} catch (err) {
activeAbortersRef.current.delete(subAborter);
// 取数失败不阻断研讨:该席位无资料即可,研讨阶段它仍可自行检索。
finalizeDialogue(bubbleId, `(取数失败) ${(err as Error).message}`, "取数失败");
markBatchStatus(agentId, "done");
parallelStreamRef.current.delete(bubbleId);
return null;
}
}),
);
setParallelBatch([]);
setSelectedParallelSeats([]);
resetParallelStreams();
gatheredDeliveriesRef.current = results.filter(
(r): r is { name: string; content: string } => !!r,
);
},
[
appendStreamingDialogue,
finalizeDialogue,
ingestParallelDelta,
resetParallelStreams,
markParallelSpeakers,
markSpeakerIdle,
resolveSeatThreadId,
handleArtifactToolPhase,
handleUpstreamFrame,
ingestSubagentTaskFrame,
setDialogueConfidence,
appendStepIfNew,
],
);
// 按当前模式分发到对应编排函数。init / 恢复 / 干预 / 澄清回复统一走这里。
const runActiveOrchestration = useCallback(
(seedMessage: string, ids: ThreadIdMap, coord: string) => {
async (seedMessage: string, ids: ThreadIdMap, coord: string) => {
const mode = orchestrationModeRef.current;
// 研讨前并行取数(opt-in,每轮一次):先把取数产物准备好,再分发到具体编排(研讨轮注入资料)。
// gatherPhaseDoneRef 闸门保证澄清续跑 / 干预重入不重复取数;置位在 await 前,避免并发重入双跑。
if (gatherFirstRef.current && !gatherPhaseDoneRef.current) {
gatherPhaseDoneRef.current = true;
try {
await runGatherPhase(ids);
} catch (err) {
console.warn("[roundtable] 研讨前并行取数阶段失败,跳过取数继续研讨:", err);
}
}
// dag:**只在计划尚未跑过时**执行整张 DAG;一旦跑过(用户干预 / 恢复 / 澄清回复),
// 改走 leader 自由派活循环,由总控接着派活,而不是把 DAG 从头重跑一遍。
if (
@@ -2513,7 +2748,7 @@ export function useStep2Orchestration(
}
return runOrchestration(seedMessage, ids, coord);
},
[runOrchestration, runChainOrchestration, runDagOrchestration],
[runGatherPhase, runOrchestration, runChainOrchestration, runDagOrchestration],
);
// ─── Effects ─────────────────────────────────────────────────────
@@ -2829,6 +3064,9 @@ export function useStep2Orchestration(
step2InitRef.current = false;
// 新一轮研讨:允许 DAG 计划重新执行一遍。
dagPlanExecutedRef.current = false;
// 新一轮研讨:允许「研讨前并行取数」再取一次(清掉上一轮取数产物 + 闸门)。
gatherPhaseDoneRef.current = false;
gatheredDeliveriesRef.current = [];
setInitNonce((n) => n + 1);
}, []);
@@ -2858,7 +3096,22 @@ export function useStep2Orchestration(
// 需要 ref 立刻可读到作业的真实线程,否则读到旧值导致接管失败。
threadIdsRef.current = snapshot.threadIds;
coordinatorNameRef.current = snapshot.coordinatorName;
setStep2RoundtableDialogues(snapshot.step2RoundtableDialogues);
// 历史快照是**静止记录**:任何残留「流式/加载中」的气泡(用户中途点了「停止」,
// 或草稿在流式期间被自动保存)都强制收尾为静止态。否则用户点聊天记录回看时,这些
// 气泡仍显示「调度中 / 等待响应 / 正在输出…」+ 加载光标,让人误以为还在进行(其实早已结束)。
// streaming===true 与「加载中」文案一一对应(finalizeDialogue 收尾时必置 false),故据此即可精确识别。
setStep2RoundtableDialogues(
snapshot.step2RoundtableDialogues.map((d) => {
if (!d.streaming) return d;
const hasText = (d.content ?? "").trim().length > 0;
return {
...d,
streaming: false,
content: hasText ? d.content : "(已结束)",
confidence: "已结束",
};
}),
);
setLastLeaderContent(snapshot.lastLeaderContent);
setHasConsensus(snapshot.hasConsensus);
setConsensusPercentage(snapshot.consensusPercentage);
@@ -2947,6 +3200,8 @@ export function useStep2Orchestration(
hasAutoOpenedRef.current = new Set();
pendingInjectPromptRef.current = null;
dagPlanExecutedRef.current = false;
gatherPhaseDoneRef.current = false;
gatheredDeliveriesRef.current = [];
deselectArtifact();
step2InitRef.current = false;
}, [abortAllInFlight, deselectArtifact, setArtifacts, resetParallelStreams]);
@@ -325,6 +325,12 @@ export function useStep3Dashboard(options: UseStep3DashboardOptions): UseStep3Da
newMessage: message,
model: selectedModel || undefined,
signal: aborter.signal,
// 模型自动容错:后端切到下一个模型重跑 → 清空失败尝试的半截累计(acc + 气泡)。
onModelSwitch: (info) => {
acc = "";
setDialogues((prev) => prev.map((d) => (d.id === bubbleId ? { ...d, content: "" } : d)));
setDialogueConfidence(bubbleId, `模型切换:${info.failedModel}→${info.nextModel}(${info.reason})`);
},
onTextDelta: (text) => {
appendToDialogue(bubbleId, text);
acc += text;
@@ -770,6 +770,16 @@ export function useStep3Report(
newMessage: prompt,
model: selectedModel || undefined,
signal: aborter.signal,
// 模型自动容错:后端切到下一个模型重跑 → 清空失败尝试半截正文 + 步骤卡留可见提示。
onModelSwitch: (info) => {
setDialogues((prev) => prev.map((d) => (d.id === bubbleId ? { ...d, content: "" } : d)));
setDialogueConfidence(bubbleId, `模型切换:${info.failedModel}→${info.nextModel}`);
appendStepIfNew(
bubbleId,
`⚠️ 模型容错:「${info.failedModel}」${info.reason},改用「${info.nextModel}」`,
`model_switch:${info.nextModel}`,
);
},
onTextDelta: (text) => appendToDialogue(bubbleId, text),
onPhaseChange: (p, toolName, toolArgs) => {
const label = reportPhaseLabel(p, toolName);
@@ -23,6 +23,7 @@ import type {
} from "@/roundtable-planning/api/drafts";
import {
buildArtifactDownloadUrl,
initStructureThread,
initSummaryThread,
listSessionArtifacts,
streamMultiAgent,
@@ -48,11 +49,14 @@ import {
type FlowIntent,
} from "@/roundtable-planning/api/flow-extract";
import { nowTime } from "@/roundtable-planning/lib/roundtable-constants";
import { readActionDetail } from "@/core/auth/task-deeplink";
/** 报告输出文件的固定虚拟路径(恢复历史快照时用它重建 stub)。 */
const SUMMARY_OUTPUT_PATH = "/mnt/user-data/outputs/方案总结报告.md";
/** 内置单例 id —— 恢复草稿后续问时无 init 返回值,用它兜底拼 dAgentThreadId。 */
const SUMMARY_AGENT_NAME = "roundtable-summary";
/** 结构化抽取智能体 id —— 入库轮由它(走 ingest run policy)真正调用入库技能。 */
const STRUCTURE_AGENT_NAME = "roundtable-structure";
export type SummaryPhase = "idle" | "creating" | "streaming" | "done" | "error";
@@ -89,6 +93,15 @@ interface UseStep3SummaryOptions {
* 技能(技能必需信息)。非深链(无 taskId)时入库功能整体不出现。
*/
taskId?: string | null;
/**
* 入库适用性判定选中的技能名(来自 `/ingest-eligibility`)。入库时作为提示传给结构化
* 输出智能体,引导它优先用这个技能(它仍会自行读 SKILL.md 判断);缺省时让它自行挑选。
*/
ingestSkill?: string | null;
/** 业务码(如 6BF/rwfx-A)——入库时给智能体做场景线索,帮它挑对入库技能。 */
ingestBusinessCode?: string | null;
/** 业务链条名称——入库场景线索之一。 */
ingestChainName?: string | null;
}
/** 第三步入库状态机。 */
@@ -150,25 +163,36 @@ export interface UseStep3SummaryReturn {
resolveIngestChoice: (choice: "now" | "later" | "never") => void;
/** 入库协助选项点选(开始入库/补充内容后再入库/只是提问→转交普通对话)。 */
resolveIngestClarification: (choice: "start_ingest" | "add_data" | "other") => void;
/** 手动入库(按钮 / 直接触发):在总结线程跑入库技能并显示步骤条。 */
/**
* 入库时尚无流程图 → 挂起的「是否先生成流程图」协助(非空 → 组件展示协助选项)。
* 数据入库以结构化流程图为核心内容,没有流程图时先问用户要不要生成。
*/
pendingFlowForIngest: boolean;
/** 「无流程图」协助点选:生成流程图(生成后再走入库询问)/ 暂不入库。 */
resolveFlowForIngest: (choice: "generate" | "cancel") => void;
/** 手动入库(按钮 / 直接触发):让结构化输出智能体走完整运行时自行调用入库技能。 */
runIngest: (opts?: { note?: string }) => void;
}
/** 演示用:步骤条之间的小停顿,让「调用入库技能」的过程看得见。 */
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** 把研讨原料拼成一段(首轮 prompt 和「恢复后无线程续问」都用得到)。 */
function buildMaterials(opts: {
intentReady: ReportIntent | null;
seatDeliveries: ReportSeatDelivery[];
consensusText: string;
coordinatorPrompt?: string | null;
/** xdfx:本次「行动名称」,作为材料抬头喂进总结(报告围绕该行动展开)。 */
actionName?: string | null;
}): string {
const { intentReady, seatDeliveries, consensusText, coordinatorPrompt } = opts;
const { intentReady, seatDeliveries, consensusText, coordinatorPrompt, actionName } = opts;
const parts: string[] = [];
const an = actionName?.trim();
if (an) {
parts.push("# 本次行动");
parts.push(an);
parts.push("");
}
const cp = coordinatorPrompt?.trim();
if (cp) {
parts.push("# 业务链总控编排提示(最高优先级,按它的关注点/结构/口径来组织报告)");
@@ -280,6 +304,7 @@ function buildSummaryPrompt(opts: {
seatDeliveries: ReportSeatDelivery[];
consensusText: string;
coordinatorPrompt?: string | null;
actionName?: string | null;
flowMode?: boolean;
}): string {
const parts: string[] = [];
@@ -301,6 +326,18 @@ function buildSummaryPrompt(opts: {
}
parts.push("");
parts.push(buildMaterials(opts));
// 意图对齐 + 缺口核对 + 防幻觉护栏(弱席位场景的质量兜底)——两种模式通用,与后端 build_summary_prompt 同义。
parts.push("");
parts.push(
"【动笔前必做:意图对齐与缺口核对】各席位可能由能力较弱的模型产出,未必扣住用户意图、未必充分。" +
"你是这份总结的质量兜底,不能只把各席位交付简单拼接。请先把上面的「任务意图」(目标/约束/关键假设)拆成" +
"用户核心诉求清单(编排提示对最终产出的要求也并入),逐条核对各席位交付+共识是否覆盖、够不够、有无跑题或矛盾;" +
"再据此组织:① 能从已有原料重组/推理补上的→直接补全讲透;② 缺真实信息补不了的→绝不凭空编。" +
"**写进 .md 报告文件的必须是一份完整、干净、可直接使用、无需用户修改的报告——不要在报告文件里写「待补充/不足/⚠️」之类提示或占位**。" +
"**但在对话回复正文、报告之后,必须追加一段简短「核对说明」**(只在对话里、**不写进 .md 文件**):逐条说明产出是否覆盖了用户意图、哪些充分/哪些不足/有哪些可补充(可在对话里让我补全);" +
"**即便都已覆盖、无明显缺口,也要明确写一句「已核对:各诉求均已覆盖,无明显缺口」,这段核对说明任何时候都不要省略。**" +
"最终产出要明显比各席位交付的简单拼接更扣用户意图。",
);
if (opts.flowMode) {
parts.push(
"请严格遵循你的职责设定:全程简体中文。" +
@@ -417,6 +454,26 @@ function summaryPhaseLabel(phase: StreamPhase, toolName?: string): string {
}
}
/** 入库轮的工具阶段 → 中文步骤标签(让前端步骤条体现「读技能说明 → 执行入库」真实过程)。 */
function ingestPhaseLabel(phase: StreamPhase, toolName?: string): string {
switch (phase) {
case "connecting":
return "调度入库技能";
case "connected":
return "已连接,等待响应";
case "tool_calling":
if (toolName === "read_file") return "读取入库技能说明(SKILL.md)";
if (toolName === "bash" || toolName === "write_file") return "调用入库技能执行入库";
return toolName ? `调用工具:${toolName}` : "调用入库技能";
case "tool_result":
return "处理入库结果";
case "streaming":
return "汇报入库结果";
default:
return "入库中…";
}
}
export function useStep3Summary(
options: UseStep3SummaryOptions,
): UseStep3SummaryReturn {
@@ -432,6 +489,9 @@ export function useStep3Summary(
onSummarySaved,
ingestAvailable,
taskId: ingestTaskId,
ingestSkill,
ingestBusinessCode,
ingestChainName,
} = options;
const onSummarySavedRef = useRef(onSummarySaved);
@@ -442,11 +502,21 @@ export function useStep3Summary(
// ── 入库状态 ──
const [ingestStatus, setIngestStatus] = useState<IngestStatus>("idle");
const [pendingIngestClarification, setPendingIngestClarification] = useState<string | null>(null);
// 入库时尚无流程图 → 挂起「是否先生成流程图」协助(数据入库以结构化流程图为核心内容)。
const [pendingFlowForIngest, setPendingFlowForIngest] = useState<boolean>(false);
// 镜像供 render 外的回调(runFlowExtract 完成、ask 拦截)同步读到最新值。
const ingestStatusRef = useRef<IngestStatus>("idle");
useEffect(() => {
ingestStatusRef.current = ingestStatus;
}, [ingestStatus]);
// 重新分析(重跑总结 / 重新或修改流程图)前把入库状态整体复位为 idle —— 旧报告/旧流程图的
// 「是否入库」询问卡、入库协助卡、手动入库按钮全部初始化隐藏,避免「都重新分析了还问是否入库」
// 的歧义。流程图类重分析完成后 runFlowExtract 会在 idle 时重新发起入库询问。
const resetIngestState = useCallback(() => {
setIngestStatus("idle");
setPendingIngestClarification(null);
setPendingFlowForIngest(false);
}, []);
// 入库功能「有效可用」= 技能可用 **且** 处于深链(taskId)模式。
const ingestEnabled = !!ingestAvailable && !!ingestTaskId;
const ingestAvailableRef = useRef<boolean>(ingestEnabled);
@@ -458,8 +528,17 @@ export function useStep3Summary(
useEffect(() => {
ingestTaskIdRef.current = ingestTaskId ?? null;
}, [ingestTaskId]);
// 入库演示运行序号:新一轮入库 / 中断会自增,旧循环据此自停(防重复入库)。
// 入库运行序号:新一轮入库 / 中断会自增,旧循环据此自停(防重复入库)。
const ingestRunRef = useRef(0);
// 入库场景线索(适用性判定选中的技能 + 业务码/链名)——镜像供 runIngest 回调读最新值。
const ingestSkillRef = useRef<string | null>(ingestSkill ?? null);
const ingestBusinessCodeRef = useRef<string | null>(ingestBusinessCode ?? null);
const ingestChainNameRef = useRef<string | null>(ingestChainName ?? null);
useEffect(() => {
ingestSkillRef.current = ingestSkill ?? null;
ingestBusinessCodeRef.current = ingestBusinessCode ?? null;
ingestChainNameRef.current = ingestChainName ?? null;
}, [ingestSkill, ingestBusinessCode, ingestChainName]);
const {
setArtifacts,
@@ -983,9 +1062,21 @@ export function useStep3Summary(
dAgentThreadId: { [agentName]: threadId },
displayName: "方案总结报告",
newMessage: prompt,
// 深链接业务码:后端为 summary 单例注入「业务链完整性核对」(核对产出相对业务链完不完整)。
businessCode: ingestBusinessCodeRef.current,
model: selectedModel || undefined,
files: files && files.length > 0 ? files : undefined,
signal: aborter.signal,
// 模型自动容错:后端切到下一个模型重跑 → 清空失败尝试的半截正文 + 在步骤卡留一条可见提示。
onModelSwitch: (info) => {
setDialogues((prev) => prev.map((d) => (d.id === bubbleId ? { ...d, content: "" } : d)));
setDialogueConfidence(bubbleId, `模型切换:${info.failedModel}→${info.nextModel}`);
appendStepIfNew(
bubbleId,
`⚠️ 模型容错:「${info.failedModel}」${info.reason},改用「${info.nextModel}」`,
`model_switch:${info.nextModel}`,
);
},
onTextDelta: (text) => appendToDialogue(bubbleId, text),
onPhaseChange: (p, toolName, pArgs) => {
const label = summaryPhaseLabel(p, toolName);
@@ -1078,10 +1169,25 @@ export function useStep3Summary(
seatDeliveries,
chainLevels,
coordinatorPrompt,
// 深链接业务码:后端按业务链抽取规范强制注入完整层级(根治"无论什么业务都按目的→行为体抽")。
businessCode: ingestBusinessCodeRef.current,
// xdfx(7BF):根节点用「行动名称」(流程图根节点显示当前行动,而非任务名)。
rootLabel:
ingestBusinessCodeRef.current === "7BF" ? readActionDetail()?.actionName ?? null : null,
model: selectedModel || undefined,
currentGraph: opts?.currentGraph ?? null,
instruction: opts?.instruction,
signal: aborter.signal,
// 模型自动容错:后端切到下一个模型重抽 → 清空抽取气泡里失败尝试的半截内容 + 留可见提示。
onModelSwitch: (info) => {
setDialogues((prev) => prev.map((d) => (d.id === extractBubbleId ? { ...d, content: "" } : d)));
setDialogueConfidence(extractBubbleId, `模型切换:${info.failedModel}→${info.nextModel}`);
appendStepIfNew(
extractBubbleId,
`⚠️ 模型容错:「${info.failedModel}」${info.reason},改用「${info.nextModel}」`,
`model_switch:${info.nextModel}`,
);
},
onExtractDelta: (t) => appendToDialogue(extractBubbleId, t),
onValidating: () => {
setFlowPhase("validating");
@@ -1139,10 +1245,12 @@ export function useStep3Summary(
const regenerateFlow = useCallback(() => {
if (!currentMdRef.current.trim() && seatDeliveries.length === 0) return;
aborterRef.current?.abort();
// 重画流程图 = 重新分析 → 先复位入库状态(隐藏旧图的入库询问/按钮),新图生成完会重新询问。
resetIngestState();
const aborter = new AbortController();
aborterRef.current = aborter;
void runFlowExtract(aborter);
}, [runFlowExtract, seatDeliveries]);
}, [runFlowExtract, seatDeliveries, resetIngestState]);
/** Phase 3:画布手动改/删节点后回写图 + 持久化(序列化进草稿快照)。 */
const updateFlowGraph = useCallback(
@@ -1175,6 +1283,9 @@ export function useStep3Summary(
setSeatStubMessages({});
setFlowGraphState(null);
setFlowPhase("idle");
// 整体重跑(重试 / 重新生成)= 重新分析 → 复位入库状态,旧产物的入库询问/按钮先隐藏;
// 重跑出新流程图后 runFlowExtract 会重新询问是否入库。
resetIngestState();
const aborter = new AbortController();
aborterRef.current = aborter;
@@ -1194,6 +1305,9 @@ export function useStep3Summary(
seatDeliveries,
consensusText,
coordinatorPrompt,
// xdfx(7BF):把本次行动名称喂进总结材料,让报告围绕该行动展开。
actionName:
ingestBusinessCodeRef.current === "7BF" ? readActionDetail()?.actionName ?? null : null,
flowMode,
});
await streamOnce({ bubbleId, prompt, aborter, flowRound: flowMode });
@@ -1229,6 +1343,7 @@ export function useStep3Summary(
finalizeDialogue,
streamOnce,
runFlowExtract,
resetIngestState,
]);
/**
@@ -1247,60 +1362,118 @@ export function useStep3Summary(
}, [selectedModel]);
/**
* 入库(示例 · 演示用):在**总结线程**上出一条「知识库入库」气泡,按
* 调度 → 调用入库技能 →(补充内容)→ 提交 → 完成 的步骤条演示调用过程,与第二步同款。
* 真实入库技能后续替换这里(改为真的跑技能 / 调入库接口)。
* 入库(真执行):让**结构化输出智能体**(`roundtable-structure`,走 ingest run policy
* 的完整 agent 运行时)**自己挑选合适的入库技能、读 SKILL.md 并调用**完成入库——
* 而不是前端代它调技能。出一条「数据入库」气泡,实时显示它读技能说明 / 执行入库的
* 真实工具步骤与最终汇报。
*
* 入库内容**以最后修改后的为准**:当前报告 md + 最新流程图(画布手动改也同步进来),
* 并把 **taskId**(深链外部任务 id,入库技能必需信息)随消息一起传给智能体。
*/
const runIngest = useCallback(
async (opts?: { note?: string }) => {
// 未挂载入库技能(或非深链模式)→ 不执行任何入库操作。
// 未挂载/不适用入库技能(或非深链模式)→ 不执行任何入库操作。
if (!ingestAvailableRef.current) return;
setPendingIngestClarification(null);
// 数据入库以**结构化流程图**为核心内容。意图理解后先判断是否已生成流程图:
// 没有 → 不入库,挂起「是否先生成流程图」协助;有 → 正常调用智能体入库。
if (!flowGraphRef.current) {
setPendingFlowForIngest(true);
return;
}
setPendingFlowForIngest(false);
setIngestStatus("running");
const myRun = ++ingestRunRef.current;
const aborter = new AbortController();
const bubbleId = appendStreamingDialogue({
sender: "知识库入库",
sender: "数据入库",
avatarType: "blue",
agentThreadId: liveThreadRef.current ?? undefined,
});
const title = intentReady?.objective?.trim() || "会商方案";
// 入库数据**以最后修改后的为准**:读 flowGraphRef.current(画布手动改图也会同步进来)
// 与当前报告 md。taskId 是入库技能必需信息,必须随入库一起传给技能。
const flow = flowGraphRef.current;
const md = currentMdRef.current;
const taskId = ingestTaskIdRef.current;
const submitArgs: Record<string, unknown> = {
title,
taskId, // 技能必需:深链外部任务 id
hasReport: !!md.trim(),
flowNodes: flow?.nodes?.length ?? 0,
flowEdges: flow?.edges?.length ?? 0,
...(opts?.note ? { note: opts.note } : {}),
};
const steps: Array<{ label: string; key: string; args?: Record<string, unknown> }> = [
{ label: "调度入库技能", key: "tool_calling:ingest_dispatch", args: { taskId } },
{ label: "调用「知识库入库」技能", key: "tool_calling:ingest_skill", args: { skill: "knowledge-base-ingest", taskId } },
...(opts?.note
? [{ label: "并入补充内容", key: "tool_calling:ingest_append", args: { note: opts.note } }]
: []),
{ label: "提交方案数据入库(以最新流程图为准)", key: "tool_calling:ingest_submit", args: submitArgs },
const skillHint = ingestSkillRef.current;
const businessCode = ingestBusinessCodeRef.current;
const chainName = ingestChainNameRef.current;
const flowJson = flow ? serializeFlowGraph(flow) : "";
// 入库指令:把场景线索 + taskId + 报告 + 结构化流程图全量给智能体,让它按 SOUL 的
// 「五、入库」流程自行挑技能、读 SKILL.md、按契约调用(taskId 必传)。
const promptParts: string[] = [
"【任务】本轮请执行「入库」:把本次会商成果沉淀进知识库。请按你的设定(SOUL「五、入库」)",
"自行挑选**适合当前业务场景**的入库技能(技能名可能含「六步法」等场景线索),用 read_file 读它的",
"SKILL.md,再严格按其契约调用完成入库。**taskId 是入库技能的必需信息,务必随入库一起传入。**",
"",
"【业务场景】",
`- 方案标题:${title}`,
];
for (const s of steps) {
if (ingestRunRef.current !== myRun) return; // 被新一轮入库 / 中断取代
setDialogueConfidence(bubbleId, s.label);
appendStepIfNew(bubbleId, s.label, s.key, s.args);
await sleep(700);
}
if (ingestRunRef.current !== myRun) return;
finalizeDialogue(
bubbleId,
`✅ 已将「${title}」入库到知识库(示例技能 · 演示用,后续接入真实入库技能)。`,
"入库完成",
if (businessCode) promptParts.push(`- 业务码:${businessCode}`);
if (chainName) promptParts.push(`- 业务链名称:${chainName}`);
if (skillHint) promptParts.push(`- 适用性判定建议优先使用的入库技能:${skillHint}(仍请你读其 SKILL.md 确认)`);
promptParts.push(
`- taskId(必传给入库技能):${taskId ?? "(未提供)"}`,
"",
"【入库内容(以下为最终、用户最后修改后的成果,入库以此为准)】",
"—— 方案总结报告(Markdown)——",
md.trim() || "(无报告正文)",
"",
"—— 结构化流程图(flow-json,含节点/连线/层级)——",
flowJson || "(无结构化流程图)",
);
setIngestStatus("done");
persistSummary(); // 把入库气泡 + ingestStatus 落进草稿
if (opts?.note?.trim()) {
promptParts.push("", "【用户补充内容(请一并纳入入库)】", opts.note.trim());
}
const prompt = promptParts.join("\n");
try {
const init = await initStructureThread({ signal: aborter.signal });
if (ingestRunRef.current !== myRun || aborter.signal.aborted) return;
const threadId = init.threadId;
const agentName = init.agentName;
setDialogues((prev) =>
prev.map((d) => (d.id === bubbleId ? { ...d, agentThreadId: threadId } : d)),
);
const res = await streamMultiAgent({
agentType: "special",
agentName,
dAgentThreadId: { [agentName]: threadId },
displayName: "数据入库",
newMessage: prompt,
model: selectedModel || undefined,
signal: aborter.signal,
onTextDelta: (text) => {
if (ingestRunRef.current === myRun) appendToDialogue(bubbleId, text);
},
onPhaseChange: (p, toolName) => {
if (ingestRunRef.current !== myRun) return;
const label = ingestPhaseLabel(p, toolName);
setDialogueConfidence(bubbleId, label);
appendStepIfNew(bubbleId, label, `${p}:${toolName ?? ""}`);
},
});
if (ingestRunRef.current !== myRun || aborter.signal.aborted) return;
finalizeDialogue(bubbleId, res.content || `✅ 已完成「${title}」数据入库。`, "入库完成");
setIngestStatus("done");
persistSummary(); // 把入库气泡 + ingestStatus 落进草稿
} catch (err) {
if (ingestRunRef.current !== myRun || aborter.signal.aborted) return;
const msg = err instanceof Error ? err.message : String(err);
finalizeDialogue(bubbleId, `入库失败:${msg}`, "入库失败");
setIngestStatus("asking"); // 失败回到可重试(按钮/询问仍在)
}
},
[appendStreamingDialogue, appendStepIfNew, setDialogueConfidence, finalizeDialogue, intentReady, persistSummary],
[
appendStreamingDialogue,
appendToDialogue,
appendStepIfNew,
setDialogueConfidence,
finalizeDialogue,
setDialogues,
selectedModel,
intentReady,
persistSummary,
],
);
/** 流程图后入库询问三选一。 */
@@ -1319,6 +1492,26 @@ export function useStep3Summary(
[runIngest, persistSummary],
);
/**
* 「入库时无流程图」协助点选:
* - generate → 关闭协助、生成流程图(生成完成后会自动弹出「是否入库」询问,再由用户入库);
* - cancel → 关闭协助、置「稍后入库」(手动入库按钮仍在,可生成流程图后再入库)。
*/
const resolveFlowForIngest = useCallback(
(choice: "generate" | "cancel") => {
setPendingFlowForIngest(false);
if (choice === "generate") {
// 重置为 idle —— 流程图生成完成后 runFlowExtract 在 idle 时会自动询问入库。
setIngestStatus("idle");
regenerateFlow();
} else {
setIngestStatus("later");
persistSummary();
}
},
[regenerateFlow, persistSummary],
);
const ask = useCallback(
async (message: string, files?: File[], opts?: { forcedIntent?: FlowIntent; skipIngest?: boolean }) => {
const text = message.trim();
@@ -1366,16 +1559,25 @@ export function useStep3Summary(
// 带附件时跳过分类(附件多用于报告 Q&A/改报告);澄清后用户点选则用 forcedIntent 跳过分类。
// reuseBubbleId:意图分类期间先建的「调度中」气泡,定了意图后由对应分支复用(不等接口返回、像第一步)。
let reuseBubbleId: number | null = null;
// 「重新生成报告」复位入库状态后,待报告重写完成、若已有流程图则重新询问是否入库。
let reaskIngestAfter = false;
if (text && !hasFiles) {
let intent: FlowIntent | undefined = opts?.forcedIntent;
let dispatchBubbleId: number | null = null;
if (!intent) {
// **立刻**显示「智能体调度中」气泡(不等意图接口返回),消除连接卡顿时的"卡住"感。
dispatchBubbleId = appendStreamingDialogue({ sender: "智能体", avatarType: "blue" });
// 入库可用(按钮已出现、未入库 / 未在跑)时把 canIngest 传给意图识别——让「帮我入库」被识别为
// ingest 而不是落到 qa/unclear(之前主分类器不懂入库,只有「稍后入库待命」时才识别入库,是个缺口)。
const canIngestNow =
ingestAvailableRef.current &&
ingestStatusRef.current !== "running" &&
ingestStatusRef.current !== "done";
const r = await classifyFlowIntent({
message: text,
hasReport: !!currentMdRef.current.trim(),
hasFlow: !!flowGraphRef.current,
canIngest: canIngestNow,
model: selectedModel || undefined,
});
intent = r.intent;
@@ -1387,7 +1589,16 @@ export function useStep3Summary(
setPendingFlowClarification(text); // 组件渲染选项让用户自己定
return;
}
if (intent === "ingest") {
// 识别为入库(后端已保证仅 can_ingest 时才会返回 ingest)→ 直接入库;复用调度气泡。
if (dispatchBubbleId != null) finalizeDialogue(dispatchBubbleId, "正在入库…", "入库中");
await runIngest();
return;
}
if (intent === "regenerate_flow" || intent === "modify_flow") {
// 重新/修改流程图 = 重新分析 → 先复位入库状态(隐藏旧图入库询问/按钮),
// runFlowExtract 出新图后会在 idle 时重新询问是否入库。
resetIngestState();
const flowAborter = new AbortController();
aborterRef.current = flowAborter;
const cur = flowGraphRef.current;
@@ -1401,6 +1612,12 @@ export function useStep3Summary(
}
// regenerate_report | qa → 复用调度气泡走下方总结线程路径。
reuseBubbleId = dispatchBubbleId;
// 重新生成报告 = 重新分析 → 复位入库状态先隐藏旧的入库询问/按钮(qa 仅提问不复位);
// 报告重写完后若已有流程图,再重新询问是否入库(见 streamOnce 收尾后的 reaskIngestAfter)。
if (intent === "regenerate_report") {
resetIngestState();
reaskIngestAfter = true;
}
// intent === "regenerate_report" | "qa" → 落到下方总结线程续问路径:
// **追加**用户气泡 + 在原线程上让智能体重写报告 / 增量改 / 回答(**不清空历史**)。
// regenerate_report 不再走 run()(run 会 setDialogues([]) 清空,导致"覆盖聊天记录、
@@ -1496,6 +1713,11 @@ export function useStep3Summary(
flowRound,
});
}
if (aborter.signal.aborted) return;
// 报告重写完成、且入库可用 + 已有流程图 → 重新询问是否入库(复位后再问,针对新报告)。
if (reaskIngestAfter && ingestAvailableRef.current && flowGraphRef.current) {
setIngestStatus("asking");
}
} catch (err) {
if (aborter.signal.aborted) return;
const msg = err instanceof Error ? err.message : String(err);
@@ -1521,6 +1743,7 @@ export function useStep3Summary(
streamOnce,
runFlowExtract,
runIngest,
resetIngestState,
],
);
@@ -1706,6 +1929,8 @@ export function useStep3Summary(
pendingIngestClarification,
resolveIngestChoice,
resolveIngestClarification,
pendingFlowForIngest,
resolveFlowForIngest,
runIngest: (opts?: { note?: string }) => void runIngest(opts),
};
}
@@ -22,6 +22,29 @@ export interface ChainSeat {
name: string;
/** 描述快照,同样作为实时数据的回退。 */
description?: string;
/**
* 可选「席位模型覆盖」:该席位作为子智能体执行时用的 LLM model name(须是后端
* `config.yaml` `models[]` 里的一个 `name`)。空 / 缺省 = 不覆盖,运行时回退到全局
* 所选模型。选入研讨时灌进 `agentConfigs[speakerId].model`(见 `RoundtablePlanningPage`
* 的 `handleConfirmAgents`)→ 走现有 per-seat 模型链路。
*/
model?: string | null;
/**
* 可选「会商技能识别强化」开关(弱模型补偿)。true = 该席位作为会商子智能体执行时,把其
* 配置的技能(名称 + SKILL.md 路径 + 必须先 read_file 的硬指令)拼进本轮任务。与该席位
* 智能体自身的同名开关(智能体编辑里的开关)取 OR。缺省 / false = 关。随 `seats` JSON 落库
* (无需 DB 列),在链条编辑器里逐席位开关。
*/
seat_skill_directive?: boolean;
/**
* 可选「席位推理深度覆盖」:覆盖链条级 `seatMode`,只对该席位生效。值是同一套
* `SeatMode`(flash/thinking/pro/ultra);null / 缺省 = 跟随链条级默认。用于「卡顿提速」:
* 把信息收集/边角席位单独降到 `flash`(不思考、最快),只给关键席位留 `pro`/`ultra`。
* 随 `seats` JSON 落库(无需 DB 列,但需在后端 `ChainSeatSchema` 显式声明,否则 model_dump
* 会剥掉)。**字段名用 snake_case `seat_mode`** 与 `model`/`seat_skill_directive` 一致(seats
* 数组在 `api/chains.ts` 不做 camel↔snake 转换,键名须与后端 schema 逐字匹配)。
*/
seat_mode?: SeatMode | null;
}
/** 一条可复用的业务链条(与后端 `/api/roundtable-chains` 记录对应)。 */
@@ -54,6 +77,12 @@ export interface BusinessChain {
* 缺省 = 未设,调用方回退 `DEFAULT_SEAT_MODE`(pro)。
*/
seatMode?: SeatMode;
/**
* 可选「研讨前并行取数」开关(逐条 opt-in,缺省 false)。true = 选入研讨时,研讨前先跑一轮
* **全席位并行『取数』**(各席位只调技能取数、不研讨),产出作为共享资料注入后续研讨轮,把最慢
* 的技能延迟前置并行、给(尤其 chain 串行的)研讨段提速。三种编排通用。后端列 `gather_first`。
*/
gatherFirst?: boolean;
/** 是否已发布为公共(所有账号可在「公共」筛选查看 / 选入研讨)。 */
isPublic?: boolean;
/** 是否当前用户所有(仅本人可编辑 / 删除 / 发布;公共筛选里别人的链条为 false)。 */
@@ -70,8 +99,12 @@ export interface BusinessChain {
* `agents` + 一个 `mode`。
*/
export interface SeatSelectionResult {
/** 有序席位 —— 与现有 `handleConfirmAgents` 入参兼容。dag 模式下按 stage 展平排序。 */
agents: Array<{ agent_id: string; name: string }>;
/**
* 有序席位 —— 与现有 `handleConfirmAgents` 入参兼容。dag 模式下按 stage 展平排序。
* `model` 为该席位在来源链条里配置的模型覆盖(空 / 缺省 = 跟随全局模型)。
* `seat_skill_directive` 为该席位在来源链条里配置的「技能识别强化」开关(缺省 = 关)。
*/
agents: Array<{ agent_id: string; name: string; model?: string | null; seat_skill_directive?: boolean; seatMode?: SeatMode | null }>;
/**
* 决定 Step 2 走哪种编排:
* - `recommend` 总控自由派活;
@@ -97,6 +130,11 @@ export interface SeatSelectionResult {
* 缺省由调用方按 `DEFAULT_SEAT_MODE`(pro)处理。
*/
seatMode?: SeatMode;
/**
* 「研讨前并行取数」开关(来源链条的 `gatherFirst`)。true = 研讨前先并行取数再研讨。
* 三种编排通用,缺省 false。recommend(无链条)= false。
*/
gatherFirst?: boolean;
}
/** 链条席位数硬约束,与圆桌推荐弹窗的 `MIN_SELECTED`/`MAX_SELECTED` 对齐。 */
@@ -122,6 +160,16 @@ export function buildChainSeatSelection(
const nameById = new Map(candidates.map((c) => [c.agent_id, c.name]));
const seatNameById = new Map(chain.seats.map((s) => [s.agent_id, s.name]));
const nameOf = (id: string) => nameById.get(id) ?? seatNameById.get(id) ?? id;
// 席位模型覆盖(链条配置):按 agent_id 取,空/缺省 = 跟随全局。
const modelById = new Map(chain.seats.map((s) => [s.agent_id, s.model ?? null]));
const modelOf = (id: string) => modelById.get(id) ?? null;
// 席位「技能识别强化」开关(链条配置):按 agent_id 取,缺省 = 关。
const skillById = new Map(chain.seats.map((s) => [s.agent_id, s.seat_skill_directive ?? false]));
const skillOf = (id: string) => skillById.get(id) ?? false;
// 席位「推理深度覆盖」(链条配置 seat_mode):按 agent_id 取,null/缺省 = 跟随链条级 seatMode。
// 输出到 SeatSelectionResult.agents[].seatMode(camel,喂给编排/作业的 seatModes map)。
const seatModeById = new Map(chain.seats.map((s) => [s.agent_id, s.seat_mode ?? null]));
const seatModeOf = (id: string) => seatModeById.get(id) ?? null;
const survivingSeats = chain.seats.filter((s) => existingIds.has(s.agent_id));
if (survivingSeats.length < CHAIN_MIN_SEATS) return null;
@@ -143,13 +191,13 @@ export function buildChainSeatSelection(
if (hasParallel || hasGoal || hasCoord) {
const agents = plan.stages
.flatMap((st) => st.agentIds)
.map((id) => ({ agent_id: id, name: nameOf(id) }));
return { agents, mode: "dag", chain: chainMeta, plan, dagExecMode: "fast", seatMode: chain.seatMode };
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), seatMode: seatModeOf(id) }));
return { agents, mode: "dag", chain: chainMeta, plan, dagExecMode: "fast", seatMode: chain.seatMode, gatherFirst: chain.gatherFirst ?? false };
}
}
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id) }));
return { agents, mode: "chain", chain: chainMeta, seatMode: chain.seatMode };
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
return { agents, mode: "chain", chain: chainMeta, seatMode: chain.seatMode, gatherFirst: chain.gatherFirst ?? false };
}
/**
@@ -13,6 +13,7 @@
* 对应需求文档 `docs/roundtable-dag-orchestration.md` §2(分层编辑器,竖列分组)。
*/
import type { BusinessChain, ChainSeat } from "@/roundtable-planning/lib/business-chain";
import type { SeatMode } from "@/roundtable-planning/lib/seat-mode";
/** 一个并行 stage:含其并行席位与可选「本阶段目标」(注入给总控/席位,仅 dag 模式生效)。 */
export interface StageGroup {
@@ -112,6 +113,49 @@ export function setStageGoal(groups: StageGroups, stageIdx: number, goal: string
return groups.map((g, i) => (i === stageIdx ? { ...g, goal } : g));
}
/**
* 设置某个席位的「模型覆盖」(不可变,供编辑器席位下拉 onChange)。
* `model` 为 null/"" 表示清除覆盖(跟随全局模型)。按 agent_id 定位,跨 stage 适用。
*/
export function setSeatModel(groups: StageGroups, agentId: string, model: string | null): StageGroups {
return groups.map((g) => {
if (!g.seats.some((s) => s.agent_id === agentId)) return g;
return {
...g,
seats: g.seats.map((s) => (s.agent_id === agentId ? { ...s, model: model || null } : s)),
};
});
}
/**
* 设置某个席位的「会商技能识别强化」开关(不可变,供编辑器席位下拉 onChange)。
* 按 agent_id 定位,跨 stage 适用。随 `seats` JSON 落库。
*/
export function setSeatSkillDirective(groups: StageGroups, agentId: string, enabled: boolean): StageGroups {
return groups.map((g) => {
if (!g.seats.some((s) => s.agent_id === agentId)) return g;
return {
...g,
seats: g.seats.map((s) => (s.agent_id === agentId ? { ...s, seat_skill_directive: enabled } : s)),
};
});
}
/**
* 设置某个席位的「推理深度覆盖」(不可变,供编辑器席位下拉 onChange)。
* `mode` 为 null = 清除覆盖(跟随链条级 seatMode)。按 agent_id 定位,跨 stage 适用。
* 随 `seats` JSON 落库。
*/
export function setSeatMode(groups: StageGroups, agentId: string, mode: SeatMode | null): StageGroups {
return groups.map((g) => {
if (!g.seats.some((s) => s.agent_id === agentId)) return g;
return {
...g,
seats: g.seats.map((s) => (s.agent_id === agentId ? { ...s, seat_mode: mode } : s)),
};
});
}
// ── 变换(均返回新结构,不可变)──────────────────────────────────────────────
/** 末尾追加一个**新单席位 stage**(线性追加,pool 点击加入默认行为)。 */
@@ -392,6 +392,13 @@ export function buildDagStageLeaderTask(args: {
lines.push(
`【本阶段目标】${goalText}`,
"请据此目标为每个席位拆解任务,并要求他们**显式承接上一阶段的产出**来完成本阶段目标。",
"⚠️ 派活时**严格忠实于本阶段目标,不要自行新增目标里没有的「数量上限 / 只取最有代表性的 N 组 / 精简归纳成几条」等限制**," +
"也不要照搬其它阶段的数量(如上一阶段筛了 3 组,不代表本阶段也只要 3 组);" +
"目标没要求筛选 / 限定数量时,就要求席位**按其职责把每一条都完整输出**——" +
"若上一阶段有 N 条产出需逐条处理,就让席位**逐条、全部**产出(有多少条就出多少条),绝不替席位归纳 / 合并 / 只取代表性的几条。",
"⚠️ 也**不要替席位新增目标 / 席位职责之外的「输出体例 / 风格」要求**(如『写成连贯故事 / 要有场景感 / " +
"举具体城市景区为例 / 虚构时间地点情节』等)——派活只需转达本阶段目标 + 上一阶段产物 + 承接关系," +
"**让席位严格按它自己的职责设定(SOUL)输出**,且**忠实基于上一阶段的真实产物做分析,不要诱导席位脱离输入去编造 / 虚构事例**。",
);
}
lines.push(
@@ -66,6 +66,10 @@ function toStep2Dialogue(d: JobDialogue, idxByAgent: Map<string, number>): Step2
if (d.role === "leader") {
return { ...base, sender: "总控协调", avatarType: "blue", confidence: "派活说明" };
}
// 模型自动容错的系统提示气泡(后端 progress.model_switch 以 role="system" 落库)。
if (d.role === "system") {
return { ...base, sender: d.name || "系统提示", avatarType: "amber", confidence: "模型容错" };
}
const aid = d.agentId ?? "";
return {
...base,
@@ -52,7 +52,8 @@ export interface DispatchChainNode {
/** 一条研讨对话记录(leader 说明 / 某席位交付)。 */
export interface JobDialogue {
id: number;
role: "leader" | "seat";
// "system" = 模型自动容错等系统提示气泡(后端 progress.model_switch 落库)。
role: "leader" | "seat" | "system";
agentId: string | null;
name: string;
content: string;
@@ -132,6 +133,26 @@ export interface StartJobPayload {
* reasoning/subagent 三字段发给后端。
*/
seatMode?: SeatMode;
/**
* 每席位「技能识别强化」开关映射 {agentId: bool}(沿用所选业务链条里每个席位的配置)。
* 后台席位 run 按 agentId 查表(与各席位智能体自身的同名开关取 OR)决定是否注入。缺省 {}。
*/
seatSkillDirectives?: Record<string, boolean>;
/**
* 每席位「推理深度覆盖」映射 {agentId: SeatMode | null}(沿用所选业务链条里每个席位单独配的
* 推理深度)。后台席位 run 按 agentId 查表,覆盖优先、否则跟随链条级 `seatMode`。缺省 {}。
*/
seatModes?: Record<string, SeatMode | null>;
/**
* 「研讨前并行取数」开关(来源链条的 gatherFirst)。true = 后台作业研讨前先并行取数再研讨。
* 在 `toStartBody` 里下发为后端 `gather_first`。缺省 false。
*/
gatherFirst?: boolean;
/**
* 深链接业务码(rwfx→6BF 等)。透传给后台总结报告的「业务链完整性核对」(写实业务如 rwfx 才生效)。
* 普通会商省略。`toStartBody` 里下发为后端 `business_code`。
*/
businessCode?: string | null;
}
/** 终态集合——SSE/轮询判定作业是否结束。 */
@@ -27,6 +27,7 @@ import {
Bot,
ChevronDown,
ChevronUp,
Gauge,
GitBranch,
Globe,
GripVertical,
@@ -37,6 +38,7 @@ import {
Plus,
Save,
Sliders,
Sparkles,
SplitSquareVertical,
Trash2,
UserPlus,
@@ -63,9 +65,20 @@ import {
import { CSS } from "@dnd-kit/utilities";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Switch } from "@/components/ui/switch";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
import { ModelNameSelect } from "@/components/workspace/model-name-select";
import { listAgents } from "@/core/agents";
import { getStoredAuth } from "@/core/auth";
import {
filterRecommendCandidates,
@@ -74,6 +87,7 @@ import {
import {
createChain,
deleteChain,
getChain,
listChains,
optimizeChainPrompt,
setChainPublic,
@@ -103,6 +117,9 @@ import {
moveStage,
removeSeat as removeSeatFromGroups,
seatExistsInGroups,
setSeatMode as setSeatModeOnGroups,
setSeatModel,
setSeatSkillDirective,
setStageGoal,
splitSeatToNewStage,
stageGroupsToSeats,
@@ -156,6 +173,8 @@ export default function BusinessChainEditorPage() {
// 当前编辑链条的发布状态 / 是否本人所有(发布按钮 + 只读保护用)。
const [currentChainPublic, setCurrentChainPublic] = useState(false);
const [currentChainMine, setCurrentChainMine] = useState(true);
// 管理员:可编辑 / 发布 / 删除任意账号的链条(与「全部链条」筛选配套)。
const isAdmin = getStoredAuth()?.system_role === "admin";
const [publishing, setPublishing] = useState(false);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
@@ -163,6 +182,8 @@ export default function BusinessChainEditorPage() {
const [coordinatorPrompt, setCoordinatorPrompt] = useState("");
// 默认席位执行模式(快速/思考/专业问答/多智能体)—— 选入研讨时弹窗默认用它。
const [seatMode, setSeatMode] = useState<SeatMode>(DEFAULT_SEAT_MODE);
// 链条级「研讨前并行取数」开关(逐条 opt-in,默认关):开 = 选入研讨时研讨前先并行取数再研讨。
const [gatherFirst, setGatherFirst] = useState<boolean>(false);
// 分层编排是唯一数据源;落库时展平为 seats + 折叠为 stages。
const [stageGroups, setStageGroups] = useState<StageGroups>([]);
const [saving, setSaving] = useState(false);
@@ -288,6 +309,7 @@ export default function BusinessChainEditorPage() {
setDescription(chain.description ?? "");
setCoordinatorPrompt(chain.coordinatorPrompt ?? "");
setSeatMode(chain.seatMode ?? DEFAULT_SEAT_MODE);
setGatherFirst(chain.gatherFirst ?? false);
setStageGroups(chainToStageGroups(chain));
setStep(1);
}, []);
@@ -300,21 +322,40 @@ export default function BusinessChainEditorPage() {
setDescription("");
setCoordinatorPrompt("");
setSeatMode(DEFAULT_SEAT_MODE);
setGatherFirst(false);
setStageGroups([]);
setStep(1);
}, []);
// ─── URL 参数 chainId:从「业务链条」弹窗点「设置」进来时自动切到该链条 ──────
// 只在链条列表加载完后应用一次(用 ref 闸门避免覆盖用户后续的手动切换)。
const appliedChainParamRef = useRef(false);
// ─── URL 参数 chainId:从「业务链条」弹窗 / 列表点「设置」进来时自动切到该链条 ──────
// 按「已应用的 chainId」做闸门(而非「只应用一次」):当 URL 的 chainId 变化时重新加载。
// 关键修复:此编辑器实例在多次导航间可能不卸载(从弹窗进来时尤甚),用「只应用一次」的
// 旧闸门会导致第二次打开另一条链条时根本不加载,currentChainId 停在上一条 → 保存打到错误
// 的 id → 后端 404「已删除」,必须重新登录(整页刷新重建组件)才恢复。改为追踪已应用的 id
// 后,chainId 变了就重载;同一 chainId 不重复加载,也不覆盖用户在编辑器内的手动切换。
const appliedChainIdRef = useRef<string | null>(null);
useEffect(() => {
if (appliedChainParamRef.current) return;
const chainId = searchParams.get("chainId");
if (!chainId) return;
if (chains.length === 0) return; // 等 refreshChains 拉回列表
const chain = chains.find((c) => c.id === chainId);
if (chain) loadChain(chain);
appliedChainParamRef.current = true; // 命中或链条已不存在,都不再重试
if (appliedChainIdRef.current === chainId) return; // 这条已加载过,别覆盖用户后续操作
appliedChainIdRef.current = chainId;
// 优先用「我的链条」列表里已拉到的对象(省一次请求);不在列表里(管理员从「全部链条」
// 点设置 / 公共链条 / 自己没有任何链条)则直接按 id 拉取。后端对管理员放开任意链条、
// 对所有人放开已发布公共链条;拉不到给出提示并保持空白新建态。
const local = chains.find((c) => c.id === chainId);
if (local) {
loadChain(local);
return;
}
void (async () => {
try {
const chain = await getChain(chainId);
if (chain) loadChain(chain);
else toast.error("该业务链条不存在或无权访问");
} catch {
// 静默:取不到就保持当前(空白)状态。
}
})();
}, [chains, searchParams, loadChain]);
// ─── 席位增删改(全部委托给 lib/chain-stages 纯函数)────────────────────
@@ -359,6 +400,21 @@ export default function BusinessChainEditorPage() {
setStageGroups((prev) => setStageGoal(prev, stageIdx, goal));
}, []);
// 席位模型覆盖:编辑器席位下拉 onChange(null = 清除,跟随全局)。
const setSeatModelCb = useCallback((agentId: string, model: string | null) => {
setStageGroups((prev) => setSeatModel(prev, agentId, model));
}, []);
// 席位「会商技能识别强化」开关:编辑器席位下拉 onChange。
const setSeatSkillDirectiveCb = useCallback((agentId: string, enabled: boolean) => {
setStageGroups((prev) => setSeatSkillDirective(prev, agentId, enabled));
}, []);
// 席位「推理深度覆盖」:编辑器席位小图标下拉 onChange(null = 清除,跟随链条级 seatMode)。
const setSeatModeCb = useCallback((agentId: string, mode: SeatMode | null) => {
setStageGroups((prev) => setSeatModeOnGroups(prev, agentId, mode));
}, []);
// ── 提示词 AI 优化(总控提示词 / 各 Stage 阶段目标)────────────────────────
const [optimizingCoordinator, setOptimizingCoordinator] = useState(false);
const [goalOptimizingIdx, setGoalOptimizingIdx] = useState<number | null>(null);
@@ -555,6 +611,12 @@ export default function BusinessChainEditorPage() {
agent_id: s.agent_id,
name: live?.name ?? s.name,
description: live?.description ?? s.description ?? "",
// 席位模型覆盖:随席位一起落库(空 → null = 跟随全局)。
model: s.model ?? null,
// 席位「会商技能识别强化」开关:随席位一起落库(缺省 = false 关)。
seat_skill_directive: s.seat_skill_directive ?? false,
// 席位「推理深度覆盖」:随席位一起落库(null = 跟随链条级 seatMode)。
seat_mode: s.seat_mode ?? null,
};
});
// 总控编排提示:trim 后空串落 null(清空),与后端「空=不注入」一致。
@@ -573,6 +635,7 @@ export default function BusinessChainEditorPage() {
stageGoals,
coordinatorPrompt: coordPrompt,
seatMode,
gatherFirst,
});
if (!updated) {
toast.error("链条已不存在,可能被删除");
@@ -592,6 +655,7 @@ export default function BusinessChainEditorPage() {
stageGoals,
coordinatorPrompt: coordPrompt,
seatMode,
gatherFirst,
});
setCurrentChainId(created.id);
toast.success("已创建业务链条");
@@ -607,6 +671,7 @@ export default function BusinessChainEditorPage() {
description,
coordinatorPrompt,
seatMode,
gatherFirst,
stageGroups,
seatCountInvalid,
currentChainId,
@@ -745,6 +810,22 @@ export default function BusinessChainEditorPage() {
</p>
</div>
{/* 研讨前并行取数:逐条 opt-in 的提速开关(默认关)。 */}
<div className={cn("flex items-start justify-between gap-3 border border-border bg-muted/30 p-3", R_CARD)}>
<div className="space-y-1">
<label className="flex items-center gap-1 text-xs font-semibold text-foreground">
<Gauge className="size-3.5 text-primary" />
研讨前并行取数(提速)
</label>
<p className="text-[11px] leading-relaxed text-muted-foreground">
开启后,选入研讨时会**先并行跑一轮「只取数」**:各席位同时用技能把相关信息收集回来(不研讨),
产出作为共享资料注入后续研讨轮。把最慢的技能检索前置、并行做一次,给(尤其按链条顺序串行的)
研讨段大幅提速;研讨阶段席位仍可按需再调技能。
</p>
</div>
<Switch checked={gatherFirst} onCheckedChange={setGatherFirst} className="mt-0.5 shrink-0" />
</div>
{/* 总控提示词:label + AI 优化(配色沿用现有 primary)+ 大号等宽编辑区 */}
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
@@ -928,8 +1009,8 @@ export default function BusinessChainEditorPage() {
{/* 右侧操作 */}
<div className="ml-auto flex items-center gap-2">
{/* 发布 / 取消发布:仅已保存且本人所有的链条。发布后所有账号可在「公共」筛选查看 / 选用。 */}
{currentChainId && currentChainMine && (
{/* 发布 / 取消发布:已保存且本人所有(或管理员)的链条。发布后所有账号可在「公共」筛选查看 / 选用。 */}
{currentChainId && (currentChainMine || isAdmin) && (
<button
type="button"
onClick={handleTogglePublish}
@@ -1121,6 +1202,9 @@ export default function BusinessChainEditorPage() {
onRemoveSeat={removeSeat}
onMergeSeat={mergeSeatToStage}
onSplitSeat={splitSeat}
onSeatModelChange={setSeatModelCb}
onSeatSkillDirectiveChange={setSeatSkillDirectiveCb}
onSeatModeChange={setSeatModeCb}
onStageGoalChange={setGoal}
goalOptimizingIdx={goalOptimizingIdx}
onOptimizeGoal={handleOptimizeStageGoal}
@@ -1298,6 +1382,9 @@ function StagesColumn({
onRemoveSeat,
onMergeSeat,
onSplitSeat,
onSeatModelChange,
onSeatSkillDirectiveChange,
onSeatModeChange,
onStageGoalChange,
goalOptimizingIdx,
onOptimizeGoal,
@@ -1313,6 +1400,9 @@ function StagesColumn({
onRemoveSeat: (agentId: string) => void;
onMergeSeat: (agentId: string, targetStageIdx: number) => void;
onSplitSeat: (agentId: string) => void;
onSeatModelChange: (agentId: string, model: string | null) => void;
onSeatSkillDirectiveChange: (agentId: string, enabled: boolean) => void;
onSeatModeChange: (agentId: string, mode: SeatMode | null) => void;
onStageGoalChange: (stageIdx: number, goal: string) => void;
/** 正在 AI 优化阶段目标的 stage 下标(null = 没有进行中的优化)。 */
goalOptimizingIdx: number | null;
@@ -1410,6 +1500,9 @@ function StagesColumn({
onRemoveSeat={onRemoveSeat}
onMergeSeat={onMergeSeat}
onSplitSeat={onSplitSeat}
onSeatModelChange={onSeatModelChange}
onSeatSkillDirectiveChange={onSeatSkillDirectiveChange}
onSeatModeChange={onSeatModeChange}
onGoalChange={(goal) => onStageGoalChange(stageIdx, goal)}
goalOptimizing={goalOptimizingIdx === stageIdx}
anyGoalOptimizing={goalOptimizingIdx !== null}
@@ -1438,6 +1531,9 @@ function StageSection({
onRemoveSeat,
onMergeSeat,
onSplitSeat,
onSeatModelChange,
onSeatSkillDirectiveChange,
onSeatModeChange,
onGoalChange,
goalOptimizing,
anyGoalOptimizing,
@@ -1455,6 +1551,9 @@ function StageSection({
onRemoveSeat: (agentId: string) => void;
onMergeSeat: (agentId: string, targetStageIdx: number) => void;
onSplitSeat: (agentId: string) => void;
onSeatModelChange: (agentId: string, model: string | null) => void;
onSeatSkillDirectiveChange: (agentId: string, enabled: boolean) => void;
onSeatModeChange: (agentId: string, mode: SeatMode | null) => void;
onGoalChange: (goal: string) => void;
/** 本 Stage 的阶段目标正在 AI 优化中。 */
goalOptimizing: boolean;
@@ -1615,6 +1714,9 @@ function StageSection({
onMergeUp={() => onMergeSeat(seat.agent_id, stageIdx - 1)}
onMergeDown={() => onMergeSeat(seat.agent_id, stageIdx + 1)}
onSplit={() => onSplitSeat(seat.agent_id)}
onModelChange={(model) => onSeatModelChange(seat.agent_id, model)}
onSkillDirectiveChange={(enabled) => onSeatSkillDirectiveChange(seat.agent_id, enabled)}
onSeatModeChange={(mode) => onSeatModeChange(seat.agent_id, mode)}
onDetail={() => onSeatDetail(seat.agent_id, seat.name)}
/>
))}
@@ -1637,6 +1739,9 @@ function SeatStrip({
onMergeUp,
onMergeDown,
onSplit,
onModelChange,
onSkillDirectiveChange,
onSeatModeChange,
onDetail,
}: {
seat: ChainSeat;
@@ -1649,6 +1754,12 @@ function SeatStrip({
onMergeUp: () => void;
onMergeDown: () => void;
onSplit: () => void;
/** 席位模型覆盖变更(null = 清除,跟随全局)。 */
onModelChange: (model: string | null) => void;
/** 席位「会商技能识别强化」开关变更。 */
onSkillDirectiveChange: (enabled: boolean) => void;
/** 席位「推理深度覆盖」变更(null = 跟随链条级 seatMode)。 */
onSeatModeChange: (mode: SeatMode | null) => void;
onDetail: () => void;
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
@@ -1699,8 +1810,106 @@ function SeatStrip({
)}
</div>
{/* 控制:查看详情 / 并入上一阶段 / 独立成阶段 / 并入下一阶段 / 移除 */}
{/* 席位模型覆盖(右侧操作区):空 = 跟随全局所选模型;选了则该席位作为子智能体
执行时用此模型。技能重的席位配强模型、边角席位配快模型,配合技能白名单实现
「强弱搭配」。放到右侧操作区,与名称/描述解耦,卡片更整洁。 */}
<div className="flex shrink-0 items-center border-l border-border px-2.5">
<div
className={cn(
"flex items-center gap-1.5 border border-border/70 bg-muted/40 py-1 pl-2 pr-1",
R_CTRL,
)}
title="该席位作为子智能体执行时使用的模型;「跟随全局」= 用第二步顶部所选模型"
>
<span className="shrink-0 select-none text-[10px] font-medium text-muted-foreground">模型</span>
<ModelNameSelect
value={seat.model ?? null}
onChange={onModelChange}
defaultLabel="跟随全局"
triggerClassName="h-6 max-w-[150px] border-none bg-transparent text-[11px] shadow-none hover:bg-background/60"
/>
</div>
</div>
{/* 控制:推理深度 / 技能识别强化 / 查看详情 / 并入上一阶段 / 独立成阶段 / 并入下一阶段 / 移除 */}
<div className="flex shrink-0 items-center gap-0.5 border-l border-border px-2">
{/* 席位推理深度覆盖:小图标 → 下拉框(跟随链条默认 + 四档)。设了覆盖 = 高亮。
「卡顿提速」用:把信息收集/边角席位降到「快速」,只给关键席位留「专业/多智能体」。 */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
title="席位推理深度(覆盖链条默认;降到「快速」可在模型卡顿时大幅提速)"
className={cn(
"p-1 transition",
R_CTRL,
seat.seat_mode
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Gauge className="size-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-60">
<DropdownMenuLabel className="text-[11px] font-semibold">
席位推理深度
<span className="mt-0.5 block text-[10px] font-normal text-muted-foreground">
覆盖链条级默认,仅本席位生效。模型卡顿时把次要席位降到「快速」可大幅提速。
</span>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem
className={cn("text-xs", !seat.seat_mode && "font-semibold text-primary")}
onClick={() => onSeatModeChange(null)}
>
跟随链条默认
</DropdownMenuItem>
{SEAT_MODE_OPTIONS.map((opt) => (
<DropdownMenuItem
key={opt.value}
className={cn("flex-col items-start gap-0 text-xs", seat.seat_mode === opt.value && "font-semibold text-primary")}
onClick={() => onSeatModeChange(opt.value)}
>
<span>{opt.label}</span>
<span className="text-[10px] font-normal leading-tight text-muted-foreground">{opt.description}</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* 会商技能识别强化:小图标 → 下拉框(开关 + 说明)。开启 = 高亮。 */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
title="会商技能识别强化(弱模型补偿)"
className={cn(
"p-1 transition",
R_CTRL,
seat.seat_skill_directive
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Sparkles className="size-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64 p-3">
<div className="flex items-start justify-between gap-3">
<div className="space-y-0.5">
<p className="text-xs font-semibold text-foreground">会商技能识别强化</p>
<p className="text-[11px] leading-relaxed text-muted-foreground">
开启后,该席位作为会商子智能体执行时,会把已配置的技能(含 SKILL.md
路径与「先 read_file 再用」硬指令)拼进任务,补偿弱模型不识别技能。也可在该智能体编辑里打开(任一即生效)。
</p>
</div>
<Switch
checked={seat.seat_skill_directive ?? false}
onCheckedChange={onSkillDirectiveChange}
/>
</div>
</DropdownMenuContent>
</DropdownMenu>
<button
type="button"
onClick={onDetail}
@@ -61,6 +61,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { getStoredAuth } from "@/core/auth";
import { useRouteNavigate } from "@/core/route-base";
import { cn } from "@/lib/utils";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
@@ -83,6 +84,8 @@ export default function BusinessChainListPage() {
const navigate = useRouteNavigate();
// 整片脱敏:链条列表页展示文本(链条名/描述/席位名/标题)。
const dzRef = useDesensitizeSubtree<HTMLDivElement>();
// 管理员:额外多一个「全部链条」筛选,且可编辑 / 发布 / 删除任意账号的链条。
const isAdmin = getStoredAuth()?.system_role === "admin";
// 进入编辑器:带 chainId = 打开并切到该链条;不带 = 空白新建。
// 路径写 workspace base,`useRouteNavigate` 会按当前路由 base 改写。
@@ -314,13 +317,14 @@ export default function BusinessChainListPage() {
{/* 筛选工具栏 */}
<div className="mb-6 flex flex-col gap-4 rounded-2xl border border-zinc-100 bg-white p-4 shadow-sm dark:border-[#1A2F5A] dark:bg-[#122347] lg:flex-row lg:items-center lg:justify-between">
{/* 我的 / 公共 */}
{/* 我的 / 公共 /(管理员)全部 */}
<div className="flex self-start rounded-xl bg-zinc-100 p-1 dark:bg-[#0C1836]">
{(
[
["mine", "我的链条"],
["public", "公共列表"],
] as const
...(isAdmin ? ([["all", "全部链条"]] as const) : []),
] as [ChainScope, string][]
).map(([key, label]) => (
<button
key={key}
@@ -439,6 +443,7 @@ export default function BusinessChainListPage() {
<ChainCard
key={chain.id}
chain={chain}
canManage={isAdmin || chain.isMine !== false}
publishing={publishingId === chain.id}
onSettings={() => goConfigure(chain.id)}
onTogglePublic={() => handleTogglePublic(chain)}
@@ -450,6 +455,7 @@ export default function BusinessChainListPage() {
) : (
<ChainTable
chains={visibleChains}
canManage={isAdmin}
publishingId={publishingId}
onSettings={(c) => goConfigure(c.id)}
onTogglePublic={handleTogglePublic}
@@ -620,18 +626,20 @@ function EmptyState({
function ChainCard({
chain,
canManage,
publishing,
onSettings,
onTogglePublic,
onDelete,
}: {
chain: BusinessChain;
/** 能否编辑 / 发布 / 删除(本人链条 或 管理员)。 */
canManage: boolean;
publishing: boolean;
onSettings: () => void;
onTogglePublic: () => void;
onDelete: () => void;
}) {
const isMine = chain.isMine !== false;
const ownerName = chain.ownerName ? chain.ownerName.split("@")[0] : "";
return (
@@ -685,8 +693,8 @@ function ChainCard({
</div>
</div>
{/* 操作按钮:仅本人链条可发布 / 设置 / 删除(公共里别人的链条只读浏览)。 */}
{isMine && (
{/* 操作按钮:本人链条或管理员可发布 / 设置 / 删除(普通用户看别人的链条只读浏览)。 */}
{canManage && (
<div className="flex shrink-0 items-center gap-1 opacity-80 transition-opacity group-hover:opacity-100">
<button
type="button"
@@ -892,12 +900,15 @@ function dotClass(avatarType: string): string {
function ChainTable({
chains,
canManage,
publishingId,
onSettings,
onTogglePublic,
onDelete,
}: {
chains: BusinessChain[];
/** 管理员:可管理任意链条(即使非本人)。 */
canManage: boolean;
publishingId: string | null;
onSettings: (c: BusinessChain) => void;
onTogglePublic: (c: BusinessChain) => void;
@@ -919,7 +930,7 @@ function ChainTable({
</thead>
<tbody className="divide-y divide-zinc-100 text-xs text-zinc-800 dark:divide-[#1A2F5A] dark:text-[#C5CFE0]">
{chains.map((chain) => {
const isMine = chain.isMine !== false;
const isMine = canManage || chain.isMine !== false;
const ownerName = chain.ownerName ? chain.ownerName.split("@")[0] : "—";
return (
<tr
@@ -15,24 +15,26 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useSearchParams } from "react-router-dom";
import { toast } from "sonner";
import {
ArrowLeft,
Boxes,
Code2,
ExternalLink,
LayoutPanelTop,
Loader2,
Pencil,
RefreshCw,
Sparkles,
} from "lucide-react";
import { Loader2, RefreshCw, Sparkles } from "lucide-react";
import { fetchDashboardInputJson } from "@/core/auth/dashboard-input";
import { readCopTaskDetail } from "@/core/auth/task-deeplink";
import { desensitizeDeep } from "@/lib/desensitize";
import { desensitize, makeDesensitizer } from "@/lib/desensitize";
import { useSensitiveWords, wordsToMap } from "@/strategy-components/api/sensitive-words";
import { useModels } from "@/core/models/hooks";
import { useTheme } from "@/contexts/ThemeContext";
import { DashboardApp } from "@/roundtable-planning/dashboard/DashboardApp";
import { Compass, Crosshair, Shield, Mountain, Lightbulb, Flag, FileText } from "lucide-react";
import { DashboardApp, type DashboardPage } from "@/roundtable-planning/dashboard/DashboardApp";
import { SituationOverview } from "@/roundtable-planning/dashboard-agent/SituationOverview";
import { EnemyDetail } from "@/roundtable-planning/dashboard-agent/EnemyDetail";
import { OurSituation } from "@/roundtable-planning/dashboard-agent/OurSituation";
import { EnvironmentDetail } from "@/roundtable-planning/dashboard-agent/EnvironmentDetail";
import { Judgement } from "@/roundtable-planning/dashboard-agent/Judgement";
import { Decision } from "@/roundtable-planning/dashboard-agent/Decision";
import { Disposal } from "@/roundtable-planning/dashboard-agent/Disposal";
import { parseSqReport, type SqReport } from "@/roundtable-planning/dashboard-agent/sq-report";
import { DesensitizeProvider } from "@/roundtable-planning/dashboard-agent/ui";
import { adaptReportData } from "@/roundtable-planning/dashboard/data-context";
import { DashboardChatPanel } from "@/roundtable-planning/components/DashboardChatPanel";
import { Step2SandboxLayout } from "@/roundtable-planning/components/Step2SandboxLayout";
@@ -56,9 +58,33 @@ function formatNow(): string {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/**
* 用**指定脱敏函数**深度遍历对象/数组(仅替换字符串值),返回新值(不改入参)。
* 与 `desensitizeDeep` 的差别:脱敏函数由调用方传入——这里直接用 `/api/sensitive-words`
* 查询结果构造(见组件内 `desensitizeText`),避免依赖全局 `DESENSITIZE_MAP` 的异步回灌时序。
*/
function deepDesensitize<T>(value: T, fn: (s: string) => string): T {
if (typeof value === "string") return fn(value) as unknown as T;
if (Array.isArray(value)) return value.map((v) => deepDesensitize(v, fn)) as unknown as T;
if (value && typeof value === "object") {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = deepDesensitize(v, fn);
return out as T;
}
return value;
}
type DashView = "chat" | "page";
type RenderMode = "app" | "html";
/**
* 静态页面阶段开关(先按设计图搭总览版式,动态数据后续再接):
* - 默认落在「大屏页面」视图,直接展示 SituationOverview 静态版式;
* - 不自动调用智能体抽取(避免静态阶段空跑)。
* 接入动态数据后置为 false 即恢复原有「请求数据→智能体抽取→查看大屏」流程。
*/
const STATIC_PREVIEW = true;
/** 从 URL / 路由 state / 登录暂存任务详情解析 taskId。 */
function useTaskId(): string {
const [searchParams] = useSearchParams();
@@ -83,6 +109,8 @@ export default function DashboardAgentPage() {
// 输入 JSON(登录拉取/占位)——auto-start 时由 buildInitialPrompt 闭包读取。
const inputRef = useRef<unknown>(null);
// 战情报告解析结果(selectSqReport → 各页面展示模型);解析失败/无数据 → null(页面回退占位)。
const [sqReport, setSqReport] = useState<SqReport | null>(null);
const dashboard = useStep3Dashboard({
intentReady: null,
@@ -113,7 +141,8 @@ export default function DashboardAgentPage() {
} = dashboard;
const [loading, setLoading] = useState(true);
const [view, setView] = useState<DashView>("chat");
// 静态阶段默认进「大屏页面」,直接展示静态版式(见 STATIC_PREVIEW)。
const [view, setView] = useState<DashView>(STATIC_PREVIEW ? "page" : "chat");
const [renderMode, setRenderMode] = useState<RenderMode>("app");
// 真实接口请求失败/无数据时的提示(真实模式不拿假数据兜底,改为提示+重试)。
const [inputError, setInputError] = useState<string | null>(null);
@@ -152,6 +181,18 @@ export default function DashboardAgentPage() {
fetchDashboardInputJson(taskId).catch(() => null),
]);
inputRef.current = input;
// 解析战情报告 → 各页面展示模型(容错:异常/无数据均不抛错,页面回退占位)。
try {
const parsed = parseSqReport(input);
// 调试:在浏览器控制台打印「接口原始 JSON」与「解析后的战情数据」,便于核对解析是否正确。
// eslint-disable-next-line no-console
console.log("[大屏绘制] taskId=%s\n原始输入 JSON:", taskId, input, "\n解析后 sqReport:", parsed);
setSqReport(parsed);
} catch (err) {
// eslint-disable-next-line no-console
console.warn("[大屏绘制] parseSqReport 解析失败:", err, "\n原始输入:", input);
setSqReport(null);
}
const savedDialogues = (session?.transcript as Step2Dialogue[] | undefined) ?? [];
const validReport = session?.reportJson && parseReportJson(session.reportJson);
if (validReport) {
@@ -161,14 +202,20 @@ export default function DashboardAgentPage() {
} else if (savedDialogues.length > 0) {
// 有历史聊天但无有效结果 → 进生成过程展示历史,不自动重跑(点「重新绘制」可重生成)。
hydrateTranscriptRef.current(savedDialogues, session?.reportJson ?? null);
setView("chat");
// 静态阶段仍停在「大屏页面」看版式(历史对话可点「编辑」查看)。
setView(STATIC_PREVIEW ? "page" : "chat");
} else {
// 无任何记录 → 接口返回了真实数据才启动模型抽取;否则提示(真实模式不拿假数据兜底)。
setView("chat");
if (input) {
startRef.current();
// 静态阶段(STATIC_PREVIEW):不自动抽取,停在「大屏页面」展示静态版式。
if (STATIC_PREVIEW) {
setView("page");
} else {
setInputError("未获取到任务数据:接口请求失败或未返回内容,请稍后重试。");
setView("chat");
if (input) {
startRef.current();
} else {
setInputError("未获取到任务数据:接口请求失败或未返回内容,请稍后重试。");
}
}
}
} finally {
@@ -206,8 +253,17 @@ export default function DashboardAgentPage() {
return () => setPreviewEnabled(false);
}, [view, setPreviewEnabled]);
// 展示层脱敏函数:**直接用 `/api/sensitive-words` 查询结果**构造(不走全局 DESENSITIZE_MAP),
// 避免与 `replaceDesensitizeMap` 的 effect 时序竞态——与侧边栏/导航栏菜单脱敏同一手法。
// 后台为空(或未加载)时回退到全局种子 `desensitize`。供大屏所有 react 页面 + 导航 Tab 文本共用。
const { data: sensitiveWords } = useSensitiveWords();
const desensitizeText = useMemo(() => {
const map = wordsToMap(sensitiveWords ?? []);
return Object.keys(map).length > 0 ? makeDesensitizer(map) : desensitize;
}, [sensitiveWords]);
// ── 大屏渲染数据(深度脱敏后渲染,覆盖大屏所有展示文本) ──
const report = useMemo(() => (data ? desensitizeDeep(data) : null), [data]);
const report = useMemo(() => (data ? deepDesensitize(data, desensitizeText) : null), [data, desensitizeText]);
const dashboardData = useMemo(
() => (report ? adaptReportData(report, formatNow()) : undefined),
[report],
@@ -218,6 +274,35 @@ export default function DashboardAgentPage() {
);
const hasResult = !!dashboardData || !!dashboardHtml;
// 展示层脱敏:所有页面文本经深度替换后再渲染(与会商大屏一致),脱敏函数来自后台敏感词查询。
const safeReport = useMemo<SqReport | null>(() => {
if (!sqReport) return null;
try {
return deepDesensitize(sqReport, desensitizeText) as SqReport;
} catch {
return sqReport; // 脱敏异常不影响展示
}
}, [sqReport, desensitizeText]);
// 是否有可展示的真实数据:战情报告(safeReport)或已生成的大屏(report-json / HTML)。
// 三者皆无 → 不渲染大屏的导航栏与标题,仅显示「暂无数据」。
const hasData = !!safeReport || !!dashboardData || !!dashboardHtml;
// 战情多页:总览 + 六个详情页;详情页传入对应的(脱敏后)真实数据(无则页面回退占位)。
// 导航 Tab 文本(label)也经 desensitizeText 脱敏后再传给 DashboardApp 渲染导航栏。
const dashPages: DashboardPage[] = useMemo(
() => [
{ id: "overview", label: desensitizeText("总览"), icon: <Compass className="h-4 w-4" />, content: <SituationOverview data={safeReport} /> },
{ id: "enemy", label: desensitizeText("敌情"), icon: <Crosshair className="h-4 w-4" />, content: <EnemyDetail data={safeReport?.enemy} /> },
{ id: "ours", label: desensitizeText("我情"), icon: <Shield className="h-4 w-4" />, content: <OurSituation data={safeReport?.ours} /> },
{ id: "field", label: desensitizeText("战场环境"), icon: <Mountain className="h-4 w-4" />, content: <EnvironmentDetail data={safeReport?.environment} /> },
{ id: "judge", label: desensitizeText("情况判断"), icon: <Lightbulb className="h-4 w-4" />, content: <Judgement data={safeReport?.judgement} /> },
{ id: "decision", label: desensitizeText("决心建议"), icon: <Flag className="h-4 w-4" />, content: <Decision data={safeReport?.decision} /> },
{ id: "disposal", label: desensitizeText("处置建议"), icon: <FileText className="h-4 w-4" />, content: <Disposal data={safeReport?.disposal} /> },
],
[safeReport, desensitizeText],
);
// 网页渲染:blob URL 作 iframe src(:target 导航需独立文档 URL,见 Step3DashboardMode 注释)。
const [htmlBlobUrl, setHtmlBlobUrl] = useState<string | null>(null);
useEffect(() => {
@@ -311,94 +396,39 @@ export default function DashboardAgentPage() {
}
return (
<div className="flex h-full min-h-0 flex-col text-slate-800 dark:text-slate-200">
{/* 顶栏 */}
<div className="dashboard-agent-topbar shrink-0 flex flex-wrap items-center justify-between gap-3 border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-6 py-3">
<div className="flex items-center gap-2.5">
<Sparkles className="h-4.5 w-4.5 text-primary" />
<h3 className="text-sm font-black tracking-tight text-slate-900">大屏绘制智能体</h3>
<span className="inline-flex items-center gap-1.5 rounded-full border border-red-200/50 bg-[var(--brand-200)]/60 px-2 py-0.5 text-[10px] font-bold text-primary">
{(phase === "creating" || phase === "streaming") && <Loader2 className="h-3 w-3 animate-spin" />}
{view === "chat" ? "生成过程" : "大屏页面"}
</span>
</div>
<div className="flex items-center gap-2">
{view === "page" ? (
<>
<div className="inline-flex items-center gap-0.5 rounded-xl border border-slate-200 bg-slate-50 p-0.5">
<button
type="button"
onClick={() => setRenderMode("app")}
title="用应用内 React 组件渲染(Tab 切换、动画、席位钻取)"
className={`flex items-center gap-1 rounded-lg px-2.5 py-1 text-[10.5px] font-bold transition ${
renderMode === "app"
? "border border-slate-200 bg-white text-primary shadow-sm"
: "text-slate-500 hover:text-slate-700"
}`}
>
<Boxes className="h-3.5 w-3.5" />
应用渲染
</button>
<button
type="button"
onClick={() => setRenderMode("html")}
disabled={!dashboardHtml}
title={dashboardHtml ? "用自包含 HTML 大屏渲染(与新窗口/下载一致)" : "尚无已生成的 HTML,先完成一次绘制"}
className={`flex items-center gap-1 rounded-lg px-2.5 py-1 text-[10.5px] font-bold transition disabled:cursor-not-allowed disabled:opacity-40 ${
renderMode === "html"
? "border border-slate-200 bg-white text-primary shadow-sm"
: "text-slate-500 hover:text-slate-700"
}`}
>
<Code2 className="h-3.5 w-3.5" />
网页渲染
</button>
</div>
<button
type="button"
onClick={() => setView("chat")}
title="回到生成过程,加载聊天记录继续问答修改"
className="flex items-center gap-1 rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-[10.5px] font-bold text-slate-700 transition hover:bg-slate-50"
>
<Pencil className="h-3.5 w-3.5 text-slate-500" />
编辑
</button>
<button
type="button"
onClick={handleOpenNewWindow}
title={renderMode === "html" ? "新标签页打开自包含 HTML 大屏" : "新标签页打开应用内 React 大屏(全屏)"}
className="flex items-center gap-1 rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-[10.5px] font-bold text-slate-700 transition hover:bg-slate-50"
>
<ExternalLink className="h-3.5 w-3.5 text-slate-500" />
新窗口打开
</button>
</>
) : (
hasResult && (
<button
type="button"
onClick={() => setView("page")}
title="查看已生成的大屏页面"
className="flex items-center gap-1 rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-[10.5px] font-bold text-slate-700 transition hover:bg-slate-50"
>
<LayoutPanelTop className="h-3.5 w-3.5 text-slate-500" />
查看大屏
</button>
)
)}
</div>
</div>
// dashboard-agent-fontscale:本页字号下限 16px(见 globals.css,仅作用于本页)。
<div className="dashboard-agent-fontscale flex h-full min-h-0 flex-col text-slate-800 dark:text-slate-200">
{/* 主体 */}
{loading ? (
// 加载框:请求战情报告期间显示,拿到数据后再渲染大屏(避免先闪占位再跳真实数据)。
<div className="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-slate-500">
<Loader2 className="h-6 w-6 animate-spin text-primary" />
<div className="text-center">
<div className="font-semibold text-slate-700">正在请求任务数据…</div>
<div className="mt-1 text-xs text-slate-400">拉取接口返回后将自动开始智能体抽取绘制</div>
<div className="mt-1 text-xs text-slate-400">拉取接口返回后展示大屏</div>
</div>
</div>
) : view === "page" ? (
!hasData ? (
// 无数据:隐藏大屏导航栏与顶部标题,仅显示「暂无数据」。
<div className="flex flex-1 items-center justify-center text-sm text-slate-400">
暂无数据
</div>
) : renderMode === "html" && htmlBlobUrl ? (
<iframe
title="任务研讨大屏"
src={htmlBlobUrl}
className="min-h-0 w-full flex-1 border-0 bg-white"
sandbox="allow-scripts allow-popups allow-downloads allow-same-origin"
/>
) : (
<div className="min-h-0 flex-1 overflow-auto">
{/* 注入后台敏感词脱敏函数:让战情各页(含静态卡片标题/表头/脚注等)统一脱敏。 */}
<DesensitizeProvider value={desensitizeText}>
<DashboardApp data={dashboardData} pages={dashPages} />
</DesensitizeProvider>
</div>
)
) : inputError && dialogues.length === 0 ? (
<div className="flex flex-1 items-center justify-center p-8 text-center text-sm text-slate-500">
<div className="max-w-sm">
@@ -414,19 +444,6 @@ export default function DashboardAgentPage() {
</button>
</div>
</div>
) : view === "page" ? (
renderMode === "html" && htmlBlobUrl ? (
<iframe
title="任务研讨大屏"
src={htmlBlobUrl}
className="min-h-0 w-full flex-1 border-0 bg-white"
sandbox="allow-scripts allow-popups allow-downloads allow-same-origin"
/>
) : (
<div className="min-h-0 flex-1 overflow-auto">
<DashboardApp data={dashboardData} />
</div>
)
) : (
<div className="min-h-0 flex-1 p-3">
<section className="h-full min-h-0 overflow-hidden rounded-2xl border border-slate-200/60 bg-white">
@@ -24,6 +24,8 @@
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { getStoredAuth } from "@/core/auth";
import { setRoundtableErrorContext } from "@/roundtable-planning/api/diagnostics-report";
import {
Activity,
BookOpen,
@@ -44,6 +46,7 @@ import {
Loader2,
Pencil,
Plus,
RotateCw,
Save,
Settings,
Sparkles,
@@ -67,6 +70,7 @@ import { getAvatar, Man1Avatar, RobotAvatar } from "@/roundtable-planning/compon
import { ImportRoundtableDraftDialog } from "@/components/workspace/roundtable-draft-share-dialogs";
import { TaskPurposeDialog } from "@/strategy-components/components/task-components/TaskPurposeDialog";
import { TaskJumpBar } from "@/strategy-components/components/task-components/TaskJumpBar";
import { RwfxSqReportGate } from "@/strategy-components/components/task-components/RwfxSqReportGate";
import type { TaskBusiness } from "@/core/auth/task-buttons";
import {
derivePurposeLevels,
@@ -78,6 +82,7 @@ import { RecommendAgentsDialog } from "@/roundtable-planning/components/Recommen
import { BusinessChainListDialog } from "@/roundtable-planning/components/BusinessChainListDialog";
import { DispatchChainJobModal } from "@/roundtable-planning/components/DispatchChainJobModal";
import { Step1Panel } from "@/roundtable-planning/components/Step1Panel";
import { readActionDetail, readCopTaskDetail } from "@/core/auth/task-deeplink";
import { Step2Panel } from "@/roundtable-planning/components/Step2Panel";
import { Step3Panel } from "@/roundtable-planning/components/Step3Panel";
import type {
@@ -98,7 +103,7 @@ import { useStep3Summary } from "@/roundtable-planning/hooks/useStep3Summary";
import { useStep3Report } from "@/roundtable-planning/hooks/useStep3Report";
import { useStep3Dashboard } from "@/roundtable-planning/hooks/useStep3Dashboard";
import { isDashboardHtml } from "@/roundtable-planning/lib/report-template";
import { isIngestSkillAvailable } from "@/roundtable-planning/api/ingest";
import { checkIngestEligibility } from "@/roundtable-planning/api/ingest";
import { stripReasoning } from "@/roundtable-planning/lib/reasoning";
import {
BUILTIN_AGENT_META,
@@ -157,10 +162,29 @@ interface RoundtablePrefill {
businessCode?: string;
/** 外部任务 id(无界抽屉):聊天记录按此存取、打开时回显最新一条。 */
taskId?: string;
/** xdfx 深链:原始行动 id(URL ?taskId= 传入的就是它)。供会商取行动详情用。 */
actionId?: string;
/** xdfx 深链:行动名称(注入 Step 1 首条用户消息——任务名称+任务描述+行动名称)。 */
actionName?: string;
/** 是否进入即自动开跑 Step 1 意图分析。 */
autoStart?: boolean;
}
/**
* 会商「聊天记录」存储键:草稿(useDraftPersistence / useRoundtableDrafts)与后台作业
* (startJob / getJobByDraft / cancelJob)统一按此键隔离与回显。
*
* - **xdfx-A(行动分析会商)**:同一任务下可派生多个「行动」,各行动的会商需互相独立,
* 故按「行动id」(`actionId`,即深链 URL `?taskId=` 原始传入值) 隔离,而非解析出的真实任务id。
* - 其它业务:无 `actionId`,回退真实 `taskId`。
*
* ⚠️ 仅用于聊天记录/作业存储。目的树、入库技能、任务详情、底部快捷跳转栏仍用真实
* `prefill.taskId`(见各调用点),不受此键影响。
*/
function recordTaskIdOf(prefill: RoundtablePrefill | null): string | null {
return prefill?.actionId ?? prefill?.taskId ?? null;
}
/**
* 无界(wujie)抽屉场景:父页面通过 `window.$wujie.props` 注入「任务名称/描述/业务链条」。
* iframe 降级时 props 可能晚于首帧,故再读 hash 路由 query 作兜底(宿主 `appendEmbedQueryToUrl` 写入)。
@@ -195,6 +219,11 @@ function readWujiePrefill(): RoundtablePrefill | null {
*/
const ROUNDTABLE_DEEPLINK_PREFILL_KEY = "roundtable:deeplink-prefill";
// 进第三步三流「错峰起跑」的基准间隔(毫秒)。结果绘制延迟 1×、大屏延迟 2×,把三个
// start_run 的写尖峰摊开,避免单 worker + 单 sqlite 锁瞬时被打满导致回环 502(削峰,
// 不影响并行展示进度)。取值偏小,用户基本无感。
const STEP3_STAGGER_MS = 300;
/** 按路由 path 持久化深链 prefill,供刷新后恢复。隐私模式/quota 异常静默失败。 */
function persistDeeplinkPrefill(path: string, prefill: RoundtablePrefill): void {
try {
@@ -283,6 +312,10 @@ export default function RoundtablePlanningPage() {
const [taskRestoreResolved, setTaskRestoreResolved] = useState<boolean>(
!prefillRef.current?.taskId,
);
// 深链/预填自动会话:进入页面后要先建意图线程、(带 taskId 时)回显历史草稿,这段时间
// 页面只有一句欢迎语、问答还没真正开始,线程创建慢时像卡住。下面这个标志用来在超时后
// 强制撤掉「启动加载遮罩」,避免万一初始化卡死把界面永久锁住。
const [bootLoadingExpired, setBootLoadingExpired] = useState<boolean>(false);
const { models: availableModels, isLoading: modelsLoading } = useModels();
@@ -305,6 +338,16 @@ export default function RoundtablePlanningPage() {
// Step 2 席位执行模式(快速/思考/专业问答/多智能体问答)——决定每个子智能体席位的
// 推理深度。由「选择参会智能体」弹窗确认时的 SeatSelectionResult.seatMode 决定。
const [seatMode, setSeatMode] = useState<SeatMode>(DEFAULT_SEAT_MODE);
// Step 2 每席位「技能识别强化」开关映射 {agentId: bool}:由所选业务链条里**每个席位**的同名
// 配置决定(recommend 无链条 → 空 {})。透传给每个席位 run,与各席位智能体自身的开关取 OR。
const [seatSkillDirectives, setSeatSkillDirectives] = useState<Record<string, boolean>>({});
// Step 2 每席位「推理深度覆盖」映射 {agentId: SeatMode|null}:由所选业务链条里**每个席位**单独配
// 的推理深度决定(null/未配 → 跟随链条级 seatMode)。透传给席位 run(覆盖优先、否则跟随 seatMode)。
// 「卡顿提速」用:把次要席位降到 flash 即可大幅缩短第二步耗时。
const [seatModes, setSeatModes] = useState<Record<string, SeatMode | null>>({});
// Step 2「研讨前并行取数」开关:由所选业务链条的 gatherFirst 决定(recommend / 无链条 → false)。
// true = 研讨前先并行跑一轮全席位『取数』,产出作为共享资料注入研讨轮,给(尤其 chain 串行)研讨段提速。
const [gatherFirst, setGatherFirst] = useState<boolean>(false);
// Step 2 编排模式:recommend = 总控自由派活;chain = 总控按业务链条顺序派活;
// dag = 分层 DAG(stage 内并行、stage 间串行,配合 orchestrationPlan)。
// 由推荐弹窗确认时的 SeatSelectionResult.mode 决定(见 handleConfirmAgents)。
@@ -328,11 +371,45 @@ export default function RoundtablePlanningPage() {
// 加载草稿时 hydrateStep3 恢复;新建任务清空。step3SavedTick 递增触发一次草稿自动保存。
const [step3Report, setStep3Report] = useState<DraftStep3Snapshot | null>(null);
const [step3SavedTick, setStep3SavedTick] = useState<number>(0);
// 入库技能是否可用(决定第三步生成流程图后是否询问入库 + 显示手动入库按钮)。挂载查一次。
// 入库是否可用 + 选中的入库技能:不再前端硬编码关键字,而是让**结构化输出智能体**读它
// 挂载的入库技能 + 当前业务场景**自行判断**是否有适合本场景的入库技能(决定第三步是否询问
// 入库 + 显示手动入库按钮)。入库仅深链(taskId)模式才有意义,故仅在该模式下判定。
const [ingestAvailable, setIngestAvailable] = useState<boolean>(false);
const [ingestSkill, setIngestSkill] = useState<string>("");
const ingestTaskIdForCheck = prefillRef.current?.taskId ?? null;
const ingestBusinessCode = prefillRef.current?.businessCode ?? null;
useEffect(() => {
void isIngestSkillAvailable().then(setIngestAvailable).catch(() => setIngestAvailable(false));
}, []);
if (!ingestTaskIdForCheck) {
setIngestAvailable(false);
setIngestSkill("");
return;
}
let cancelled = false;
void checkIngestEligibility({
taskId: ingestTaskIdForCheck,
businessCode: ingestBusinessCode,
chainName: chainMeta?.title ?? null,
coordinatorPrompt: orchestrationPlan?.coordinatorPrompt ?? null,
})
.then((r) => {
if (cancelled) return;
setIngestAvailable(r.canIngest);
setIngestSkill(r.skill);
})
.catch(() => {
if (cancelled) return;
setIngestAvailable(false);
setIngestSkill("");
});
return () => {
cancelled = true;
};
}, [
ingestTaskIdForCheck,
ingestBusinessCode,
chainMeta?.title,
orchestrationPlan?.coordinatorPrompt,
]);
const step2RunsRef = useRef<DraftStep2RunSnapshot[]>([]);
const activeStep2RunIdRef = useRef<string | null>(null);
// 并行执行时收起左侧栏 —— 全局工作区侧栏(最左)走 useSidebarSafe(与「打开沙箱」同一路径,
@@ -426,6 +503,9 @@ export default function RoundtablePlanningPage() {
currentStep,
selectedModel,
selectedMode: seatMode,
seatSkillDirectives,
seatModes,
gatherFirst,
orchestrationMode,
orchestrationPlan,
dagExecMode,
@@ -651,7 +731,8 @@ export default function RoundtablePlanningPage() {
currentStep,
setCurrentStep,
triggerToast,
taskId: prefillRef.current?.taskId ?? null,
// 聊天记录存储键:xdfx-A 按行动id 隔离,其它业务按真实 taskId(见 recordTaskIdOf)。
taskId: recordTaskIdOf(prefillRef.current),
intentSending: step1.isIntentSending,
step2FinalizedCount,
step3SavedTick,
@@ -878,6 +959,19 @@ export default function RoundtablePlanningPage() {
dashboardFlow.abort();
step2.resetStep2State();
step2.setSelectedAgents(normalized);
// per-seat 模型覆盖:业务链条为某些席位指定了模型 → 写进 agentConfigs。speakerId =
// 席位序号 + 2(与 selectedAgents 索引对齐,1 号是总控),与派活时
// `agentConfigs[meta.speakerId]?.model` 的读取一致。空 / 未指定 → model:""(跟随全局),
// 同时清掉上一轮选择残留的席位模型覆盖;prompt/temp/weight 沿用既有 Persona 配置。
step2.setAgentConfigs((prev) => {
const next = { ...prev };
result.agents.forEach((a, i) => {
const speakerId = i + 2;
const base = next[speakerId] ?? { model: "", weight: 85, temp: 0.3, prompt: "" };
next[speakerId] = { ...base, model: a.model ?? "" };
});
return next;
});
step2.resetInitGate();
// 这是从第一步确认席位、开启的一轮**实时**研讨(非查看历史/草稿) → 清掉
// “查看历史”闸门,否则之前看过历史记录留下的 true 会一直把「后台挂起」按钮藏掉。
@@ -890,6 +984,18 @@ export default function RoundtablePlanningPage() {
setOrchestrationMode(result.mode);
// 席位执行模式:弹窗未带(旧调用)时回退默认 pro,保证行为可预期。
setSeatMode(result.seatMode ?? DEFAULT_SEAT_MODE);
// 会商技能识别强化:取所选业务链条里**每席位**的开关 → {agentId: bool} 映射
// (recommend / 旧调用未带 → 空 {},各席位仅靠其智能体自身开关)。
setSeatSkillDirectives(
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.seat_skill_directive ?? false])),
);
// 每席位推理深度覆盖:取所选业务链条里**每席位**单独配的 seatMode → {agentId: SeatMode|null}
// 映射(recommend / 未配 → null,跟随链条级 seatMode)。
setSeatModes(
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.seatMode ?? null])),
);
// 研讨前并行取数:取所选业务链条的开关(recommend / 旧调用未带 → false)。
setGatherFirst(result.gatherFirst ?? false);
setChainMeta(result.mode === "recommend" ? null : result.chain ?? null);
setOrchestrationPlan(result.mode === "dag" ? result.plan ?? null : null);
setDagExecMode(result.mode === "dag" ? result.dagExecMode ?? "fast" : "fast");
@@ -956,7 +1062,8 @@ export default function RoundtablePlanningPage() {
// C1.5(无界回显):带 taskId 时,挂载即按任务取最新草稿回显。命中 → 抑制 autoStart
// (避免重复发首条消息);未命中 → 放行 autoStart 走全新任务。只跑一次。
useEffect(() => {
const tid = prefillRef.current?.taskId;
// 回显聊天记录按存储键(xdfx-A=行动id),与 useDraftPersistence 的 taskId 保持一致。
const tid = recordTaskIdOf(prefillRef.current);
if (!tid) return;
let cancelled = false;
void (async () => {
@@ -1004,7 +1111,13 @@ export default function RoundtablePlanningPage() {
if (!step1.intentThreadId || step1.intentReady) return;
const title = prefill.taskTitle?.trim();
const goal = prefill.taskGoal?.trim();
const text = [title ? `任务名称:${title}` : "", goal ? `任务描述:${goal}` : ""]
// xdfx(行动分析):除任务名称/描述外,再带上「行动名称」一起交给任务理解智能体。
const actionName = prefill.businessCode === "7BF" ? prefill.actionName?.trim() : "";
const text = [
title ? `任务名称:${title}` : "",
goal ? `任务描述:${goal}` : "",
actionName ? `行动名称:${actionName}` : "",
]
.filter(Boolean)
.join("\n");
if (!text) return;
@@ -1052,6 +1165,35 @@ export default function RoundtablePlanningPage() {
};
}, []);
// ── 启动加载遮罩(深链/预填自动会话)──────────────────────────────
// 是否是「自动会话」:深链 -A、taskId、businessCode/chainId 任一存在即自动进入问答,
// 用户没有手动操作,进入页面到问答之间必须给出明确加载反馈。
const isAutoSession = Boolean(
prefillRef.current?.autoStart ||
prefillRef.current?.taskId ||
prefillRef.current?.businessCode ||
prefillRef.current?.chainId,
);
// 「问答已开始」:自动发出的首条用户消息已入列 / 正在流式 / 已得到意图结果,任一为真即认为
// 已经动起来,可以撤掉遮罩交给 Step1Panel 自身的流式占位。
const conversationStarted =
step1.isIntentSending ||
step1.intentReady != null ||
step1.interactiveMessages.some((m) => m.sender === "user");
// 遮罩展示条件:自动会话 + 仍在 Step1 + 问答还没开始 + 没有初始化报错 + 没到安全超时。
const showBootLoading =
isAutoSession &&
currentStep === 1 &&
!conversationStarted &&
!step1.intentInitError &&
!bootLoadingExpired;
// 安全超时:无论如何最多遮 30s,避免初始化卡死锁住界面(用户仍可手动操作底层页面)。
useEffect(() => {
if (!showBootLoading) return;
const timer = window.setTimeout(() => setBootLoadingExpired(true), 30_000);
return () => window.clearTimeout(timer);
}, [showBootLoading]);
/** 组装无界回传载荷:总控共识 + 各智能体最终交付(剔除总控席位)。 */
const buildWujieConsensusPayload = useCallback(
() => ({
@@ -1078,6 +1220,14 @@ export default function RoundtablePlanningPage() {
return emitWujieEvent("roundtable:consensus", buildWujieConsensusPayload());
}, [buildWujieConsensusPayload, inWujieEmbed]);
// 让前端报错上报器能把每条报错归属到当前草稿 / 任务(无需穿进每个底层 api 调用)。
useEffect(() => {
setRoundtableErrorContext({
draftId: drafts.currentDraftId ?? undefined,
taskId: prefillRef.current?.taskId ?? undefined,
});
}, [drafts.currentDraftId]);
const handleSettingsClick = useCallback(() => {
if (inWujieEmbed) {
const deliverables = buildWujieConsensusPayload().deliverables;
@@ -1090,8 +1240,13 @@ export default function RoundtablePlanningPage() {
}
return;
}
// 管理员:打开「会商诊断日志」页(全流程报错排查)。非管理员维持原占位提示。
if (getStoredAuth()?.system_role === "admin") {
navigate("/page/strategy/admin/roundtable-diagnostics");
return;
}
triggerToast("⚙️ 系统管理面板拉取中(暂不开放外部审计)");
}, [buildWujieConsensusPayload, emitConsensusToParent, inWujieEmbed, triggerToast]);
}, [buildWujieConsensusPayload, emitConsensusToParent, inWujieEmbed, navigate, triggerToast]);
// C4(无界回传):第二步**本次 live 研讨** newly 达成共识时,把总控结论 + 各智能体交付广播给父页面。
// 草稿/任务回显(抽屉重开)已在 hydrate 时 markRestoredConsensusAsEmitted,不再重复 emit。
@@ -1174,6 +1329,10 @@ export default function RoundtablePlanningPage() {
ingestAvailable,
// 入库仅深链(taskId)模式(会商 rwfx-A 等)才有;taskId 入库时必传给技能。
taskId: prefillRef.current?.taskId ?? null,
// 入库场景线索:适用性判定选中的技能 + 业务码/链名,入库时引导智能体挑对入库技能。
ingestSkill,
ingestBusinessCode,
ingestChainName: chainMeta?.title ?? null,
});
// render 期镜像总结报告的实时对话(文字 + 步骤条) + stub + 入库状态,供 getStep3Snapshot 落库。
step3SummaryConvoRef.current = {
@@ -1213,6 +1372,19 @@ export default function RoundtablePlanningPage() {
// 已有存稿则恢复展示。只在「本次会话首次进入第三步」时编排一次 —— 之后进出第三步
// 全是续看(流在页面层不中断);切换草稿 / 新建任务时复位入口闸门。
const step3EnteredRef = useRef(false);
// 进第三步「错峰起跑」定时器。三流虽互无依赖、要并行展示进度,但若**同一刻**一起
// 调 start()(各自 init thread + run/stream),会把单 worker 网关 + 单连接 sqlite
// checkpoint 锁的瞬时压力顶满,回环 /runs/stream 概率性返回非 200 → 前端冒 502。
// 这里把后两个流的**起跑**各往后挪一点点(仅错开 start_run 的写尖峰,不是串行等前一个
// 跑完),削峰即可。定时器存 ref,切草稿 / 重新 hydrate / 新建任务时统一清掉,避免迟发的
// start() 打到已被复位/中断的上下文。
const step3StartTimersRef = useRef<number[]>([]);
const clearStep3StartTimers = useCallback(() => {
for (const t of step3StartTimersRef.current) {
if (typeof window !== "undefined") window.clearTimeout(t);
}
step3StartTimersRef.current = [];
}, []);
// step3Report 用 ref 持最新值,供 hydrate 同步读取(避免闭包取到旧草稿快照)。
const step3ReportRef = useRef(step3Report);
step3ReportRef.current = step3Report;
@@ -1234,8 +1406,24 @@ export default function RoundtablePlanningPage() {
// 保证总结/经典/大屏的展示数据跟随当前草稿实时切换。
const hydrateStep3Flows = useCallback(() => {
step3EnteredRef.current = true;
// 重新编排前先清掉上一轮可能还没触发的错峰定时器(切草稿重 hydrate 时)。
clearStep3StartTimers();
const rep = step3ReportRef.current;
// ① 方案总结报告
// 错峰起跑助手:把一个尚未起跑的流延迟 delayMs 后再 start();触发前再校验
// step3EnteredRef(被新建任务 / 切草稿复位为 false 则跳过),避免迟发的 start()
// 打到已被中断的上下文。delay=0 表示立即(同步)起跑。
const staggerStart = (start: () => void, delayMs: number) => {
if (delayMs <= 0 || typeof window === "undefined") {
start();
return;
}
const id = window.setTimeout(() => {
if (!step3EnteredRef.current) return;
start();
}, delayMs);
step3StartTimersRef.current.push(id);
};
// ① 方案总结报告(主页,立即起跑)
const savedSum = rep?.summaryReport;
if (savedSum && (savedSum.md.trim() || (savedSum.closing ?? "").trim())) {
summaryFlow.hydrateSaved(savedSum);
@@ -1243,14 +1431,14 @@ export default function RoundtablePlanningPage() {
summaryFlow.start();
}
// ② 结果绘制(经典模式一)。旧版草稿可能把大屏 HTML 存在 html 槽位(带 marker),
// 那不是经典产物 → 经典照常启动。
// 那不是经典产物 → 经典照常启动。错峰 ~300ms,削掉与总结的同刻 start 尖峰。
if (rep?.html && !isDashboardHtml(rep.html)) {
reportFlow.hydrateSaved(rep);
} else {
reportFlow.start(); // 与总结报告并行绘制,进入「结果绘制」即见进行中过程/结果
staggerStart(() => reportFlow.start(), STEP3_STAGGER_MS); // 仍并行绘制,只是起跑错开
}
// ③ 大屏多页(模式二):优先 dashboardJson(按当前主题渲染);旧版 marker html 兜底。
// 带上大屏生成过程的完整对话(文字 + 步骤条),恢复时整段回显。
// 带上大屏生成过程的完整对话(文字 + 步骤条),恢复时整段回显。错峰 ~600ms。
const dashSaved = {
dialogues: rep?.dashboardDialogues,
seatStubMessages: rep?.dashboardSeatStubMessages,
@@ -1260,10 +1448,10 @@ export default function RoundtablePlanningPage() {
} else if (rep?.html && isDashboardHtml(rep.html)) {
dashboardFlow.hydrateSaved(rep.html, dashSaved);
} else {
dashboardFlow.start();
staggerStart(() => dashboardFlow.start(), STEP3_STAGGER_MS * 2);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [summaryFlow, reportFlow, dashboardFlow]);
}, [summaryFlow, reportFlow, dashboardFlow, clearStep3StartTimers]);
// 切换草稿:先停掉旧草稿的在途 Step3 流(防串台)。声明在 hydrate effect **之前**,
// 保证同一提交内先 abort 旧流、再由下方 effect hydrate 新草稿,顺序不颠倒。
@@ -1274,6 +1462,7 @@ export default function RoundtablePlanningPage() {
const prev = abortPrevDraftIdRef.current;
abortPrevDraftIdRef.current = drafts.currentDraftId;
if (prev && drafts.currentDraftId && prev !== drafts.currentDraftId) {
clearStep3StartTimers(); // 切草稿:取消尚未触发的错峰 start,防打到新草稿上下文
summaryFlow.abort();
reportFlow.abort();
dashboardFlow.abort();
@@ -1304,7 +1493,7 @@ export default function RoundtablePlanningPage() {
step2.stopOrchestration();
// 1. 取消后端作业:避免前后端双跑/抢同一线程(409),线程随后由前端接管续跑。
// executor.cancel 会 task.cancel() 中断在跑的 run,DB 同步置 cancelled。
await cancelJob(jobId, prefillRef.current?.taskId ?? null).catch(() => null);
await cancelJob(jobId, recordTaskIdOf(prefillRef.current)).catch(() => null);
// 2. 加载作业最近写回草稿的快照:恢复 threadIds(作业真实线程)+ 协调名 + 完整对话。
// hydrateFromDraft 已同步写好 threadIds/coordinatorName 的 ref,供下一步接管即时读取。
await drafts.handleLoadDraft(draftId);
@@ -1335,6 +1524,7 @@ export default function RoundtablePlanningPage() {
setStep3Report(null);
// 停掉页面层的 Step3 三个生成流(新任务不该带着旧任务的流跑)+ 复位进入闸门,
// 并停止后台作业实时跟随(作业本身继续在后台跑)。
clearStep3StartTimers(); // 取消尚未触发的错峰 start
summaryFlow.abort();
reportFlow.abort();
dashboardFlow.abort();
@@ -1358,6 +1548,15 @@ export default function RoundtablePlanningPage() {
triggerToast("✨ 已开始新任务,请在第一步与任务理解智能体澄清需求");
}, [resetToStep1, triggerToast]);
// 深链接(taskId)模式专用的「重新分析」:清空第一步会话、保留当前任务(prefill 不动),并复位
// autoStarted 闸门,让 C2 自动把「任务名称/描述」重新作为首条消息发出,对同一任务重做意图分析。
// 与「新建任务」(全新空白任务) 区分——深链接下任务是固定的,重来=重新分析这条任务。
const handleReanalyze = useCallback(() => {
autoStartedRef.current = false;
resetToStep1();
triggerToast("🔄 已重新分析当前任务");
}, [resetToStep1, triggerToast]);
// 无界抽屉保活复用:父页面重开抽屉时 `bus.$emit('roundtable:reset')` → 子应用回到第一步。
// 非无界环境下 onWujieEvent 返回 no-op,安全无副作用。
useEffect(() => {
@@ -1398,7 +1597,8 @@ export default function RoundtablePlanningPage() {
if (agents.length === 0) return null;
// 后台挂起发起前**立刻强制存一次**当前聊天(保住发起时刻的本地研讨记录,防丢)。
const draftId = await drafts.saveDraftNow(2);
const tid = prefillRef.current?.taskId ?? null;
// 后台作业按聊天记录存储键归属(xdfx-A=行动id):报告写回对应 task-draft 存储、去重一致。
const tid = recordTaskIdOf(prefillRef.current);
// 防重复:该草稿已有在跑作业就不再新建(避免重复作业 / 前后端双跑)。
const existing = draftId ? await getJobByDraft(draftId, tid).catch(() => null) : null;
const alreadyRunning =
@@ -1416,6 +1616,10 @@ export default function RoundtablePlanningPage() {
agents,
model: selectedModel || undefined, // 模型沿用第二步选择
seatMode, // 席位执行模式沿用第二步选择(后台续跑同样按此模式跑席位)
seatSkillDirectives, // 每席位技能识别强化沿用所选业务链条里各席位的开关
seatModes, // 每席位推理深度覆盖沿用所选业务链条里各席位的配置
gatherFirst, // 研讨前并行取数沿用所选业务链条的开关
businessCode: prefillRef.current?.businessCode ?? undefined, // 深链接业务码 → 后台总结业务链完整性核对
// 后台作业引擎支持 dag(后端 _run_dag:stage 串行 / stage 内并行)——
// 直接把当前编排模式透传,业务链的分层 / 并行 / 阶段目标 / 总控提示词全部保留。
orchestrationMode,
@@ -1432,6 +1636,9 @@ export default function RoundtablePlanningPage() {
drafts,
selectedModel,
seatMode,
seatSkillDirectives,
seatModes,
gatherFirst,
orchestrationMode,
orchestrationPlan,
chainMeta,
@@ -1455,11 +1662,15 @@ export default function RoundtablePlanningPage() {
const intent = buildInitialIntent();
const model = selectedModel || undefined;
const seatModeSnap = seatMode;
const seatSkillDirectivesSnap = seatSkillDirectives;
const seatModesSnap = seatModes;
const gatherFirstSnap = gatherFirst;
const mode = orchestrationMode;
const chainSnap = chainMeta;
const planSnap = mode === "dag" ? orchestrationPlan : null;
const draftId = drafts.currentDraftId;
const tid = prefillRef.current?.taskId ?? null;
// 后台作业按聊天记录存储键归属(xdfx-A=行动id),与草稿存储一致。
const tid = recordTaskIdOf(prefillRef.current);
// 立刻:标记「挂起中」+ 跳回第一步 + 提示(不等接口)。
if (draftId) markPendingSuspend(draftId);
@@ -1489,6 +1700,10 @@ export default function RoundtablePlanningPage() {
agents,
model,
seatMode: seatModeSnap,
seatSkillDirectives: seatSkillDirectivesSnap,
seatModes: seatModesSnap,
gatherFirst: gatherFirstSnap,
businessCode: prefillRef.current?.businessCode ?? undefined,
orchestrationMode: mode,
chain: chainSnap,
orchestrationPlan: planSnap,
@@ -1512,6 +1727,9 @@ export default function RoundtablePlanningPage() {
buildInitialIntent,
selectedModel,
seatMode,
seatSkillDirectives,
seatModes,
gatherFirst,
orchestrationMode,
orchestrationPlan,
chainMeta,
@@ -1547,11 +1765,15 @@ export default function RoundtablePlanningPage() {
if (agents.length === 0) return;
startJobKeepalive({
draftId: drafts.currentDraftId ?? undefined,
taskId: prefillRef.current?.taskId ?? undefined,
taskId: recordTaskIdOf(prefillRef.current) ?? undefined,
intent: buildInitialIntent(),
agents,
model: selectedModel || undefined,
seatMode,
seatSkillDirectives,
seatModes,
gatherFirst,
businessCode: prefillRef.current?.businessCode ?? undefined,
orchestrationMode,
chain: chainMeta,
orchestrationPlan: orchestrationMode === "dag" ? orchestrationPlan : null,
@@ -1611,10 +1833,34 @@ export default function RoundtablePlanningPage() {
return (
<div
className={cn(
"roundtable-planning theme-transition flex h-full min-h-0 flex-col bg-[#fef6f6] font-sans text-slate-800 selection:bg-red-200",
"roundtable-planning theme-transition relative flex h-full min-h-0 flex-col bg-[#fef6f6] font-sans text-slate-800 selection:bg-red-200",
isDark && "roundtable-planning--dark",
)}
>
{/* 启动加载遮罩:深链/预填自动会话从进入页面到问答真正开始(建意图线程 / 回显历史草稿)
期间全屏覆盖,避免线程创建慢时页面像卡住。问答一旦开始或超时即撤掉。 */}
{showBootLoading && (
<div
className="absolute inset-0 z-50 flex items-center justify-center bg-white"
role="status"
aria-live="polite"
>
<div className="flex flex-col items-center gap-7 px-8">
<div className="flex flex-col items-center gap-2 text-center">
<p className="text-lg font-semibold tracking-wide text-slate-800">
正在准备多智能体会商
</p>
<p className="text-sm text-slate-400">正在初始化任务理解智能体,请稍候…</p>
</div>
<span className="inline-flex items-center gap-1.5">
<span className="h-2 w-2 animate-bounce rounded-full bg-red-400 [animation-delay:-0.3s]" />
<span className="h-2 w-2 animate-bounce rounded-full bg-red-400 [animation-delay:-0.15s]" />
<span className="h-2 w-2 animate-bounce rounded-full bg-red-400" />
</span>
</div>
</div>
)}
<RecommendAgentsDialog
open={isRecommendDialogOpen}
intent={step1.intentReady}
@@ -1709,7 +1955,8 @@ export default function RoundtablePlanningPage() {
</button>
)}
{!inWujieEmbed && (
{/* 深链接(taskId)模式:业务链由 businessCode 自动决定,隐藏手动「业务链条」入口。 */}
{!inWujieEmbed && !prefillRef.current?.taskId && (
<button
id="business-chain-btn"
onClick={() => setIsChainListOpen(true)}
@@ -1721,15 +1968,28 @@ export default function RoundtablePlanningPage() {
</button>
)}
<button
id="new-task-btn"
onClick={handleStartNewTask}
title="清空当前会话,从第一步开始一个全新任务"
className="bg-emerald-600 text-white hover:bg-emerald-700 text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition-all shadow-sm shadow-emerald-500/10 active:scale-95"
>
<Sparkles className="w-3.5 h-3.5" />
新建任务
</button>
{/* 深链接(taskId)模式:任务固定,把「新建任务」换成「重新分析」——清空会话、对同一任务重做意图分析。 */}
{prefillRef.current?.taskId ? (
<button
id="reanalyze-task-btn"
onClick={handleReanalyze}
title="清空当前会话,对当前任务重新做意图分析"
className="bg-emerald-600 text-white hover:bg-emerald-700 text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition-all shadow-sm shadow-emerald-500/10 active:scale-95"
>
<RotateCw className="w-3.5 h-3.5" />
重新分析
</button>
) : (
<button
id="new-task-btn"
onClick={handleStartNewTask}
title="清空当前会话,从第一步开始一个全新任务"
className="bg-emerald-600 text-white hover:bg-emerald-700 text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1.5 transition-all shadow-sm shadow-emerald-500/10 active:scale-95"
>
<Sparkles className="w-3.5 h-3.5" />
新建任务
</button>
)}
<button
id="save-draft-header-btn"
@@ -1781,7 +2041,13 @@ export default function RoundtablePlanningPage() {
<button
id="settings-btn"
onClick={handleSettingsClick}
title={inWujieEmbed ? "回传各智能体交付结果给宿主" : "系统设置"}
title={
inWujieEmbed
? "回传各智能体交付结果给宿主"
: getStoredAuth()?.system_role === "admin"
? "会商诊断日志"
: "系统设置"
}
className="p-1.5 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 transition-colors dark:text-muted-foreground dark:hover:bg-accent dark:hover:text-foreground"
>
<Settings className="w-4 h-4" />
@@ -1814,7 +2080,8 @@ export default function RoundtablePlanningPage() {
onSelectChain={handleSelectChainFromSidebar}
onOpenDraft={drafts.handleLoadDraft}
activeDraftId={drafts.currentDraftId}
entryRailTaskId={prefillRef.current?.taskId ?? null}
entryRailTaskId={recordTaskIdOf(prefillRef.current)}
entryRailBusinessCode={prefillRef.current?.businessCode ?? null}
/>
{/* MIDDLE VIEWPORT */}
@@ -1825,7 +2092,10 @@ export default function RoundtablePlanningPage() {
{currentStep === 1 && (
<Step1Panel
headerLeftSlot={
prefillRef.current?.taskId && purposeLevels.length > 0 ? (
// 「原任务已有结果」(目的树预览)只在 rwfx-A(6BF)模式显示;xdfx/3qfx 不显示。
prefillRef.current?.taskId &&
prefillRef.current?.businessCode === "6BF" &&
purposeLevels.length > 0 ? (
<PurposeFlowPreview
levels={purposeLevels}
onOpen={() => setIsTaskPurposeOpen(true)}
@@ -1984,6 +2254,16 @@ export default function RoundtablePlanningPage() {
roundtable
/>
)}
{/* 任务分析会商(rwfx-A)深链:与单智能体共用 3q 预检闸门,未完成则引导前往三情**会商**(3qfx-A)。 */}
{prefillRef.current?.taskId &&
prefillRef.current?.businessCode &&
BUSINESS_CODE_TO_TASK_BUSINESS[prefillRef.current.businessCode] === "rwfx" && (
<RwfxSqReportGate
taskId={prefillRef.current.taskId}
targetGoPath="3qfx-A"
targetLabel="3qfx 会商"
/>
)}
</div>
);
}
@@ -2344,6 +2624,8 @@ interface LeftSidebarProps {
activeDraftId: string | null;
/** 深链 taskId 模式:Step1 落地左栏「分析记录」只列该任务的草稿。 */
entryRailTaskId?: string | null;
/** 深链业务码:左上角卡片据此决定显示「当前任务」(rwfx/3qfx) 还是「当前行动」(xdfx)。 */
entryRailBusinessCode?: string | null;
}
function Step2SandboxSidebarSync({
@@ -2390,6 +2672,7 @@ function LeftSidebar({
onOpenDraft,
activeDraftId,
entryRailTaskId,
entryRailBusinessCode,
}: LeftSidebarProps) {
// 整片脱敏:左侧面板(任务概览/参与角色/人工参与等)的所有文本——标题、动态内容、
// 嵌套子组件文本一并脱敏。消息列表与沙箱是另外的容器,不挂此 Hook,保持原文。
@@ -2527,6 +2810,7 @@ function LeftSidebar({
onOpenDraft={onOpenDraft}
activeDraftId={activeDraftId}
taskId={entryRailTaskId ?? null}
businessCode={entryRailBusinessCode ?? null}
/>
)}
</section>
@@ -2573,6 +2857,7 @@ function RoundtableEntryRail({
onOpenDraft,
activeDraftId,
taskId,
businessCode,
}: {
selectedChainId: string | null;
onSelectChain: (chain: BusinessChain) => void;
@@ -2580,12 +2865,25 @@ function RoundtableEntryRail({
activeDraftId: string | null;
/** 深链 taskId 模式:分析记录只列该任务的草稿。 */
taskId?: string | null;
/** 深链业务码:xdfx(7BF) 左上角显示「当前行动」,其余显示「当前任务」。 */
businessCode?: string | null;
}) {
const [chains, setChains] = useState<BusinessChain[]>([]);
const [expandedChainId, setExpandedChainId] = useState<string | null>(null);
const { drafts: records, refresh } = useRoundtableDrafts(taskId);
// 深链接(taskId)模式:左上角不显示「业务链选择」(链条已由 businessCode 自动决定),改为展示
// 当前任务(rwfx/3qfx)或当前行动(xdfx)。xdfx 的根是「行动」,故展示行动名称 + 叙事。
const deeplink = Boolean(taskId);
const isXdfx = businessCode === "7BF";
const taskDetail = deeplink && !isXdfx ? readCopTaskDetail() : null;
const actionDetail = deeplink && isXdfx ? readActionDetail() : null;
useEffect(() => {
// 深链接模式不展示业务链选择 → 不必拉公共链条。
if (deeplink) {
void refresh();
return;
}
let cancelled = false;
void listChains("public")
.then((all) => {
@@ -2598,7 +2896,7 @@ function RoundtableEntryRail({
return () => {
cancelled = true;
};
}, [refresh]);
}, [refresh, deeplink]);
const formatTime = (value: string) => {
const date = new Date(value);
@@ -2614,7 +2912,49 @@ function RoundtableEntryRail({
return (
<>
{/* 业务链(公共,前 3 个) */}
{/* 深链接(taskId)模式:左上角展示「当前任务」(rwfx/3qfx)或「当前行动」(xdfx),替代业务链选择。 */}
{deeplink ? (
isXdfx ? (
<div className="bg-white border border-[#ECE7E4] rounded-2xl p-4 shadow-[0_4px_20px_rgba(0,0,0,0.02)]">
<div className="flex items-center gap-2 mb-3">
<span className="flex items-center justify-center w-5 h-5 rounded-md bg-primary text-primary-foreground">
<Target className="w-3 h-3" strokeWidth={2.5} />
</span>
<h2 className="text-sm font-semibold tracking-wide text-slate-900">当前行动</h2>
</div>
<div>
<p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">行动名称</p>
<p className="mt-0.5 text-xs font-semibold leading-relaxed text-slate-800">
{actionDetail?.actionName?.trim() || "(未获取到行动名称)"}
</p>
</div>
</div>
) : (
<div className="bg-white border border-[#ECE7E4] rounded-2xl p-4 shadow-[0_4px_20px_rgba(0,0,0,0.02)]">
<div className="flex items-center gap-2 mb-3">
<span className="flex items-center justify-center w-5 h-5 rounded-md bg-primary text-primary-foreground">
<Clipboard className="w-3 h-3" strokeWidth={2.5} />
</span>
<h2 className="text-sm font-semibold tracking-wide text-slate-900">当前任务</h2>
</div>
<div className="space-y-2">
<div>
<p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">任务名称</p>
<p className="mt-0.5 text-xs font-semibold leading-relaxed text-slate-800">
{taskDetail?.taskName?.trim() || "(未获取到任务名称)"}
</p>
</div>
<div>
<p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">任务描述</p>
<p className="mt-0.5 whitespace-pre-wrap text-[11px] leading-relaxed text-slate-600">
{taskDetail?.taskContent?.trim() || "(未获取到任务描述)"}
</p>
</div>
</div>
</div>
)
) : (
/* 业务链(公共,前 3 个) */
<div className="bg-white border border-[#ECE7E4] rounded-2xl p-4 shadow-[0_4px_20px_rgba(0,0,0,0.02)] transition-shadow duration-300 hover:shadow-[0_4px_24px_rgba(45,37,34,0.04)]">
<div className="flex items-center gap-2 mb-3">
<span className="flex items-center justify-center w-5 h-5 rounded-md bg-primary text-primary-foreground">
@@ -2795,6 +3135,7 @@ function RoundtableEntryRail({
</div>
)}
</div>
)}
{/* 分析记录(圆桌历史草稿) */}
<div className="bg-white border border-[#ECE7E4] rounded-2xl p-4 shadow-[0_4px_20px_rgba(0,0,0,0.02)] flex-1 flex flex-col min-h-[200px] overflow-hidden">
@@ -2857,13 +3198,16 @@ function RoundtableEntryRail({
{completed ? "已完成" : "未完成"}
</span>
</div>
{/* 下:时间(左下) + 步骤(右下) */}
<div className="mt-2 flex items-center justify-between">
<span className="font-mono text-[10px] text-neutral-400">
{/* 下:时间(左下) + 业务链(右下,无链条显示「自由模式」) */}
<div className="mt-2 flex items-center justify-between gap-2">
<span className="font-mono text-[10px] text-neutral-400 shrink-0">
{formatTime(rec.updatedAt)}
</span>
<span className="rounded-[5px] bg-neutral-100 px-1.5 py-0.5 text-[10px] font-medium text-neutral-500">
第 {rec.furthestStep} 步
<span
className="max-w-[60%] truncate rounded-[5px] bg-neutral-100 px-1.5 py-0.5 text-[10px] font-medium text-neutral-500"
title={rec.chainTitle || "自由模式"}
>
{rec.chainTitle || "自由模式"}
</span>
</div>
</button>
@@ -556,3 +556,38 @@
.roundtable-planning--dark .custom-scrollbar-inner::-webkit-scrollbar-thumb {
background: color-mix(in oklch, var(--primary) 35%, var(--border));
}
/* =============================================================================
* 会商消息列表滚动条易用性修复(Step1/Step2/Step3 都受益)。
*
* 症状:鼠标移到右侧纵向滚动条滑块上特别容易触发「左右拖动」,导致点不到滑块。
*
* 根因 1(Step2/Step3 有沙箱/流程图分栏时):分栏拖拽手柄
* `#roundtable-step2-separator`(react-resizable-panels Separator)默认命中区是
* `::after { left:50%; width:16px; transform:translateX(-50%) }`——居中跨在分隔线
* 上、向左探出 8px,正好压住左侧消息列表那条贴右边的纵向滚动条。于是抓滚动条时
* 实际抓到了 `cursor-col-resize` 的手柄命中区 → 误触发左右拖动、点不到滑块。
* 修法:把命中区整体挪到分隔线**右侧(沙箱一侧)**,左侧滚动条彻底让出。
* ID 选择器特异性(1,0,1) 高于 Tailwind 的 `after:*` 工具类(0,1,1),无视加载顺序生效。
*
* 根因 2(所有步骤通用):默认滚动条只有 6px,太细难抓。仅在 .roundtable-planning
* 作用域内加宽到 12px,并用「透明边框 + background-clip:padding-box」把可见滑块收
* 成带内边距的圆条(更像可抓的条,而非贴边细线),命中区仍是整 12px。
* ========================================================================== */
#roundtable-step2-separator::after {
left: 0;
right: auto;
width: 14px;
transform: none;
}
.roundtable-planning ::-webkit-scrollbar {
width: 12px;
height: 12px;
}
.roundtable-planning ::-webkit-scrollbar-thumb {
border: 3px solid transparent;
background-clip: padding-box;
border-radius: 9999px;
}
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more