Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
719ff6f210 | ||
|
|
1f74586032 |
No files matched your search
@@ -104,6 +104,3 @@ docs/backups
|
|||||||
|
|
||||||
# uv lockfile (not tracked per project preference)
|
# uv lockfile (not tracked per project preference)
|
||||||
offline-backend-20260512/backend/uv.lock
|
offline-backend-20260512/backend/uv.lock
|
||||||
|
|
||||||
# misc
|
|
||||||
.DS_Store
|
|
||||||
@@ -80,15 +80,11 @@ 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`
|
- **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)
|
- **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).
|
- **轻应用中心 (Light App Center)**: a sibling of 任务管理 in the sidebar with two pages — 应用管理 (admin registers `window_open` or `iframe` mini-apps with a route-param builder: login params resolved from `localStorage.userInfo`, theme params literal) and 应用列表 (card grid of `window_open` apps, `window.open` launch). `iframe` apps are mounted under a chosen parent menu (XK/PG/TY/综合管理) and **dynamically injected into the sidebar** by `core/page-layout/use-sidebar-menu.ts` (`useSidebarMenuItems`), opening in the `LightAppIframeView` host. Client + React Query hooks in `strategy-components/api/light-apps.ts`; URL builder/constants in `strategy-components/lib/light-app.ts`. Backend: `/api/light-apps` (global/shared, admin-gated writes).
|
||||||
- **菜单管理 (Menu Management, admin-only)**: an **overlay** over the static sidebar menu — `MenuManagementPage` (`pages/MenuManagementPage.tsx`, route `/page/strategy/admin/menu-management`, opened from the admin-only 「菜单管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`). Admins rename / 停用·启用 / reorder (↑↓ or @dnd-kit drag) / re-parent (horizontal drag **or** the edit dialog's 「移动到」parent selector) any node across 一级/二级/三级, **including injected iframe light-app nodes** (`light-app-<appId>`). The static tree (`core/page-layout/sidebar-menu.ts`) stays the source of icons/routes; only per-node deltas (`label`/`disabled`/`parentId`/`sortOrder`) persist to the backend. Merge logic in `core/page-layout/menu-overrides.ts` (`applyMenuOverrides`, applied in `use-sidebar-menu.ts` after light-app injection, before role filter; disabling a node hides its whole subtree) — strict **3-level cap** (`wouldExceedDepth`). Client `strategy-components/api/menu-overrides.ts`. Backend: `/api/menu-overrides` (global/shared; open read, admin atomic replace-all).
|
|
||||||
- **敏感词管理 (Sensitive Word Management)**: configures the **展示层脱敏映射** (原始词 → 替换词). **Gated on the username `lqq`** (not the admin role) — `getAccountDisplayName().toLowerCase() === "lqq"` (username = email `@` prefix, else `user_id`, same as the profile page); the dropdown entry, the route guard, and the page-level guard all use this check. `src/lib/desensitize.ts` ships a frozen seed map `SEED_DESENSITIZE_MAP` (the deployment seed) plus a live mutable `DESENSITIZE_MAP` (initialized from the seed so `desensitize()` works before any fetch). `DesensitizeWordsLoader` (mounted in `App.tsx` `AppProviders`) fetches `/api/sensitive-words` on startup and, if non-empty, calls `replaceDesensitizeMap(...)` to make the backend config the source of truth (empty/failed → keep seed). Page `SensitiveWordsPage.tsx` (route `/page/strategy/admin/sensitive-words`, opened from the 「敏感词管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`, present in **both** full + collapsed sidebar modes) lists/adds/edits/启停/deletes words and saves the **whole set atomically** (replace-all); a 「导入种子词」 button merges any missing `SEED_DESENSITIZE_MAP` entries into the editor. Client + hooks in `strategy-components/api/sensitive-words.ts` (`wordsToMap` folds enabled rows into the runtime map). Backend: `/api/sensitive-words` (global/shared; open read, write allowed for admin **or** the `lqq` account), mirroring 菜单管理's store shape. **侧边栏 + 导航栏 menu labels are desensitized** at the data source: `useSidebarMenuItems`/`useActiveThirdLevel` (`core/page-layout/use-sidebar-menu.ts`) map every node's `label` through a desensitizer built **directly from the `/api/sensitive-words` query** (`makeDesensitizer(wordsToMap(words))`, falling back to the global seed `desensitize` while empty) — this sidesteps the `replaceDesensitizeMap` effect-timing race. Only `label` is rewritten; `path`/`id`/`icon` are untouched so routing/highlight are unaffected. All nav surfaces (`page-sidebar.tsx`, `page-sidebar-dark.tsx`, `page-sidebar-v1.tsx`, `strategy-components/Header.tsx`, `PageRoutes.tsx`) consume this hook and are covered; `MenuManagementPage` uses the raw tree so admins still edit real labels.
|
|
||||||
- **按钮管理 (Task Button Management, admin-only)**: configures the **可配置跳转按钮** rendered in the left task panel of the task deep-link workspaces (rwfx / 3qfx / xdfx, see `TaskFxWorkspace`). Each button = `{business, label, linkType, target, appendTaskId, idParam, idKind, enabled, sortOrder}`; `linkType` is `url` (外链 `window.open`, optional append of `?{idParam}={id}` — **`idParam` is the editable query-param name**, e.g. `id`/`task_id`), `business` (内部切换到另一业务, reuses `resolveTaskDeeplinkTarget`, always task id), or `purpose` (弹出当前任务的「任务目的」表格 via the shared `TaskPurposeDialog`, no target — configurable for any page incl. xdfx). **`idKind` (`task`/`action`) only matters for xdfx**: its deep-link `?taskId=` is an 行动id and the 任务id is resolved at login (`fetchTaskIdFromAction`) — `TaskContext` now also stashes the raw `actionId`, so a url button can append either (default `task`). Page `TaskButtonsPage.tsx` (route `/page/strategy/admin/task-buttons`, **admin-gated**, entry「按钮管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both full + collapsed modes) has per-business tabs, edits name/type/target/启停/排序/增删, saves the **whole set atomically** (replace-all), plus 「导入默认」 to merge code-seed defaults. **Seed/fallback** (like 敏感词管理): only when the whole table is empty (fresh deploy, never saved) do the workspace + page fall back to `defaultTaskButtons(cfg)` — rwfx's url buttons (编辑/下一步/3q详情) built from the **live** `/api/public/config/task-deeplink` plus cross-business switch buttons for **all three** businesses (each switches to the other two — rwfx→三情/行动, 3qfx→任务/行动, xdfx→任务/三情). Once saved, the store is the sole source of truth. The old hardcoded jump buttons were migrated out: `TaskFxWorkspace` no longer hardcodes 切换到三情分析, `TaskActionsPanel` keeps only the non-jump 清除记录, and `TaskPurposePanel` dropped its 3q详情 button (now configurable) **and defaults the 目的树 table to collapsed** (chevron toggle). Helpers `core/auth/task-buttons.ts` (`TaskButton`, `defaultTaskButtons`, `resolveTaskButtons`, `buttonsForBusiness`, `runTaskButton`), client+hooks `strategy-components/api/task-buttons.ts`. Backend: `/api/task-buttons` (global/shared; open read, admin replace-all), store `deerflow.persistence.task_buttons` (table `task_buttons`, auto-created by `create_all`), wired `app.state.task_button_store`. Tests: `tests/test_task_buttons.py`.
|
|
||||||
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
|
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
|
||||||
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
|
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
|
||||||
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
|
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
|
||||||
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
|
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
|
||||||
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. The roundtable target also threads the URL `taskId` into `roundtablePrefill.taskId` (`resolveTaskDeeplinkTarget(goPath, detail, taskId)`), which turns on two taskId-scoped behaviors: (1) **separate, unpartitioned per-task storage** — taskId 会商聊天记录 live in their **own** store/table (`roundtable_task_drafts`), keyed **only by `task_id`** (one taskId = many records, shared across users, **no user 分权** at all; `created_by` is audit-only), kept entirely out of the per-user personal store (`roundtable_drafts`, now strictly per-user) so the two never mix. Backend router `/api/roundtable-task-drafts` (`GET /by-task/{id}` + `/by-task/{id}/latest`, `POST`, `GET/PUT/DELETE /{id}` — all user-agnostic); frontend client `roundtable-planning/api/task-drafts.ts`, and `useDraftPersistence`/`useRoundtableDrafts` route **all** CRUD to it when a `taskId` is present (else the personal `drafts.ts`). The matching **background jobs** are shared by task too: `roundtable_jobs.task_id` marks a task job; reads/dedup/stream/resume/cancel pass `?task_id=` so any user opening the task sees the same running 研讨 (progress/flowchart), and the executor writes the final report back to the task-draft store. Existing rows are moved over by `scripts/migrate_roundtable_task_drafts.py` (migration `20260618_01`). The history dropdown filters to the task and 新建 keeps the binding; (2) **Step-3 auto structured output** — after the `roundtable-summary` agent writes the Markdown report it automatically runs a second round emitting a `flow-json` flowchart (`useStep3Summary` `autoFlow`+`chainLevels`), whose hierarchy follows the business chain's stage goals (任务 → 目的 → 行为体 → …; coordinatorPrompt-specified hierarchy wins) and whose nodes never carry 阶段编号/阶段名 (the prior bug). **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. **All three single-agent businesses share `TaskFxWorkspace`** (`task-components/TaskFxWorkspace.tsx`): left = a「当前任务」card (`readCopTaskDetail()` 任务名称 + 简介, desensitized, 留存 above 新建对话) + per-task 1:N conversation list (`useTaskThreads(taskId, agentId)` — filtered by **both** `metadata.taskId` AND `metadata.agent_id` so the three businesses' conversations stay isolated even though they share one taskId) + 新建对话; the `…/chats` index (`TaskFxIndexResolver`) opens the latest task thread or 新建. The right `:thread_id` host differs by business: **rwfx** → `TaskFxChat` (`AgentChatPage taskGate`) = full workspace (non-`lite`): 目的树闸门 panel + 清除记录 (placed under 新建对话); **xdfx** → also `TaskFxChat` (same 目的树闸门 query+display, same `purpose_detail_url`) but workspace passed `lite`; **3qfx** → `TaskBindChat` (`AgentChatPage taskBind`, `lite`) = 1:N list only, no gate, and 新建对话 **auto-sends** the task opening text (`taskAutoSendText`; gate Line truncated
|
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A (resolved via `/api/business-mapping`, opening message in `sessionStorage.pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats/:thread_id}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. The agent chat is rendered via `TaskEmbeddedAgentChat`, which passes `AgentChatPage`'s `chatBasePath` prop so the post-send URL rewrite + new-chat button stay in the task-management context (instead of the standalone `/agents/...` route). Any failure (no consumer URL / fetch error / unmapped goPath / no configured agent) silently falls back to the default home. Helpers: `core/auth/task-deeplink.ts`.
|
||||||
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
|
|
||||||
|
|
||||||
### Configuration
|
### Configuration
|
||||||
|
|
||||||
|
|||||||
@@ -5,13 +5,7 @@
|
|||||||
VITE_USE_REAL_DATA=true
|
VITE_USE_REAL_DATA=true
|
||||||
|
|
||||||
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(consumer 外网不可达时调试用)。
|
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(consumer 外网不可达时调试用)。
|
||||||
VITE_MOCK_COP_TASK_DETAIL=true
|
VITE_MOCK_COP_TASK_DETAIL=false
|
||||||
|
|
||||||
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:true 走本地样例假数据(真实接口未就绪时调试用);联调通过后置 false。
|
|
||||||
VITE_MOCK_SQ_REPORT=true
|
|
||||||
|
|
||||||
# 深链任务详情(cop-task-detail:任务名称/描述)数据源:true 走本地假数据(真实接口未就绪时调试用);联调通过后置 false。
|
|
||||||
VITE_MOCK_COP_TASK_DETAIL=true
|
|
||||||
|
|
||||||
# Gateway / DeerFlow API
|
# Gateway / DeerFlow API
|
||||||
VITE_BACKEND_BASE_URL=http://127.0.0.1:8001
|
VITE_BACKEND_BASE_URL=http://127.0.0.1:8001
|
||||||
|
|||||||
@@ -7,12 +7,6 @@ VITE_USE_REAL_DATA=true
|
|||||||
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
|
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
|
||||||
VITE_MOCK_COP_TASK_DETAIL=false
|
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
|
# Gateway / DeerFlow API
|
||||||
VITE_BACKEND_BASE_URL=http://47.88.25.99:7001
|
VITE_BACKEND_BASE_URL=http://47.88.25.99:7001
|
||||||
VITE_LANGGRAPH_BASE_URL=http://47.88.25.99:7001/api
|
VITE_LANGGRAPH_BASE_URL=http://47.88.25.99:7001/api
|
||||||
|
|||||||
@@ -7,9 +7,6 @@ VITE_USE_REAL_DATA=true
|
|||||||
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
|
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
|
||||||
VITE_MOCK_COP_TASK_DETAIL=false
|
VITE_MOCK_COP_TASK_DETAIL=false
|
||||||
|
|
||||||
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:默认真实接口;真实接口未就绪可改 true 走本地样例假数据。
|
|
||||||
VITE_MOCK_SQ_REPORT=false
|
|
||||||
|
|
||||||
# Gateway / DeerFlow API
|
# Gateway / DeerFlow API
|
||||||
VITE_BACKEND_BASE_URL=https://ch1.b.uat.4.cn/deerflow
|
VITE_BACKEND_BASE_URL=https://ch1.b.uat.4.cn/deerflow
|
||||||
VITE_LANGGRAPH_BASE_URL=https://ch1.b.uat.4.cn/deerflow/api
|
VITE_LANGGRAPH_BASE_URL=https://ch1.b.uat.4.cn/deerflow/api
|
||||||
|
|||||||
@@ -7,12 +7,6 @@ VITE_USE_REAL_DATA=true
|
|||||||
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
|
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(调试用)。
|
||||||
VITE_MOCK_COP_TASK_DETAIL=false
|
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
|
# Gateway / DeerFlow API
|
||||||
VITE_BACKEND_BASE_URL=https://ch1.b.sit.4.cn/deerflow
|
VITE_BACKEND_BASE_URL=https://ch1.b.sit.4.cn/deerflow
|
||||||
VITE_LANGGRAPH_BASE_URL=https://ch1.b.sit.4.cn/deerflow/api
|
VITE_LANGGRAPH_BASE_URL=https://ch1.b.sit.4.cn/deerflow/api
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import { useEffect, useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { Navigate, Route, Routes } from "react-router-dom";
|
import { Navigate, Route, Routes } from "react-router-dom";
|
||||||
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
||||||
|
|
||||||
import { DesensitizeWordsLoader } from "@/components/desensitize-words-loader";
|
|
||||||
import { FontScaleApplier } from "@/components/font-scale";
|
import { FontScaleApplier } from "@/components/font-scale";
|
||||||
import { QueryClientProvider } from "@/components/query-client-provider";
|
import { QueryClientProvider } from "@/components/query-client-provider";
|
||||||
import { AuthSyncWatcher } from "@/core/auth/sync";
|
import { AuthSyncWatcher } from "@/core/auth/sync";
|
||||||
@@ -17,10 +16,6 @@ import {
|
|||||||
} from "@/core/embed/params";
|
} from "@/core/embed/params";
|
||||||
import { usePublicEmbedTheme } from "@/core/embed/background";
|
import { usePublicEmbedTheme } from "@/core/embed/background";
|
||||||
import { readWujieProps } from "@/core/embed/wujie";
|
import { readWujieProps } from "@/core/embed/wujie";
|
||||||
import {
|
|
||||||
resolveForcedEmbedTheme,
|
|
||||||
syncEmbedSessionFromSearch,
|
|
||||||
} from "@/core/embed/embed-session";
|
|
||||||
|
|
||||||
import { HashRouter, useLocation } from "react-router-dom";
|
import { HashRouter, useLocation } from "react-router-dom";
|
||||||
|
|
||||||
@@ -45,16 +40,7 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
|||||||
const locale = useMemo(() => detectLocale(), []);
|
const locale = useMemo(() => detectLocale(), []);
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const publicEmbedTheme = usePublicEmbedTheme();
|
const publicEmbedTheme = usePublicEmbedTheme();
|
||||||
// iframe 嵌入会话(按标签页 sessionStorage)集中在此同步:任何带 `&embed=1` 的入口(深链登录页
|
|
||||||
// 或直接深链路由)一进来就启用、`embed=0` 关闭,后续干净路由靠会话维持去 chrome + 强制主题。
|
|
||||||
useEffect(() => {
|
|
||||||
syncEmbedSessionFromSearch(location.search);
|
|
||||||
}, [location.search]);
|
|
||||||
const forcedTheme = useMemo(() => {
|
const forcedTheme = useMemo(() => {
|
||||||
// iframe 嵌入模式(外部系统 `&embed=1`)最高优先:按本标签页的嵌入主题强制明/暗。
|
|
||||||
// 走 next-themes forcedTheme(不写 localStorage)→ 同浏览器另开的正常系统页不受影响。
|
|
||||||
const embedTheme = resolveForcedEmbedTheme(location.search);
|
|
||||||
if (embedTheme) return embedTheme;
|
|
||||||
const routeTheme = resolveForcedThemeForPath(location.pathname);
|
const routeTheme = resolveForcedThemeForPath(location.pathname);
|
||||||
if (routeTheme) return routeTheme;
|
if (routeTheme) return routeTheme;
|
||||||
if (location.pathname === "/embed/roundtable") {
|
if (location.pathname === "/embed/roundtable") {
|
||||||
@@ -90,7 +76,6 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
|||||||
<ThemeProvider>
|
<ThemeProvider>
|
||||||
<ChatProvider>
|
<ChatProvider>
|
||||||
<AuthSyncWatcher />
|
<AuthSyncWatcher />
|
||||||
<DesensitizeWordsLoader />
|
|
||||||
<FontScaleApplier />
|
<FontScaleApplier />
|
||||||
{children}
|
{children}
|
||||||
</ChatProvider>
|
</ChatProvider>
|
||||||
|
|||||||
@@ -826,7 +826,13 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</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" && (
|
{searchType === "human" && (
|
||||||
<div className="bg-white p-[10px] grid grid-cols-5 gap-[10px]">
|
<div className="bg-white p-[10px] grid grid-cols-5 gap-[10px]">
|
||||||
{listData.map((item: listDataItem, index: number) => {
|
{listData.map((item: listDataItem, index: number) => {
|
||||||
|
|||||||
@@ -545,7 +545,12 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="p-[10px]">
|
<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) => (
|
{userList.map((item, index) => (
|
||||||
<div key={index} className="user-item p-[10px] relative">
|
<div key={index} className="user-item p-[10px] relative">
|
||||||
<div className="absolute top-[5px] right-[10px]">
|
<div className="absolute top-[5px] right-[10px]">
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
import { useEffect } from "react";
|
|
||||||
|
|
||||||
import { replaceDesensitizeMap } from "@/lib/desensitize";
|
|
||||||
import { useSensitiveWords, wordsToMap } from "@/strategy-components/api/sensitive-words";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 启动时把后台「敏感词管理」配置加载进运行时脱敏映射表。
|
|
||||||
*
|
|
||||||
* - 后台返回**非空**时:用其中「启用」的词条整体替换运行时映射
|
|
||||||
* ({@link replaceDesensitizeMap}),后台即唯一真源,被删除的词不再生效。
|
|
||||||
* - 后台为空(全新部署还没配置)或拉取失败:什么都不做,保持使用
|
|
||||||
* `src/lib/desensitize.ts` 内置的种子映射。
|
|
||||||
*
|
|
||||||
* 渲染 `null`;挂在 `AppProviders` 里(QueryClientProvider 之内)。与「敏感词管理」
|
|
||||||
* 页共享同一份 React Query 缓存,保存后会自动刷新并回灌运行时映射。
|
|
||||||
*/
|
|
||||||
export function DesensitizeWordsLoader() {
|
|
||||||
const { data } = useSensitiveWords();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (data && data.length > 0) {
|
|
||||||
replaceDesensitizeMap(wordsToMap(data));
|
|
||||||
}
|
|
||||||
}, [data]);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -6,8 +6,6 @@ import { getStoredAuth } from "@/core/auth";
|
|||||||
import { isWujieEnv } from "@/core/embed/wujie";
|
import { isWujieEnv } from "@/core/embed/wujie";
|
||||||
import {
|
import {
|
||||||
defaultExpandedIds,
|
defaultExpandedIds,
|
||||||
menuItemContainsPath,
|
|
||||||
menuItemMatchesPath,
|
|
||||||
type MenuItem,
|
type MenuItem,
|
||||||
} from "@/core/page-layout/sidebar-menu";
|
} from "@/core/page-layout/sidebar-menu";
|
||||||
import { useSidebarMenuItems } from "@/core/page-layout/use-sidebar-menu";
|
import { useSidebarMenuItems } from "@/core/page-layout/use-sidebar-menu";
|
||||||
@@ -55,7 +53,13 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
|
|||||||
}, 180);
|
}, 180);
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasActiveChild = (item: MenuItem): boolean => menuItemContainsPath(item, pathname);
|
const hasActiveChild = (item: MenuItem): boolean => {
|
||||||
|
if (item.path && (pathname === item.path || pathname.startsWith(item.path + "/"))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return item.children?.some(hasActiveChild) ?? false;
|
||||||
|
};
|
||||||
|
|
||||||
// lazy init:仅在首次 render 计算一次 active id;之后由下面的 useEffect 跟随 pathname 同步
|
// lazy init:仅在首次 render 计算一次 active id;之后由下面的 useEffect 跟随 pathname 同步
|
||||||
const [activeTopId, setActiveTopId] = useState<string>(
|
const [activeTopId, setActiveTopId] = useState<string>(
|
||||||
@@ -148,9 +152,9 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
|
|||||||
const isSidebarItemActive = (item: MenuItem) =>
|
const isSidebarItemActive = (item: MenuItem) =>
|
||||||
inWujieEnv
|
inWujieEnv
|
||||||
? item.id === activeTopId
|
? item.id === activeTopId
|
||||||
: item.path || item.aliasPaths?.length
|
: item.path
|
||||||
? menuItemMatchesPath(item, pathname)
|
? pathname === item.path || pathname.startsWith(item.path + "/")
|
||||||
: menuItemContainsPath(item, pathname);
|
: hasActiveChild(item);
|
||||||
const handleSidebarItemClick = (item: MenuItem) => {
|
const handleSidebarItemClick = (item: MenuItem) => {
|
||||||
if (inWujieEnv) {
|
if (inWujieEnv) {
|
||||||
handleTopItemClick(item);
|
handleTopItemClick(item);
|
||||||
@@ -172,9 +176,7 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
|
|||||||
{items.map((item) => {
|
{items.map((item) => {
|
||||||
const hasChildren = !!item.children?.length;
|
const hasChildren = !!item.children?.length;
|
||||||
const isExpanded = expandedIds.has(item.id);
|
const isExpanded = expandedIds.has(item.id);
|
||||||
const isSelected = item.path || item.aliasPaths?.length
|
const isSelected = item.path ? pathname === item.path : hasActiveChild(item);
|
||||||
? menuItemMatchesPath(item, pathname)
|
|
||||||
: hasActiveChild(item);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -7,10 +7,7 @@ import {
|
|||||||
ChevronsUpDown,
|
ChevronsUpDown,
|
||||||
Folder,
|
Folder,
|
||||||
FolderOpen,
|
FolderOpen,
|
||||||
ListTree,
|
|
||||||
MousePointerClick,
|
|
||||||
Settings,
|
Settings,
|
||||||
ShieldAlert,
|
|
||||||
User,
|
User,
|
||||||
Wrench,
|
Wrench,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
@@ -24,20 +21,13 @@ import {
|
|||||||
import { NotificationDialog } from "@/components/workspace/notification-dialog";
|
import { NotificationDialog } from "@/components/workspace/notification-dialog";
|
||||||
import { SettingsDialog } from "@/components/workspace/settings";
|
import { SettingsDialog } from "@/components/workspace/settings";
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
import { useTheme } from "@/contexts/ThemeContext";
|
||||||
import { getAccountDisplayName, getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
|
|
||||||
/** 敏感词管理仅对用户名为 lqq 的账号可见(用户名 = 设置→个人信息页展示名)。 */
|
|
||||||
const SENSITIVE_WORDS_USERNAME = "lqq";
|
|
||||||
const canManageSensitiveWords = () =>
|
|
||||||
getAccountDisplayName().toLowerCase() === SENSITIVE_WORDS_USERNAME;
|
|
||||||
import { isWujieEnv } from "@/core/embed/wujie";
|
import { isWujieEnv } from "@/core/embed/wujie";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import { useUnreadCount } from "@/core/notifications";
|
import { useUnreadCount } from "@/core/notifications";
|
||||||
import {
|
import {
|
||||||
defaultExpandedIds,
|
defaultExpandedIds,
|
||||||
getActiveThirdLevelItems,
|
getActiveThirdLevelItems,
|
||||||
menuItemContainsPath,
|
|
||||||
menuItemMatchesPath,
|
|
||||||
type MenuItem,
|
type MenuItem,
|
||||||
} from "@/core/page-layout/sidebar-menu";
|
} from "@/core/page-layout/sidebar-menu";
|
||||||
import { useSidebarMenuItems } from "@/core/page-layout/use-sidebar-menu";
|
import { useSidebarMenuItems } from "@/core/page-layout/use-sidebar-menu";
|
||||||
@@ -51,8 +41,12 @@ type PageSidebarProps = {
|
|||||||
|
|
||||||
type SettingsSection = "account" | "appearance" | "memory" | "tools" | "about";
|
type SettingsSection = "account" | "appearance" | "memory" | "tools" | "about";
|
||||||
|
|
||||||
const hasActiveChild = (item: MenuItem, pathname: string): boolean =>
|
const hasActiveChild = (item: MenuItem, pathname: string): boolean => {
|
||||||
menuItemContainsPath(item, pathname);
|
if (item.path && (pathname === item.path || pathname.startsWith(item.path + "/"))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return item.children?.some((child) => hasActiveChild(child, pathname)) ?? false;
|
||||||
|
};
|
||||||
|
|
||||||
const findFirstRoutePath = (items?: MenuItem[]): string | null => {
|
const findFirstRoutePath = (items?: MenuItem[]): string | null => {
|
||||||
if (!items?.length) {
|
if (!items?.length) {
|
||||||
@@ -122,9 +116,9 @@ function SecondaryNavSidebar() {
|
|||||||
const secondaryItems = activeTopItem?.children ?? [];
|
const secondaryItems = activeTopItem?.children ?? [];
|
||||||
|
|
||||||
const isItemActive = (item: MenuItem) =>
|
const isItemActive = (item: MenuItem) =>
|
||||||
item.path || item.aliasPaths?.length
|
item.path
|
||||||
? menuItemMatchesPath(item, pathname)
|
? pathname === item.path || pathname.startsWith(item.path + "/")
|
||||||
: menuItemContainsPath(item, pathname);
|
: hasActiveChild(item, pathname);
|
||||||
|
|
||||||
const handleItemClick = (item: MenuItem) => {
|
const handleItemClick = (item: MenuItem) => {
|
||||||
const path = item.path ?? findFirstRoutePath(item.children);
|
const path = item.path ?? findFirstRoutePath(item.children);
|
||||||
@@ -206,30 +200,6 @@ function SecondaryNavSidebar() {
|
|||||||
<User className="size-4" />
|
<User className="size-4" />
|
||||||
个人信息
|
个人信息
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
{isAdmin && (
|
|
||||||
<DropdownMenuItem
|
|
||||||
onClick={() => navigate("/page/strategy/admin/menu-management")}
|
|
||||||
>
|
|
||||||
<ListTree className="size-4" />
|
|
||||||
菜单管理
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
{isAdmin && (
|
|
||||||
<DropdownMenuItem
|
|
||||||
onClick={() => navigate("/page/strategy/admin/task-buttons")}
|
|
||||||
>
|
|
||||||
<MousePointerClick className="size-4" />
|
|
||||||
按钮管理
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
{canManageSensitiveWords() && (
|
|
||||||
<DropdownMenuItem
|
|
||||||
onClick={() => navigate("/page/strategy/admin/sensitive-words")}
|
|
||||||
>
|
|
||||||
<ShieldAlert className="size-4" />
|
|
||||||
敏感词管理
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -241,8 +211,9 @@ function SecondaryNavSidebar() {
|
|||||||
<nav className="light-sidebar-subnav" aria-label="三级菜单">
|
<nav className="light-sidebar-subnav" aria-label="三级菜单">
|
||||||
{thirdItems.map((child) => {
|
{thirdItems.map((child) => {
|
||||||
const ChildIcon = child.icon;
|
const ChildIcon = child.icon;
|
||||||
const childActive = menuItemMatchesPath(child, pathname)
|
const childActive = child.path
|
||||||
|| (child.children?.length ? menuItemContainsPath(child, pathname) : false);
|
? pathname === child.path || pathname.startsWith(child.path + "/")
|
||||||
|
: hasActiveChild(child, pathname);
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={child.id}
|
key={child.id}
|
||||||
@@ -330,7 +301,7 @@ function LegacyAccordionSidebar({
|
|||||||
|
|
||||||
const renderLeaf = (item: MenuItem, depth = 0) => {
|
const renderLeaf = (item: MenuItem, depth = 0) => {
|
||||||
const Icon = item.icon;
|
const Icon = item.icon;
|
||||||
const isActive = menuItemMatchesPath(item, pathname);
|
const isActive = !!item.path && pathname === item.path;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
@@ -496,24 +467,6 @@ function LegacyAccordionSidebar({
|
|||||||
<User className="size-4" />
|
<User className="size-4" />
|
||||||
个人信息
|
个人信息
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
{isAdmin && (
|
|
||||||
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/menu-management")}>
|
|
||||||
<ListTree className="size-4" />
|
|
||||||
菜单管理
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
{isAdmin && (
|
|
||||||
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/task-buttons")}>
|
|
||||||
<MousePointerClick className="size-4" />
|
|
||||||
按钮管理
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
{canManageSensitiveWords() && (
|
|
||||||
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/sensitive-words")}>
|
|
||||||
<ShieldAlert className="size-4" />
|
|
||||||
敏感词管理
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
|
|
||||||
export interface AutoGrowTextareaProps
|
|
||||||
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
|
|
||||||
/** 内容增长高度上限(px),超过后框内滚动。默认 200。 */
|
|
||||||
maxHeight?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自适应高度的多行输入框。
|
|
||||||
*
|
|
||||||
* 内容增多时自动扩展高度(输入框处于底部布局时即「向上扩展」),到 `maxHeight` 后框内滚动。
|
|
||||||
* 体验对齐通用问答页(`/page/strategy/qa/general`)的 tdesign `autosize` 输入框,但保留原生
|
|
||||||
* `<textarea>`,从而沿用各调用处自带的 Tailwind 样式 / 边框 / 占位色,无需 TDesign 包裹层。
|
|
||||||
*
|
|
||||||
* 用法:当成普通受控 `<textarea>` 用(传 `value` + `onChange`)。高度在布局阶段随 `value` 重算,
|
|
||||||
* 也在 `onChange` 时即时重算(兼顾非受控/输入法场景)。最小高度交给调用方的 `min-h-*` className
|
|
||||||
* 或 `rows` 控制——本组件不强加最小高度。换行/发送(Enter/Shift+Enter)逻辑由调用方的
|
|
||||||
* `onKeyDown` 决定。
|
|
||||||
*/
|
|
||||||
export const AutoGrowTextarea = React.forwardRef<
|
|
||||||
HTMLTextAreaElement,
|
|
||||||
AutoGrowTextareaProps
|
|
||||||
>(function AutoGrowTextarea(
|
|
||||||
{ maxHeight = 200, value, onChange, onInput, style, rows = 1, ...rest },
|
|
||||||
ref,
|
|
||||||
) {
|
|
||||||
const innerRef = React.useRef<HTMLTextAreaElement | null>(null);
|
|
||||||
React.useImperativeHandle(ref, () => innerRef.current as HTMLTextAreaElement);
|
|
||||||
|
|
||||||
const resize = React.useCallback(() => {
|
|
||||||
const el = innerRef.current;
|
|
||||||
if (!el) return;
|
|
||||||
el.style.height = "auto";
|
|
||||||
const next = Math.min(el.scrollHeight, maxHeight);
|
|
||||||
el.style.height = `${next}px`;
|
|
||||||
el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden";
|
|
||||||
}, [maxHeight]);
|
|
||||||
|
|
||||||
// 受控值变化(含外部清空、粘贴大段文本)后在布局阶段重算,避免闪烁。
|
|
||||||
React.useLayoutEffect(() => {
|
|
||||||
resize();
|
|
||||||
}, [resize, value]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<textarea
|
|
||||||
ref={innerRef}
|
|
||||||
rows={rows}
|
|
||||||
value={value}
|
|
||||||
onChange={onChange}
|
|
||||||
onInput={(e) => {
|
|
||||||
onInput?.(e);
|
|
||||||
resize();
|
|
||||||
}}
|
|
||||||
style={{ resize: "none", ...style }}
|
|
||||||
{...rest}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -401,7 +401,7 @@ export function PositionManagementPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex size-full min-h-0 flex-col gap-4 overflow-auto p-6">
|
<div className="flex flex-col gap-4 p-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-lg font-semibold">岗位管理</h1>
|
<h1 className="text-lg font-semibold">岗位管理</h1>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export function UserManagementPage() {
|
|||||||
const { data: users, isLoading, error } = useAllUsers(true);
|
const { data: users, isLoading, error } = useAllUsers(true);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex size-full min-h-0 flex-col gap-6 overflow-auto p-6">
|
<div className="flex flex-col gap-6 p-6">
|
||||||
<SettingsSection
|
<SettingsSection
|
||||||
title={t.adminUsers.title}
|
title={t.adminUsers.title}
|
||||||
description={t.adminUsers.description}
|
description={t.adminUsers.description}
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
/**
|
|
||||||
* 智能体图标底色 —— 按 id 稳定散列到一组主题色,复刻参考图的彩色方块。
|
|
||||||
*
|
|
||||||
* 浅色模式沿用原高彩度彩色(不改);深蓝主题改用《深蓝 UI 规范》§1.1.7/§1.1.8 的蓝-青系
|
|
||||||
* (docs/ui规范-深蓝,克制、不刺眼),仅深蓝主题下生效,互不影响。
|
|
||||||
*
|
|
||||||
* 全量版通用问答左栏(GeneralQaSidebar)与 zzJC/zzXD 模块左栏(AgentModuleSidebar)共用,
|
|
||||||
* 保证彩色卡片配色完全一致。
|
|
||||||
*/
|
|
||||||
|
|
||||||
const AGENT_COLORS_LIGHT = [
|
|
||||||
{ from: "#fb7185", to: "#ef4444" },
|
|
||||||
{ from: "#60a5fa", to: "#3b82f6" },
|
|
||||||
{ from: "#fbbf24", to: "#f59e0b" },
|
|
||||||
{ from: "#34d399", to: "#10b981" },
|
|
||||||
{ from: "#a78bfa", to: "#8b5cf6" },
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
const AGENT_COLORS_DARK = [
|
|
||||||
{ from: "#4096FF", to: "#1677FF" }, // 蓝(链接蓝 → 主色)
|
|
||||||
{ from: "#36CFC9", to: "#13C2C2" }, // 青(辅色)
|
|
||||||
{ from: "#6388FF", to: "#0958D9" }, // 紫蓝(装饰紫 → 主色深一档)
|
|
||||||
{ from: "#5CDBD3", to: "#08979C" }, // 浅青 → 深青
|
|
||||||
{ from: "#69B1FF", to: "#003EB3" }, // 浅蓝 → 主色按下
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
/** 按 agent id 稳定散列出一对渐变色(from → to)。`isDark` 切换深蓝/浅色调色板。 */
|
|
||||||
export function agentColor(id: string, isDark: boolean) {
|
|
||||||
let hash = 0;
|
|
||||||
for (let i = 0; i < id.length; i++) {
|
|
||||||
hash = (hash * 31 + id.charCodeAt(i)) >>> 0;
|
|
||||||
}
|
|
||||||
const palette = isDark ? AGENT_COLORS_DARK : AGENT_COLORS_LIGHT;
|
|
||||||
return palette[hash % palette.length]!;
|
|
||||||
}
|
|
||||||
@@ -229,10 +229,6 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
);
|
);
|
||||||
const [editPublished, setEditPublished] = useState(agent.published);
|
const [editPublished, setEditPublished] = useState(agent.published);
|
||||||
const [editIsPrivate, setEditIsPrivate] = useState(agent.is_private);
|
const [editIsPrivate, setEditIsPrivate] = useState(agent.is_private);
|
||||||
// 会商席位「技能识别强化」开关(弱模型补偿)。默认关。
|
|
||||||
const [editSeatSkillDirective, setEditSeatSkillDirective] = useState(
|
|
||||||
agent.seat_skill_directive ?? false,
|
|
||||||
);
|
|
||||||
const [editSquareId, setEditSquareId] = useState(agent.square_id ?? "");
|
const [editSquareId, setEditSquareId] = useState(agent.square_id ?? "");
|
||||||
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
|
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
|
||||||
const { data: publishSquares } = usePublishSquares();
|
const { data: publishSquares } = usePublishSquares();
|
||||||
@@ -278,7 +274,6 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
setEditSquareId(agent.square_id ?? "");
|
setEditSquareId(agent.square_id ?? "");
|
||||||
setSelectedSkills(agent.skills ?? []);
|
setSelectedSkills(agent.skills ?? []);
|
||||||
setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions));
|
setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions));
|
||||||
setEditSeatSkillDirective(agent.seat_skill_directive ?? false);
|
|
||||||
}, [
|
}, [
|
||||||
agent.common_questions,
|
agent.common_questions,
|
||||||
agent.description,
|
agent.description,
|
||||||
@@ -287,7 +282,6 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
agent.published,
|
agent.published,
|
||||||
agent.square_id,
|
agent.square_id,
|
||||||
agent.skills,
|
agent.skills,
|
||||||
agent.seat_skill_directive,
|
|
||||||
editOpen,
|
editOpen,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -301,8 +295,6 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
if (agentDetail) {
|
if (agentDetail) {
|
||||||
setEditSoul(agentDetail.soul ?? "");
|
setEditSoul(agentDetail.soul ?? "");
|
||||||
setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions));
|
setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions));
|
||||||
// 列表响应不带 config 额外字段(seat_skill_directive 为 null),详情才有真值。
|
|
||||||
setEditSeatSkillDirective(agentDetail.seat_skill_directive ?? false);
|
|
||||||
} else {
|
} else {
|
||||||
setEditSoul(agent.soul ?? "");
|
setEditSoul(agent.soul ?? "");
|
||||||
}
|
}
|
||||||
@@ -394,8 +386,6 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
request.skills = selectedSkills;
|
request.skills = selectedSkills;
|
||||||
if (JSON.stringify(nextQuestions) !== JSON.stringify(baselineQuestions))
|
if (JSON.stringify(nextQuestions) !== JSON.stringify(baselineQuestions))
|
||||||
request.common_questions = nextQuestions;
|
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) {
|
if (Object.keys(request).length === 0) {
|
||||||
setEditOpen(false);
|
setEditOpen(false);
|
||||||
@@ -970,19 +960,6 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
onChange={setEditCommonQuestions}
|
onChange={setEditCommonQuestions}
|
||||||
/>
|
/>
|
||||||
</div>
|
</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 className="flex items-center justify-between rounded-md border p-3">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-medium">公开发布</p>
|
<p className="text-sm font-medium">公开发布</p>
|
||||||
|
|||||||
@@ -1,620 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import {
|
|
||||||
Bot,
|
|
||||||
ChevronDown,
|
|
||||||
Download,
|
|
||||||
FileJson,
|
|
||||||
FileText,
|
|
||||||
Loader2,
|
|
||||||
MessageSquare,
|
|
||||||
MoreHorizontal,
|
|
||||||
Pencil,
|
|
||||||
Pin,
|
|
||||||
PinOff,
|
|
||||||
Search,
|
|
||||||
Share2,
|
|
||||||
Star,
|
|
||||||
Trash2,
|
|
||||||
X,
|
|
||||||
} from "lucide-react";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { useParams, usePathname, useRouter } from "next/navigation";
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
|
|
||||||
import { agentColor } from "@/components/workspace/agent-icon-color";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import {
|
|
||||||
DropdownMenu,
|
|
||||||
DropdownMenuContent,
|
|
||||||
DropdownMenuItem,
|
|
||||||
DropdownMenuSeparator,
|
|
||||||
DropdownMenuSub,
|
|
||||||
DropdownMenuSubContent,
|
|
||||||
DropdownMenuSubTrigger,
|
|
||||||
DropdownMenuTrigger,
|
|
||||||
} from "@/components/ui/dropdown-menu";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { ShareConversationDialog } from "@/components/workspace/thread-share-dialogs";
|
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
|
||||||
import { useAgentsPaginated } from "@/core/agents";
|
|
||||||
import { getAPIClient } from "@/core/api";
|
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
|
||||||
import { useRouteBase } from "@/core/route-base";
|
|
||||||
import { usePublishSquares } from "@/core/system-settings/hooks";
|
|
||||||
import {
|
|
||||||
exportThreadAsJSON,
|
|
||||||
exportThreadAsMarkdown,
|
|
||||||
} from "@/core/threads/export";
|
|
||||||
import {
|
|
||||||
useDeleteThread,
|
|
||||||
useRenameThread,
|
|
||||||
useThreads,
|
|
||||||
useToggleThreadFavorite,
|
|
||||||
useToggleThreadPin,
|
|
||||||
} from "@/core/threads/hooks";
|
|
||||||
import type { AgentThread, AgentThreadState } from "@/core/threads/types";
|
|
||||||
import {
|
|
||||||
isThreadFavorite,
|
|
||||||
isThreadPinned,
|
|
||||||
sortThreadsPinnedFirst,
|
|
||||||
titleOfThread,
|
|
||||||
usePathOfThread,
|
|
||||||
} from "@/core/threads/utils";
|
|
||||||
import { env } from "@/env";
|
|
||||||
import { desensitize } from "@/lib/desensitize";
|
|
||||||
import { isIMEComposing } from "@/lib/ime";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
|
||||||
/** 「我的」作用域的下拉选项值;其余选项值为各发布广场(publish square)的 id。 */
|
|
||||||
const MINE_SCOPE = "mine";
|
|
||||||
|
|
||||||
// 列表一次拉取的条数。超出时底部出现「查看全部」入口,跳到完整的智能体管理页,
|
|
||||||
// 避免静默截断。侧边栏只做快速切换,不在此分页。
|
|
||||||
const LIST_PAGE_SIZE = 50;
|
|
||||||
|
|
||||||
// 「最近的对话」未搜索时最多展示条数(与首页「通用问答」左栏一致)。
|
|
||||||
const MAX_RECENT_CHATS = 10;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 智能体问答页左侧「智能体列表 + 最近对话」栏(参考首页通用问答左栏)。
|
|
||||||
*
|
|
||||||
* 自上而下:
|
|
||||||
* 1. 顶部下拉:选「我的」(默认,= 我创建/收藏的)或任一「广场」(发布广场),
|
|
||||||
* 与「智能体管理」页主标签一致;下方为智能体名称模糊搜索框。
|
|
||||||
* 2. 智能体列表:所选作用域下的智能体;点击进入该智能体的新对话。当前智能体高亮。
|
|
||||||
* 3. 最近的对话:跨智能体的近期会话(参考首页),点击打开;支持重命名/置顶/收藏/
|
|
||||||
* 分享/导出/删除。当前会话高亮。
|
|
||||||
*
|
|
||||||
* 仅在独立的智能体问答整页展示;任务工作区 / zzJC·zzXD 模块 / 嵌入态不展示。
|
|
||||||
*/
|
|
||||||
export function AgentChatSidebar({ activeAgentId }: { activeAgentId?: string }) {
|
|
||||||
const { t } = useI18n();
|
|
||||||
const routeBase = useRouteBase();
|
|
||||||
const { theme } = useTheme();
|
|
||||||
const isDark = theme === "dark";
|
|
||||||
|
|
||||||
const { data: publishSquares } = usePublishSquares();
|
|
||||||
// 每个发布广场对应一个下拉选项;后端至少返回一个内置默认广场。
|
|
||||||
const squares = useMemo(
|
|
||||||
() => publishSquares?.squares ?? [],
|
|
||||||
[publishSquares?.squares],
|
|
||||||
);
|
|
||||||
|
|
||||||
// 作用域:MINE_SCOPE 或某个广场 id。默认「我的」。
|
|
||||||
const [scope, setScope] = useState<string>(MINE_SCOPE);
|
|
||||||
|
|
||||||
// 模糊搜索智能体名称:防抖 300ms 后走服务端 search(后端按原始名 / 脱敏名匹配),
|
|
||||||
// 在当前来源(我的 / 某广场)内过滤,能搜全量而非仅当前 50 条。
|
|
||||||
const [searchInput, setSearchInput] = useState("");
|
|
||||||
const [search, setSearch] = useState("");
|
|
||||||
useEffect(() => {
|
|
||||||
const timer = setTimeout(() => setSearch(searchInput.trim()), 300);
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}, [searchInput]);
|
|
||||||
|
|
||||||
// 「智能体」区可收起(持久化);收起后只留标题栏,下方「最近的对话」占满剩余空间。
|
|
||||||
const [agentsCollapsed, setAgentsCollapsed] = useState(
|
|
||||||
() =>
|
|
||||||
typeof window !== "undefined" &&
|
|
||||||
localStorage.getItem("agent-chat-sidebar:agents-collapsed") === "true",
|
|
||||||
);
|
|
||||||
const toggleAgents = () =>
|
|
||||||
setAgentsCollapsed((v) => {
|
|
||||||
localStorage.setItem("agent-chat-sidebar:agents-collapsed", String(!v));
|
|
||||||
return !v;
|
|
||||||
});
|
|
||||||
|
|
||||||
// 若所选广场被管理员删除,回退到「我的」,避免指向不存在的广场。
|
|
||||||
useEffect(() => {
|
|
||||||
if (
|
|
||||||
scope !== MINE_SCOPE &&
|
|
||||||
squares.length > 0 &&
|
|
||||||
!squares.some((sq) => sq.id === scope)
|
|
||||||
) {
|
|
||||||
setScope(MINE_SCOPE);
|
|
||||||
}
|
|
||||||
}, [scope, squares]);
|
|
||||||
|
|
||||||
const isMine = scope === MINE_SCOPE;
|
|
||||||
const { agents, total, isLoading, isFetching } = useAgentsPaginated({
|
|
||||||
scope: isMine ? "mine" : "square",
|
|
||||||
sort: "time_desc",
|
|
||||||
page: 1,
|
|
||||||
pageSize: LIST_PAGE_SIZE,
|
|
||||||
square: isMine ? undefined : scope,
|
|
||||||
search: search || undefined,
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
// 配色与 AgentModuleSidebar 一致:浅色白底,深蓝主题半透明深蓝玻璃面板。
|
|
||||||
<aside className="flex h-full w-(--sidebar-width) shrink-0 flex-col overflow-hidden border-r border-border/70 bg-white text-foreground backdrop-blur-md dark:border-[#2b8ffe]/45 dark:bg-[#032650]/80">
|
|
||||||
{/* 智能体(上半,可收起)。展开时:标题栏 + 来源下拉/名称搜索 + 列表;
|
|
||||||
收起时只留标题栏,下方「最近的对话」占满剩余空间。 */}
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col",
|
|
||||||
agentsCollapsed ? "shrink-0" : "min-h-0 flex-[3]",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={toggleAgents}
|
|
||||||
className="text-foreground/80 hover:bg-accent/40 flex shrink-0 items-center justify-between border-b border-border/60 px-3 py-2.5 text-[12px] font-semibold transition-colors select-none"
|
|
||||||
title={agentsCollapsed ? "展开智能体" : "收起智能体"}
|
|
||||||
>
|
|
||||||
<span>智能体</span>
|
|
||||||
<ChevronDown
|
|
||||||
className={cn(
|
|
||||||
"text-muted-foreground size-4 shrink-0 transition-transform duration-200",
|
|
||||||
agentsCollapsed && "-rotate-90",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{!agentsCollapsed && (
|
|
||||||
<>
|
|
||||||
{/* 来源下拉(我的 / 各广场)+ 智能体名称模糊搜索 */}
|
|
||||||
<div className="shrink-0 space-y-2 border-b border-border/60 px-3 py-2.5">
|
|
||||||
<Select value={scope} onValueChange={setScope}>
|
|
||||||
<SelectTrigger className="h-9 w-full text-sm" title="切换智能体来源">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent position="popper" side="bottom" sideOffset={4}>
|
|
||||||
<SelectItem value={MINE_SCOPE}>我的</SelectItem>
|
|
||||||
{squares.map((sq) => (
|
|
||||||
<SelectItem key={sq.id} value={sq.id}>
|
|
||||||
{sq.name}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<div className="relative">
|
|
||||||
<Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2" />
|
|
||||||
<Input
|
|
||||||
value={searchInput}
|
|
||||||
onChange={(e) => setSearchInput(e.target.value)}
|
|
||||||
placeholder="搜索智能体名称"
|
|
||||||
className="h-9 pl-8 pr-8 text-sm"
|
|
||||||
aria-label="搜索智能体名称"
|
|
||||||
/>
|
|
||||||
{searchInput && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setSearchInput("")}
|
|
||||||
className="text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2"
|
|
||||||
title="清除"
|
|
||||||
aria-label="清除搜索"
|
|
||||||
>
|
|
||||||
<X className="size-3.5" />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 智能体列表(独立滚动) */}
|
|
||||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-2 py-3">
|
|
||||||
{isLoading && agents.length === 0 ? (
|
|
||||||
<div className="text-muted-foreground flex h-24 items-center justify-center gap-2 text-xs">
|
|
||||||
<Loader2 className="size-3.5 animate-spin" />
|
|
||||||
加载中…
|
|
||||||
</div>
|
|
||||||
) : agents.length === 0 ? (
|
|
||||||
<p className="px-3 py-1.5 text-xs text-muted-foreground/70">
|
|
||||||
{search
|
|
||||||
? "未找到匹配的智能体"
|
|
||||||
: isMine
|
|
||||||
? "暂无智能体"
|
|
||||||
: "该广场暂无智能体"}
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col gap-1 transition-opacity",
|
|
||||||
isFetching && "opacity-60",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{agents.map((agent) => {
|
|
||||||
const href = `${routeBase}/agents/${agent.id}/chats/new`;
|
|
||||||
const isActive = agent.id === activeAgentId;
|
|
||||||
const { from, to } = agentColor(agent.id, isDark);
|
|
||||||
return (
|
|
||||||
<Link
|
|
||||||
key={agent.id}
|
|
||||||
href={href}
|
|
||||||
className={cn(
|
|
||||||
"group relative flex w-full items-start gap-2.5 rounded-xl border px-2.5 py-2 transition-colors",
|
|
||||||
isActive
|
|
||||||
? "border-primary/40 bg-primary/5"
|
|
||||||
: "border-transparent hover:border-border hover:bg-accent/50",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className="mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg text-white shadow-sm"
|
|
||||||
style={{
|
|
||||||
backgroundImage: `linear-gradient(135deg, ${from}, ${to})`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Bot className="size-[18px]" />
|
|
||||||
</span>
|
|
||||||
<span className="min-w-0 flex-1">
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"block truncate text-[13px] font-semibold",
|
|
||||||
isActive ? "text-primary" : "text-foreground",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{desensitize(agent.name)}
|
|
||||||
</span>
|
|
||||||
<span className="mt-0.5 block truncate text-[11px] leading-snug text-muted-foreground">
|
|
||||||
{agent.description
|
|
||||||
? desensitize(agent.description)
|
|
||||||
: "智能体助手"}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
{isActive && (
|
|
||||||
<span className="absolute top-1/2 right-1 h-6 w-1 -translate-y-1/2 rounded-full bg-primary" />
|
|
||||||
)}
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{/* 超出一页时引导到完整的智能体管理页(不在侧边栏静默截断) */}
|
|
||||||
{total > agents.length && (
|
|
||||||
<Link
|
|
||||||
href={`${routeBase}/agents`}
|
|
||||||
className="text-muted-foreground hover:text-foreground hover:bg-accent/50 mt-0.5 rounded-lg px-3 py-1.5 text-center text-xs transition-colors"
|
|
||||||
>
|
|
||||||
共 {total} 个,查看全部 →
|
|
||||||
</Link>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 最近的对话(下半,独立滚动)—— 参考首页通用问答左栏 */}
|
|
||||||
<RecentChatsPane activeAgentId={activeAgentId} />
|
|
||||||
</aside>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 「最近的对话」面板(参考首页 GeneralQaSidebar 的「最近的对话」区块)。
|
|
||||||
* 跨智能体的近期会话,点击打开;支持重命名/置顶/收藏/分享/导出/删除。
|
|
||||||
*/
|
|
||||||
function RecentChatsPane({ activeAgentId }: { activeAgentId?: string }) {
|
|
||||||
const { t } = useI18n();
|
|
||||||
const pathname = usePathname();
|
|
||||||
const router = useRouter();
|
|
||||||
const pathOf = usePathOfThread();
|
|
||||||
|
|
||||||
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
|
|
||||||
const { data: threads = [] } = useThreads();
|
|
||||||
const { mutate: deleteThread } = useDeleteThread();
|
|
||||||
const { mutate: renameThread } = useRenameThread();
|
|
||||||
const { toggle: togglePin } = useToggleThreadPin();
|
|
||||||
const { toggle: toggleFavorite } = useToggleThreadFavorite();
|
|
||||||
|
|
||||||
const [query, setQuery] = useState("");
|
|
||||||
const [renameDialogOpen, setRenameDialogOpen] = useState(false);
|
|
||||||
const [renameThreadId, setRenameThreadId] = useState<string | null>(null);
|
|
||||||
const [renameValue, setRenameValue] = useState("");
|
|
||||||
const [shareThreadId, setShareThreadId] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// 排除调度/引导/会商类会话,与首页一致;置顶优先。
|
|
||||||
const visibleThreads = useMemo(
|
|
||||||
() =>
|
|
||||||
sortThreadsPinnedFirst(
|
|
||||||
threads.filter(
|
|
||||||
(thread) =>
|
|
||||||
thread.metadata?.thread_type !== "scheduler" &&
|
|
||||||
thread.metadata?.thread_type !== "bootstrap" &&
|
|
||||||
thread.metadata?.thread_type !== "roundtable",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
[threads],
|
|
||||||
);
|
|
||||||
|
|
||||||
const filteredThreads = useMemo(() => {
|
|
||||||
const q = query.trim().toLowerCase();
|
|
||||||
const list = q
|
|
||||||
? visibleThreads.filter((thread) =>
|
|
||||||
titleOfThread(thread, t.pages.newChat).toLowerCase().includes(q),
|
|
||||||
)
|
|
||||||
: visibleThreads;
|
|
||||||
return q ? list : list.slice(0, MAX_RECENT_CHATS);
|
|
||||||
}, [visibleThreads, query, t.pages.newChat]);
|
|
||||||
|
|
||||||
const handleDelete = useCallback(
|
|
||||||
(threadId: string) => {
|
|
||||||
deleteThread({ threadId });
|
|
||||||
if (threadId === threadIdFromPath) {
|
|
||||||
const threadIndex = threads.findIndex((th) => th.thread_id === threadId);
|
|
||||||
let nextThreadPath = pathOf("new", { agent_id: activeAgentId });
|
|
||||||
if (threadIndex > -1) {
|
|
||||||
if (threads[threadIndex + 1]) {
|
|
||||||
nextThreadPath = pathOf(threads[threadIndex + 1]!);
|
|
||||||
} else if (threads[threadIndex - 1]) {
|
|
||||||
nextThreadPath = pathOf(threads[threadIndex - 1]!);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
void router.push(nextThreadPath);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[activeAgentId, deleteThread, pathOf, router, threadIdFromPath, threads],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleRenameClick = useCallback(
|
|
||||||
(threadId: string, currentTitle: string) => {
|
|
||||||
setRenameThreadId(threadId);
|
|
||||||
setRenameValue(currentTitle);
|
|
||||||
setRenameDialogOpen(true);
|
|
||||||
},
|
|
||||||
[],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleRenameSubmit = useCallback(() => {
|
|
||||||
if (renameThreadId && renameValue.trim()) {
|
|
||||||
renameThread({ threadId: renameThreadId, title: renameValue.trim() });
|
|
||||||
setRenameDialogOpen(false);
|
|
||||||
setRenameThreadId(null);
|
|
||||||
setRenameValue("");
|
|
||||||
}
|
|
||||||
}, [renameThread, renameThreadId, renameValue]);
|
|
||||||
|
|
||||||
const handleExport = useCallback(
|
|
||||||
async (thread: AgentThread, format: "markdown" | "json") => {
|
|
||||||
try {
|
|
||||||
const apiClient = getAPIClient();
|
|
||||||
const state = await apiClient.threads.getState<AgentThreadState>(
|
|
||||||
thread.thread_id,
|
|
||||||
);
|
|
||||||
const messages = state.values?.messages ?? [];
|
|
||||||
if (messages.length === 0) {
|
|
||||||
toast.error(t.conversation.noMessages);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (format === "markdown") exportThreadAsMarkdown(thread, messages);
|
|
||||||
else exportThreadAsJSON(thread, messages);
|
|
||||||
toast.success(t.common.exportSuccess);
|
|
||||||
} catch {
|
|
||||||
toast.error("Failed to export conversation");
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[t],
|
|
||||||
);
|
|
||||||
|
|
||||||
const isStatic = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-0 flex-[2] flex-col overflow-y-auto border-t border-border/60 px-2 py-3">
|
|
||||||
<h2 className="mb-1 flex items-center gap-1.5 px-3 py-1 text-[11px] font-semibold tracking-[0.04em] text-muted-foreground/80 select-none">
|
|
||||||
<span>{t.sidebar.recentChats}</span>
|
|
||||||
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-normal text-muted-foreground tabular-nums">
|
|
||||||
{visibleThreads.length}
|
|
||||||
</span>
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
{/* 历史会话搜索框 */}
|
|
||||||
<div className="relative mb-1.5 px-1">
|
|
||||||
<Search className="text-muted-foreground/60 pointer-events-none absolute top-1/2 left-3.5 size-3.5 -translate-y-1/2" />
|
|
||||||
<Input
|
|
||||||
value={query}
|
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
|
||||||
placeholder="搜索历史会话…"
|
|
||||||
className="h-8 rounded-lg border-border bg-card pl-8 text-[12px]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-0.5">
|
|
||||||
{filteredThreads.length === 0 ? (
|
|
||||||
<div className="text-muted-foreground/70 px-3 py-4 text-center text-[12px]">
|
|
||||||
{query ? "没有匹配的会话" : t.chats.noChats}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
filteredThreads.map((thread) => {
|
|
||||||
const href = pathOf(thread);
|
|
||||||
const isActive = href === pathname;
|
|
||||||
const pinned = isThreadPinned(thread);
|
|
||||||
const favorited = isThreadFavorite(thread);
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={thread.thread_id}
|
|
||||||
className="group/item relative flex items-center"
|
|
||||||
>
|
|
||||||
<Link
|
|
||||||
href={href}
|
|
||||||
className={cn(
|
|
||||||
"relative flex h-9 min-w-0 flex-1 items-center gap-2 rounded-lg px-2.5 text-[13px] transition-colors",
|
|
||||||
isActive
|
|
||||||
? "border border-primary/40 bg-primary/5 font-medium text-primary"
|
|
||||||
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<MessageSquare
|
|
||||||
className={cn(
|
|
||||||
"size-3.5 shrink-0",
|
|
||||||
isActive ? "text-primary" : "text-muted-foreground/70",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
{pinned && (
|
|
||||||
<Pin className="text-muted-foreground/70 size-3 shrink-0" />
|
|
||||||
)}
|
|
||||||
<span className="truncate">
|
|
||||||
{desensitize(titleOfThread(thread, t.pages.newChat))}
|
|
||||||
</span>
|
|
||||||
{isActive && (
|
|
||||||
<span className="absolute top-1/2 right-1 h-5 w-1 -translate-y-1/2 rounded-full bg-primary" />
|
|
||||||
)}
|
|
||||||
</Link>
|
|
||||||
{!isStatic && (
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="text-muted-foreground hover:bg-background group-hover/item:opacity-100 data-[state=open]:opacity-100 absolute right-1 flex size-6 items-center justify-center rounded-md opacity-0 transition-opacity"
|
|
||||||
>
|
|
||||||
<MoreHorizontal className="size-4" />
|
|
||||||
<span className="sr-only">{t.common.more}</span>
|
|
||||||
</button>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent
|
|
||||||
className="w-48 rounded-lg"
|
|
||||||
side="right"
|
|
||||||
align="start"
|
|
||||||
>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() =>
|
|
||||||
handleRenameClick(
|
|
||||||
thread.thread_id,
|
|
||||||
titleOfThread(thread, t.pages.newChat),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Pencil className="text-muted-foreground" />
|
|
||||||
<span>{t.common.rename}</span>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => togglePin(thread.thread_id, !pinned)}
|
|
||||||
>
|
|
||||||
{pinned ? (
|
|
||||||
<PinOff className="text-muted-foreground" />
|
|
||||||
) : (
|
|
||||||
<Pin className="text-muted-foreground" />
|
|
||||||
)}
|
|
||||||
<span>{pinned ? t.common.unpin : t.common.pin}</span>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() =>
|
|
||||||
toggleFavorite(thread.thread_id, !favorited)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Star
|
|
||||||
className={
|
|
||||||
favorited
|
|
||||||
? "fill-amber-400 text-amber-400"
|
|
||||||
: "text-muted-foreground"
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<span>
|
|
||||||
{favorited ? t.common.unfavorite : t.common.favorite}
|
|
||||||
</span>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => setShareThreadId(thread.thread_id)}
|
|
||||||
>
|
|
||||||
<Share2 className="text-muted-foreground" />
|
|
||||||
<span>{t.common.share}</span>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuSub>
|
|
||||||
<DropdownMenuSubTrigger>
|
|
||||||
<Download className="text-muted-foreground" />
|
|
||||||
<span>{t.common.export}</span>
|
|
||||||
</DropdownMenuSubTrigger>
|
|
||||||
<DropdownMenuSubContent>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => handleExport(thread, "markdown")}
|
|
||||||
>
|
|
||||||
<FileText className="text-muted-foreground" />
|
|
||||||
<span>{t.common.exportAsMarkdown}</span>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => handleExport(thread, "json")}
|
|
||||||
>
|
|
||||||
<FileJson className="text-muted-foreground" />
|
|
||||||
<span>{t.common.exportAsJSON}</span>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuSubContent>
|
|
||||||
</DropdownMenuSub>
|
|
||||||
<DropdownMenuSeparator />
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => handleDelete(thread.thread_id)}
|
|
||||||
>
|
|
||||||
<Trash2 className="text-muted-foreground" />
|
|
||||||
<span>{t.common.delete}</span>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 重命名弹窗 */}
|
|
||||||
<Dialog open={renameDialogOpen} onOpenChange={setRenameDialogOpen}>
|
|
||||||
<DialogContent className="sm:max-w-[425px]">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>{t.common.rename}</DialogTitle>
|
|
||||||
</DialogHeader>
|
|
||||||
<div className="py-4">
|
|
||||||
<Input
|
|
||||||
value={renameValue}
|
|
||||||
onChange={(e) => setRenameValue(e.target.value)}
|
|
||||||
placeholder={t.common.rename}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === "Enter" && !isIMEComposing(e)) {
|
|
||||||
e.preventDefault();
|
|
||||||
handleRenameSubmit();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<DialogFooter>
|
|
||||||
<Button variant="outline" onClick={() => setRenameDialogOpen(false)}>
|
|
||||||
{t.common.cancel}
|
|
||||||
</Button>
|
|
||||||
<Button onClick={handleRenameSubmit}>{t.common.save}</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
{/* 分享弹窗 */}
|
|
||||||
<ShareConversationDialog
|
|
||||||
threadId={shareThreadId}
|
|
||||||
open={shareThreadId !== null}
|
|
||||||
onOpenChange={(o) => {
|
|
||||||
if (!o) setShareThreadId(null);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -76,8 +76,6 @@ interface AgentDraft {
|
|||||||
published: boolean;
|
published: boolean;
|
||||||
featured: boolean;
|
featured: boolean;
|
||||||
templateName: string;
|
templateName: string;
|
||||||
/** 会商席位「技能识别强化」开关。 */
|
|
||||||
seatSkillDirective: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function draftFromAgent(agent: Agent): AgentDraft {
|
function draftFromAgent(agent: Agent): AgentDraft {
|
||||||
@@ -90,7 +88,6 @@ function draftFromAgent(agent: Agent): AgentDraft {
|
|||||||
published: agent.published,
|
published: agent.published,
|
||||||
featured: agent.featured_order != null,
|
featured: agent.featured_order != null,
|
||||||
templateName: agent.template_name ?? "",
|
templateName: agent.template_name ?? "",
|
||||||
seatSkillDirective: agent.seat_skill_directive ?? false,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,17 +131,14 @@ export function AgentDetailPanel({
|
|||||||
agentName,
|
agentName,
|
||||||
onAskQuestion,
|
onAskQuestion,
|
||||||
disabled,
|
disabled,
|
||||||
defaultCollapsed,
|
|
||||||
}: {
|
}: {
|
||||||
agent: Agent | null | undefined;
|
agent: Agent | null | undefined;
|
||||||
agentName: string;
|
agentName: string;
|
||||||
onAskQuestion: (text: string) => void;
|
onAskQuestion: (text: string) => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
/** 初始收起(任务工作区进入时默认收起智能体信息面板)。 */
|
|
||||||
defaultCollapsed?: boolean;
|
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [collapsed, setCollapsed] = useState(defaultCollapsed ?? false);
|
const [collapsed, setCollapsed] = useState(false);
|
||||||
const [mobileOpen, setMobileOpen] = useState(false);
|
const [mobileOpen, setMobileOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState(false);
|
const [editing, setEditing] = useState(false);
|
||||||
const [draft, setDraft] = useState<AgentDraft | null>(null);
|
const [draft, setDraft] = useState<AgentDraft | null>(null);
|
||||||
@@ -298,8 +292,6 @@ export function AgentDetailPanel({
|
|||||||
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
|
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
|
||||||
if (draft.templateName.trim() !== (agent.template_name ?? ""))
|
if (draft.templateName.trim() !== (agent.template_name ?? ""))
|
||||||
request.template_name = draft.templateName.trim();
|
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 (nextPublished !== agent.published) request.published = nextPublished;
|
||||||
if (JSON.stringify(draft.skills) !== JSON.stringify(agent.skills ?? []))
|
if (JSON.stringify(draft.skills) !== JSON.stringify(agent.skills ?? []))
|
||||||
request.skills = draft.skills;
|
request.skills = draft.skills;
|
||||||
@@ -566,21 +558,6 @@ export function AgentDetailPanel({
|
|||||||
配置后,对话生成的 Markdown 文件可一键发布到知识入库接口。
|
配置后,对话生成的 Markdown 文件可一键发布到知识入库接口。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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 className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-medium">公开发布</p>
|
<p className="text-sm font-medium">公开发布</p>
|
||||||
|
|||||||
@@ -364,7 +364,7 @@ export function AgentGallery() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex size-full min-h-0 flex-col">
|
<div className="flex size-full flex-col">
|
||||||
{/* Page header */}
|
{/* Page header */}
|
||||||
<div className="flex items-center justify-between border-b px-6 py-4">
|
<div className="flex items-center justify-between border-b px-6 py-4">
|
||||||
<div>
|
<div>
|
||||||
@@ -392,7 +392,7 @@ export function AgentGallery() {
|
|||||||
setSort("time_desc");
|
setSort("time_desc");
|
||||||
setPublisher(null);
|
setPublisher(null);
|
||||||
}}
|
}}
|
||||||
className="flex min-h-0 flex-1 flex-col overflow-hidden"
|
className="flex flex-1 flex-col overflow-hidden"
|
||||||
>
|
>
|
||||||
<div className="mx-6 mt-4 flex flex-col gap-3">
|
<div className="mx-6 mt-4 flex flex-col gap-3">
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import Link from "next/link";
|
|||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
|
|
||||||
import { agentColor } from "@/components/workspace/agent-icon-color";
|
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
|
||||||
import { useAgents } from "@/core/agents";
|
import { useAgents } from "@/core/agents";
|
||||||
import type { Agent } from "@/core/agents";
|
import type { Agent } from "@/core/agents";
|
||||||
import { useAgentModuleConfig } from "@/core/system-settings/hooks";
|
import { useAgentModuleConfig } from "@/core/system-settings/hooks";
|
||||||
@@ -127,9 +125,6 @@ export function AgentModuleSidebar({
|
|||||||
}) {
|
}) {
|
||||||
const routeBase = useRouteBase();
|
const routeBase = useRouteBase();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
// 智能体图标配色分主题:深蓝主题用规范蓝-青系,其它(浅色)保持原高彩度色,互不影响。
|
|
||||||
const { theme } = useTheme();
|
|
||||||
const isDark = theme === "dark";
|
|
||||||
const { agents } = useAgents();
|
const { agents } = useAgents();
|
||||||
const { data: threads = [] } = useThreads();
|
const { data: threads = [] } = useThreads();
|
||||||
const { data: moduleConfig } = useAgentModuleConfig(moduleKey);
|
const { data: moduleConfig } = useAgentModuleConfig(moduleKey);
|
||||||
@@ -170,10 +165,7 @@ export function AgentModuleSidebar({
|
|||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// 原有布局不变,仅做配色适配:深色下左栏改为半透明深蓝玻璃面板(对齐 .sidebar-contents:
|
<aside className="flex h-full w-(--sidebar-width) shrink-0 flex-col overflow-hidden border-r border-border/70 bg-card/60 backdrop-blur-sm">
|
||||||
// bg rgba(3,38,80,.8) + 蓝色发光边框),叠 backdrop-blur 让外壳的深蓝底图朦胧透出;
|
|
||||||
// 浅色保持白底。其余颜色已走语义 token 自适配。
|
|
||||||
<aside className="flex h-full w-(--sidebar-width) shrink-0 flex-col overflow-hidden border-r border-border/70 bg-white text-foreground backdrop-blur-md dark:border-[#2b8ffe]/45 dark:bg-[#032650]/80">
|
|
||||||
{onOpenSettings && (
|
{onOpenSettings && (
|
||||||
<div className="flex shrink-0 items-center justify-between border-b border-border/60 px-3 py-2">
|
<div className="flex shrink-0 items-center justify-between border-b border-border/60 px-3 py-2">
|
||||||
<span className="text-xs font-semibold text-foreground/80">智能体</span>
|
<span className="text-xs font-semibold text-foreground/80">智能体</span>
|
||||||
@@ -182,22 +174,22 @@ export function AgentModuleSidebar({
|
|||||||
onClick={onOpenSettings}
|
onClick={onOpenSettings}
|
||||||
title="模块设置"
|
title="模块设置"
|
||||||
aria-label="模块设置"
|
aria-label="模块设置"
|
||||||
className="text-muted-foreground hover:text-foreground rounded-md p-1 transition-colors hover:bg-accent/60"
|
className="text-muted-foreground hover:text-foreground rounded-md p-1 transition-colors hover:bg-sidebar-accent/60"
|
||||||
>
|
>
|
||||||
<Settings className="size-4" />
|
<Settings className="size-4" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 上半:按类型分组的智能体(彩色卡片,与全量版看齐) */}
|
{/* 上半:按类型分组的智能体 */}
|
||||||
<div className="flex min-h-0 flex-[3] flex-col overflow-y-auto px-2 py-3">
|
<div className="flex min-h-0 flex-[3] flex-col overflow-y-auto px-2 py-3">
|
||||||
<h2 className="mb-1 px-3 py-1 text-[11px] font-semibold tracking-[0.04em] text-muted-foreground/80 select-none">
|
<h2 className="text-muted-foreground/70 px-2 mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
|
||||||
智能体类型
|
智能体类型
|
||||||
</h2>
|
</h2>
|
||||||
{groups.length === 0 ? (
|
{groups.length === 0 ? (
|
||||||
<p className="px-3 py-1.5 text-xs text-muted-foreground/70">暂无智能体</p>
|
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">暂无智能体</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col gap-1.5">
|
<div className="flex flex-col gap-0.5">
|
||||||
{groups.map((group) => {
|
{groups.map((group) => {
|
||||||
const isCollapsed = collapsed.has(group.key);
|
const isCollapsed = collapsed.has(group.key);
|
||||||
return (
|
return (
|
||||||
@@ -205,11 +197,11 @@ export function AgentModuleSidebar({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => toggleGroup(group.key)}
|
onClick={() => toggleGroup(group.key)}
|
||||||
className="flex w-full items-center justify-between px-3 py-1 text-[11px] font-semibold tracking-[0.04em] text-muted-foreground/80 transition-colors hover:text-muted-foreground select-none"
|
className="flex w-full items-center justify-between gap-1 rounded-lg px-2 py-1.5 text-xs font-semibold text-foreground/80 hover:bg-sidebar-accent/60"
|
||||||
>
|
>
|
||||||
<span className="flex items-center gap-1.5 truncate">
|
<span className="flex items-center gap-1.5 truncate">
|
||||||
<span className="truncate">{group.label}</span>
|
<span className="truncate">{group.label}</span>
|
||||||
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-normal text-muted-foreground tabular-nums">
|
<span className="text-muted-foreground/60 text-[10px] font-normal tabular-nums">
|
||||||
{group.agents.length}
|
{group.agents.length}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
@@ -221,48 +213,22 @@ export function AgentModuleSidebar({
|
|||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
{!isCollapsed && (
|
{!isCollapsed && (
|
||||||
<div className="mt-1 flex flex-col gap-1">
|
<div className="mt-0.5 flex flex-col gap-0.5 pl-1">
|
||||||
{group.agents.map((agent) => {
|
{group.agents.map((agent) => {
|
||||||
const href = `${routeBase}/agents/${agent.id}/chats/new`;
|
const href = `${routeBase}/agents/${agent.id}/chats/new`;
|
||||||
const isActive = agent.id === activeAgentId;
|
const isActive = agent.id === activeAgentId;
|
||||||
const { from, to } = agentColor(agent.id, isDark);
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
key={`${group.key}:${agent.id}`}
|
key={`${group.key}:${agent.id}`}
|
||||||
href={href}
|
href={href}
|
||||||
className={cn(
|
className={cn(
|
||||||
"group relative flex w-full items-start gap-2.5 rounded-xl border px-2.5 py-2 transition-colors",
|
"flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground hover:text-foreground hover:bg-sidebar-accent/60",
|
||||||
isActive
|
isActive &&
|
||||||
? "border-primary/40 bg-primary/5"
|
"bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary",
|
||||||
: "border-transparent hover:border-border hover:bg-accent/50",
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<span
|
<Bot className="size-3.5 shrink-0 text-muted-foreground/70" />
|
||||||
className="mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg text-white shadow-sm"
|
<span className="truncate">{desensitize(agent.name)}</span>
|
||||||
style={{
|
|
||||||
backgroundImage: `linear-gradient(135deg, ${from}, ${to})`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Bot className="size-[18px]" />
|
|
||||||
</span>
|
|
||||||
<span className="min-w-0 flex-1">
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"block truncate text-[13px] font-semibold",
|
|
||||||
isActive ? "text-primary" : "text-foreground",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{desensitize(agent.name)}
|
|
||||||
</span>
|
|
||||||
<span className="mt-0.5 block truncate text-[11px] leading-snug text-muted-foreground">
|
|
||||||
{agent.description
|
|
||||||
? desensitize(agent.description)
|
|
||||||
: "智能体助手"}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
{isActive && (
|
|
||||||
<span className="absolute top-1/2 right-1 h-6 w-1 -translate-y-1/2 rounded-full bg-primary" />
|
|
||||||
)}
|
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -275,13 +241,13 @@ export function AgentModuleSidebar({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 下半:聊天记录(仅本模块智能体会话),简单列表、配色与全量版统一 */}
|
{/* 下半:聊天记录(仅本模块智能体会话) */}
|
||||||
<div className="flex min-h-0 flex-[2] flex-col overflow-y-auto border-t border-border/60 px-2 py-3">
|
<div className="flex min-h-0 flex-[2] flex-col overflow-y-auto border-t border-border/60 px-2 py-3">
|
||||||
<h2 className="mb-1 px-3 py-1 text-[11px] font-semibold tracking-[0.04em] text-muted-foreground/80 select-none">
|
<h2 className="text-muted-foreground/70 px-2 mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
|
||||||
聊天记录
|
聊天记录
|
||||||
</h2>
|
</h2>
|
||||||
{moduleThreads.length === 0 ? (
|
{moduleThreads.length === 0 ? (
|
||||||
<p className="px-3 py-1.5 text-xs text-muted-foreground/70">暂无聊天记录</p>
|
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">暂无聊天记录</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col gap-0.5">
|
<div className="flex flex-col gap-0.5">
|
||||||
{moduleThreads.map((thread) => {
|
{moduleThreads.map((thread) => {
|
||||||
@@ -292,24 +258,15 @@ export function AgentModuleSidebar({
|
|||||||
key={thread.thread_id}
|
key={thread.thread_id}
|
||||||
href={href}
|
href={href}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex h-9 min-w-0 items-center gap-2 rounded-lg px-2.5 text-[13px] transition-colors",
|
"flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] text-muted-foreground hover:text-foreground hover:bg-sidebar-accent/60",
|
||||||
isActive
|
isActive &&
|
||||||
? "border border-primary/40 bg-primary/5 font-medium text-primary"
|
"bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary",
|
||||||
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<MessageSquare
|
<MessageSquare className="size-3.5 shrink-0 text-muted-foreground/70" />
|
||||||
className={cn(
|
|
||||||
"size-3.5 shrink-0",
|
|
||||||
isActive ? "text-primary" : "text-muted-foreground/70",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<span className="truncate">
|
<span className="truncate">
|
||||||
{desensitize(titleOfThread(thread, "未命名对话"))}
|
{desensitize(titleOfThread(thread, "未命名对话"))}
|
||||||
</span>
|
</span>
|
||||||
{isActive && (
|
|
||||||
<span className="absolute top-1/2 right-1 h-5 w-1 -translate-y-1/2 rounded-full bg-primary" />
|
|
||||||
)}
|
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -86,7 +86,6 @@ import { desensitize } from "@/lib/desensitize";
|
|||||||
import { isIMEComposing } from "@/lib/ime";
|
import { isIMEComposing } from "@/lib/ime";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
import { agentColor } from "./agent-icon-color";
|
|
||||||
import { SidebarCollapseButton } from "./workspace-header";
|
import { SidebarCollapseButton } from "./workspace-header";
|
||||||
|
|
||||||
const NEW_CHAT_PATH = "/page/workspace/chats/new";
|
const NEW_CHAT_PATH = "/page/workspace/chats/new";
|
||||||
@@ -97,8 +96,33 @@ const MORE_CHATS_HREF = "/page/workspace/chats";
|
|||||||
/** 常用智能体最多展示个数。 */
|
/** 常用智能体最多展示个数。 */
|
||||||
const MAX_FREQUENT = 4;
|
const MAX_FREQUENT = 4;
|
||||||
|
|
||||||
// 智能体图标配色(按 id 稳定散列、分主题)抽到共享模块 ./agent-icon-color,
|
// 智能体图标统一用 Bot 机器人图标;底色按 id 稳定散列到一组主题色,复刻参考图的彩色方块。
|
||||||
// 与 zzJC/zzXD 模块左栏(AgentModuleSidebar)共用,保证彩色卡片配色完全一致。
|
// 浅色模式沿用原高彩度彩色(不改);深蓝主题改用《深蓝 UI 规范》§1.1.7/§1.1.8 的蓝-青系
|
||||||
|
// (docs/ui规范-深蓝,克制、不刺眼),仅深蓝主题下生效,互不影响。
|
||||||
|
const AGENT_COLORS_LIGHT = [
|
||||||
|
{ from: "#fb7185", to: "#ef4444" },
|
||||||
|
{ from: "#60a5fa", to: "#3b82f6" },
|
||||||
|
{ from: "#fbbf24", to: "#f59e0b" },
|
||||||
|
{ from: "#34d399", to: "#10b981" },
|
||||||
|
{ from: "#a78bfa", to: "#8b5cf6" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const AGENT_COLORS_DARK = [
|
||||||
|
{ from: "#4096FF", to: "#1677FF" }, // 蓝(链接蓝 → 主色)
|
||||||
|
{ from: "#36CFC9", to: "#13C2C2" }, // 青(辅色)
|
||||||
|
{ from: "#6388FF", to: "#0958D9" }, // 紫蓝(装饰紫 → 主色深一档)
|
||||||
|
{ from: "#5CDBD3", to: "#08979C" }, // 浅青 → 深青
|
||||||
|
{ from: "#69B1FF", to: "#003EB3" }, // 浅蓝 → 主色按下
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
function agentColor(id: string, isDark: boolean) {
|
||||||
|
let hash = 0;
|
||||||
|
for (let i = 0; i < id.length; i++) {
|
||||||
|
hash = (hash * 31 + id.charCodeAt(i)) >>> 0;
|
||||||
|
}
|
||||||
|
const palette = isDark ? AGENT_COLORS_DARK : AGENT_COLORS_LIGHT;
|
||||||
|
return palette[hash % palette.length]!;
|
||||||
|
}
|
||||||
|
|
||||||
/** 折叠区块标题(带 chevron 与可选计数徽标)。 */
|
/** 折叠区块标题(带 chevron 与可选计数徽标)。 */
|
||||||
function SectionLabel({
|
function SectionLabel({
|
||||||
@@ -300,10 +324,8 @@ export function GeneralQaSidebar() {
|
|||||||
const isStatic = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
|
const isStatic = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// 背景走 sidebar token(浅主题=白、浅蓝主题=浅蓝);深蓝(.dark)主题下由 gq-sidebar
|
// 背景走 sidebar token(浅主题=白、深蓝主题=深蓝),不要写死 bg-white,否则全量版深蓝主题下侧栏仍是白底。
|
||||||
// 改为「深蓝主题底图 + 半透明蓝罩」玻璃面板(见 globals.css),与右侧 workspace-chat-bg
|
<div className="flex h-full min-h-0 flex-col bg-sidebar text-sidebar-foreground">
|
||||||
// 主区同底图、略深一档作面板区分,不要写死 bg-white。
|
|
||||||
<div className="gq-sidebar flex h-full min-h-0 flex-col bg-sidebar text-sidebar-foreground">
|
|
||||||
{/* ── 顶部:新对话胶囊 + 收起按钮 ── */}
|
{/* ── 顶部:新对话胶囊 + 收起按钮 ── */}
|
||||||
<div className="flex items-center gap-2 px-3 pt-3 pb-2">
|
<div className="flex items-center gap-2 px-3 pt-3 pb-2">
|
||||||
{/* 新对话按钮:完全自定义样式(不复用 Button variant)。borderColor / color 走
|
{/* 新对话按钮:完全自定义样式(不复用 Button variant)。borderColor / color 走
|
||||||
|
|||||||
@@ -61,9 +61,8 @@ import {
|
|||||||
} from "@/components/ui/dropdown-menu";
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { apiFetch } from "@/core/api";
|
import { apiFetch } from "@/core/api";
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import { isHiddenFromUIMessage } from "@/core/messages/utils";
|
import { useModels } from "@/core/models/hooks";
|
||||||
import { useModels } from "@/core/models/hooks";
|
|
||||||
import type { AgentThreadContext } from "@/core/threads";
|
import type { AgentThreadContext } from "@/core/threads";
|
||||||
import { textOfMessage } from "@/core/threads/utils";
|
import { textOfMessage } from "@/core/threads/utils";
|
||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
@@ -468,15 +467,14 @@ export function InputBox({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const visibleMessages = thread.messages.filter((m) => !isHiddenFromUIMessage(m));
|
const lastAi = [...thread.messages].reverse().find((m) => m.type === "ai");
|
||||||
const lastAi = [...visibleMessages].reverse().find((m) => m.type === "ai");
|
|
||||||
const lastAiId = lastAi?.id ?? null;
|
const lastAiId = lastAi?.id ?? null;
|
||||||
if (!lastAiId || lastAiId === lastGeneratedForAiIdRef.current) {
|
if (!lastAiId || lastAiId === lastGeneratedForAiIdRef.current) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
lastGeneratedForAiIdRef.current = lastAiId;
|
lastGeneratedForAiIdRef.current = lastAiId;
|
||||||
|
|
||||||
const recent = visibleMessages
|
const recent = thread.messages
|
||||||
.filter((m) => m.type === "human" || m.type === "ai")
|
.filter((m) => m.type === "human" || m.type === "ai")
|
||||||
.map((m) => {
|
.map((m) => {
|
||||||
const role = m.type === "human" ? "user" : "assistant";
|
const role = m.type === "human" ? "user" : "assistant";
|
||||||
|
|||||||
@@ -20,10 +20,9 @@ import {
|
|||||||
groupMessages,
|
groupMessages,
|
||||||
hasContent,
|
hasContent,
|
||||||
hasPresentFiles,
|
hasPresentFiles,
|
||||||
hasReasoning,
|
hasReasoning,
|
||||||
hasToolCalls,
|
hasToolCalls,
|
||||||
isHiddenFromUIMessage,
|
} from "@/core/messages/utils";
|
||||||
} from "@/core/messages/utils";
|
|
||||||
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
|
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
|
||||||
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
|
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
|
||||||
import { useSkills } from "@/core/skills/hooks";
|
import { useSkills } from "@/core/skills/hooks";
|
||||||
@@ -152,10 +151,7 @@ export function MessageList({
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const allMessages = useMemo(
|
const allMessages = thread.messages;
|
||||||
() => thread.messages.filter((m) => !isHiddenFromUIMessage(m)),
|
|
||||||
[thread.messages],
|
|
||||||
);
|
|
||||||
const messages = useMemo(
|
const messages = useMemo(
|
||||||
() =>
|
() =>
|
||||||
hiddenMessageIds.size === 0
|
hiddenMessageIds.size === 0
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { toast } from "sonner";
|
|||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { clearStoredAuth, getAccountDisplayName, getStoredAuth } from "@/core/auth";
|
import { clearStoredAuth, getStoredAuth } from "@/core/auth";
|
||||||
|
|
||||||
import { SettingsSection } from "./settings-section";
|
import { SettingsSection } from "./settings-section";
|
||||||
|
|
||||||
@@ -37,7 +37,8 @@ export function AccountSettingsPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const displayName = getAccountDisplayName(auth);
|
const usernameFromEmail = (auth.email ?? "").split("@")[0] ?? "";
|
||||||
|
const displayName = usernameFromEmail || auth.user_id;
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
clearStoredAuth();
|
clearStoredAuth();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { DropletIcon, LayoutGridIcon, LayoutIcon, ListIcon, MoonIcon, PanelLeftIcon, SunIcon } from "lucide-react";
|
import { DropletIcon, LayoutGridIcon, LayoutIcon, ListIcon, MoonIcon, PanelLeftIcon, SunIcon } from "lucide-react";
|
||||||
import { useMemo, useState, type ComponentType, type SVGProps } from "react";
|
import { useMemo, type ComponentType, type SVGProps } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
@@ -20,8 +20,6 @@ import { Separator } from "@/components/ui/separator";
|
|||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
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 { enUS, isLocale, zhCN, type Locale } from "@/core/i18n";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import { useLocalSettings } from "@/core/settings";
|
import { useLocalSettings } from "@/core/settings";
|
||||||
@@ -66,29 +64,6 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
|||||||
const cleanupWords =
|
const cleanupWords =
|
||||||
citationDisplay?.cleanup_words ?? settings.display.citationCleanupWords ?? [];
|
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 (
|
const handleSetGlobalDefault = async (
|
||||||
value: "light" | "dark" | "lightblue",
|
value: "light" | "dark" | "lightblue",
|
||||||
) => {
|
) => {
|
||||||
@@ -420,28 +395,6 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
|||||||
|
|
||||||
<Separator />
|
<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
|
<SettingsSection
|
||||||
title="对话体验"
|
title="对话体验"
|
||||||
description="问答过程中的辅助显示。"
|
description="问答过程中的辅助显示。"
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { User } from "lucide-react";
|
|
||||||
import { useMemo } from "react";
|
|
||||||
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
|
||||||
import { useMyPosition } from "@/core/positions";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { readUserInfo } from "@/strategy-components/lib/light-app";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 名称 + 岗位 用户标识。全量模式由 strategy-components/Header.tsx 顶栏右侧展示;
|
|
||||||
* 紧凑模式(不带全局顶栏)无处承载,故抽成共享组件,复用同一套数据来源
|
|
||||||
* (`readUserInfo().userName` 优先、回退 auth 邮箱前缀;岗位取 `useMyPosition`),
|
|
||||||
* 供页面级顶栏(如 ChatPage)右侧复用,保证两套布局一致。
|
|
||||||
*
|
|
||||||
* 配色按当前内容区前景色(foreground / muted-foreground),适配聊天页浅底顶栏,
|
|
||||||
* 而非 Header 的白字贴 banner 方案。
|
|
||||||
*/
|
|
||||||
export function UserIdentityBadge({ className }: { className?: string }) {
|
|
||||||
const auth = getStoredAuth();
|
|
||||||
const { data: myPosition } = useMyPosition();
|
|
||||||
const positionName = myPosition?.name?.trim() || "";
|
|
||||||
|
|
||||||
// 与 Header.tsx 一致:外部登录写入的真实用户名优先,缺省回退邮箱前缀。
|
|
||||||
const displayName = useMemo(() => {
|
|
||||||
const info = readUserInfo();
|
|
||||||
const name = typeof info.userName === "string" ? info.userName.trim() : "";
|
|
||||||
if (name) return name;
|
|
||||||
const email = auth?.email?.trim();
|
|
||||||
return email ? email.split("@")[0] : "用户";
|
|
||||||
}, [auth?.email]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn("flex shrink-0 items-center gap-2", className)}
|
|
||||||
title={positionName ? `${displayName}·${positionName}` : displayName}
|
|
||||||
>
|
|
||||||
<div className="bg-muted text-muted-foreground flex size-7 shrink-0 items-center justify-center rounded-full">
|
|
||||||
<User className="size-3.5" />
|
|
||||||
</div>
|
|
||||||
<div className="hidden min-w-0 text-left sm:block">
|
|
||||||
<p className="text-foreground truncate text-sm font-medium leading-tight">
|
|
||||||
{displayName}
|
|
||||||
</p>
|
|
||||||
{positionName && (
|
|
||||||
<p className="text-muted-foreground truncate text-[11px] leading-tight">
|
|
||||||
{positionName}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -58,10 +58,6 @@ export interface Agent {
|
|||||||
/** 入库模板名(外部知识入库接口的 templateName)。配置后该智能体会话中的
|
/** 入库模板名(外部知识入库接口的 templateName)。配置后该智能体会话中的
|
||||||
* Markdown 产物右上角出现"发布入库"按钮。空/缺省 = 不支持入库。 */
|
* Markdown 产物右上角出现"发布入库"按钮。空/缺省 = 不支持入库。 */
|
||||||
template_name?: string | null;
|
template_name?: string | null;
|
||||||
/** 会商席位「技能识别强化」开关。作为会商席位运行时,是否把本智能体配置的技能
|
|
||||||
* (名称 + SKILL.md 路径 + 必须先 read_file 的硬指令) 拼进本轮任务以补偿弱模型。
|
|
||||||
* 与业务链条同名开关取 OR。null/false = 关 (默认)。 */
|
|
||||||
seat_skill_directive?: boolean | null;
|
|
||||||
tags?: Tag[];
|
tags?: Tag[];
|
||||||
featured_order?: number | null;
|
featured_order?: number | null;
|
||||||
/** Whether the current user has favorited (收藏) this agent. */
|
/** Whether the current user has favorited (收藏) this agent. */
|
||||||
@@ -95,8 +91,6 @@ export interface CreateAgentRequest {
|
|||||||
tool_groups?: string[] | null;
|
tool_groups?: string[] | null;
|
||||||
common_questions?: AgentQuestion[] | null;
|
common_questions?: AgentQuestion[] | null;
|
||||||
template_name?: string | null;
|
template_name?: string | null;
|
||||||
/** 会商席位「技能识别强化」开关;缺省/false = 关。 */
|
|
||||||
seat_skill_directive?: boolean | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateAgentRequest {
|
export interface UpdateAgentRequest {
|
||||||
@@ -112,6 +106,4 @@ export interface UpdateAgentRequest {
|
|||||||
common_questions?: AgentQuestion[] | null;
|
common_questions?: AgentQuestion[] | null;
|
||||||
/** 入库模板名;传空字符串表示清除。 */
|
/** 入库模板名;传空字符串表示清除。 */
|
||||||
template_name?: string | null;
|
template_name?: string | null;
|
||||||
/** 会商席位「技能识别强化」开关;缺省/false = 关。 */
|
|
||||||
seat_skill_directive?: boolean | null;
|
|
||||||
}
|
}
|
||||||
@@ -1,223 +0,0 @@
|
|||||||
/**
|
|
||||||
* 大屏绘制智能体「独立页面」的**输入 JSON** 适配 seam。
|
|
||||||
*
|
|
||||||
* 设计意图:深链 `?taskId=` 模式下,后端提供「研判情报报告」接口
|
|
||||||
* GET `{VITE_AIPI_CONSUMER_URL}/cop/selectSqReport?taskId=`
|
|
||||||
* 返回该任务的多类情报内容;本页把它**提取成干净的结构化 JSON** 交给智能体分析
|
|
||||||
* → 产出 report-json → 绘制大屏(react / html)。
|
|
||||||
*
|
|
||||||
* 接口返回结构:`{ state, msg, data: [{ id, taskId, ..., contentJson, categoryType }] }`,
|
|
||||||
* 其中 `contentJson` 是**被转义的 JSON 字符串**,`categoryType` 形如「敌情关键事件 JSON」。
|
|
||||||
* 本模块 `extractSqReport` 把每条的 `contentJson` 反序列化、按 `categoryType` 归类,
|
|
||||||
* 拼成 `{ taskId, categories: { 敌情关键事件: [...], 决心建议: {...}, ... } }` 喂给智能体。
|
|
||||||
*
|
|
||||||
* ⚠️ 真实接口现在还**请求不到**:通过 `VITE_MOCK_SQ_REPORT=true`(见 `utils/request.ts`)
|
|
||||||
* 走后端给的样例假数据(`sq-report-mock.json`),机制与 cop-task-detail 假数据一致。
|
|
||||||
* 联调通过后把该 env 置 false 即走真实接口;接口/数据若有变只需改 `extractSqReport`。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { requestCrudService } from "@/service/request-axios-service";
|
|
||||||
import { readCopTaskDetail } from "@/core/auth/task-deeplink";
|
|
||||||
|
|
||||||
/** 本页输入 JSON 暂存的 sessionStorage key(拉取一次后复用,避免重复请求)。 */
|
|
||||||
export const DASHBOARD_INPUT_STORAGE_KEY = "dashboard.inputJson";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 🧪 演示用模拟业务 JSON —— JSON 接口未就绪、也没有登录任务详情时的兜底输入。
|
|
||||||
* 让大屏页可立即跑通:智能体分析这份数据 → report-json → 渲染大屏。
|
|
||||||
* ⚠️ 接口就绪后删除本常量及其兜底引用。
|
|
||||||
*/
|
|
||||||
export const DEMO_DASHBOARD_INPUT = {
|
|
||||||
taskId: "DEMO-涉台舆情",
|
|
||||||
taskName: "2026 第一季度涉台舆情态势研判",
|
|
||||||
taskContent:
|
|
||||||
"汇总境内外多平台涉台舆情数据,研判热点叙事走势、关键行为体立场与传播渠道分布,识别风险并给出处置建议。",
|
|
||||||
overview:
|
|
||||||
"本季涉台舆情整体平稳但局部波动,'两岸交流''和平发展'类正向叙事占比上升,少数账号借军事议题制造紧张;境外智库与媒体联动放大特定框架。",
|
|
||||||
period: "2026-01-01 ~ 2026-03-31",
|
|
||||||
kpis: {
|
|
||||||
总信息量: 1284000,
|
|
||||||
日均增速: "12%",
|
|
||||||
正向占比: "58%",
|
|
||||||
负向占比: "19%",
|
|
||||||
识别风险点: 7,
|
|
||||||
覆盖平台: 12,
|
|
||||||
},
|
|
||||||
channels: [
|
|
||||||
{ platform: "微博", share: 34 },
|
|
||||||
{ platform: "境外社媒(X/FB)", share: 27 },
|
|
||||||
{ platform: "短视频", share: 18 },
|
|
||||||
{ platform: "新闻门户", share: 13 },
|
|
||||||
{ platform: "论坛/贴吧", share: 8 },
|
|
||||||
],
|
|
||||||
narratives: [
|
|
||||||
{ theme: "两岸交流与融合发展", sentiment: "正向", volume: 42, trend: "up" },
|
|
||||||
{ theme: "和平稳定·避战", sentiment: "正向", volume: 26, trend: "up" },
|
|
||||||
{ theme: "军事演训与安全", sentiment: "中性偏负", volume: 21, trend: "flat" },
|
|
||||||
{ theme: "外部势力介入", sentiment: "负向", volume: 11, trend: "down" },
|
|
||||||
],
|
|
||||||
actors: [
|
|
||||||
{ name: "主流官媒", stance: "正面引导", influence: 88, note: "议程设置与权威发布" },
|
|
||||||
{ name: "岛内民间团体", stance: "中性多元", influence: 64, note: "交流合作类内容活跃" },
|
|
||||||
{ name: "境外智库", stance: "负面框架", influence: 57, note: "联动媒体放大紧张叙事" },
|
|
||||||
{ name: "自媒体大V", stance: "立场分化", influence: 49, note: "情绪化传播、易被借势" },
|
|
||||||
],
|
|
||||||
risks: [
|
|
||||||
{ label: "军事议题被恶意剪辑放大", level: "high" },
|
|
||||||
{ label: "境外智库联动制造紧张框架", level: "high" },
|
|
||||||
{ label: "个别大V情绪化带节奏", level: "mid" },
|
|
||||||
{ label: "短视频谣言二次传播", level: "mid" },
|
|
||||||
{ label: "节假日期间信息量骤增", level: "low" },
|
|
||||||
],
|
|
||||||
timeline: [
|
|
||||||
{ phase: "数据汇聚", desc: "12 平台多源采集与清洗去重" },
|
|
||||||
{ phase: "叙事识别", desc: "聚类提炼核心叙事与情感倾向" },
|
|
||||||
{ phase: "行为体画像", desc: "关键账号立场与影响力建模" },
|
|
||||||
{ phase: "风险研判", desc: "识别高危议题与传播链路" },
|
|
||||||
{ phase: "处置建议", desc: "分级响应与正向引导预案" },
|
|
||||||
],
|
|
||||||
weeklyVolume: [
|
|
||||||
{ week: "W1", value: 86 },
|
|
||||||
{ week: "W2", value: 92 },
|
|
||||||
{ week: "W3", value: 110 },
|
|
||||||
{ week: "W4", value: 134 },
|
|
||||||
{ week: "W5", value: 121 },
|
|
||||||
{ week: "W6", value: 158 },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 「研判情报报告」接口完整地址:`{VITE_AIPI_CONSUMER_URL}/cop/selectSqReport`。 */
|
|
||||||
function sqReportUrl(): string {
|
|
||||||
const value = (import.meta.env as Record<string, unknown>).VITE_AIPI_CONSUMER_URL;
|
|
||||||
const base = typeof value === "string" ? value.replace(/\/+$/, "") : "";
|
|
||||||
return base ? `${base}/cop/selectSqReport` : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 把单条 `contentJson` 反序列化为对象/数组/原值(已是对象则原样返回)。 */
|
|
||||||
function parseContentJson(raw: unknown): unknown {
|
|
||||||
if (typeof raw !== "string") return raw ?? null;
|
|
||||||
const text = raw.trim();
|
|
||||||
if (!text) return null;
|
|
||||||
try {
|
|
||||||
return JSON.parse(text);
|
|
||||||
} catch {
|
|
||||||
return text; // 解析失败就把原始字符串透传给智能体,让它自行理解
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 去掉 categoryType 末尾的「 JSON」后缀,作为归类键(如「敌情关键事件 JSON」→「敌情关键事件」)。 */
|
|
||||||
function categoryKey(categoryType: unknown, index: number): string {
|
|
||||||
const raw = typeof categoryType === "string" ? categoryType.trim() : "";
|
|
||||||
const cleaned = raw.replace(/\s*JSON\s*$/i, "").trim();
|
|
||||||
return cleaned || `分类${index + 1}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把 selectSqReport 的整包响应**提取**成喂给智能体的干净结构化输入:
|
|
||||||
* `{ taskId, source, categories: { [类目]: 反序列化后的内容 } }`
|
|
||||||
* 返回 null 表示无可用内容(调用方据此回退/不开跑)。
|
|
||||||
*/
|
|
||||||
export function extractSqReport(body: unknown, taskId: string): unknown | null {
|
|
||||||
const data = (body && typeof body === "object" ? (body as { data?: unknown }).data : null) as
|
|
||||||
| Array<Record<string, unknown>>
|
|
||||||
| undefined;
|
|
||||||
if (!Array.isArray(data) || data.length === 0) return null;
|
|
||||||
const categories: Record<string, unknown> = {};
|
|
||||||
data.forEach((item, index) => {
|
|
||||||
const content = parseContentJson(item?.contentJson);
|
|
||||||
if (content == null) return;
|
|
||||||
let key = categoryKey(item?.categoryType, index);
|
|
||||||
if (key in categories) key = `${key}(${index + 1})`; // 同名类目去重保留
|
|
||||||
categories[key] = content;
|
|
||||||
});
|
|
||||||
if (Object.keys(categories).length === 0) return null;
|
|
||||||
return { taskId, source: "cop/selectSqReport", categories };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 输入 JSON 缓存**仅供开发(mock)使用**:`VITE_MOCK_SQ_REPORT==='true'` 时才读/写缓存,
|
|
||||||
* 避免开发反复请求样例假数据。真实接口模式(false)下不读不写缓存,**始终拉取真实数据**。
|
|
||||||
*/
|
|
||||||
function inputCacheEnabled(): boolean {
|
|
||||||
return (import.meta.env as Record<string, unknown>).VITE_MOCK_SQ_REPORT === "true";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读取暂存的输入 JSON(仅 mock 开发模式生效,真实模式恒返回 null 以强制重新拉取)。 */
|
|
||||||
export function readDashboardInputJson(): unknown | null {
|
|
||||||
if (!inputCacheEnabled()) return null;
|
|
||||||
try {
|
|
||||||
const raw = sessionStorage.getItem(DASHBOARD_INPUT_STORAGE_KEY);
|
|
||||||
return raw ? JSON.parse(raw) : null;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 暂存输入 JSON(仅 mock 开发模式生效;隐私模式/quota 异常静默失败)。 */
|
|
||||||
export function persistDashboardInputJson(data: unknown): void {
|
|
||||||
if (!inputCacheEnabled()) return;
|
|
||||||
try {
|
|
||||||
sessionStorage.setItem(DASHBOARD_INPUT_STORAGE_KEY, JSON.stringify(data));
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 用登录暂存的任务详情拼一份占位输入(接口未就绪时的回退)。 */
|
|
||||||
function placeholderFromCopTask(taskId: string): unknown | null {
|
|
||||||
const detail = readCopTaskDetail();
|
|
||||||
if (!detail) return taskId ? { taskId } : null;
|
|
||||||
return {
|
|
||||||
taskId,
|
|
||||||
taskName: detail.taskName,
|
|
||||||
taskContent: detail.taskContent,
|
|
||||||
overview: detail.overview,
|
|
||||||
taskDirection: detail.taskDirection,
|
|
||||||
_note: "占位输入(真实业务 JSON 接口未就绪)",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 取本页的输入 JSON:**先请求 selectSqReport,待其返回后再交给模型抽取**。
|
|
||||||
*
|
|
||||||
* - 真实接口模式(`VITE_MOCK_SQ_REPORT=false`):不读缓存、不兜底假数据——
|
|
||||||
* **只用接口真实返回的内容**;请求失败或返回空一律返回 `null`(页面据此提示「请求失败/无数据」,
|
|
||||||
* 绝不拿占位/演示数据去喂模型,避免「没等接口就抽取假数据」)。
|
|
||||||
* - mock 开发模式(true):走本地样例假数据(见 utils/request.ts)并缓存避免反复请求;
|
|
||||||
* 仅此模式在接口不可用时回退 copTaskDetail 占位 / DEMO 演示数据,保证开发能跑通。
|
|
||||||
*/
|
|
||||||
export async function fetchDashboardInputJson(
|
|
||||||
taskId: string,
|
|
||||||
opts?: { forceRefresh?: boolean },
|
|
||||||
): Promise<unknown | null> {
|
|
||||||
const mock = inputCacheEnabled(); // true=mock/开发;false=真实接口
|
|
||||||
// forceRefresh(重新分析/修改时):跳过缓存,强制重新请求接口拿**最新数据**(数据可能已变化)。
|
|
||||||
const cached = opts?.forceRefresh ? null : readDashboardInputJson(); // 真实模式恒 null(缓存仅开发用)
|
|
||||||
if (cached) return cached;
|
|
||||||
|
|
||||||
const url = sqReportUrl();
|
|
||||||
if (url && taskId) {
|
|
||||||
try {
|
|
||||||
// service 拦截器统一注入鉴权并返回 response.data(整包 body)。
|
|
||||||
// await 在此:必须**等接口返回**后才有 body 可 extract → 再由上层启动模型抽取。
|
|
||||||
const body = await requestCrudService.get(url, { taskId });
|
|
||||||
const extracted = extractSqReport(body, taskId);
|
|
||||||
if (extracted) {
|
|
||||||
persistDashboardInputJson(extracted); // 真实模式 no-op
|
|
||||||
return extracted;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* 请求失败:真实模式返回 null(见下),mock 模式落占位/DEMO */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 真实接口模式:**不兜底假数据**。失败/空 → null,让页面提示而不是拿假数据喂模型。
|
|
||||||
if (!mock) return null;
|
|
||||||
|
|
||||||
// 以下兜底**仅 mock/开发模式**:copTaskDetail 占位 / DEMO 演示数据,保证开发能看效果。
|
|
||||||
const placeholder = placeholderFromCopTask(taskId);
|
|
||||||
const detail = readCopTaskDetail();
|
|
||||||
const resolved = detail ? placeholder : { ...DEMO_DASHBOARD_INPUT, taskId: taskId || DEMO_DASHBOARD_INPUT.taskId };
|
|
||||||
if (resolved) persistDashboardInputJson(resolved);
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
@@ -9,8 +9,6 @@
|
|||||||
* theme 不存(直接走 ThemeContext,避免双源)。
|
* theme 不存(直接走 ThemeContext,避免双源)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { authStorageGet, authStorageSet } from "@/core/auth/scoped-storage";
|
|
||||||
|
|
||||||
export const EXTERNAL_LOGIN_STORAGE_KEYS = {
|
export const EXTERNAL_LOGIN_STORAGE_KEYS = {
|
||||||
ticket: "login.ticket",
|
ticket: "login.ticket",
|
||||||
userId: "login.userId",
|
userId: "login.userId",
|
||||||
@@ -29,25 +27,32 @@ export type ExternalLoginParams = {
|
|||||||
|
|
||||||
/** 把外部跳转带来的三个参数写到 localStorage;隐私模式 / quota 异常时静默失败 */
|
/** 把外部跳转带来的三个参数写到 localStorage;隐私模式 / quota 异常时静默失败 */
|
||||||
export function persistExternalLoginParams(params: ExternalLoginParams): void {
|
export function persistExternalLoginParams(params: ExternalLoginParams): void {
|
||||||
// 嵌入(iframe)态走 sessionStorage(按标签页隔离),正常态走 localStorage —— 见 scoped-storage.ts。
|
try {
|
||||||
if (params.ticket) {
|
if (params.ticket) {
|
||||||
authStorageSet(EXTERNAL_LOGIN_STORAGE_KEYS.ticket, params.ticket);
|
localStorage.setItem(EXTERNAL_LOGIN_STORAGE_KEYS.ticket, params.ticket);
|
||||||
}
|
}
|
||||||
if (params.userId) {
|
if (params.userId) {
|
||||||
authStorageSet(EXTERNAL_LOGIN_STORAGE_KEYS.userId, params.userId);
|
localStorage.setItem(EXTERNAL_LOGIN_STORAGE_KEYS.userId, params.userId);
|
||||||
}
|
}
|
||||||
if (params.env) {
|
if (params.env) {
|
||||||
authStorageSet(EXTERNAL_LOGIN_STORAGE_KEYS.env, params.env);
|
localStorage.setItem(EXTERNAL_LOGIN_STORAGE_KEYS.env, params.env);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// localStorage 不可用时不阻断登录流程
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 读取持久化的外部登录参数;不可用时返回空字符串 */
|
/** 读取持久化的外部登录参数;不可用时返回空字符串 */
|
||||||
export function readExternalLoginParams(): Required<ExternalLoginParams> {
|
export function readExternalLoginParams(): Required<ExternalLoginParams> {
|
||||||
return {
|
try {
|
||||||
ticket: authStorageGet(EXTERNAL_LOGIN_STORAGE_KEYS.ticket) ?? "",
|
return {
|
||||||
userId: authStorageGet(EXTERNAL_LOGIN_STORAGE_KEYS.userId) ?? "",
|
ticket: localStorage.getItem(EXTERNAL_LOGIN_STORAGE_KEYS.ticket) ?? "",
|
||||||
env: authStorageGet(EXTERNAL_LOGIN_STORAGE_KEYS.env) ?? "",
|
userId: localStorage.getItem(EXTERNAL_LOGIN_STORAGE_KEYS.userId) ?? "",
|
||||||
};
|
env: localStorage.getItem(EXTERNAL_LOGIN_STORAGE_KEYS.env) ?? "",
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { ticket: "", userId: "", env: "" };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,110 +1,94 @@
|
|||||||
export interface LoginByUsernameResponse {
|
export interface LoginByUsernameResponse {
|
||||||
access_token: string;
|
access_token: string;
|
||||||
token_type: string;
|
token_type: string;
|
||||||
expires_in: number;
|
expires_in: number;
|
||||||
user_id: string;
|
user_id: string;
|
||||||
email: string;
|
email: string;
|
||||||
system_role: string;
|
system_role: string;
|
||||||
needs_setup: boolean;
|
needs_setup: boolean;
|
||||||
created: boolean;
|
created: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
import {
|
const AUTH_STORAGE_KEY = "deerflow.auth";
|
||||||
authStorageGet,
|
|
||||||
authStorageRemove,
|
function isBrowser(): boolean {
|
||||||
authStorageSet,
|
return typeof window !== "undefined";
|
||||||
} from "@/core/auth/scoped-storage";
|
}
|
||||||
|
|
||||||
const AUTH_STORAGE_KEY = "deerflow.auth";
|
export function getStoredAuth(): LoginByUsernameResponse | null {
|
||||||
|
if (!isBrowser()) {
|
||||||
function isBrowser(): boolean {
|
return null;
|
||||||
return typeof window !== "undefined";
|
}
|
||||||
}
|
const raw = window.localStorage.getItem(AUTH_STORAGE_KEY);
|
||||||
|
if (!raw) {
|
||||||
export function getStoredAuth(): LoginByUsernameResponse | null {
|
return null;
|
||||||
if (!isBrowser()) {
|
}
|
||||||
return null;
|
try {
|
||||||
}
|
return JSON.parse(raw) as LoginByUsernameResponse;
|
||||||
// 嵌入(iframe)态走 sessionStorage、正常态走 localStorage —— 隔离 iframe 登录用户与正常登录用户。
|
} catch {
|
||||||
const raw = authStorageGet(AUTH_STORAGE_KEY);
|
return null;
|
||||||
if (!raw) {
|
}
|
||||||
return null;
|
}
|
||||||
}
|
|
||||||
try {
|
export function setStoredAuth(auth: LoginByUsernameResponse) {
|
||||||
return JSON.parse(raw) as LoginByUsernameResponse;
|
if (!isBrowser()) {
|
||||||
} catch {
|
return;
|
||||||
return null;
|
}
|
||||||
}
|
window.localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(auth));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setStoredAuth(auth: LoginByUsernameResponse) {
|
export function clearStoredAuth() {
|
||||||
if (!isBrowser()) {
|
if (!isBrowser()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
authStorageSet(AUTH_STORAGE_KEY, JSON.stringify(auth));
|
window.localStorage.removeItem(AUTH_STORAGE_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearStoredAuth() {
|
/**
|
||||||
if (!isBrowser()) {
|
* 把登录用户名写入 localStorage.userInfo.userName(顶栏用户区据此显示)。
|
||||||
return;
|
* 仅在尚未设置时写入,避免覆盖外部登录(yUserId)从 consumer 拿到的用户名。
|
||||||
}
|
*/
|
||||||
authStorageRemove(AUTH_STORAGE_KEY);
|
export function setStoredUserName(name: string | null | undefined) {
|
||||||
}
|
if (!isBrowser()) {
|
||||||
|
return;
|
||||||
/** 与设置 → 个人信息页「用户名」一致:邮箱 @ 前缀,否则 user_id。 */
|
}
|
||||||
export function getAccountDisplayName(
|
const trimmed = name?.trim();
|
||||||
auth: LoginByUsernameResponse | null = getStoredAuth(),
|
if (!trimmed) {
|
||||||
): string {
|
return;
|
||||||
if (!auth) return "用户";
|
}
|
||||||
const usernameFromEmail = (auth.email ?? "").split("@")[0] ?? "";
|
let info: Record<string, unknown> = {};
|
||||||
return usernameFromEmail || auth.user_id || "用户";
|
try {
|
||||||
}
|
const raw = window.localStorage.getItem("userInfo");
|
||||||
|
if (raw) {
|
||||||
/**
|
const parsed = JSON.parse(raw);
|
||||||
* 把登录用户名写入 localStorage.userInfo.userName(轻应用登录参数等场景使用)。
|
if (parsed && typeof parsed === "object") {
|
||||||
* 仅在尚未设置时写入,避免覆盖外部登录(yUserId)从 consumer 拿到的用户名。
|
info = parsed as Record<string, unknown>;
|
||||||
*/
|
}
|
||||||
export function setStoredUserName(name: string | null | undefined) {
|
}
|
||||||
if (!isBrowser()) {
|
} catch {
|
||||||
return;
|
info = {};
|
||||||
}
|
}
|
||||||
const trimmed = name?.trim();
|
if (typeof info.userName === "string" && info.userName.trim()) {
|
||||||
if (!trimmed) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
info.userName = trimmed;
|
||||||
let info: Record<string, unknown> = {};
|
window.localStorage.setItem("userInfo", JSON.stringify(info));
|
||||||
try {
|
}
|
||||||
const raw = authStorageGet("userInfo");
|
|
||||||
if (raw) {
|
export function getAccessToken(): string | undefined {
|
||||||
const parsed = JSON.parse(raw);
|
const auth = getStoredAuth();
|
||||||
if (parsed && typeof parsed === "object") {
|
const token = auth?.access_token?.trim();
|
||||||
info = parsed as Record<string, unknown>;
|
return token ? token : undefined;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} catch {
|
export function getAuthorizationHeaderValue(): string | undefined {
|
||||||
info = {};
|
const auth = getStoredAuth();
|
||||||
}
|
const token = auth?.access_token?.trim();
|
||||||
if (typeof info.userName === "string" && info.userName.trim()) {
|
if (!token) {
|
||||||
return;
|
return undefined;
|
||||||
}
|
}
|
||||||
info.userName = trimmed;
|
const rawType = auth?.token_type?.trim();
|
||||||
authStorageSet("userInfo", JSON.stringify(info));
|
const tokenType = rawType ? rawType : "Bearer";
|
||||||
}
|
return `${tokenType} ${token}`;
|
||||||
|
}
|
||||||
export function getAccessToken(): string | undefined {
|
|
||||||
const auth = getStoredAuth();
|
|
||||||
const token = auth?.access_token?.trim();
|
|
||||||
return token ? token : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getAuthorizationHeaderValue(): string | undefined {
|
|
||||||
const auth = getStoredAuth();
|
|
||||||
const token = auth?.access_token?.trim();
|
|
||||||
if (!token) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const rawType = auth?.token_type?.trim();
|
|
||||||
const tokenType = rawType ? rawType : "Bearer";
|
|
||||||
return `${tokenType} ${token}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
/**
|
|
||||||
* 鉴权 / 身份存储的「按登录态隔离」选择器。
|
|
||||||
*
|
|
||||||
* 诉求:外部系统用 iframe 套用咱们的深链问答时,**iframe 里登录的用户**要和**同浏览器正常登录
|
|
||||||
* 的用户**完全隔离——不然 iframe 里随便登一个用户,会覆盖正常标签页的登录态(甚至触发跨标签
|
|
||||||
* 账号变更提示)。
|
|
||||||
*
|
|
||||||
* 根因:同源下 `localStorage` 跨所有标签页共享,鉴权 token(`deerflow.auth`)/ 身份(`userInfo`)/
|
|
||||||
* 外部登录参数(`login.*` / `tools_token`)都存在那里,iframe 一写就污染正常页。
|
|
||||||
*
|
|
||||||
* 方案:嵌入态(`isEmbedActive()`,见 [[embed-session]])下,这些键改走 **sessionStorage**——它按
|
|
||||||
* **标签页/浏览上下文**隔离,iframe(即便同源)有自己独立的一份,写它绝不动正常标签页的
|
|
||||||
* localStorage,也不会触发正常页的 `storage` 事件(见 sync.tsx 的跨标签账号监听)。正常态仍走
|
|
||||||
* localStorage,行为零变化。
|
|
||||||
*
|
|
||||||
* 把所有受保护键的读写都收口到 `authStorage()`,保证同一标签页内读写落到同一处(嵌入态恒为
|
|
||||||
* sessionStorage、正常态恒为 localStorage;嵌入标志一进程内不翻转,故一致)。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { isEmbedActive, isIsolatedSession } from "@/core/embed/embed-session";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 返回当前应使用的鉴权存储:嵌入态(iframe)**或**独立会话态(`?isolate=1`)→ sessionStorage
|
|
||||||
* (按标签页隔离);否则 → localStorage(跨标签共享、持久)。非浏览器环境返回 null(调用方各自
|
|
||||||
* 有 SSR 守卫)。两种隔离态等价于「本标签页鉴权独立、绝不污染其它标签页登录态」,区别仅在于嵌入态
|
|
||||||
* 还会去 chrome / 强制主题,独立会话态只切换存储。
|
|
||||||
*/
|
|
||||||
export function authStorage(): Storage | null {
|
|
||||||
if (typeof window === "undefined") return null;
|
|
||||||
return isEmbedActive() || isIsolatedSession() ? window.sessionStorage : window.localStorage;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读受保护键(嵌入态 sessionStorage / 正常态 localStorage)。 */
|
|
||||||
export function authStorageGet(key: string): string | null {
|
|
||||||
try {
|
|
||||||
return authStorage()?.getItem(key) ?? null;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 写受保护键。隐私模式 / quota 异常静默失败。 */
|
|
||||||
export function authStorageSet(key: string, value: string): void {
|
|
||||||
try {
|
|
||||||
authStorage()?.setItem(key, value);
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 删受保护键。 */
|
|
||||||
export function authStorageRemove(key: string): void {
|
|
||||||
try {
|
|
||||||
authStorage()?.removeItem(key);
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 受 `authStorage()` 收口管理的鉴权 / 身份键:四个精确键 + `login.` 前缀(外部登录参数族
|
|
||||||
* ticket/userId/env/maxkeyOnlineToken/userDetailToken)。用于「开启独立会话」时把当前登录态从
|
|
||||||
* localStorage 快照搬进 sessionStorage,避免切换存储后被登出。
|
|
||||||
*/
|
|
||||||
const PROTECTED_AUTH_EXACT_KEYS = ["deerflow.auth", "userInfo", "userId", "tools_token"];
|
|
||||||
const PROTECTED_AUTH_PREFIX = "login.";
|
|
||||||
|
|
||||||
function isProtectedAuthKey(key: string): boolean {
|
|
||||||
return PROTECTED_AUTH_EXACT_KEYS.includes(key) || key.startsWith(PROTECTED_AUTH_PREFIX);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把 localStorage 里的鉴权 / 身份键**快照复制**进 sessionStorage(覆盖式)。
|
|
||||||
*
|
|
||||||
* 「外观」设置开启独立会话时调用:此后 `authStorage()` 改读 sessionStorage,若不先搬一份当前账号
|
|
||||||
* 过去就会瞬间「未登录」。每次开启都重新快照(覆盖旧值),确保拿到的是当前 localStorage 的最新账号。
|
|
||||||
* 仅搬受保护键,不动 sessionStorage 里既有的本标签页专属态(embed.session / 任务上下文等)。
|
|
||||||
*/
|
|
||||||
export function migrateAuthToSession(): void {
|
|
||||||
if (typeof window === "undefined") return;
|
|
||||||
try {
|
|
||||||
const ls = window.localStorage;
|
|
||||||
const ss = window.sessionStorage;
|
|
||||||
for (let i = 0; i < ls.length; i++) {
|
|
||||||
const key = ls.key(i);
|
|
||||||
if (key && isProtectedAuthKey(key)) {
|
|
||||||
const value = ls.getItem(key);
|
|
||||||
if (value !== null) ss.setItem(key, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,6 @@ import { useEffect, useRef } from "react";
|
|||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { isEmbedActive, isIsolatedSession } from "@/core/embed/embed-session";
|
|
||||||
|
|
||||||
const AUTH_STORAGE_KEY = "deerflow.auth";
|
const AUTH_STORAGE_KEY = "deerflow.auth";
|
||||||
const SETTLE_DELAY_MS = 1200;
|
const SETTLE_DELAY_MS = 1200;
|
||||||
@@ -22,10 +21,6 @@ export function AuthSyncWatcher() {
|
|||||||
const lastUserIdRef = useRef<string | null>(readUserId());
|
const lastUserIdRef = useRef<string | null>(readUserId());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 嵌入(iframe)态 / 独立会话态(?isolate=1):鉴权走按标签页的 sessionStorage,本就不与其它标签页
|
|
||||||
// 共享,且不应被其它标签页的 localStorage 账号变更打扰 —— 直接不挂跨标签监听。
|
|
||||||
if (isEmbedActive() || isIsolatedSession()) return;
|
|
||||||
|
|
||||||
let settleTimer: ReturnType<typeof setTimeout> | null = null;
|
let settleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
function evaluateSettledIdentity() {
|
function evaluateSettledIdentity() {
|
||||||
@@ -52,11 +47,6 @@ export function AuthSyncWatcher() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleStorage(event: StorageEvent) {
|
function handleStorage(event: StorageEvent) {
|
||||||
// 运行时若已切到独立会话(「外观」开关在挂载后才开启):鉴权改读本标签页 sessionStorage,
|
|
||||||
// 不应再被其它标签页的 localStorage 账号变更打扰 —— 即时忽略,无需刷新页面。
|
|
||||||
if (isEmbedActive() || isIsolatedSession()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Ignore unrelated keys and localStorage.clear(). Backend session loss is
|
// Ignore unrelated keys and localStorage.clear(). Backend session loss is
|
||||||
// handled centrally through 401 responses.
|
// handled centrally through 401 responses.
|
||||||
if (event.key !== AUTH_STORAGE_KEY) {
|
if (event.key !== AUTH_STORAGE_KEY) {
|
||||||
|
|||||||
@@ -1,261 +0,0 @@
|
|||||||
/**
|
|
||||||
* 任务工作区(任务深链 rwfx / 3qfx / xdfx,见 ``TaskFxWorkspace``)左侧栏的
|
|
||||||
* **可配置跳转按钮**。
|
|
||||||
*
|
|
||||||
* 数据源优先级:后端 ``/api/task-buttons``(全局共享、admin 整体替换)。**仅当整张表
|
|
||||||
* 为空(全新部署、从未保存过)**时回退到代码种子默认(``defaultTaskButtons``,从实时
|
|
||||||
* 任务深链配置读出 rwfx 的 4 个历史按钮,3qfx/xdfx 为空)——这样真实跳转地址通过实时
|
|
||||||
* config 进种子,避免写死;一旦保存过,后端即唯一数据源。
|
|
||||||
*
|
|
||||||
* 按钮两类(``linkType``):``url`` 外链(``window.open``,可选追加 ``?id=任务id``)/
|
|
||||||
* ``business`` 内部切换到另一业务(复用 [[task-deeplink]] 的 ``resolveTaskDeeplinkTarget``)。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import {
|
|
||||||
appendQueryParam,
|
|
||||||
type TaskDeeplinkConfig,
|
|
||||||
} from "@/core/auth/task-deeplink-config";
|
|
||||||
import {
|
|
||||||
readCopTaskDetail,
|
|
||||||
resolveTaskDeeplinkTarget,
|
|
||||||
} from "@/core/auth/task-deeplink";
|
|
||||||
|
|
||||||
/** 任务工作区业务码(与路由 taskBase 一一对应)。 */
|
|
||||||
export type TaskBusiness = "rwfx" | "3qfx" | "xdfx";
|
|
||||||
|
|
||||||
/** 业务元数据:每个 = 一个任务深链页面。``goPath`` 为深链 ``?goPath=`` 值;``desc`` 给管理页说明。 */
|
|
||||||
export const TASK_BUSINESSES: {
|
|
||||||
code: TaskBusiness;
|
|
||||||
/** 页面名(tab 主标题)。 */
|
|
||||||
name: string;
|
|
||||||
/** 深链 goPath 值。 */
|
|
||||||
goPath: string;
|
|
||||||
/** 页面说明。 */
|
|
||||||
desc: string;
|
|
||||||
}[] = [
|
|
||||||
{
|
|
||||||
code: "rwfx",
|
|
||||||
name: "任务分析",
|
|
||||||
goPath: "rwfx",
|
|
||||||
desc: "完整版任务工作区(带目的树闸门),通过 ?goPath=rwfx 进入。",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
code: "3qfx",
|
|
||||||
name: "三情分析",
|
|
||||||
goPath: "3qfx",
|
|
||||||
desc: "精简版工作区(无目的树闸门),通过 ?goPath=3qfx 进入。",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
code: "xdfx",
|
|
||||||
name: "行动分析",
|
|
||||||
goPath: "xdfx",
|
|
||||||
desc: "精简版工作区,通过 ?goPath=xdfx 进入(深链 taskId 实为行动id)。",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
/** ``url``=外链 / ``business``=切换业务 / ``purpose``=弹出任务目的树表格(无需 target)。 */
|
|
||||||
export type TaskButtonLinkType = "url" | "business" | "purpose";
|
|
||||||
|
|
||||||
/** 追加的 id 取哪种:``task``=任务id(默认)/ ``action``=行动id(仅 xdfx 二者不同)。 */
|
|
||||||
export type TaskButtonIdKind = "task" | "action";
|
|
||||||
|
|
||||||
/** ``url`` 外链打开方式:``blank``=新窗口(默认)/ ``self``=当前窗口(嵌入态即当前 iframe)。 */
|
|
||||||
export type TaskButtonOpenMode = "blank" | "self";
|
|
||||||
|
|
||||||
/** 一个可配置跳转按钮。 */
|
|
||||||
export interface TaskButton {
|
|
||||||
id: string;
|
|
||||||
business: TaskBusiness;
|
|
||||||
label: string;
|
|
||||||
linkType: TaskButtonLinkType;
|
|
||||||
/** ``url``=完整地址;``business``=目标业务码(如 ``3qfx``)。 */
|
|
||||||
target: string;
|
|
||||||
/** ``url`` 类型是否追加 id 查询参数。 */
|
|
||||||
appendTaskId: boolean;
|
|
||||||
/** 追加的查询参数名(如 ``id`` / ``task_id``);空则用 ``id``。 */
|
|
||||||
idParam: string;
|
|
||||||
/**
|
|
||||||
* ``url`` 追加 id 时取任务id 还是行动id。仅 xdfx(行动分析)二者不同:深链原始 ``?taskId=``
|
|
||||||
* 实为行动id,任务id 由 action 接口解析。其它业务两者相同。
|
|
||||||
*/
|
|
||||||
idKind: TaskButtonIdKind;
|
|
||||||
/** ``url`` 外链打开方式:``blank``=新窗口(默认)/ ``self``=当前窗口。仅 ``url`` 类型有意义。 */
|
|
||||||
openMode: TaskButtonOpenMode;
|
|
||||||
enabled: boolean;
|
|
||||||
sortOrder: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 内部切换可选的目标业务(``business`` 类型按钮的下拉项)。 */
|
|
||||||
export const TASK_BUSINESS_TARGETS: { code: TaskBusiness; label: string }[] = [
|
|
||||||
{ code: "3qfx", label: "三情分析" },
|
|
||||||
{ code: "rwfx", label: "任务分析" },
|
|
||||||
{ code: "xdfx", label: "行动分析" },
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 代码种子默认按钮(仅在后端整张表为空时使用):
|
|
||||||
* - rwfx:历史 4 个按钮(编辑/下一步/3q详情,地址取自实时任务深链配置)+ 切换到三情/行动分析;
|
|
||||||
* - 3qfx / xdfx:互相切换到另外两个业务。
|
|
||||||
* 即「三个业务都带切换按钮」。已保存过则用页面「导入默认」把缺失项补进来。
|
|
||||||
*/
|
|
||||||
export function defaultTaskButtons(cfg: TaskDeeplinkConfig): TaskButton[] {
|
|
||||||
const sw = (
|
|
||||||
id: string,
|
|
||||||
business: TaskBusiness,
|
|
||||||
label: string,
|
|
||||||
target: TaskBusiness,
|
|
||||||
sortOrder: number,
|
|
||||||
): TaskButton => ({
|
|
||||||
id,
|
|
||||||
business,
|
|
||||||
label,
|
|
||||||
linkType: "business",
|
|
||||||
target,
|
|
||||||
appendTaskId: false,
|
|
||||||
idParam: "id",
|
|
||||||
idKind: "task",
|
|
||||||
openMode: "blank",
|
|
||||||
enabled: true,
|
|
||||||
sortOrder,
|
|
||||||
});
|
|
||||||
// 目的树弹框按钮(无需 target)。
|
|
||||||
const pz = (id: string, business: TaskBusiness, sortOrder: number): TaskButton => ({
|
|
||||||
id,
|
|
||||||
business,
|
|
||||||
label: "弹框查看",
|
|
||||||
linkType: "purpose",
|
|
||||||
target: "",
|
|
||||||
appendTaskId: false,
|
|
||||||
idParam: "id",
|
|
||||||
idKind: "task",
|
|
||||||
openMode: "blank",
|
|
||||||
enabled: true,
|
|
||||||
sortOrder,
|
|
||||||
});
|
|
||||||
return [
|
|
||||||
// rwfx(任务分析):外链 + 切换
|
|
||||||
{
|
|
||||||
id: "rwfx-edit",
|
|
||||||
business: "rwfx",
|
|
||||||
label: "编辑",
|
|
||||||
linkType: "url",
|
|
||||||
target: cfg.treemapEditUrl,
|
|
||||||
appendTaskId: true,
|
|
||||||
idParam: "id",
|
|
||||||
idKind: "task",
|
|
||||||
openMode: "blank",
|
|
||||||
enabled: true,
|
|
||||||
sortOrder: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "rwfx-next",
|
|
||||||
business: "rwfx",
|
|
||||||
label: "下一步",
|
|
||||||
linkType: "url",
|
|
||||||
target: cfg.treemapNextUrl,
|
|
||||||
appendTaskId: true,
|
|
||||||
idParam: "id",
|
|
||||||
idKind: "task",
|
|
||||||
openMode: "blank",
|
|
||||||
enabled: true,
|
|
||||||
sortOrder: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "rwfx-detail3q",
|
|
||||||
business: "rwfx",
|
|
||||||
label: "3q详情",
|
|
||||||
linkType: "url",
|
|
||||||
target: cfg.detail3qUrl,
|
|
||||||
appendTaskId: true,
|
|
||||||
idParam: "id",
|
|
||||||
idKind: "task",
|
|
||||||
openMode: "blank",
|
|
||||||
enabled: true,
|
|
||||||
sortOrder: 2,
|
|
||||||
},
|
|
||||||
sw("rwfx-switch3q", "rwfx", "切换到三情分析", "3qfx", 3),
|
|
||||||
sw("rwfx-switchxd", "rwfx", "切换到行动分析", "xdfx", 4),
|
|
||||||
pz("rwfx-purpose", "rwfx", 5),
|
|
||||||
// 3qfx(三情分析):切换到任务/行动分析
|
|
||||||
sw("3qfx-switchrw", "3qfx", "切换到任务分析", "rwfx", 0),
|
|
||||||
sw("3qfx-switchxd", "3qfx", "切换到行动分析", "xdfx", 1),
|
|
||||||
// xdfx(行动分析):切换到任务/三情分析 + 弹框查看
|
|
||||||
sw("xdfx-switchrw", "xdfx", "切换到任务分析", "rwfx", 0),
|
|
||||||
sw("xdfx-switch3q", "xdfx", "切换到三情分析", "3qfx", 1),
|
|
||||||
pz("xdfx-purpose", "xdfx", 2),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 实际生效的按钮列表:后端有任意一条记录时即以后端为准;整张表为空才回退种子默认。
|
|
||||||
* (与 [[敏感词管理]] 的种子语义一致:空=从未配置→用种子;非空=已配置→后端说了算,
|
|
||||||
* 哪怕某业务被清空也不回退。)
|
|
||||||
*/
|
|
||||||
export function resolveTaskButtons(
|
|
||||||
stored: TaskButton[],
|
|
||||||
cfg: TaskDeeplinkConfig,
|
|
||||||
): TaskButton[] {
|
|
||||||
return stored.length > 0 ? stored : defaultTaskButtons(cfg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 取某业务下、启用的按钮,按 sortOrder 升序。 */
|
|
||||||
export function buttonsForBusiness(
|
|
||||||
buttons: TaskButton[],
|
|
||||||
business: TaskBusiness,
|
|
||||||
): TaskButton[] {
|
|
||||||
return buttons
|
|
||||||
.filter((b) => b.business === business && b.enabled)
|
|
||||||
.sort((a, b) => a.sortOrder - b.sortOrder);
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface RunTaskButtonCtx {
|
|
||||||
/** 任务id(xdfx 为 action 接口解析后的真实任务id;其它业务即深链原始 id)。 */
|
|
||||||
taskId: string;
|
|
||||||
/** 行动id(xdfx 深链原始 ?taskId=;其它业务通常等于 taskId)。 */
|
|
||||||
actionId?: string;
|
|
||||||
navigate: (path: string, opts?: { state?: Record<string, unknown> }) => void;
|
|
||||||
/** 跳转/打开失败时的提示回调(默认 noop)。 */
|
|
||||||
onError?: (message: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 执行一个跳转按钮:
|
|
||||||
* - ``url``:拼地址(可选追加 ``?id=``,取任务id 或行动id 视 ``idKind``)新标签打开;地址为空提示未配置。
|
|
||||||
* - ``business``:复用深链解析(会按目标业务重绑任务上下文)后 ``navigate``(始终用任务id)。
|
|
||||||
*/
|
|
||||||
export async function runTaskButton(btn: TaskButton, ctx: RunTaskButtonCtx): Promise<void> {
|
|
||||||
const fail = (m: string) => ctx.onError?.(m);
|
|
||||||
// purpose(目的树弹框)由组件层处理(需打开 React 弹框),此处不动作。
|
|
||||||
if (btn.linkType === "purpose") return;
|
|
||||||
if (btn.linkType === "url") {
|
|
||||||
const base = btn.target.trim();
|
|
||||||
if (!base) {
|
|
||||||
fail(`未配置「${btn.label}」的跳转地址`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// 行动分析(xdfx)可选追加行动id;否则用任务id。行动id 缺失时回退任务id。
|
|
||||||
const id = btn.idKind === "action" ? ctx.actionId || ctx.taskId : ctx.taskId;
|
|
||||||
const param = (btn.idParam || "id").trim() || "id";
|
|
||||||
const url = btn.appendTaskId && id ? appendQueryParam(base, param, id) : base;
|
|
||||||
// 打开方式:self=当前窗口(嵌入态即当前 iframe);否则 blank=新窗口(默认)。
|
|
||||||
if (btn.openMode === "self") {
|
|
||||||
window.location.assign(url);
|
|
||||||
} else {
|
|
||||||
window.open(url, "_blank", "noopener,noreferrer");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// business:内部切换到另一业务
|
|
||||||
const detail = readCopTaskDetail();
|
|
||||||
if (!detail || !ctx.taskId) {
|
|
||||||
fail("缺少任务信息,无法跳转");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const target = await resolveTaskDeeplinkTarget(btn.target, detail, ctx.taskId);
|
|
||||||
if (target) ctx.navigate(target.path, { state: target.state });
|
|
||||||
else fail(`未配置「${btn.label}」对应的业务智能体`);
|
|
||||||
} catch {
|
|
||||||
fail("跳转失败,请稍后再试");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
/**
|
|
||||||
* 任务深链(``goPath=rwfx``)的运行时配置:从后端公开只读接口
|
|
||||||
* ``GET /api/public/config/task-deeplink`` 读取(地址、测试开关、测试假数据全在后端
|
|
||||||
* ``config.yaml`` 的 ``task_deeplink`` 段,改完即时生效,前端无需重建)。
|
|
||||||
*
|
|
||||||
* 两种用法:
|
|
||||||
* - 命令式(登录深链流程,非 React 环境):``fetchTaskDeeplinkConfig()`` 拉取并模块级缓存;
|
|
||||||
* ``getCachedTaskDeeplinkConfig()`` 同步读缓存(拼跳转地址用)。
|
|
||||||
* - React 组件:``useTaskDeeplinkConfig()``(见 [[task-purpose]] 的面板/列表)。
|
|
||||||
*
|
|
||||||
* 拉取失败 → 用内置默认值(``test=false`` + 真实 URL)兜底,功能不整体挂掉。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { apiFetch } from "@/core/api/fetch-client";
|
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
|
||||||
|
|
||||||
export interface TaskDeeplinkConfig {
|
|
||||||
/** 目的树查询走假数据。 */
|
|
||||||
test: boolean;
|
|
||||||
/** 删除接口走假数据(该接口未开发完时打开)。 */
|
|
||||||
deleteTest: boolean;
|
|
||||||
/** 行动→任务解析走假数据(xdfx 行动id→任务id)。 */
|
|
||||||
actionTest: boolean;
|
|
||||||
/** 目的树查询完整 URL(调用追加 ?taskId=)。 */
|
|
||||||
purposeDetailUrl: string;
|
|
||||||
/** 删除完整 URL(调用追加 ?taskId=)。 */
|
|
||||||
deleteUrl: string;
|
|
||||||
/** B 系统树形完整编辑页 URL(跳转追加 ?id=)。 */
|
|
||||||
treemapEditUrl: string;
|
|
||||||
/** B 系统树形下一步页 URL(跳转追加 ?id=)。 */
|
|
||||||
treemapNextUrl: string;
|
|
||||||
/** 行动详情接口基址(xdfx 行动→任务):调用追加 /{actionId},返回 data.taskId 为真正任务id。 */
|
|
||||||
actionDetailUrl: string;
|
|
||||||
/** 「3q详情」详情页 URL(rwfx 目的树面板链接,跳转追加 ?id= 任务id);留空则前端提示未配置。 */
|
|
||||||
detail3qUrl: string;
|
|
||||||
/** 测试假数据:purposeDetail = 原始 {state,msg,data};delete = {message,success};
|
|
||||||
* actionDetail = 原始 {state,msg,data:{taskId,...}}。 */
|
|
||||||
mock: {
|
|
||||||
purposeDetail?: unknown;
|
|
||||||
delete?: { message?: string; success?: boolean };
|
|
||||||
actionDetail?: unknown;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 内置默认值(后端拿不到时兜底;真实 URL + 关闭测试)。 */
|
|
||||||
export const DEFAULT_TASK_DEEPLINK_CONFIG: TaskDeeplinkConfig = {
|
|
||||||
test: false,
|
|
||||||
deleteTest: false,
|
|
||||||
actionTest: false,
|
|
||||||
purposeDetailUrl: "https://ch1.b.uat.4.cn/consumer/taskAnalyseSearch/getTaskPurposeDetail",
|
|
||||||
deleteUrl: "https://ch1.b.uat.4.cn/consumer/taskAnalyseSearch/delete",
|
|
||||||
treemapEditUrl: "https://ch1.b.uat.4.cn/web/#/task/item-aicoh/step-mode-treemap-full-edit",
|
|
||||||
treemapNextUrl: "https://ch1.b.uat.4.cn/web/#/task/item-aicoh/step-mode-treemap-full-next",
|
|
||||||
actionDetailUrl: "https://ch1.b.uat.4.cn/consumer/plan/action",
|
|
||||||
detail3qUrl: "",
|
|
||||||
mock: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 后端 snake_case 响应 → 前端 camelCase;缺字段回退默认值。 */
|
|
||||||
function normalize(body: unknown): TaskDeeplinkConfig {
|
|
||||||
const o = body && typeof body === "object" ? (body as Record<string, unknown>) : {};
|
|
||||||
const d = DEFAULT_TASK_DEEPLINK_CONFIG;
|
|
||||||
const str = (v: unknown, fallback: string) =>
|
|
||||||
typeof v === "string" && v.trim() ? v : fallback;
|
|
||||||
const mock = o.mock && typeof o.mock === "object" ? (o.mock as Record<string, unknown>) : {};
|
|
||||||
return {
|
|
||||||
test: o.test === true,
|
|
||||||
deleteTest: o.delete_test === true,
|
|
||||||
actionTest: o.action_test === true,
|
|
||||||
purposeDetailUrl: str(o.purpose_detail_url, d.purposeDetailUrl),
|
|
||||||
deleteUrl: str(o.delete_url, d.deleteUrl),
|
|
||||||
treemapEditUrl: str(o.treemap_edit_url, d.treemapEditUrl),
|
|
||||||
treemapNextUrl: str(o.treemap_next_url, d.treemapNextUrl),
|
|
||||||
actionDetailUrl: str(o.action_detail_url, d.actionDetailUrl),
|
|
||||||
// detail_3q_url 允许为空(地址待定),不回退默认;只在配了非空时才生效。
|
|
||||||
detail3qUrl: typeof o.detail_3q_url === "string" ? o.detail_3q_url : d.detail3qUrl,
|
|
||||||
mock: {
|
|
||||||
purposeDetail: mock.purpose_detail,
|
|
||||||
delete:
|
|
||||||
mock.delete && typeof mock.delete === "object"
|
|
||||||
? (mock.delete as { message?: string; success?: boolean })
|
|
||||||
: undefined,
|
|
||||||
actionDetail: mock.action_detail,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let cached: TaskDeeplinkConfig | null = null;
|
|
||||||
let inflight: Promise<TaskDeeplinkConfig> | null = null;
|
|
||||||
|
|
||||||
/** 拉取(带模块级缓存 + 去重);失败回退默认值。 */
|
|
||||||
export async function fetchTaskDeeplinkConfig(): Promise<TaskDeeplinkConfig> {
|
|
||||||
if (cached) return cached;
|
|
||||||
if (inflight) return inflight;
|
|
||||||
inflight = (async () => {
|
|
||||||
try {
|
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/public/config/task-deeplink`);
|
|
||||||
if (!res.ok) throw new Error(`task-deeplink config ${res.status}`);
|
|
||||||
cached = normalize(await res.json());
|
|
||||||
} catch {
|
|
||||||
cached = { ...DEFAULT_TASK_DEEPLINK_CONFIG };
|
|
||||||
} finally {
|
|
||||||
inflight = null;
|
|
||||||
}
|
|
||||||
return cached;
|
|
||||||
})();
|
|
||||||
return inflight;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 同步读缓存(未拉取过则返回默认值)。 */
|
|
||||||
export function getCachedTaskDeeplinkConfig(): TaskDeeplinkConfig {
|
|
||||||
return cached ?? DEFAULT_TASK_DEEPLINK_CONFIG;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 在完整 URL(可能含 `#` 片段)后追加查询参数,供跳转/调用拼 id/taskId。 */
|
|
||||||
export function appendQueryParam(url: string, key: string, value: string): string {
|
|
||||||
if (!url) return "";
|
|
||||||
const sep = url.includes("?") ? "&" : "?";
|
|
||||||
return `${url}${sep}${key}=${encodeURIComponent(value)}`;
|
|
||||||
}
|
|
||||||
@@ -16,13 +16,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { requestCrudService } from "@/service/request-axios-service";
|
import { requestCrudService } from "@/service/request-axios-service";
|
||||||
import { clearTaskContext, persistTaskContext } from "@/core/auth/task-purpose";
|
|
||||||
import { fetchTaskDeeplinkConfig } from "@/core/auth/task-deeplink-config";
|
|
||||||
import { listBusinessMappings } from "@/strategy-components/api/business-mapping";
|
import { listBusinessMappings } from "@/strategy-components/api/business-mapping";
|
||||||
|
|
||||||
/** xdfx 业务码:深链传入的是「行动id」,需先调 action 接口解析出真正的「任务id」。 */
|
|
||||||
const XDFX_BUSINESS_CODE = "7BF";
|
|
||||||
|
|
||||||
/** consumer 接口返回的任务详情(data 字段)。 */
|
/** consumer 接口返回的任务详情(data 字段)。 */
|
||||||
export interface CopTaskDetail {
|
export interface CopTaskDetail {
|
||||||
id: string | number | null;
|
id: string | number | null;
|
||||||
@@ -35,9 +30,6 @@ export interface CopTaskDetail {
|
|||||||
/** 任务详情整包暂存的 sessionStorage key(目标页/后续可读取)。 */
|
/** 任务详情整包暂存的 sessionStorage key(目标页/后续可读取)。 */
|
||||||
export const COP_TASK_DETAIL_STORAGE_KEY = "login.copTaskDetail";
|
export const COP_TASK_DETAIL_STORAGE_KEY = "login.copTaskDetail";
|
||||||
|
|
||||||
/** 行动详情整包暂存的 sessionStorage key(xdfx 行动分析:会商/单智能体读取行动名称/叙事)。 */
|
|
||||||
export const ACTION_DETAIL_STORAGE_KEY = "login.actionDetail";
|
|
||||||
|
|
||||||
/** goPath 基础码 → 业务码(配置管理 businessCode)。 */
|
/** goPath 基础码 → 业务码(配置管理 businessCode)。 */
|
||||||
const GOPATH_BUSINESS_CODE: Record<string, string> = {
|
const GOPATH_BUSINESS_CODE: Record<string, string> = {
|
||||||
"3qfx": "3Q", // 三情分析
|
"3qfx": "3Q", // 三情分析
|
||||||
@@ -77,28 +69,8 @@ function consumerBaseUrl(): string {
|
|||||||
return typeof value === "string" ? value.replace(/\/+$/, "") : "";
|
return typeof value === "string" ? value.replace(/\/+$/, "") : "";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** cop-task-detail 是否走本地假数据:开关 `VITE_MOCK_COP_TASK_DETAIL=true`(真实接口未就绪时调试用)。 */
|
/** 拉取任务详情;缺少 consumer 地址 / 返回不合法时返回 null。 */
|
||||||
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> {
|
export async function fetchCopTaskDetail(taskId: string): Promise<CopTaskDetail | null> {
|
||||||
if (copTaskDetailMockEnabled()) {
|
|
||||||
return mockCopTaskDetail(taskId);
|
|
||||||
}
|
|
||||||
const base = consumerBaseUrl();
|
const base = consumerBaseUrl();
|
||||||
if (!base || !taskId) return null;
|
if (!base || !taskId) return null;
|
||||||
// service 拦截器已统一注入 `Authorization: Bearer admin` 并返回 response.data(整包 body)。
|
// service 拦截器已统一注入 `Authorization: Bearer admin` 并返回 response.data(整包 body)。
|
||||||
@@ -134,111 +106,17 @@ export function readCopTaskDetail(): CopTaskDetail | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 把行动详情整包暂存到 sessionStorage(xdfx 行动分析用;隐私模式/quota 异常时静默失败)。 */
|
|
||||||
export function persistActionDetail(detail: ActionDetail): void {
|
|
||||||
try {
|
|
||||||
sessionStorage.setItem(ACTION_DETAIL_STORAGE_KEY, JSON.stringify(detail));
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读取暂存的行动详情(会商左上角「当前行动」、单智能体行动详情卡都可读)。 */
|
|
||||||
export function readActionDetail(): ActionDetail | null {
|
|
||||||
try {
|
|
||||||
const raw = sessionStorage.getItem(ACTION_DETAIL_STORAGE_KEY);
|
|
||||||
return raw ? (JSON.parse(raw) as ActionDetail) : null;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 行动详情接口 ``{action_detail_url}/{actionId}`` 返回的 ``data`` 字段(xdfx 行动分析用)。 */
|
|
||||||
export interface ActionDetail {
|
|
||||||
/** 行动id(深链 ?taskId= 传入的就是它)。 */
|
|
||||||
id: string;
|
|
||||||
/** 该行动归属的真正「任务id」。 */
|
|
||||||
taskId: string;
|
|
||||||
/** 所属目的id。 */
|
|
||||||
purposeId: string;
|
|
||||||
/** 行动名称。 */
|
|
||||||
actionName: string;
|
|
||||||
/** 行动状态码。 */
|
|
||||||
actionStatus: number | string;
|
|
||||||
/** 行动叙事 / 描述。 */
|
|
||||||
narration: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* xdfx 深链:用「行动id」调行动详情接口 ``{action_detail_url}/{actionId}``,取出整包行动详情。
|
|
||||||
* ``action_test=true`` 时直接用后端配置里的假数据(接口未通时用)。
|
|
||||||
* 缺地址 / 返回不合法 → 返回 null。
|
|
||||||
*/
|
|
||||||
export async function fetchActionDetail(actionId: string): Promise<ActionDetail | null> {
|
|
||||||
if (!actionId) return null;
|
|
||||||
const cfg = await fetchTaskDeeplinkConfig();
|
|
||||||
let body: unknown;
|
|
||||||
if (cfg.actionTest) {
|
|
||||||
body = cfg.mock.actionDetail;
|
|
||||||
} else if (cfg.actionDetailUrl) {
|
|
||||||
const base = cfg.actionDetailUrl.replace(/\/+$/, "");
|
|
||||||
// service 拦截器已统一注入 Authorization: Bearer admin 并返回整包 body;行动id 走路径段。
|
|
||||||
body = await requestCrudService.get(`${base}/${encodeURIComponent(actionId)}`);
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const data = body && typeof body === "object" ? (body as { data?: unknown }).data : null;
|
|
||||||
if (!data || typeof data !== "object") return null;
|
|
||||||
const d = data as Record<string, unknown>;
|
|
||||||
const detail: ActionDetail = {
|
|
||||||
id: d.id != null ? String(d.id) : "",
|
|
||||||
taskId: d.taskId != null ? String(d.taskId) : "",
|
|
||||||
purposeId: d.purposeId != null ? String(d.purposeId) : "",
|
|
||||||
actionName: typeof d.actionName === "string" ? d.actionName : "",
|
|
||||||
actionStatus:
|
|
||||||
typeof d.actionStatus === "number" || typeof d.actionStatus === "string" ? d.actionStatus : "",
|
|
||||||
narration: typeof d.narration === "string" ? d.narration : "",
|
|
||||||
};
|
|
||||||
// 取到即整包暂存:登录解析任务id 时(resolveDeeplinkTaskId→fetchTaskIdFromAction)就会缓存它,
|
|
||||||
// 之后会商左上角「当前行动」、单智能体行动详情卡都能直接 readActionDetail(),避免重复请求。
|
|
||||||
persistActionDetail(detail);
|
|
||||||
return detail;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* xdfx 深链:用「行动id」解析出真正的「任务id」(取行动详情的 ``data.taskId``)。
|
|
||||||
* 缺地址 / 返回不合法 → 返回 ""(调用方据此回退)。
|
|
||||||
*/
|
|
||||||
export async function fetchTaskIdFromAction(actionId: string): Promise<string> {
|
|
||||||
return (await fetchActionDetail(actionId))?.taskId ?? "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 据 goPath 把深链 URL 里的原始 id 解析成真正的「任务id」:
|
|
||||||
* - xdfx(行动分析):URL 传入的是「行动id」,调 action 接口换成 ``data.taskId``;
|
|
||||||
* 解析失败返回 ""(让调用方回退默认首页,避免拿行动id当任务id污染后续查询/绑定)。
|
|
||||||
* - 其它业务:URL 传入的本就是任务id,原样返回。
|
|
||||||
*/
|
|
||||||
export async function resolveDeeplinkTaskId(goPath: string, rawId: string): Promise<string> {
|
|
||||||
const parsed = parseGoPath(goPath);
|
|
||||||
if (parsed?.businessCode === XDFX_BUSINESS_CODE) {
|
|
||||||
return fetchTaskIdFromAction(rawId);
|
|
||||||
}
|
|
||||||
return rawId;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TaskDeeplinkTarget {
|
export interface TaskDeeplinkTarget {
|
||||||
path: string;
|
path: string;
|
||||||
/** react-router navigate 的 state(多智能体会商用 roundtablePrefill)。 */
|
/** react-router navigate 的 state(多智能体会商用 roundtablePrefill)。 */
|
||||||
state?: Record<string, unknown>;
|
state?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 用 taskName / taskContent 拼出开场信息文本;末尾附上任务 id(task_id),供后端识别任务。 */
|
/** 用 taskName / taskContent 拼出开场信息文本。 */
|
||||||
function buildOpeningText(detail: CopTaskDetail, taskId: string): string {
|
function buildOpeningText(detail: CopTaskDetail): string {
|
||||||
return [
|
return [
|
||||||
detail.taskName ? `任务名称:${detail.taskName}` : "",
|
detail.taskName ? `任务名称:${detail.taskName}` : "",
|
||||||
detail.taskContent ? `任务内容:${detail.taskContent}` : "",
|
detail.taskContent ? `任务内容:${detail.taskContent}` : "",
|
||||||
taskId ? `任务id(task_id)为${taskId}` : "",
|
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join("\n");
|
.join("\n");
|
||||||
@@ -246,43 +124,22 @@ function buildOpeningText(detail: CopTaskDetail, taskId: string): string {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 据 goPath + 任务详情解析跳转目标。
|
* 据 goPath + 任务详情解析跳转目标。
|
||||||
* - 多智能体会商:返回带 ``roundtablePrefill``(businessCode 让会商页自动选用配置的业务链条;
|
* - 多智能体会商:返回带 ``roundtablePrefill``(businessCode 让会商页自动选用配置的业务链条)的 state。
|
||||||
* taskId 让会商页按任务隔离存取草稿/聊天记录)的 state。
|
|
||||||
* - 单智能体问答:解析「配置管理」里该业务配置的智能体;把开场信息写入
|
* - 单智能体问答:解析「配置管理」里该业务配置的智能体;把开场信息写入
|
||||||
* ``sessionStorage.pendingAgentMessage``(AgentChatPage 自动发出)。
|
* ``sessionStorage.pendingAgentMessage``(AgentChatPage 自动发出)。
|
||||||
* 无法识别 goPath / 未配置智能体时返回 null(调用方回退到默认首页)。
|
* 无法识别 goPath / 未配置智能体时返回 null(调用方回退到默认首页)。
|
||||||
*
|
|
||||||
* @param taskId 真实任务 id(xdfx 已由 action 接口解析;其它业务即深链原始 ?taskId=)。
|
|
||||||
* 用于按任务隔离草稿/对话;与 consumer 返回的 detail.id 区分。
|
|
||||||
* @param rawId 深链 URL 的原始 ``?taskId=``(xdfx 为「行动id」)。供需追加行动id 的按钮用;
|
|
||||||
* 省略时回退 taskId。
|
|
||||||
*/
|
*/
|
||||||
export async function resolveTaskDeeplinkTarget(
|
export async function resolveTaskDeeplinkTarget(
|
||||||
goPath: string,
|
goPath: string,
|
||||||
detail: CopTaskDetail,
|
detail: CopTaskDetail,
|
||||||
taskId: string,
|
|
||||||
rawId?: string,
|
|
||||||
): Promise<TaskDeeplinkTarget | null> {
|
): Promise<TaskDeeplinkTarget | null> {
|
||||||
const parsed = parseGoPath(goPath);
|
const parsed = parseGoPath(goPath);
|
||||||
if (!parsed) return null;
|
if (!parsed) return null;
|
||||||
const taskBase = BUSINESS_TASK_BASE[parsed.businessCode];
|
const taskBase = BUSINESS_TASK_BASE[parsed.businessCode];
|
||||||
if (!taskBase) return null;
|
if (!taskBase) return null;
|
||||||
|
|
||||||
// 清掉上一次深链可能残留的任务上下文(单智能体分支会用本次任务重新写入)。
|
|
||||||
clearTaskContext();
|
|
||||||
|
|
||||||
if (parsed.roundtable) {
|
if (parsed.roundtable) {
|
||||||
// 多智能体会商:嵌进对应业务的「任务管理」布局;businessCode 让会商页自动选用配置的业务链条;
|
// 多智能体会商:嵌进对应业务的「任务管理」布局;businessCode 让会商页自动选用配置的业务链条。
|
||||||
// taskId 让会商页按任务隔离存取草稿(一个 taskId 多条记录),并触发第三步自动结构化输出。
|
|
||||||
// xdfx(行动分析):根是「行动」——把行动名称随首条消息交给任务理解,左上角展示「当前行动」。
|
|
||||||
// 行动详情登录解析任务id 时已缓存(fetchActionDetail 内 persistActionDetail);这里优先读缓存。
|
|
||||||
let actionName = "";
|
|
||||||
let actionId = "";
|
|
||||||
if (parsed.businessCode === XDFX_BUSINESS_CODE && rawId) {
|
|
||||||
actionId = rawId;
|
|
||||||
const ad = readActionDetail() ?? (await fetchActionDetail(rawId));
|
|
||||||
actionName = ad?.actionName ?? "";
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
path: `${taskBase}/roundtable`,
|
path: `${taskBase}/roundtable`,
|
||||||
state: {
|
state: {
|
||||||
@@ -290,9 +147,6 @@ export async function resolveTaskDeeplinkTarget(
|
|||||||
taskTitle: detail.taskName,
|
taskTitle: detail.taskName,
|
||||||
taskGoal: detail.taskContent,
|
taskGoal: detail.taskContent,
|
||||||
businessCode: parsed.businessCode,
|
businessCode: parsed.businessCode,
|
||||||
taskId: taskId || undefined,
|
|
||||||
...(actionId ? { actionId } : {}),
|
|
||||||
...(actionName ? { actionName } : {}),
|
|
||||||
autoStart: true,
|
autoStart: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -308,15 +162,14 @@ export async function resolveTaskDeeplinkTarget(
|
|||||||
}
|
}
|
||||||
if (!agentId) return null;
|
if (!agentId) return null;
|
||||||
|
|
||||||
// 单智能体问答统一走「任务工作区」(任务↔对话 1:N,按 taskId + agentId 隔离不同业务的对话列表):
|
try {
|
||||||
// 暂存任务上下文(taskId + agentId + 开场信息),跳到 chats 索引,由工作区按 taskId 决定
|
sessionStorage.setItem(
|
||||||
// 开最新历史对话 / 新建。rwfx 在工作区里额外过「目的树闸门」;3qfx/xdfx 仅 1:N 列表,
|
"pendingAgentMessage",
|
||||||
// 新建对话直接带开场信息自动发出(见 task-purpose / AgentChatPage 的 taskGate / taskBind)。
|
JSON.stringify({ agentId, text: buildOpeningText(detail) }),
|
||||||
persistTaskContext({
|
);
|
||||||
taskId,
|
} catch {
|
||||||
agentId,
|
/* noop */
|
||||||
openingText: buildOpeningText(detail, taskId),
|
}
|
||||||
actionId: rawId || taskId,
|
// 单智能体问答:同样嵌进对应业务的「任务管理」布局。
|
||||||
});
|
return { path: `${taskBase}/agent/${agentId}/chats/new` };
|
||||||
return { path: `${taskBase}/agent/${agentId}/chats` };
|
|
||||||
}
|
}
|
||||||
@@ -1,326 +0,0 @@
|
|||||||
/**
|
|
||||||
* 任务深链(``goPath=rwfx``)的「目的树闸门 + 任务↔对话绑定」支持。
|
|
||||||
*
|
|
||||||
* 角色区分:
|
|
||||||
* - **目的树数据**:B 系统里的策划结果,走 ``getTaskPurposeDetail`` / ``delete``(地址、测试
|
|
||||||
* 开关、测试假数据都来自 [[task-deeplink-config]] / 后端 config.yaml),与聊天对话无关。
|
|
||||||
* 新建对话(含首次进入)前用它做「已有数据→覆盖确认」闸门。
|
|
||||||
* - **对话(thread)**:聊天会话;通过 thread 的 ``metadata.taskId`` 标签把多个对话挂到同一个
|
|
||||||
* 任务下(1:N),列表用 useThreadsPage({ metadata:{ taskId } }) 过滤。详见 [[task-deeplink]]。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import {
|
|
||||||
appendQueryParam,
|
|
||||||
fetchTaskDeeplinkConfig,
|
|
||||||
getCachedTaskDeeplinkConfig,
|
|
||||||
} from "@/core/auth/task-deeplink-config";
|
|
||||||
import { requestCrudService } from "@/service/request-axios-service";
|
|
||||||
import type {
|
|
||||||
FlowGraphData,
|
|
||||||
FlowGraphEdge,
|
|
||||||
FlowGraphNode,
|
|
||||||
FlowNodeType,
|
|
||||||
} from "@/roundtable-planning/lib/flow-graph";
|
|
||||||
|
|
||||||
/** 归一化后的目的树节点(用于展示,逐层:目的→行为体→预期行为→驱动因素→叙事)。 */
|
|
||||||
export interface PurposeTreeNode {
|
|
||||||
/** 节点类型中文标签。 */
|
|
||||||
label: string;
|
|
||||||
/** 节点主文本(目的/行为体名/预期/因素/叙事内容)。 */
|
|
||||||
text: string;
|
|
||||||
/** 推荐理由(若有)。 */
|
|
||||||
reason?: string;
|
|
||||||
children: PurposeTreeNode[];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 当前 rwfx 任务上下文(深链进入或「新建对话」时暂存,供闸门面板与绑定使用)。 */
|
|
||||||
export interface TaskContext {
|
|
||||||
taskId: string;
|
|
||||||
agentId: string;
|
|
||||||
/** 自动发出的开场信息(任务名称/内容)。 */
|
|
||||||
openingText: string;
|
|
||||||
/** 深链原始 id(xdfx 为「行动id」,需追加行动id 的按钮用;其它业务等于 taskId)。 */
|
|
||||||
actionId?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const TASK_CONTEXT_STORAGE_KEY = "task.rwfxContext";
|
|
||||||
|
|
||||||
/* --------------------------- 目的树查询/删除 --------------------------- */
|
|
||||||
|
|
||||||
/** 逐层 dto 字段映射:key=childrenList 里出现的 *Dto 字段名。 */
|
|
||||||
const DTO_FIELD_MAP: Record<string, { label: string; textKey: string }> = {
|
|
||||||
purposeDto: { label: "目的", textKey: "zzPurpose" },
|
|
||||||
actorDto: { label: "行为体", textKey: "actorName" },
|
|
||||||
expectedBehaviorDto: { label: "预期行为", textKey: "behavior" },
|
|
||||||
drivingFactorDto: { label: "驱动因素", textKey: "drivingFactor" },
|
|
||||||
narrationDto: { label: "叙事", textKey: "narration" },
|
|
||||||
};
|
|
||||||
|
|
||||||
// 取节点主文本时跳过的字段(id/时间/标记/理由等非展示文本),保证容错。
|
|
||||||
const SKIP_TEXT_KEY = /(^id$|Id$|Time$|Flag$|Type$|Level$|recReason|createBy|updateBy|^mid$)/i;
|
|
||||||
|
|
||||||
/** 从一个 dto 里取展示文本:优先 preferredKey,否则取第一个像「内容」的字符串字段。 */
|
|
||||||
function pickDtoText(dto: Record<string, unknown>, preferredKey?: string): string {
|
|
||||||
if (preferredKey && typeof dto[preferredKey] === "string" && (dto[preferredKey] as string).trim()) {
|
|
||||||
return dto[preferredKey] as string;
|
|
||||||
}
|
|
||||||
for (const [k, v] of Object.entries(dto)) {
|
|
||||||
if (typeof v === "string" && v.trim() && !SKIP_TEXT_KEY.test(k)) return v;
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把一层节点归一化为 {label,text,reason,children}。**容错**:
|
|
||||||
* - 优先匹配已知 dto(目的/行为体/...);未知 ``*Dto`` 字段也兜底(标签取字段名去 Dto);
|
|
||||||
* - 文本字段改名也能取到(pickDtoText 兜底);
|
|
||||||
* - 完全不认识的结构仍递归 childrenList,避免整棵树丢失。
|
|
||||||
*/
|
|
||||||
function normalizeNode(raw: unknown): PurposeTreeNode | null {
|
|
||||||
if (!raw || typeof raw !== "object") return null;
|
|
||||||
const obj = raw as Record<string, unknown>;
|
|
||||||
const isObj = (k: string) => obj[k] && typeof obj[k] === "object" && !Array.isArray(obj[k]);
|
|
||||||
// 先找已知 dto,再兜底任意 `*Dto` 字段。
|
|
||||||
let dtoKey = Object.keys(DTO_FIELD_MAP).find(isObj);
|
|
||||||
if (!dtoKey) dtoKey = Object.keys(obj).find((k) => /Dto$/.test(k) && isObj(k));
|
|
||||||
|
|
||||||
const childrenRaw = Array.isArray(obj.childrenList) ? obj.childrenList : [];
|
|
||||||
const children = childrenRaw
|
|
||||||
.map(normalizeNode)
|
|
||||||
.filter((n): n is PurposeTreeNode => n !== null);
|
|
||||||
|
|
||||||
if (!dtoKey) {
|
|
||||||
// 不认识的结构:仅当有子节点时保留为占位节点,否则丢弃。
|
|
||||||
return children.length ? { label: "节点", text: "", children } : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const mapped = DTO_FIELD_MAP[dtoKey];
|
|
||||||
const dto = obj[dtoKey] as Record<string, unknown>;
|
|
||||||
const label = mapped?.label ?? dtoKey.replace(/Dto$/, "");
|
|
||||||
const text = pickDtoText(dto, mapped?.textKey);
|
|
||||||
const reason =
|
|
||||||
typeof dto.recReason === "string" && (dto.recReason as string).trim()
|
|
||||||
? (dto.recReason as string)
|
|
||||||
: undefined;
|
|
||||||
return { label, text, reason, children };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 表格行:根→叶一条路径上的各层单元格(层级数可变,做了容错)。 */
|
|
||||||
export type PurposeFlatCell = { label: string; text: string; reason?: string };
|
|
||||||
|
|
||||||
/** 把目的树拍平成「一行一条叶子路径」,供表格展示(层级缺失/变动都不崩)。 */
|
|
||||||
export function flattenPurposeTree(nodes: PurposeTreeNode[]): PurposeFlatCell[][] {
|
|
||||||
const rows: PurposeFlatCell[][] = [];
|
|
||||||
const walk = (node: PurposeTreeNode, trail: PurposeFlatCell[]) => {
|
|
||||||
const next = [...trail, { label: node.label, text: node.text, reason: node.reason }];
|
|
||||||
if (!node.children || node.children.length === 0) rows.push(next);
|
|
||||||
else node.children.forEach((c) => walk(c, next));
|
|
||||||
};
|
|
||||||
nodes.forEach((n) => walk(n, []));
|
|
||||||
return rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --------------------- 目的树 → 流程图(flow-graph) --------------------- */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 目的树各层级标签 → 流程图节点类型(仅决定配色,见 FLOW_NODE_TYPE_META)。
|
|
||||||
* 未知层级回退 task。层级名本身仍原样写进节点 group,画布上当小标签显示。
|
|
||||||
*/
|
|
||||||
const PURPOSE_LABEL_TO_FLOW_TYPE: Record<string, FlowNodeType> = {
|
|
||||||
目的: "stage",
|
|
||||||
行为体: "role",
|
|
||||||
预期行为: "task",
|
|
||||||
驱动因素: "decision",
|
|
||||||
叙事: "deliverable",
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 目的树的一个层级(深度):层级中文名 + 对应流程图节点类型(决定配色)。 */
|
|
||||||
export interface PurposeLevel {
|
|
||||||
/** 层级中文名(目的 / 行为体 / 预期行为 / 驱动因素 / 叙事…)。 */
|
|
||||||
label: string;
|
|
||||||
/** 流程图节点类型(用于取 FLOW_NODE_TYPE_META 配色,与画布节点一致)。 */
|
|
||||||
type: FlowNodeType;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按**深度**抽出目的树的有序层级(每层取该深度第一个非空层级名作代表)。
|
|
||||||
*
|
|
||||||
* 目的树每一深度的层级是一致的(深度 0 = 目的、1 = 行为体、… 直到叶子叙事),
|
|
||||||
* 故逐层 BFS、每层取一个代表标签即可得到「任务策划共几级、分别是什么」,
|
|
||||||
* 供消息列表上方的「流程示例图」按层级画彩色小图标。
|
|
||||||
*/
|
|
||||||
export function derivePurposeLevels(tree: PurposeTreeNode[]): PurposeLevel[] {
|
|
||||||
const levels: PurposeLevel[] = [];
|
|
||||||
let frontier = tree;
|
|
||||||
let depth = 0;
|
|
||||||
while (frontier.length > 0 && depth < 12) {
|
|
||||||
const label = frontier.find((n) => n.label?.trim())?.label?.trim() || `层级 ${depth + 1}`;
|
|
||||||
levels.push({ label, type: PURPOSE_LABEL_TO_FLOW_TYPE[label] ?? "task" });
|
|
||||||
frontier = frontier.flatMap((n) => n.children ?? []);
|
|
||||||
depth += 1;
|
|
||||||
}
|
|
||||||
return levels;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把归一化后的目的树转换成 Step 3 流程图组件(FlowGraphPanel)认识的 FlowGraphData。
|
|
||||||
*
|
|
||||||
* - 逐层深度优先遍历,给每个节点分配稳定 id(`p1/p2/…`,按遍历顺序);
|
|
||||||
* - 父→子建一条边(from=父 id);
|
|
||||||
* - 节点主文本(`text`)作 label,层级名(`label`)作 group(画布顶部小标签),
|
|
||||||
* 推荐理由并进 detail(点节点弹窗里看)。
|
|
||||||
* - 传入 ``rootLabel`` 时,在最顶层加一个「任务」根节点,所有「目的」挂到它下面
|
|
||||||
* (与 B 系统给的「任务 → 目的 → 行为体 → …」流程一致,单一根节点);不传则保持
|
|
||||||
* 旧的「多个目的各自成根」森林(向后兼容)。
|
|
||||||
* 容错沿用 PurposeTreeNode(normalizeNode 已兜底字段/层级变动),这里不再二次判断。
|
|
||||||
*/
|
|
||||||
export function purposeTreeToFlowGraph(
|
|
||||||
tree: PurposeTreeNode[],
|
|
||||||
taskId?: string,
|
|
||||||
rootLabel?: string,
|
|
||||||
): FlowGraphData {
|
|
||||||
const nodes: FlowGraphNode[] = [];
|
|
||||||
const edges: FlowGraphEdge[] = [];
|
|
||||||
let counter = 0;
|
|
||||||
const walk = (node: PurposeTreeNode, parentId: string | null) => {
|
|
||||||
const id = `p${++counter}`;
|
|
||||||
const type = PURPOSE_LABEL_TO_FLOW_TYPE[node.label] ?? "task";
|
|
||||||
const text = node.text?.trim() || node.label || "(空)";
|
|
||||||
const detail = node.reason?.trim()
|
|
||||||
? `${text}\n理由:${node.reason.trim()}`
|
|
||||||
: node.text?.trim() || undefined;
|
|
||||||
nodes.push({ id, label: text, type, group: node.label || undefined, detail });
|
|
||||||
if (parentId) edges.push({ from: parentId, to: id });
|
|
||||||
node.children?.forEach((child) => walk(child, id));
|
|
||||||
};
|
|
||||||
// 任务为单一根节点(仅在有目的数据且传入 rootLabel 时):每个「目的」根挂到它下面。
|
|
||||||
const rootId = rootLabel && rootLabel.trim() && tree.length > 0 ? "task-root" : null;
|
|
||||||
if (rootId) {
|
|
||||||
nodes.push({ id: rootId, label: rootLabel!.trim(), type: "start", group: "任务" });
|
|
||||||
}
|
|
||||||
tree.forEach((root) => walk(root, rootId));
|
|
||||||
return {
|
|
||||||
title: taskId ? `任务目的(任务 ${taskId})` : "任务目的",
|
|
||||||
nodes,
|
|
||||||
edges,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 从接口/假数据的整包 body 里取出 data 数组并归一化成树。 */
|
|
||||||
function bodyToTree(body: unknown): PurposeTreeNode[] {
|
|
||||||
const data =
|
|
||||||
body && typeof body === "object" ? (body as { data?: unknown }).data : null;
|
|
||||||
const arr = Array.isArray(data) ? data : [];
|
|
||||||
return arr.map(normalizeNode).filter((n): n is PurposeTreeNode => n !== null);
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TaskPurposeResult {
|
|
||||||
tree: PurposeTreeNode[];
|
|
||||||
/** data 数组里有有效目的节点 = 已有策划数据。 */
|
|
||||||
hasData: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询任务目的树。``test=true`` 时直接用后端配置里的假数据;否则打真实接口
|
|
||||||
* (地址来自配置,``Authorization: Bearer admin`` 由 axios 拦截器统一注入)。
|
|
||||||
* 缺地址 / 返回不合法 → ``{ tree: [], hasData: false }``。
|
|
||||||
*/
|
|
||||||
export async function fetchTaskPurposeDetail(
|
|
||||||
taskId: string,
|
|
||||||
): Promise<TaskPurposeResult> {
|
|
||||||
if (!taskId) return { tree: [], hasData: false };
|
|
||||||
const cfg = await fetchTaskDeeplinkConfig();
|
|
||||||
let body: unknown;
|
|
||||||
if (cfg.test) {
|
|
||||||
body = cfg.mock.purposeDetail;
|
|
||||||
} else if (cfg.purposeDetailUrl) {
|
|
||||||
body = await requestCrudService.get(cfg.purposeDetailUrl, { taskId });
|
|
||||||
} else {
|
|
||||||
return { tree: [], hasData: false };
|
|
||||||
}
|
|
||||||
const tree = bodyToTree(body);
|
|
||||||
return { tree, hasData: tree.length > 0 };
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DeleteTaskPurposeResult {
|
|
||||||
message: string;
|
|
||||||
success: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 删除任务目的树(覆盖前清空 / 手动清除任务记录都走这里)。``delete_test=true`` 时
|
|
||||||
* 用后端配置里的假数据(接口未开发完时用);否则打真实接口。
|
|
||||||
*/
|
|
||||||
export async function deleteTaskPurpose(
|
|
||||||
taskId: string,
|
|
||||||
): Promise<DeleteTaskPurposeResult> {
|
|
||||||
if (!taskId) return { message: "缺少 taskId", success: false };
|
|
||||||
const cfg = await fetchTaskDeeplinkConfig();
|
|
||||||
if (cfg.deleteTest) {
|
|
||||||
const m = cfg.mock.delete ?? {};
|
|
||||||
return { message: typeof m.message === "string" ? m.message : "", success: m.success === true };
|
|
||||||
}
|
|
||||||
if (!cfg.deleteUrl) return { message: "缺少删除接口地址", success: false };
|
|
||||||
const body = await requestCrudService.get(cfg.deleteUrl, { taskId });
|
|
||||||
const obj =
|
|
||||||
body && typeof body === "object" ? (body as unknown as Record<string, unknown>) : {};
|
|
||||||
return {
|
|
||||||
message: typeof obj.message === "string" ? obj.message : "",
|
|
||||||
success: obj.success === true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ----------------------------- 跳转地址 ----------------------------- */
|
|
||||||
|
|
||||||
/** B 系统「树形完整编辑」页地址(问答后「编辑」按钮,新标签打开)。用同步缓存配置。 */
|
|
||||||
export function buildTreemapEditUrl(taskId: string): string {
|
|
||||||
const url = getCachedTaskDeeplinkConfig().treemapEditUrl;
|
|
||||||
return url && taskId ? appendQueryParam(url, "id", taskId) : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** B 系统「树形下一步」页地址(问答后「下一步」按钮,新标签打开)。 */
|
|
||||||
export function buildTreemapNextUrl(taskId: string): string {
|
|
||||||
const url = getCachedTaskDeeplinkConfig().treemapNextUrl;
|
|
||||||
return url && taskId ? appendQueryParam(url, "id", taskId) : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 「3q详情」详情页地址(目的树面板链接,新标签打开);追加 ?id=任务id。地址未配置时返回 ""。 */
|
|
||||||
export function buildDetail3qUrl(taskId: string): string {
|
|
||||||
const url = getCachedTaskDeeplinkConfig().detail3qUrl;
|
|
||||||
return url && taskId ? appendQueryParam(url, "id", taskId) : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --------------------------- 任务上下文暂存 --------------------------- */
|
|
||||||
|
|
||||||
export function persistTaskContext(ctx: TaskContext): void {
|
|
||||||
try {
|
|
||||||
sessionStorage.setItem(TASK_CONTEXT_STORAGE_KEY, JSON.stringify(ctx));
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readTaskContext(): TaskContext | null {
|
|
||||||
try {
|
|
||||||
const raw = sessionStorage.getItem(TASK_CONTEXT_STORAGE_KEY);
|
|
||||||
if (!raw) return null;
|
|
||||||
const parsed = JSON.parse(raw) as Partial<TaskContext>;
|
|
||||||
if (!parsed?.taskId || !parsed?.agentId) return null;
|
|
||||||
return {
|
|
||||||
taskId: String(parsed.taskId),
|
|
||||||
agentId: String(parsed.agentId),
|
|
||||||
openingText: typeof parsed.openingText === "string" ? parsed.openingText : "",
|
|
||||||
actionId: typeof parsed.actionId === "string" ? parsed.actionId : undefined,
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function clearTaskContext(): void {
|
|
||||||
try {
|
|
||||||
sessionStorage.removeItem(TASK_CONTEXT_STORAGE_KEY);
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,6 @@ import {
|
|||||||
EXTERNAL_LOGIN_STORAGE_KEYS,
|
EXTERNAL_LOGIN_STORAGE_KEYS,
|
||||||
persistExternalLoginParams,
|
persistExternalLoginParams,
|
||||||
} from "./external-login";
|
} from "./external-login";
|
||||||
import { authStorageSet } from "@/core/auth/scoped-storage";
|
|
||||||
|
|
||||||
const AUTH_BASE_URL = (import.meta.env.VITE_AUTH_BASE_URL || "").replace(
|
const AUTH_BASE_URL = (import.meta.env.VITE_AUTH_BASE_URL || "").replace(
|
||||||
/\/$/,
|
/\/$/,
|
||||||
@@ -50,14 +49,21 @@ type UserDetailTokenResponse = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function persistMaxkeyOnlineToken(token: string): void {
|
function persistMaxkeyOnlineToken(token: string): void {
|
||||||
// 嵌入(iframe)态走 sessionStorage(按标签页隔离),正常态走 localStorage。
|
try {
|
||||||
authStorageSet(MAXKEY_ONLINE_TOKEN_STORAGE_KEY, token);
|
localStorage.setItem(MAXKEY_ONLINE_TOKEN_STORAGE_KEY, token);
|
||||||
|
} catch {
|
||||||
|
// 静默失败,不阻断登录
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function persistUserDetailToken(data: UserDetailTokenPayload): void {
|
function persistUserDetailToken(data: UserDetailTokenPayload): void {
|
||||||
authStorageSet(USER_DETAIL_TOKEN_STORAGE_KEY, JSON.stringify(data));
|
try {
|
||||||
if (data.user_id) {
|
localStorage.setItem(USER_DETAIL_TOKEN_STORAGE_KEY, JSON.stringify(data));
|
||||||
authStorageSet(EXTERNAL_LOGIN_STORAGE_KEYS.userId, String(data.user_id));
|
if (data.user_id) {
|
||||||
|
localStorage.setItem(EXTERNAL_LOGIN_STORAGE_KEYS.userId, String(data.user_id));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 静默失败
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { requestCrudService } from "@/service/request-axios-service";
|
import { requestCrudService } from "@/service/request-axios-service";
|
||||||
import { authStorageGet, authStorageSet } from "@/core/auth/scoped-storage";
|
|
||||||
|
|
||||||
const CONSUMER_URL = import.meta.env.VITE_AIPI_CONSUMER_URL || "";
|
const CONSUMER_URL = import.meta.env.VITE_AIPI_CONSUMER_URL || "";
|
||||||
|
|
||||||
@@ -24,7 +23,7 @@ export async function loginByYUserId(
|
|||||||
token?: string | null,
|
token?: string | null,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (token) {
|
if (token) {
|
||||||
authStorageSet(TOOLS_TOKEN_STORAGE_KEY, token);
|
localStorage.setItem(TOOLS_TOKEN_STORAGE_KEY, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = (await requestCrudService.get(
|
const res = (await requestCrudService.get(
|
||||||
@@ -38,14 +37,14 @@ export async function loginByYUserId(
|
|||||||
// 注意:接口也会返回 accessToken,但 XK/PG 及 source=accessToken 要用路由透传的
|
// 注意:接口也会返回 accessToken,但 XK/PG 及 source=accessToken 要用路由透传的
|
||||||
// access_token,故登录流程随后会用 persistAccessToken 覆盖 userInfo.accessToken。
|
// access_token,故登录流程随后会用 persistAccessToken 覆盖 userInfo.accessToken。
|
||||||
const result = res.data ?? {};
|
const result = res.data ?? {};
|
||||||
authStorageSet(
|
localStorage.setItem(
|
||||||
EXTERNAL_USER_INFO_STORAGE_KEY,
|
EXTERNAL_USER_INFO_STORAGE_KEY,
|
||||||
JSON.stringify({ ...result, yUserId }),
|
JSON.stringify({ ...result, yUserId }),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function persistToolsToken(token: string): void {
|
export function persistToolsToken(token: string): void {
|
||||||
authStorageSet(TOOLS_TOKEN_STORAGE_KEY, token);
|
localStorage.setItem(TOOLS_TOKEN_STORAGE_KEY, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,7 +59,7 @@ export function persistAccessToken(token: string): void {
|
|||||||
if (!trimmed) return;
|
if (!trimmed) return;
|
||||||
let info: Record<string, unknown> = {};
|
let info: Record<string, unknown> = {};
|
||||||
try {
|
try {
|
||||||
const raw = authStorageGet(EXTERNAL_USER_INFO_STORAGE_KEY);
|
const raw = localStorage.getItem(EXTERNAL_USER_INFO_STORAGE_KEY);
|
||||||
if (raw) {
|
if (raw) {
|
||||||
const parsed = JSON.parse(raw);
|
const parsed = JSON.parse(raw);
|
||||||
if (parsed && typeof parsed === "object") {
|
if (parsed && typeof parsed === "object") {
|
||||||
@@ -71,5 +70,5 @@ export function persistAccessToken(token: string): void {
|
|||||||
info = {};
|
info = {};
|
||||||
}
|
}
|
||||||
info.accessToken = trimmed;
|
info.accessToken = trimmed;
|
||||||
authStorageSet(EXTERNAL_USER_INFO_STORAGE_KEY, JSON.stringify(info));
|
localStorage.setItem(EXTERNAL_USER_INFO_STORAGE_KEY, JSON.stringify(info));
|
||||||
}
|
}
|
||||||
@@ -1,213 +0,0 @@
|
|||||||
/**
|
|
||||||
* 「外部系统 iframe 套用深链」相关的**按标签页**会话开关。承载三个相互独立的能力,多由 URL
|
|
||||||
* 路由参数开启(独立会话 `isolate` 另可由「外观」设置里的开关在运行时切换,见 `setIsolatedSession`),
|
|
||||||
* 存进同一份 sessionStorage 会话、跨登录跳转/刷新/页内导航存活:
|
|
||||||
*
|
|
||||||
* 1. `embed=1`(可带 `&theme=`)—— **嵌入模式**:去掉全局导航栏(Header)+ 侧边栏(PageSidebar),
|
|
||||||
* 并按外部主题色强制系统明/暗(离散切换)。
|
|
||||||
* 2. `hideJump=1` —— **隐藏深链底部「快捷跳转」栏**:去掉 `TaskJumpBar` 的两部分——底部的
|
|
||||||
* 「下一步」等按钮 + 右侧垂直居中的悬浮菜单(单智能体问答 / 多智能体会商深链共用该栏)。
|
|
||||||
* 3. `isolate=1` —— **独立会话登录**:本标签页的鉴权身份按标签页隔离(见 [[scoped-storage]]
|
|
||||||
* `authStorage()`,嵌入态与独立态同走 sessionStorage)。用于同一浏览器里**另开一个标签页登
|
|
||||||
* 录不同账号**而**不覆盖**当前标签页(localStorage)的登录态——`embed` 已隐含此隔离,`isolate`
|
|
||||||
* 则是把同一套隔离单独提供给**普通(带 chrome)标签页**,不去 chrome、不强制主题、不动跳转栏。
|
|
||||||
*
|
|
||||||
* 三者可单独使用,也可叠加:`hideJump` **只**隐藏跳转栏,不动 chrome / 主题;`embed` 不影响跳转栏;
|
|
||||||
* `isolate` 只切换鉴权存储,不影响 chrome / 主题 / 跳转栏。
|
|
||||||
*
|
|
||||||
* 隔离要点(核心诉求:同一浏览器另开咱们正常系统页,**绝不能**被这些开关影响):
|
|
||||||
* - 用 **sessionStorage**(按标签页隔离、绝不跨标签)持有这些 flag,而**不用** localStorage
|
|
||||||
* (跨标签共享 → 会污染正常页)。
|
|
||||||
* - 主题走 next-themes 的 `forcedTheme`(见 App.tsx `AppProviders`)——只在本标签页生效、
|
|
||||||
* 不写 localStorage `strategy-theme`;嵌入侧绝不调 `setTheme`。
|
|
||||||
* - 去 chrome / 去跳转栏均由本模块的 sessionStorage flag 驱动,不碰 `persistSidebarEnabled` 等
|
|
||||||
* localStorage 偏好。
|
|
||||||
*
|
|
||||||
* iframe 的浏览器上下文就是它自己的标签页,sessionStorage 天然「一个 iframe 一份、随关闭消失」;
|
|
||||||
* 正常页标签页里既无这些参数也无这份会话 → 所有 `isXxx()` 恒为 false,完全不受影响。
|
|
||||||
*/
|
|
||||||
|
|
||||||
const EMBED_SESSION_KEY = "embed.session";
|
|
||||||
|
|
||||||
export type EmbedTheme = "light" | "dark";
|
|
||||||
|
|
||||||
/** 本标签页的嵌入会话(按需置位的若干独立开关)。 */
|
|
||||||
export interface EmbedSession {
|
|
||||||
/** 嵌入模式:去全局 chrome + 强制主题。 */
|
|
||||||
embed: boolean;
|
|
||||||
/** 嵌入模式下强制的主题(仅 embed 为真时有意义)。 */
|
|
||||||
theme: EmbedTheme;
|
|
||||||
/** 隐藏深链底部「快捷跳转」栏(TaskJumpBar:底部按钮 + 右侧悬浮菜单)。 */
|
|
||||||
hideJump: boolean;
|
|
||||||
/** 独立会话:鉴权身份按本标签页隔离(走 sessionStorage),用于同浏览器登录不同账号互不覆盖。 */
|
|
||||||
isolate: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** URL 布尔参数的三态:显式开 / 显式关 / 未带。 */
|
|
||||||
type FlagParam = "on" | "off" | null;
|
|
||||||
|
|
||||||
function toSearchParams(search: string): URLSearchParams {
|
|
||||||
return new URLSearchParams(search.startsWith("?") ? search : `?${search}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读某个布尔型 query 参数的三态。`1/true/yes` → on;`0/false/no` → off;缺省/其它 → null。 */
|
|
||||||
function readFlagParam(search: string, key: string): FlagParam {
|
|
||||||
const v = (toSearchParams(search).get(key) ?? "").trim().toLowerCase();
|
|
||||||
if (!v) return null;
|
|
||||||
if (v === "1" || v === "true" || v === "yes") return "on";
|
|
||||||
if (v === "0" || v === "false" || v === "no") return "off";
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读 URL 里的 `embed` 三态。 */
|
|
||||||
export function readEmbedParam(search: string): FlagParam {
|
|
||||||
return readFlagParam(search, "embed");
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读 URL 里的 `hideJump` 三态。 */
|
|
||||||
export function readHideJumpParam(search: string): FlagParam {
|
|
||||||
return readFlagParam(search, "hideJump");
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读 URL 里的 `isolate` 三态(独立会话登录)。 */
|
|
||||||
export function readIsolateParam(search: string): FlagParam {
|
|
||||||
return readFlagParam(search, "isolate");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把外部传入的主题色映射成离散明/暗。与 `resolveThemeFromQuery` 同源约定(dark-blue → 深色),
|
|
||||||
* 另外宽松接受 `dark` / 中文「深色/深蓝」直传;其余(含空)一律浅色。
|
|
||||||
*/
|
|
||||||
export function resolveEmbedThemeMode(raw: string | null | undefined): EmbedTheme {
|
|
||||||
const v = (raw ?? "").trim().toLowerCase();
|
|
||||||
if (v === "dark" || v === "dark-blue" || v === "深色" || v === "深蓝") return "dark";
|
|
||||||
return "light";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 取 URL query 里的 `theme` 值(embed 主题来源)。 */
|
|
||||||
export function readEmbedThemeParam(search: string): string {
|
|
||||||
return (toSearchParams(search).get("theme") ?? "").trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读本标签页的嵌入会话;无 → null。 */
|
|
||||||
export function readEmbedSession(): EmbedSession | null {
|
|
||||||
try {
|
|
||||||
const raw = sessionStorage.getItem(EMBED_SESSION_KEY);
|
|
||||||
if (!raw) return null;
|
|
||||||
const p = JSON.parse(raw) as Partial<EmbedSession>;
|
|
||||||
return {
|
|
||||||
embed: p.embed === true,
|
|
||||||
theme: p.theme === "dark" ? "dark" : "light",
|
|
||||||
hideJump: p.hideJump === true,
|
|
||||||
isolate: p.isolate === true,
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 写会话;无任何开关置位时直接清除(保持 sessionStorage 干净)。隐私模式/quota 异常静默失败。 */
|
|
||||||
function writeEmbedSession(next: EmbedSession): void {
|
|
||||||
try {
|
|
||||||
if (!next.embed && !next.hideJump && !next.isolate) {
|
|
||||||
sessionStorage.removeItem(EMBED_SESSION_KEY);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sessionStorage.setItem(EMBED_SESSION_KEY, JSON.stringify(next));
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 本标签页是否处于嵌入模式(驱动去全局 chrome + 强制主题)。 */
|
|
||||||
export function isEmbedActive(): boolean {
|
|
||||||
return readEmbedSession()?.embed === true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 本标签页是否要隐藏深链底部「快捷跳转」栏(TaskJumpBar)。 */
|
|
||||||
export function isJumpBarHidden(): boolean {
|
|
||||||
return readEmbedSession()?.hideJump === true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 本标签页是否处于独立会话态:鉴权身份按标签页隔离(走 sessionStorage)。
|
|
||||||
* `embed` 已隐含同样的隔离,故 `authStorage()` 取「embed || isolate」之并;这里只判 `isolate`,
|
|
||||||
* 供需要区分「纯独立会话(带 chrome)」与「嵌入态(去 chrome)」的场合使用。
|
|
||||||
*/
|
|
||||||
export function isIsolatedSession(): boolean {
|
|
||||||
return readEmbedSession()?.isolate === true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按 URL 参数同步 sessionStorage 会话(AppProviders 在每次 search 变化时调用一次)。
|
|
||||||
* **合并语义**:on 置位、off 清位、未带则沿用既有值——这样登录后跳到不带参数的干净路由时,
|
|
||||||
* 之前置位的开关不会被抹掉。
|
|
||||||
*/
|
|
||||||
export function syncEmbedSessionFromSearch(search: string): void {
|
|
||||||
const cur =
|
|
||||||
readEmbedSession() ??
|
|
||||||
{ embed: false, theme: "light" as EmbedTheme, hideJump: false, isolate: false };
|
|
||||||
const next: EmbedSession = { ...cur };
|
|
||||||
|
|
||||||
const embedParam = readEmbedParam(search);
|
|
||||||
if (embedParam === "on") {
|
|
||||||
next.embed = true;
|
|
||||||
next.theme = resolveEmbedThemeMode(readEmbedThemeParam(search));
|
|
||||||
} else if (embedParam === "off") {
|
|
||||||
next.embed = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const hideJumpParam = readHideJumpParam(search);
|
|
||||||
if (hideJumpParam === "on") next.hideJump = true;
|
|
||||||
else if (hideJumpParam === "off") next.hideJump = false;
|
|
||||||
|
|
||||||
const isolateParam = readIsolateParam(search);
|
|
||||||
if (isolateParam === "on") next.isolate = true;
|
|
||||||
else if (isolateParam === "off") next.isolate = false;
|
|
||||||
|
|
||||||
writeEmbedSession(next);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从当前 HashRouter URL(`#/path?a=b`)取出 query 串。
|
|
||||||
* 供「在 React 渲染之前」同步启用嵌入会话(main.tsx)——必须早于任何鉴权写入,
|
|
||||||
* 否则首帧 LoginPage 的 effect 可能抢在 AppProviders 同步 effect 之前把登录参数写进 localStorage。
|
|
||||||
*/
|
|
||||||
function currentHashSearch(): string {
|
|
||||||
if (typeof window === "undefined") return "";
|
|
||||||
const hash = window.location.hash || "";
|
|
||||||
const i = hash.indexOf("?");
|
|
||||||
return i >= 0 ? hash.slice(i) : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** main.tsx 在渲染前同步调用一次:据当前 URL 启用/关闭本标签页嵌入会话。 */
|
|
||||||
export function syncEmbedSessionFromCurrentUrl(): void {
|
|
||||||
syncEmbedSessionFromSearch(currentHashSearch());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 解析「应当强制的嵌入主题」供 `AppProviders` 的 `forcedTheme` 用:
|
|
||||||
* - URL 显式 `embed=1` → 用 URL `theme`(首帧即生效,登录页转场不闪烁);
|
|
||||||
* - URL 显式 `embed=0` → 不强制(undefined);
|
|
||||||
* - URL 未带 → 回退本标签页嵌入会话主题(仅 embed 置位时)。
|
|
||||||
* 非嵌入标签页恒返回 undefined → 完全不影响正常系统页的主题。
|
|
||||||
*/
|
|
||||||
export function resolveForcedEmbedTheme(search: string): EmbedTheme | undefined {
|
|
||||||
const param = readEmbedParam(search);
|
|
||||||
if (param === "on") return resolveEmbedThemeMode(readEmbedThemeParam(search));
|
|
||||||
if (param === "off") return undefined;
|
|
||||||
const session = readEmbedSession();
|
|
||||||
return session?.embed ? session.theme : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 运行时直接置位/清除本标签页的独立会话标志(供「外观」设置里的开关用,区别于 URL 参数驱动)。
|
|
||||||
* 仅切换标志;登录态的「localStorage 快照搬进 sessionStorage」由 [[scoped-storage]]
|
|
||||||
* `migrateAuthToSession()` 负责,调用顺序见 appearance 设置页。
|
|
||||||
*/
|
|
||||||
export function setIsolatedSession(on: boolean): void {
|
|
||||||
const cur =
|
|
||||||
readEmbedSession() ??
|
|
||||||
{ embed: false, theme: "light" as EmbedTheme, hideJump: false, isolate: false };
|
|
||||||
writeEmbedSession({ ...cur, isolate: on });
|
|
||||||
}
|
|
||||||
@@ -1,119 +0,0 @@
|
|||||||
import assert from "node:assert/strict";
|
|
||||||
import test from "node:test";
|
|
||||||
|
|
||||||
import {
|
|
||||||
applyMenuOverrides,
|
|
||||||
buildTreeFromMerged,
|
|
||||||
diffOverrides,
|
|
||||||
flattenMenu,
|
|
||||||
isDescendant,
|
|
||||||
mergeFlatNodes,
|
|
||||||
wouldExceedDepth,
|
|
||||||
type MenuOverride,
|
|
||||||
} from "./menu-overrides";
|
|
||||||
import type { MenuItem } from "./sidebar-menu";
|
|
||||||
|
|
||||||
// 极简图标占位(合并逻辑不关心图标本身)。
|
|
||||||
const I = (() => null) as unknown as MenuItem["icon"];
|
|
||||||
|
|
||||||
function sampleTree(): MenuItem[] {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
id: "a",
|
|
||||||
label: "A",
|
|
||||||
icon: I,
|
|
||||||
children: [
|
|
||||||
{ id: "a1", label: "A1", icon: I, path: "/a1" },
|
|
||||||
{
|
|
||||||
id: "a2",
|
|
||||||
label: "A2",
|
|
||||||
icon: I,
|
|
||||||
children: [{ id: "a2x", label: "A2X", icon: I, path: "/a2x" }],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{ id: "b", label: "B", icon: I, path: "/b" },
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
const ids = (items: MenuItem[]): string[] =>
|
|
||||||
items.flatMap((i) => [i.id, ...(i.children ? ids(i.children) : [])]);
|
|
||||||
|
|
||||||
test("无覆盖时原样返回", () => {
|
|
||||||
const tree = sampleTree();
|
|
||||||
assert.equal(applyMenuOverrides(tree, []), tree);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("改名只改 label,不动结构", () => {
|
|
||||||
const out = applyMenuOverrides(sampleTree(), [
|
|
||||||
{ nodeId: "a1", parentId: "a", sortOrder: 0, label: "改名了", disabled: false },
|
|
||||||
]);
|
|
||||||
const a = out.find((n) => n.id === "a")!;
|
|
||||||
assert.equal(a.children![0].label, "改名了");
|
|
||||||
assert.deepEqual(ids(out), ["a", "a1", "a2", "a2x", "b"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("停用一级菜单隐藏其整棵子树", () => {
|
|
||||||
const out = applyMenuOverrides(sampleTree(), [
|
|
||||||
{ nodeId: "a", parentId: null, sortOrder: 0, label: null, disabled: true },
|
|
||||||
]);
|
|
||||||
assert.deepEqual(ids(out), ["b"]); // a / a1 / a2 / a2x 全部隐藏
|
|
||||||
});
|
|
||||||
|
|
||||||
test("管理页 includeDisabled=true 保留停用节点", () => {
|
|
||||||
const merged = mergeFlatNodes(flattenMenu(sampleTree()), [
|
|
||||||
{ nodeId: "a2", parentId: "a", sortOrder: 1, label: null, disabled: true },
|
|
||||||
]);
|
|
||||||
const all = buildTreeFromMerged(merged, true);
|
|
||||||
assert.ok(ids(all).includes("a2"));
|
|
||||||
const sidebar = buildTreeFromMerged(merged, false);
|
|
||||||
assert.ok(!ids(sidebar).includes("a2"));
|
|
||||||
assert.ok(!ids(sidebar).includes("a2x")); // 子树同隐藏
|
|
||||||
});
|
|
||||||
|
|
||||||
test("改父级把子树一起搬走", () => {
|
|
||||||
// 把 a2(带子 a2x)移到一级 B 之后 → a2 成为一级。
|
|
||||||
const out = applyMenuOverrides(sampleTree(), [
|
|
||||||
{ nodeId: "a2", parentId: null, sortOrder: 5, label: null, disabled: false },
|
|
||||||
]);
|
|
||||||
const top = out.map((n) => n.id);
|
|
||||||
assert.ok(top.includes("a2"));
|
|
||||||
const a2 = out.find((n) => n.id === "a2")!;
|
|
||||||
assert.deepEqual(a2.children!.map((c) => c.id), ["a2x"]); // 子树跟随
|
|
||||||
});
|
|
||||||
|
|
||||||
test("wouldExceedDepth 阻止四级", () => {
|
|
||||||
const merged = mergeFlatNodes(flattenMenu(sampleTree()), []);
|
|
||||||
// a2x 是三级;把 a(高度3)移到 a2x 下 → 6 级,必拒。
|
|
||||||
assert.equal(wouldExceedDepth("a", "a2x", merged), true);
|
|
||||||
// a1(叶子,高度1)移到 a2 下 → a2 是二级,结果三级,允许。
|
|
||||||
assert.equal(wouldExceedDepth("a1", "a2", merged), false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("isDescendant 识别子树", () => {
|
|
||||||
const merged = mergeFlatNodes(flattenMenu(sampleTree()), []);
|
|
||||||
assert.equal(isDescendant("a", "a2x", merged), true);
|
|
||||||
assert.equal(isDescendant("a", "b", merged), false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("diffOverrides 只输出有变化的节点", () => {
|
|
||||||
const merged = mergeFlatNodes(flattenMenu(sampleTree()), []);
|
|
||||||
// 原样 → 无 diff
|
|
||||||
assert.deepEqual(diffOverrides(merged), []);
|
|
||||||
// 改一个 label
|
|
||||||
const renamed = merged.map((n) => (n.id === "b" ? { ...n, label: "B改" } : n));
|
|
||||||
const diff = diffOverrides(renamed);
|
|
||||||
assert.equal(diff.length, 1);
|
|
||||||
assert.equal(diff[0]!.nodeId, "b");
|
|
||||||
assert.equal(diff[0]!.label, "B改");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("套覆盖再 diff 可往返", () => {
|
|
||||||
const overrides: MenuOverride[] = [
|
|
||||||
{ nodeId: "a1", parentId: "a", sortOrder: 0, label: "X", disabled: false },
|
|
||||||
];
|
|
||||||
const merged = mergeFlatNodes(flattenMenu(sampleTree()), overrides);
|
|
||||||
const diff = diffOverrides(merged);
|
|
||||||
assert.equal(diff.length, 1);
|
|
||||||
assert.equal(diff[0]!.label, "X");
|
|
||||||
});
|
|
||||||
@@ -1,263 +0,0 @@
|
|||||||
/**
|
|
||||||
* 菜单覆盖层(overlay)合并逻辑。
|
|
||||||
*
|
|
||||||
* 静态菜单(sidebar-menu.ts)+ 注入的 iframe 轻应用 = 合并树,是结构/图标/路由的
|
|
||||||
* 唯一来源;后端只按节点 id 存「覆盖项」(改名 label / 停用 disabled / 排序
|
|
||||||
* sortOrder / 改父级 parentId)。渲染时把覆盖项套到合并树上重建。
|
|
||||||
*
|
|
||||||
* 图标与路由永不入库 —— 覆盖只动 label/可见性/位置/层级,所以新增的代码菜单、
|
|
||||||
* 新注册的 iframe 应用都会自动出现,且立即可被配置。
|
|
||||||
*
|
|
||||||
* 严格 3 级:一级 → 二级 → 三级,移动导致超过 3 级的非法布局会被
|
|
||||||
* `wouldExceedDepth` 拦截(后端 `_validate_depth` 二次校验)。
|
|
||||||
*/
|
|
||||||
import type { MenuItem } from "./sidebar-menu";
|
|
||||||
|
|
||||||
export const MAX_MENU_DEPTH = 3;
|
|
||||||
export const ROOT_PARENT_ID = "__root__";
|
|
||||||
|
|
||||||
/** 单个节点的覆盖项(与后端 MenuOverride 对应;camelCase 边界)。 */
|
|
||||||
export interface MenuOverride {
|
|
||||||
nodeId: string;
|
|
||||||
/** 生效的父节点 id;null = 一级菜单。 */
|
|
||||||
parentId: string | null;
|
|
||||||
sortOrder: number;
|
|
||||||
/** 改名;null/undefined 保留代码定义的 label。 */
|
|
||||||
label?: string | null;
|
|
||||||
disabled: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 拍平后的节点:保留原始定义 + 代码默认的父级/次序。 */
|
|
||||||
export interface FlatMenuNode {
|
|
||||||
id: string;
|
|
||||||
/** 代码默认 label(未改名时显示)。 */
|
|
||||||
defaultLabel: string;
|
|
||||||
defaultParentId: string | null;
|
|
||||||
defaultIndex: number;
|
|
||||||
/** 原始静态节点(含 icon/path/adminOnly/userPath,重建时复用)。 */
|
|
||||||
source: MenuItem;
|
|
||||||
/** 是否为注入的 iframe 轻应用节点(light-app-<appId>)。 */
|
|
||||||
isLightApp: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 把合并树拍平成有序节点列表,记录每个节点的代码默认父级与同级次序。 */
|
|
||||||
export function flattenMenu(items: MenuItem[]): FlatMenuNode[] {
|
|
||||||
const out: FlatMenuNode[] = [];
|
|
||||||
const walk = (nodes: MenuItem[], parentId: string | null) => {
|
|
||||||
nodes.forEach((node, index) => {
|
|
||||||
out.push({
|
|
||||||
id: node.id,
|
|
||||||
defaultLabel: node.label,
|
|
||||||
defaultParentId: parentId,
|
|
||||||
defaultIndex: index,
|
|
||||||
source: node,
|
|
||||||
isLightApp: node.id.startsWith("light-app-"),
|
|
||||||
});
|
|
||||||
if (node.children?.length) {
|
|
||||||
walk(node.children, node.id);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
walk(items, null);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 合并视图节点:拍平节点 + 生效后的 label / parentId / order / disabled。
|
|
||||||
* 菜单管理页直接编辑这份结构(含停用项,用于灰显展示)。
|
|
||||||
*/
|
|
||||||
export interface MergedMenuNode extends FlatMenuNode {
|
|
||||||
label: string;
|
|
||||||
parentId: string | null;
|
|
||||||
order: number;
|
|
||||||
disabled: boolean;
|
|
||||||
/** 该节点是否带显式覆盖项(用于「重置该项」判断)。 */
|
|
||||||
hasOverride: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 把覆盖项套到拍平节点上,得到生效后的合并节点(不重建树)。 */
|
|
||||||
export function mergeFlatNodes(
|
|
||||||
flat: FlatMenuNode[],
|
|
||||||
overrides: MenuOverride[],
|
|
||||||
): MergedMenuNode[] {
|
|
||||||
const byId = new Map(overrides.map((o) => [o.nodeId, o]));
|
|
||||||
return flat.map((node) => {
|
|
||||||
const ov = byId.get(node.id);
|
|
||||||
return {
|
|
||||||
...node,
|
|
||||||
label: ov?.label != null && ov.label !== "" ? ov.label : node.defaultLabel,
|
|
||||||
parentId: ov ? ov.parentId : node.defaultParentId,
|
|
||||||
order: ov ? ov.sortOrder : node.defaultIndex,
|
|
||||||
disabled: ov?.disabled ?? false,
|
|
||||||
hasOverride: ov != null,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把合并节点重建成菜单树。
|
|
||||||
* @param includeDisabled 渲染侧边栏时为 false(连同停用节点的整棵子树一并隐藏);
|
|
||||||
* 管理页为 true(全部展示,停用项灰显)。
|
|
||||||
*/
|
|
||||||
export function buildTreeFromMerged(
|
|
||||||
merged: MergedMenuNode[],
|
|
||||||
includeDisabled = false,
|
|
||||||
): MenuItem[] {
|
|
||||||
const parentOf = new Map(merged.map((n) => [n.id, n.parentId ?? null]));
|
|
||||||
const disabledIds = new Set(merged.filter((n) => n.disabled).map((n) => n.id));
|
|
||||||
|
|
||||||
// 停用节点本身或任一祖先被停用 → 整棵子树隐藏(渲染侧边栏时)。
|
|
||||||
const isHidden = (id: string): boolean => {
|
|
||||||
let cursor: string | null = id;
|
|
||||||
const seen = new Set<string>();
|
|
||||||
while (cursor) {
|
|
||||||
if (disabledIds.has(cursor)) return true;
|
|
||||||
if (seen.has(cursor)) break;
|
|
||||||
seen.add(cursor);
|
|
||||||
cursor = parentOf.get(cursor) ?? null;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
const visible = includeDisabled ? merged : merged.filter((n) => !isHidden(n.id));
|
|
||||||
const visibleIds = new Set(visible.map((n) => n.id));
|
|
||||||
|
|
||||||
const childrenOf = new Map<string | null, MergedMenuNode[]>();
|
|
||||||
for (const node of visible) {
|
|
||||||
// parentId 指向不存在/已隐藏的节点 → 回落到一级(数据安全网,正常数据不会触发)。
|
|
||||||
const key = node.parentId != null && visibleIds.has(node.parentId) ? node.parentId : null;
|
|
||||||
const list = childrenOf.get(key) ?? [];
|
|
||||||
list.push(node);
|
|
||||||
childrenOf.set(key, list);
|
|
||||||
}
|
|
||||||
|
|
||||||
const assemble = (parentId: string | null): MenuItem[] => {
|
|
||||||
const list = (childrenOf.get(parentId) ?? [])
|
|
||||||
.slice()
|
|
||||||
.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
|
|
||||||
return list.map((node) => {
|
|
||||||
const children = assemble(node.id);
|
|
||||||
const base: MenuItem = { ...node.source, label: node.label };
|
|
||||||
if (children.length) {
|
|
||||||
base.children = children;
|
|
||||||
} else if (base.children) {
|
|
||||||
// 原本有 children 但全被过滤/移走:保留空数组以维持「分组」语义。
|
|
||||||
base.children = [];
|
|
||||||
}
|
|
||||||
return base;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
return assemble(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 应用覆盖层并返回供侧边栏渲染的菜单树(停用项已剔除)。 */
|
|
||||||
export function applyMenuOverrides(items: MenuItem[], overrides: MenuOverride[]): MenuItem[] {
|
|
||||||
if (!overrides.length) return items;
|
|
||||||
const merged = mergeFlatNodes(flattenMenu(items), overrides);
|
|
||||||
return buildTreeFromMerged(merged, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 管理页编辑辅助 ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/** 计算某节点在「父级映射」下的深度(1=一级)。检测到环时返回 Infinity。 */
|
|
||||||
export function depthOf(nodeId: string, parentOf: Map<string, string | null>): number {
|
|
||||||
let depth = 1;
|
|
||||||
const seen = new Set<string>([nodeId]);
|
|
||||||
let cursor = parentOf.get(nodeId) ?? null;
|
|
||||||
while (cursor) {
|
|
||||||
depth += 1;
|
|
||||||
if (seen.has(cursor)) return Infinity;
|
|
||||||
seen.add(cursor);
|
|
||||||
cursor = parentOf.get(cursor) ?? null;
|
|
||||||
}
|
|
||||||
return depth;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 某节点子树的最大相对高度(叶子=1)。用于判断移动后是否超 3 级。 */
|
|
||||||
export function subtreeHeight(nodeId: string, childrenMap: Map<string | null, string[]>): number {
|
|
||||||
const kids = childrenMap.get(nodeId) ?? [];
|
|
||||||
if (!kids.length) return 1;
|
|
||||||
return 1 + Math.max(...kids.map((k) => subtreeHeight(k, childrenMap)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把 `nodeId` 移到 `targetParentId`(null=一级)后,是否会超过 3 级。
|
|
||||||
* = 目标父级深度 + 被移动子树的高度 > MAX_MENU_DEPTH。
|
|
||||||
*/
|
|
||||||
export function wouldExceedDepth(
|
|
||||||
nodeId: string,
|
|
||||||
targetParentId: string | null,
|
|
||||||
merged: MergedMenuNode[],
|
|
||||||
): boolean {
|
|
||||||
const parentOf = new Map(merged.map((n) => [n.id, n.parentId]));
|
|
||||||
const childrenMap = new Map<string | null, string[]>();
|
|
||||||
for (const n of merged) {
|
|
||||||
const key = n.parentId ?? null;
|
|
||||||
const list = childrenMap.get(key) ?? [];
|
|
||||||
list.push(n.id);
|
|
||||||
childrenMap.set(key, list);
|
|
||||||
}
|
|
||||||
const parentDepth = targetParentId == null ? 0 : depthOf(targetParentId, parentOf);
|
|
||||||
if (parentDepth === Infinity) return true;
|
|
||||||
const height = subtreeHeight(nodeId, childrenMap);
|
|
||||||
return parentDepth + height > MAX_MENU_DEPTH;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 目标父级是否落在被移动节点自身的子树内(禁止把节点移进自己的后代)。 */
|
|
||||||
export function isDescendant(
|
|
||||||
nodeId: string,
|
|
||||||
candidateParentId: string | null,
|
|
||||||
merged: MergedMenuNode[],
|
|
||||||
): boolean {
|
|
||||||
if (candidateParentId == null) return false;
|
|
||||||
const parentOf = new Map(merged.map((n) => [n.id, n.parentId]));
|
|
||||||
let cursor: string | null = candidateParentId;
|
|
||||||
const seen = new Set<string>();
|
|
||||||
while (cursor) {
|
|
||||||
if (cursor === nodeId) return true;
|
|
||||||
if (seen.has(cursor)) break;
|
|
||||||
seen.add(cursor);
|
|
||||||
cursor = parentOf.get(cursor) ?? null;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把当前合并节点与代码默认值求差,得到需要持久化的最小覆盖集。
|
|
||||||
* 只有「改名 / 停用 / 父级变化 / 同级次序变化」的节点才入库。
|
|
||||||
*/
|
|
||||||
export function diffOverrides(merged: MergedMenuNode[]): MenuOverride[] {
|
|
||||||
// 同级内按 order 排序后重排为紧凑索引,便于和 defaultIndex 比较。
|
|
||||||
const siblings = new Map<string | null, MergedMenuNode[]>();
|
|
||||||
for (const n of merged) {
|
|
||||||
const key = n.parentId ?? null;
|
|
||||||
const list = siblings.get(key) ?? [];
|
|
||||||
list.push(n);
|
|
||||||
siblings.set(key, list);
|
|
||||||
}
|
|
||||||
const compactIndex = new Map<string, number>();
|
|
||||||
for (const list of siblings.values()) {
|
|
||||||
list
|
|
||||||
.slice()
|
|
||||||
.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
|
|
||||||
.forEach((n, i) => compactIndex.set(n.id, i));
|
|
||||||
}
|
|
||||||
|
|
||||||
const out: MenuOverride[] = [];
|
|
||||||
for (const n of merged) {
|
|
||||||
const idx = compactIndex.get(n.id) ?? n.order;
|
|
||||||
const renamed = n.label !== n.defaultLabel;
|
|
||||||
const reparented = (n.parentId ?? null) !== (n.defaultParentId ?? null);
|
|
||||||
const reordered = idx !== n.defaultIndex;
|
|
||||||
if (!renamed && !reparented && !n.disabled && !reordered) continue;
|
|
||||||
out.push({
|
|
||||||
nodeId: n.id,
|
|
||||||
parentId: n.parentId ?? null,
|
|
||||||
sortOrder: idx,
|
|
||||||
label: renamed ? n.label : null,
|
|
||||||
disabled: n.disabled,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
@@ -1,372 +1,353 @@
|
|||||||
/**
|
/**
|
||||||
* 全局侧边栏菜单数据与权限过滤逻辑。
|
* 全局侧边栏菜单数据与权限过滤逻辑。
|
||||||
*
|
*
|
||||||
* 浅色 ``PageSidebar`` 和深色 ``PageSidebarDark`` 共用这份数据 —— 菜单结构与
|
* 浅色 ``PageSidebar`` 和深色 ``PageSidebarDark`` 共用这份数据 —— 菜单结构与
|
||||||
* adminOnly 权限策略对两种皮肤完全一致;UI 渲染(icon 显示/折叠样式/hover flyout)
|
* adminOnly 权限策略对两种皮肤完全一致;UI 渲染(icon 显示/折叠样式/hover flyout)
|
||||||
* 在各自组件里实现。
|
* 在各自组件里实现。
|
||||||
*
|
*
|
||||||
* 修改菜单只需改这一处,两个 sidebar 自动同步。
|
* 修改菜单只需改这一处,两个 sidebar 自动同步。
|
||||||
*/
|
*/
|
||||||
import type { ElementType } from "react";
|
import type { ElementType } from "react";
|
||||||
import {
|
import {
|
||||||
Activity,
|
Activity,
|
||||||
BookOpen,
|
BookOpen,
|
||||||
Bot,
|
Bot,
|
||||||
Brain,
|
Brain,
|
||||||
Briefcase,
|
Briefcase,
|
||||||
CalendarClock,
|
CalendarClock,
|
||||||
CircleHelp,
|
CircleHelp,
|
||||||
ClipboardList,
|
ClipboardList,
|
||||||
Database,
|
Database,
|
||||||
FileBox,
|
FileBox,
|
||||||
FileText,
|
FileText,
|
||||||
Gauge,
|
Gauge,
|
||||||
Grid3X3,
|
Grid3X3,
|
||||||
HelpCircle,
|
HelpCircle,
|
||||||
History,
|
History,
|
||||||
Layers,
|
Layers,
|
||||||
Layout,
|
Layout,
|
||||||
Library,
|
Library,
|
||||||
List,
|
List,
|
||||||
ListChecks,
|
ListChecks,
|
||||||
ListTodo,
|
ListTodo,
|
||||||
Network,
|
Network,
|
||||||
Radar,
|
Radar,
|
||||||
Settings,
|
Settings,
|
||||||
Sparkles,
|
Sparkles,
|
||||||
Target,
|
Target,
|
||||||
Trophy,
|
Trophy,
|
||||||
Users,
|
Users,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
export type MenuItem = {
|
export type MenuItem = {
|
||||||
id: string;
|
id: string;
|
||||||
label: string;
|
label: string;
|
||||||
icon: ElementType;
|
icon: ElementType;
|
||||||
path?: string;
|
path?: string;
|
||||||
/** 额外视为「当前页属于本菜单项」的路由(不在侧栏展示,仅用于高亮)。 */
|
/** 非 admin 用户使用的路由(菜单对普通用户可见时生效,与简洁模式公开排行榜一致) */
|
||||||
aliasPaths?: string[];
|
userPath?: string;
|
||||||
/** 非 admin 用户使用的路由(菜单对普通用户可见时生效,与简洁模式公开排行榜一致) */
|
adminOnly?: boolean;
|
||||||
userPath?: string;
|
children?: MenuItem[];
|
||||||
adminOnly?: boolean;
|
};
|
||||||
children?: MenuItem[];
|
|
||||||
};
|
export const sidebarMenuItems: MenuItem[] = [
|
||||||
|
{
|
||||||
export const sidebarMenuItems: MenuItem[] = [
|
id: "qa-center",
|
||||||
{
|
label: "问答管理",
|
||||||
id: "qa-center",
|
icon: HelpCircle,
|
||||||
label: "问答管理",
|
children: [
|
||||||
icon: HelpCircle,
|
{ id: "general-qa", label: "通用问答", icon: CircleHelp, path: "/page/workspace/chats/new" },
|
||||||
children: [
|
{
|
||||||
{ id: "general-qa", label: "通用问答", icon: CircleHelp, path: "/page/workspace/chats/new" },
|
id: "multi-agent-roundtable",
|
||||||
{
|
label: "多智能体会商",
|
||||||
id: "multi-agent-roundtable",
|
icon: Users,
|
||||||
label: "多智能体会商",
|
path: "/page/strategy/qa/multi-agent-roundtable",
|
||||||
icon: Users,
|
},
|
||||||
path: "/page/strategy/qa/multi-agent-roundtable",
|
// { id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
|
||||||
},
|
{
|
||||||
{
|
id: "qa-zzjc",
|
||||||
id: "dashboard-agent",
|
label: "JC支持",
|
||||||
label: "大屏绘制",
|
icon: Bot,
|
||||||
icon: Gauge,
|
path: "/page/strategy/qa/zzjc",
|
||||||
path: "/page/strategy/dashboard-agent",
|
},
|
||||||
},
|
{ id: "qa-zzxd", label: "XD应用", icon: Layout, path: "/page/strategy/qa/zzxd" },
|
||||||
// { id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
|
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
|
||||||
{
|
],
|
||||||
id: "qa-zzjc",
|
},
|
||||||
label: "JC支持",
|
{
|
||||||
icon: Bot,
|
id: "task-management",
|
||||||
path: "/page/strategy/qa/zzjc",
|
label: "任务管理",
|
||||||
},
|
icon: Target,
|
||||||
{ id: "qa-zzxd", label: "XD应用", icon: Layout, path: "/page/strategy/qa/zzxd" },
|
children: [
|
||||||
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
|
{
|
||||||
],
|
id: "xk-center-task",
|
||||||
},
|
label: "XK中任务",
|
||||||
{
|
icon: ClipboardList,
|
||||||
id: "task-management",
|
children: [
|
||||||
label: "任务管理",
|
// {
|
||||||
icon: Target,
|
// id: "xk-task-jc",
|
||||||
children: [
|
// label: "任务JC",
|
||||||
{
|
// icon: ListTodo,
|
||||||
id: "xk-center-task",
|
// path: "/page/strategy/task-management/xk-task-jc",
|
||||||
label: "XK中任务",
|
// },
|
||||||
icon: ClipboardList,
|
// {
|
||||||
children: [
|
// id: "xk-task-dispatch",
|
||||||
// {
|
// label: "任务调度",
|
||||||
// id: "xk-task-jc",
|
// icon: ListTodo,
|
||||||
// label: "任务JC",
|
// path: "/page/strategy/task-management/xk-task-dispatch",
|
||||||
// icon: ListTodo,
|
// },
|
||||||
// path: "/page/strategy/task-management/xk-task-jc",
|
],
|
||||||
// },
|
},
|
||||||
// {
|
{
|
||||||
// id: "xk-task-dispatch",
|
id: "coh-center-task",
|
||||||
// label: "任务调度",
|
label: "COH中任务",
|
||||||
// icon: ListTodo,
|
icon: Activity,
|
||||||
// path: "/page/strategy/task-management/xk-task-dispatch",
|
children: [
|
||||||
// },
|
// {
|
||||||
],
|
// id: "coh-task-3qfx",
|
||||||
},
|
// label: "3QFX",
|
||||||
{
|
// icon: ListTodo,
|
||||||
id: "coh-center-task",
|
// path: "/page/strategy/task-management/plan-task-sentiment",
|
||||||
label: "COH中任务",
|
// },
|
||||||
icon: Activity,
|
// {
|
||||||
children: [
|
// id: "coh-task-fx",
|
||||||
// {
|
// label: "任务FX",
|
||||||
// id: "coh-task-3qfx",
|
// icon: ListTodo,
|
||||||
// label: "3QFX",
|
// path: "/page/strategy/task-management/plan-task/plan-task-fx",
|
||||||
// icon: ListTodo,
|
// },
|
||||||
// path: "/page/strategy/task-management/plan-task-sentiment",
|
// {
|
||||||
// },
|
// id: "coh-task-xdfx",
|
||||||
// {
|
// label: "XDFX",
|
||||||
// id: "coh-task-fx",
|
// icon: ListTodo,
|
||||||
// label: "任务FX",
|
// path: "/page/strategy/task-management/plan-task/plan-task-action",
|
||||||
// icon: ListTodo,
|
// },
|
||||||
// path: "/page/strategy/task-management/plan-task/plan-task-fx",
|
],
|
||||||
// },
|
},
|
||||||
// {
|
{
|
||||||
// id: "coh-task-xdfx",
|
id: "pg-center-task",
|
||||||
// label: "XDFX",
|
label: "PG中任务",
|
||||||
// icon: ListTodo,
|
icon: Gauge,
|
||||||
// path: "/page/strategy/task-management/plan-task/plan-task-action",
|
children: [
|
||||||
// },
|
// {
|
||||||
],
|
// id: "pg-task-pg",
|
||||||
},
|
// label: "任务PG",
|
||||||
{
|
// icon: ListTodo,
|
||||||
id: "pg-center-task",
|
// path: "/page/strategy/task-management/effect-task-pg",
|
||||||
label: "PG中任务",
|
// },
|
||||||
icon: Gauge,
|
// {
|
||||||
children: [
|
// id: "pg-task-xdpg",
|
||||||
// {
|
// label: "XDPG",
|
||||||
// id: "pg-task-pg",
|
// icon: ListTodo,
|
||||||
// label: "任务PG",
|
// path: "/page/strategy/task-management/effect-action-pg",
|
||||||
// icon: ListTodo,
|
// },
|
||||||
// path: "/page/strategy/task-management/effect-task-pg",
|
// {
|
||||||
// },
|
// id: "pg-task-info-pg",
|
||||||
// {
|
// label: "信息PG",
|
||||||
// id: "pg-task-xdpg",
|
// icon: ListTodo,
|
||||||
// label: "XDPG",
|
// path: "/page/strategy/task-management/effect-info-pg",
|
||||||
// icon: ListTodo,
|
// },
|
||||||
// path: "/page/strategy/task-management/effect-action-pg",
|
],
|
||||||
// },
|
},
|
||||||
// {
|
{
|
||||||
// id: "pg-task-info-pg",
|
id: "ty-center-task",
|
||||||
// label: "信息PG",
|
label: "TY中任务",
|
||||||
// icon: ListTodo,
|
icon: Radar,
|
||||||
// path: "/page/strategy/task-management/effect-info-pg",
|
children: [
|
||||||
// },
|
// {
|
||||||
],
|
// id: "ty-task-xdty",
|
||||||
},
|
// label: "XDTY任务",
|
||||||
{
|
// icon: ListTodo,
|
||||||
id: "ty-center-task",
|
// path: "/page/strategy/task-management/mnty-task-mechanism",
|
||||||
label: "TY中任务",
|
// },
|
||||||
icon: Radar,
|
// {
|
||||||
children: [
|
// id: "ty-task-plan",
|
||||||
// {
|
// label: "方案TY任务",
|
||||||
// id: "ty-task-xdty",
|
// icon: ListTodo,
|
||||||
// label: "XDTY任务",
|
// path: "/page/strategy/task-management/mnty-task-plan",
|
||||||
// icon: ListTodo,
|
// },
|
||||||
// path: "/page/strategy/task-management/mnty-task-mechanism",
|
// {
|
||||||
// },
|
// id: "ty-task-xxty",
|
||||||
// {
|
// label: "XXTY任务",
|
||||||
// id: "ty-task-plan",
|
// icon: ListTodo,
|
||||||
// label: "方案TY任务",
|
// path: "/page/strategy/task-management/mnty-task-zsty",
|
||||||
// icon: ListTodo,
|
// },
|
||||||
// path: "/page/strategy/task-management/mnty-task-plan",
|
],
|
||||||
// },
|
},
|
||||||
// {
|
],
|
||||||
// id: "ty-task-xxty",
|
},
|
||||||
// label: "XXTY任务",
|
{
|
||||||
// icon: ListTodo,
|
id: "light-app-center",
|
||||||
// path: "/page/strategy/task-management/mnty-task-zsty",
|
label: "应用中心",
|
||||||
// },
|
icon: Grid3X3,
|
||||||
],
|
children: [
|
||||||
},
|
{
|
||||||
],
|
id: "light-app-management",
|
||||||
},
|
label: "应用管理",
|
||||||
{
|
icon: Layout,
|
||||||
id: "light-app-center",
|
path: "/page/strategy/light-app/management",
|
||||||
label: "应用中心",
|
adminOnly: true,
|
||||||
icon: Grid3X3,
|
},
|
||||||
children: [
|
{
|
||||||
{
|
id: "light-app-apps",
|
||||||
id: "light-app-management",
|
label: "应用列表",
|
||||||
label: "应用管理",
|
icon: List,
|
||||||
icon: Layout,
|
path: "/page/strategy/light-app/apps",
|
||||||
path: "/page/strategy/light-app/management",
|
},
|
||||||
adminOnly: true,
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "light-app-apps",
|
id: "comprehensive-management",
|
||||||
label: "应用列表",
|
label: "综合管理",
|
||||||
icon: List,
|
icon: Settings,
|
||||||
path: "/page/strategy/light-app/apps",
|
children: [
|
||||||
},
|
{
|
||||||
],
|
id: "mgmt-user-leaderboard",
|
||||||
},
|
label: "用户排行榜",
|
||||||
{
|
icon: Trophy,
|
||||||
id: "comprehensive-management",
|
path: "/page/strategy/admin/user-leaderboard",
|
||||||
label: "综合管理",
|
userPath: "/page/strategy/user-leaderboard",
|
||||||
icon: Settings,
|
},
|
||||||
children: [
|
{ id: "mgmt-agents", label: "智能体管理", icon: Bot, path: "/page/strategy/agents" },
|
||||||
{
|
{
|
||||||
id: "mgmt-user-leaderboard",
|
id: "mgmt-business-chain-mapping",
|
||||||
label: "用户排行榜",
|
label: "配置管理",
|
||||||
icon: Trophy,
|
icon: Network,
|
||||||
path: "/page/strategy/admin/user-leaderboard",
|
path: "/page/strategy/business-chain-mapping",
|
||||||
userPath: "/page/strategy/user-leaderboard",
|
},
|
||||||
},
|
{
|
||||||
{ id: "mgmt-agents", label: "智能体管理", icon: Bot, path: "/page/strategy/agents" },
|
id: "mgmt-business-chains",
|
||||||
// {
|
label: "业务链条配置",
|
||||||
// id: "mgmt-business-chain-mapping",
|
icon: Layers,
|
||||||
// label: "配置管理",
|
path: "/page/strategy/business-chains",
|
||||||
// icon: Network,
|
},
|
||||||
// path: "/page/strategy/business-chain-mapping",
|
{ id: "mgmt-skills", label: "技能管理", icon: Sparkles, path: "/page/strategy/skills" },
|
||||||
// },
|
{ id: "mgmt-memory", label: "记忆管理", icon: Brain, path: "/page/strategy/memory" },
|
||||||
{
|
{
|
||||||
id: "mgmt-business-chains",
|
id: "mgmt-tasks",
|
||||||
label: "业务链条配置",
|
label: "定时任务",
|
||||||
icon: Layers,
|
icon: ListChecks,
|
||||||
path: "/page/strategy/business-chains",
|
path: "/page/strategy/scheduled/tasks",
|
||||||
aliasPaths: ["/page/strategy/business-chain-mapping"],
|
},
|
||||||
},
|
{
|
||||||
{ id: "mgmt-skills", label: "技能管理", icon: Sparkles, path: "/page/strategy/skills" },
|
id: "mgmt-llm-metrics",
|
||||||
{ id: "mgmt-memory", label: "记忆管理", icon: Brain, path: "/page/strategy/memory" },
|
label: "大模型调用统计",
|
||||||
{
|
icon: Gauge,
|
||||||
id: "mgmt-tasks",
|
path: "/page/strategy/settings/llm-metrics",
|
||||||
label: "定时任务",
|
adminOnly: true,
|
||||||
icon: ListChecks,
|
},
|
||||||
path: "/page/strategy/scheduled/tasks",
|
{
|
||||||
},
|
id: "mgmt-users",
|
||||||
{
|
label: "用户管理",
|
||||||
id: "mgmt-llm-metrics",
|
icon: Users,
|
||||||
label: "大模型调用统计",
|
path: "/page/strategy/admin/users",
|
||||||
icon: Gauge,
|
adminOnly: true,
|
||||||
path: "/page/strategy/settings/llm-metrics",
|
},
|
||||||
adminOnly: true,
|
{
|
||||||
},
|
id: "mgmt-positions",
|
||||||
{
|
label: "岗位管理",
|
||||||
id: "mgmt-users",
|
icon: Briefcase,
|
||||||
label: "用户管理",
|
path: "/page/strategy/admin/positions",
|
||||||
icon: Users,
|
adminOnly: true,
|
||||||
path: "/page/strategy/admin/users",
|
},
|
||||||
adminOnly: true,
|
{
|
||||||
},
|
id: "mgmt-admin-scheduled-tasks",
|
||||||
{
|
label: "定时任务管理",
|
||||||
id: "mgmt-positions",
|
icon: CalendarClock,
|
||||||
label: "岗位管理",
|
path: "/page/strategy/admin/scheduled-tasks",
|
||||||
icon: Briefcase,
|
adminOnly: true,
|
||||||
path: "/page/strategy/admin/positions",
|
},
|
||||||
adminOnly: true,
|
{
|
||||||
},
|
id: "mgmt-user-activity",
|
||||||
{
|
label: "用户活动审计",
|
||||||
id: "mgmt-admin-scheduled-tasks",
|
icon: History,
|
||||||
label: "定时任务管理",
|
path: "/page/strategy/admin/user-activity",
|
||||||
icon: CalendarClock,
|
adminOnly: true,
|
||||||
path: "/page/strategy/admin/scheduled-tasks",
|
},
|
||||||
adminOnly: true,
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "mgmt-user-activity",
|
id: "resource-management",
|
||||||
label: "用户活动审计",
|
label: "资源管理",
|
||||||
icon: History,
|
icon: Database,
|
||||||
path: "/page/strategy/admin/user-activity",
|
children: [
|
||||||
adminOnly: true,
|
// {
|
||||||
},
|
// id: "resource-network-xwt",
|
||||||
],
|
// label: "网络xwt资源管理",
|
||||||
},
|
// icon: Network,
|
||||||
{
|
// path: "/page/strategy/resource-management/resource-network-actor",
|
||||||
id: "resource-management",
|
// },
|
||||||
label: "资源管理",
|
{
|
||||||
icon: Database,
|
id: "resource-knowledge-native",
|
||||||
children: [
|
label: "问答梳理",
|
||||||
// {
|
icon: BookOpen,
|
||||||
// id: "resource-network-xwt",
|
path: "/page/workspace/knowledge",
|
||||||
// label: "网络xwt资源管理",
|
},
|
||||||
// icon: Network,
|
{
|
||||||
// path: "/page/strategy/resource-management/resource-network-actor",
|
id: "resource-knowledge-base",
|
||||||
// },
|
label: "知识库资源管理",
|
||||||
{
|
icon: Library,
|
||||||
id: "resource-knowledge-native",
|
path: "/page/strategy/resource-management/resource-knowledge-base",
|
||||||
label: "问答梳理",
|
},
|
||||||
icon: BookOpen,
|
// {
|
||||||
path: "/page/workspace/knowledge",
|
// id: "resource-evaluation-index",
|
||||||
},
|
// label: "作战资源管理",
|
||||||
{
|
// icon: FileBox,
|
||||||
id: "resource-knowledge-base",
|
// path: "/page/strategy/resource-management/resource-evaluation-index",
|
||||||
label: "知识库资源管理",
|
// },
|
||||||
icon: Library,
|
],
|
||||||
path: "/page/strategy/resource-management/resource-knowledge-base",
|
},
|
||||||
},
|
];
|
||||||
// {
|
|
||||||
// id: "resource-evaluation-index",
|
/** 默认展开的菜单 id 集合(浅色版可折叠交互的初始状态) */
|
||||||
// label: "作战资源管理",
|
export const defaultExpandedIds: ReadonlySet<string> = new Set([
|
||||||
// icon: FileBox,
|
"qa-center",
|
||||||
// path: "/page/strategy/resource-management/resource-evaluation-index",
|
"light-app-center",
|
||||||
// },
|
"light-app-note-management",
|
||||||
],
|
"task-management",
|
||||||
},
|
"xk-center-task",
|
||||||
];
|
"comprehensive-management",
|
||||||
|
]);
|
||||||
/** 默认展开的菜单 id 集合(浅色版可折叠交互的初始状态) */
|
|
||||||
export const defaultExpandedIds: ReadonlySet<string> = new Set([
|
/** 该菜单项自身或任意后代的 path 是否匹配当前路由(支持子路径,如 /knowledge/:id) */
|
||||||
"qa-center",
|
export function menuItemContainsPath(item: MenuItem, pathname: string): boolean {
|
||||||
"light-app-center",
|
if (item.path && (pathname === item.path || pathname.startsWith(item.path + "/"))) {
|
||||||
"light-app-note-management",
|
return true;
|
||||||
"task-management",
|
}
|
||||||
"xk-center-task",
|
return item.children?.some((child) => menuItemContainsPath(child, pathname)) ?? false;
|
||||||
"comprehensive-management",
|
}
|
||||||
]);
|
|
||||||
|
/**
|
||||||
/** 单条路由是否与 pathname 精确匹配或为其子路径。 */
|
* 在「一级 → 二级 → 三级」菜单中,取当前路由所在的「激活二级项」的三级子项。
|
||||||
function routeMatchesPathname(pathname: string, route?: string): boolean {
|
* 浅色侧边栏据此在二级右侧展开三级列;深色顶栏据此渲染三级横条。
|
||||||
if (!route) return false;
|
* 全量模式:三级仅一项时不返回(无选择必要,侧边栏保持窄栏 / 不渲染横条)。
|
||||||
return pathname === route || pathname.startsWith(route + "/");
|
*/
|
||||||
}
|
export function getActiveThirdLevelItems(
|
||||||
|
items: MenuItem[],
|
||||||
/** 菜单项自身 path / aliasPaths 是否匹配当前路由。 */
|
pathname: string,
|
||||||
export function menuItemMatchesPath(item: MenuItem, pathname: string): boolean {
|
): MenuItem[] {
|
||||||
if (routeMatchesPathname(pathname, item.path)) return true;
|
const activeTop =
|
||||||
return item.aliasPaths?.some((p) => routeMatchesPathname(pathname, p)) ?? false;
|
items.find((item) => menuItemContainsPath(item, pathname)) ?? items[0];
|
||||||
}
|
const secondary = activeTop?.children ?? [];
|
||||||
|
const activeSecond = secondary.find(
|
||||||
/** 该菜单项自身或任意后代的 path 是否匹配当前路由(支持子路径,如 /knowledge/:id) */
|
(item) => (item.children?.length ?? 0) > 0 && menuItemContainsPath(item, pathname),
|
||||||
export function menuItemContainsPath(item: MenuItem, pathname: string): boolean {
|
);
|
||||||
if (menuItemMatchesPath(item, pathname)) return true;
|
const third = activeSecond?.children ?? [];
|
||||||
return item.children?.some((child) => menuItemContainsPath(child, pathname)) ?? false;
|
return third.length <= 1 ? [] : third;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** 按 admin 角色过滤菜单:非 admin 不展示 ``adminOnly: true`` 的项;``userPath`` 替换 ``path``。 */
|
||||||
* 在「一级 → 二级 → 三级」菜单中,取当前路由所在的「激活二级项」的三级子项。
|
export function filterMenuItemsByRole(items: MenuItem[], isAdmin: boolean): MenuItem[] {
|
||||||
* 浅色侧边栏据此在二级右侧展开三级列;深色顶栏据此渲染三级横条。
|
return items
|
||||||
* 全量模式:三级仅一项时不返回(无选择必要,侧边栏保持窄栏 / 不渲染横条)。
|
.filter((item) => !item.adminOnly || isAdmin)
|
||||||
*/
|
.map((item) => {
|
||||||
export function getActiveThirdLevelItems(
|
const children = item.children
|
||||||
items: MenuItem[],
|
? filterMenuItemsByRole(item.children, isAdmin)
|
||||||
pathname: string,
|
: undefined;
|
||||||
): MenuItem[] {
|
const base = children ? { ...item, children } : item;
|
||||||
const activeTop =
|
if (!isAdmin && base.userPath) {
|
||||||
items.find((item) => menuItemContainsPath(item, pathname)) ?? items[0];
|
const { userPath: _userPath, ...rest } = base;
|
||||||
const secondary = activeTop?.children ?? [];
|
return { ...rest, path: base.userPath };
|
||||||
const activeSecond = secondary.find(
|
}
|
||||||
(item) => (item.children?.length ?? 0) > 0 && menuItemContainsPath(item, pathname),
|
return base;
|
||||||
);
|
});
|
||||||
const third = activeSecond?.children ?? [];
|
}
|
||||||
return third.length <= 1 ? [] : third;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 按 admin 角色过滤菜单:非 admin 不展示 ``adminOnly: true`` 的项;``userPath`` 替换 ``path``。 */
|
|
||||||
export function filterMenuItemsByRole(items: MenuItem[], isAdmin: boolean): MenuItem[] {
|
|
||||||
return items
|
|
||||||
.filter((item) => !item.adminOnly || isAdmin)
|
|
||||||
.map((item) => {
|
|
||||||
const children = item.children
|
|
||||||
? filterMenuItemsByRole(item.children, isAdmin)
|
|
||||||
: undefined;
|
|
||||||
const base = children ? { ...item, children } : item;
|
|
||||||
if (!isAdmin && base.userPath) {
|
|
||||||
const { userPath: _userPath, ...rest } = base;
|
|
||||||
return { ...rest, path: base.userPath };
|
|
||||||
}
|
|
||||||
return base;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -12,12 +12,8 @@ import { useLocation } from "react-router-dom";
|
|||||||
import { Layout } from "lucide-react";
|
import { Layout } from "lucide-react";
|
||||||
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { desensitize, makeDesensitizer } from "@/lib/desensitize";
|
|
||||||
import { useLightApps, type LightApp } from "@/strategy-components/api/light-apps";
|
import { useLightApps, type LightApp } from "@/strategy-components/api/light-apps";
|
||||||
import { useMenuOverrides } from "@/strategy-components/api/menu-overrides";
|
|
||||||
import { useSensitiveWords, wordsToMap } from "@/strategy-components/api/sensitive-words";
|
|
||||||
|
|
||||||
import { applyMenuOverrides } from "./menu-overrides";
|
|
||||||
import {
|
import {
|
||||||
filterMenuItemsByRole,
|
filterMenuItemsByRole,
|
||||||
getActiveThirdLevelItems,
|
getActiveThirdLevelItems,
|
||||||
@@ -35,7 +31,7 @@ function lightAppLeaf(app: LightApp): MenuItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 在菜单树(不可变克隆)中,把 iframe 应用按 mountLocation 注入对应父节点末尾。 */
|
/** 在菜单树(不可变克隆)中,把 iframe 应用按 mountLocation 注入对应父节点末尾。 */
|
||||||
export function injectLightApps(items: MenuItem[], apps: LightApp[]): MenuItem[] {
|
function injectLightApps(items: MenuItem[], apps: LightApp[]): MenuItem[] {
|
||||||
if (apps.length === 0) return items;
|
if (apps.length === 0) return items;
|
||||||
|
|
||||||
const byMount = new Map<string, LightApp[]>();
|
const byMount = new Map<string, LightApp[]>();
|
||||||
@@ -60,43 +56,12 @@ export function injectLightApps(items: MenuItem[], apps: LightApp[]): MenuItem[]
|
|||||||
return walk(items);
|
return walk(items);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 递归对菜单标签做脱敏(仅改 `label`,path/id/icon 不动,保证高亮与路由不受影响)。 */
|
/** 返回合并了 iframe 轻应用、并按 admin 角色过滤后的菜单。 */
|
||||||
function desensitizeLabels(items: MenuItem[], fn: (text: string) => string): MenuItem[] {
|
|
||||||
return items.map((node) => ({
|
|
||||||
...node,
|
|
||||||
label: fn(node.label),
|
|
||||||
children: node.children ? desensitizeLabels(node.children, fn) : node.children,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 返回合并了 iframe 轻应用、套用了后端「菜单覆盖层」(改名/停用/排序/层级)、
|
|
||||||
* 按 admin 角色过滤、并对标签做**展示层脱敏**后的菜单。
|
|
||||||
*
|
|
||||||
* 管线顺序:静态菜单 → 注入 iframe 轻应用 → 套覆盖层(停用项被剔除)→ 角色过滤 → 标签脱敏。
|
|
||||||
* 覆盖层作用在合并后的整棵树上,所以 iframe 轻应用节点同样可被改名/停用/移层级。
|
|
||||||
*
|
|
||||||
* 脱敏直接用 `/api/sensitive-words` 查询结果构造(后台非空时用其映射,否则回退到内置种子的
|
|
||||||
* 全局 {@link desensitize}),避免依赖 {@link replaceDesensitizeMap} 的 effect 回灌时序。
|
|
||||||
*/
|
|
||||||
export function useSidebarMenuItems(isAdmin: boolean): MenuItem[] {
|
export function useSidebarMenuItems(isAdmin: boolean): MenuItem[] {
|
||||||
const { data: iframeApps = [] } = useLightApps({ appType: "iframe", enabledOnly: true });
|
const { data: iframeApps = [] } = useLightApps({ appType: "iframe", enabledOnly: true });
|
||||||
const { data: overrides = [] } = useMenuOverrides();
|
|
||||||
const { data: words = [] } = useSensitiveWords();
|
|
||||||
const desensitizeLabel = useMemo(
|
|
||||||
() => (words.length > 0 ? makeDesensitizer(wordsToMap(words)) : desensitize),
|
|
||||||
[words],
|
|
||||||
);
|
|
||||||
return useMemo(
|
return useMemo(
|
||||||
() =>
|
() => filterMenuItemsByRole(injectLightApps(sidebarMenuItems, iframeApps), isAdmin),
|
||||||
desensitizeLabels(
|
[iframeApps, isAdmin],
|
||||||
filterMenuItemsByRole(
|
|
||||||
applyMenuOverrides(injectLightApps(sidebarMenuItems, iframeApps), overrides),
|
|
||||||
isAdmin,
|
|
||||||
),
|
|
||||||
desensitizeLabel,
|
|
||||||
),
|
|
||||||
[iframeApps, overrides, isAdmin, desensitizeLabel],
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
/** Strategy 模块外部 iframe / 嵌入页链接(来自 Vite 环境变量) */
|
/** Strategy 模块外部 iframe / 嵌入页链接(来自 Vite 环境变量) */
|
||||||
|
|
||||||
import { authStorageGet } from "@/core/auth/scoped-storage";
|
|
||||||
|
|
||||||
function trimTrailingSlash(url: string): string {
|
function trimTrailingSlash(url: string): string {
|
||||||
return url.replace(/\/+$/, "");
|
return url.replace(/\/+$/, "");
|
||||||
}
|
}
|
||||||
@@ -32,7 +30,7 @@ export function getNetworkActorIframeUrl(): string {
|
|||||||
/** 读取并解析 localStorage 中的 userInfo(登录信息)。 */
|
/** 读取并解析 localStorage 中的 userInfo(登录信息)。 */
|
||||||
function readUserInfo(): Record<string, unknown> {
|
function readUserInfo(): Record<string, unknown> {
|
||||||
try {
|
try {
|
||||||
const raw = authStorageGet("userInfo");
|
const raw = localStorage.getItem("userInfo");
|
||||||
if (!raw) return {};
|
if (!raw) return {};
|
||||||
const parsed = JSON.parse(raw);
|
const parsed = JSON.parse(raw);
|
||||||
return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
|
return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
|
||||||
|
|||||||
@@ -34,9 +34,6 @@ export type ThreadStreamOptions = {
|
|||||||
context: LocalSettings["context"];
|
context: LocalSettings["context"];
|
||||||
isMock?: boolean;
|
isMock?: boolean;
|
||||||
assistantId?: string;
|
assistantId?: string;
|
||||||
/** 额外写到新建 thread 的 metadata(与 agent_id 合并)。
|
|
||||||
* 任务深链用 `{ taskId }` 把对话挂到任务下(1:N),列表按 metadata.taskId 过滤。 */
|
|
||||||
threadMetadata?: Record<string, unknown>;
|
|
||||||
onStart?: (threadId: string) => void;
|
onStart?: (threadId: string) => void;
|
||||||
onFinish?: (state: AgentThreadState) => void;
|
onFinish?: (state: AgentThreadState) => void;
|
||||||
onToolEnd?: (event: ToolEndEvent) => void;
|
onToolEnd?: (event: ToolEndEvent) => void;
|
||||||
@@ -121,39 +118,6 @@ function getRunMetadataStorage(): {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 显式停止某会话「服务端正在跑」的 run。
|
|
||||||
*
|
|
||||||
* 注意:useStream / `thread.stop()` 只中断本地 SSE 监听,服务端 run 仍会继续跑。
|
|
||||||
* 任务流程要求「开启新对话时老对话要停止」,所以这里读出 SDK 存在 sessionStorage
|
|
||||||
* (``lg:stream:{threadId}``)里的 run id,调用 ``runs.cancel`` 真正取消后端 run,
|
|
||||||
* 再清掉本地 reconnect 记录。已结束 / 不存在的 run 取消失败时静默忽略。
|
|
||||||
*/
|
|
||||||
export async function stopThreadRun(
|
|
||||||
threadId: string | null | undefined,
|
|
||||||
): Promise<void> {
|
|
||||||
if (!threadId || typeof window === "undefined") return;
|
|
||||||
let runId: string | null = null;
|
|
||||||
try {
|
|
||||||
runId = normalizeStoredRunId(
|
|
||||||
window.sessionStorage.getItem(`lg:stream:${threadId}`),
|
|
||||||
);
|
|
||||||
} catch {
|
|
||||||
runId = null;
|
|
||||||
}
|
|
||||||
if (!runId) return;
|
|
||||||
try {
|
|
||||||
await getAPIClient().runs.cancel(threadId, runId);
|
|
||||||
} catch {
|
|
||||||
/* 已结束 / 不存在 / 网络错误等忽略 */
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
window.sessionStorage.removeItem(`lg:stream:${threadId}`);
|
|
||||||
} catch {
|
|
||||||
/* noop */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getStreamErrorMessage(error: unknown): string {
|
function getStreamErrorMessage(error: unknown): string {
|
||||||
if (typeof error === "string" && error.trim()) {
|
if (typeof error === "string" && error.trim()) {
|
||||||
return error;
|
return error;
|
||||||
@@ -236,7 +200,6 @@ export function useThreadStream({
|
|||||||
context,
|
context,
|
||||||
isMock,
|
isMock,
|
||||||
assistantId,
|
assistantId,
|
||||||
threadMetadata,
|
|
||||||
onStart,
|
onStart,
|
||||||
onFinish,
|
onFinish,
|
||||||
onToolEnd,
|
onToolEnd,
|
||||||
@@ -314,15 +277,11 @@ export function useThreadStream({
|
|||||||
handleStreamStart(meta.thread_id);
|
handleStreamStart(meta.thread_id);
|
||||||
setOnStreamThreadId(meta.thread_id);
|
setOnStreamThreadId(meta.thread_id);
|
||||||
const metadataAgentId = context.agent_id ?? context.agent_name;
|
const metadataAgentId = context.agent_id ?? context.agent_name;
|
||||||
const extraMetadata =
|
if (metadataAgentId && !isMock) {
|
||||||
threadMetadata && typeof threadMetadata === "object" ? threadMetadata : {};
|
|
||||||
const metadata: Record<string, unknown> = {
|
|
||||||
...(metadataAgentId ? { agent_id: metadataAgentId } : {}),
|
|
||||||
...extraMetadata,
|
|
||||||
};
|
|
||||||
if (Object.keys(metadata).length > 0 && !isMock) {
|
|
||||||
void getAPIClient()
|
void getAPIClient()
|
||||||
.threads.update(meta.thread_id, { metadata })
|
.threads.update(meta.thread_id, {
|
||||||
|
metadata: { agent_id: metadataAgentId },
|
||||||
|
})
|
||||||
.catch(() => ({}));
|
.catch(() => ({}));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -785,10 +744,7 @@ export function useThreadStream({
|
|||||||
} as typeof thread)
|
} as typeof thread)
|
||||||
: thread;
|
: thread;
|
||||||
|
|
||||||
// 第 4 个返回值 `onStreamThreadId` = 底层 useStream 当前实际绑定的线程 id(新建/未保存时为 null)。
|
return [mergedThread, sendMessage, isUploading] as const;
|
||||||
// 调用方据此判断「流是否已切到全新线程」,避免在切换会话的那一帧把消息发进上一个会话
|
|
||||||
// (submit 的 threadId 选项仅在 hook 线程为 null/undefined 时才生效)。
|
|
||||||
return [mergedThread, sendMessage, isUploading, onStreamThreadId] as const;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useThreads(
|
export function useThreads(
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
import { toast } from "sonner";
|
|
||||||
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shared helpers for re-framing LangGraph "thread not accessible" 404s around
|
|
||||||
* the current login identity.
|
|
||||||
*
|
|
||||||
* The most common cause in practice is a login session change: a thread is
|
|
||||||
* owned by the previously logged-in account, so after switching accounts the
|
|
||||||
* backend (``app/gateway/authz.py``) correctly returns
|
|
||||||
* ``HTTP 404: {"detail":"Thread <uuid> not accessible"}``. Raw-toasting that
|
|
||||||
* 404 just leaves the user staring at a scary error. Both the chat stream
|
|
||||||
* (``core/threads/hooks.ts``) and the AI-writing stream
|
|
||||||
* (``open-canvas/contexts/AIWritingContext.tsx``) funnel their stream errors
|
|
||||||
* through here so the UX is identical: detect the login-change 404 and prompt
|
|
||||||
* the user to refresh against the current identity instead of erroring out.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/** Normalize an unknown stream error into a human-readable message string. */
|
|
||||||
export function getStreamErrorMessage(error: unknown): string {
|
|
||||||
if (typeof error === "string" && error.trim()) {
|
|
||||||
return error;
|
|
||||||
}
|
|
||||||
if (error instanceof Error && error.message.trim()) {
|
|
||||||
return error.message;
|
|
||||||
}
|
|
||||||
if (typeof error === "object" && error !== null) {
|
|
||||||
const message = Reflect.get(error, "message");
|
|
||||||
if (typeof message === "string" && message.trim()) {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
const nestedError = Reflect.get(error, "error");
|
|
||||||
if (nestedError instanceof Error && nestedError.message.trim()) {
|
|
||||||
return nestedError.message;
|
|
||||||
}
|
|
||||||
if (typeof nestedError === "string" && nestedError.trim()) {
|
|
||||||
return nestedError;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "Request failed.";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Detect "thread not found" / forbidden errors from the LangGraph SDK.
|
|
||||||
*
|
|
||||||
* Backend returns 404 both when a thread truly doesn't exist and when the
|
|
||||||
* currently authenticated user doesn't own it ("not found" = no row + no
|
|
||||||
* checkpoint, "not accessible" = row owned by another user / stale login
|
|
||||||
* session). Both mean the current user can't use this thread.
|
|
||||||
*/
|
|
||||||
export function isThreadNotAccessibleError(message: string): boolean {
|
|
||||||
const lowered = message.toLowerCase();
|
|
||||||
if (/thread\s+[\w-]{8,}\s+not\s+(found|accessible)/i.test(message)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
// Fallback: a bare 404/403 from the threads endpoint when the SDK has
|
|
||||||
// wrapped the detail differently.
|
|
||||||
return (
|
|
||||||
(lowered.includes("http 404") || lowered.includes("http 403")) &&
|
|
||||||
lowered.includes("thread")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build a label for the *current* logged-in identity (email → user_id → 未知). */
|
|
||||||
export function buildCurrentUserLabel(): string {
|
|
||||||
const auth = getStoredAuth();
|
|
||||||
if (!auth) {
|
|
||||||
return "未登录";
|
|
||||||
}
|
|
||||||
const email = auth.email?.trim();
|
|
||||||
if (email) {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
const userId = auth.user_id?.trim();
|
|
||||||
return userId ? userId : "未知用户";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Re-frame a login-change 404 around the current identity and reload the page.
|
|
||||||
*
|
|
||||||
* Shows a friendly toast naming the current login, then full-reloads after a
|
|
||||||
* short delay so the toast is visible and so TanStack Query cache / context
|
|
||||||
* providers / any state captured under the previous user get rebuilt against
|
|
||||||
* the current login. Used by streams whose session id lives in component state
|
|
||||||
* (not the URL) — a plain reload lands them back on a fresh, valid page.
|
|
||||||
*/
|
|
||||||
export function notifyThreadAccessChangedAndReload(): void {
|
|
||||||
const userLabel = buildCurrentUserLabel();
|
|
||||||
toast.info(
|
|
||||||
`当前登录用户为 ${userLabel},原会话不存在或无权访问,正在为你刷新页面…`,
|
|
||||||
);
|
|
||||||
if (typeof window !== "undefined") {
|
|
||||||
window.setTimeout(() => {
|
|
||||||
window.location.reload();
|
|
||||||
}, 900);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
/**
|
|
||||||
* 「一个任务挂多个对话」(1:N):按 thread 的 ``metadata.taskId`` 过滤出某任务下的对话列表。
|
|
||||||
*
|
|
||||||
* 新建对话时由 [[task-purpose]] 流程给 thread 打 ``metadata.taskId`` 标签
|
|
||||||
* (见 useThreadStream 的 ``threadMetadata``);这里复用服务端分页搜索按该标签过滤,
|
|
||||||
* 后端默认按 ``updated_at desc`` 排序,所以 ``threads[0]`` 即最新一条。
|
|
||||||
*
|
|
||||||
* 同一个 taskId 可能挂在多条业务链上(rwfx / 3qfx / xdfx 共用任务 id),每条业务用各自的
|
|
||||||
* 智能体。传入 ``agentId`` 时额外按 ``metadata.agent_id`` 过滤(后端 metadata 过滤是 AND/子集
|
|
||||||
* 匹配),把不同业务的对话列表隔离开——否则三种业务的对话会混在一起。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { useThreadsPage } from "@/core/threads/hooks";
|
|
||||||
import type { AgentThread } from "@/core/threads/types";
|
|
||||||
|
|
||||||
export function useTaskThreads(
|
|
||||||
taskId: string | null | undefined,
|
|
||||||
agentId?: string | null | undefined,
|
|
||||||
) {
|
|
||||||
const enabled = !!taskId;
|
|
||||||
// 任务工作区只在有 taskId 时渲染;无 taskId 时传一个不可能命中的过滤,返回空列表。
|
|
||||||
const metadata = enabled
|
|
||||||
? agentId
|
|
||||||
? { taskId, agent_id: agentId }
|
|
||||||
: { taskId }
|
|
||||||
: { taskId: "__none__" };
|
|
||||||
const query = useThreadsPage({ page: 1, pageSize: 100, metadata });
|
|
||||||
const threads: AgentThread[] = enabled ? (query.data?.threads ?? []) : [];
|
|
||||||
return {
|
|
||||||
...query,
|
|
||||||
threads,
|
|
||||||
/** 最新对话(按 updated_at desc,列表第一条)。 */
|
|
||||||
latestThreadId: threads[0]?.thread_id ?? null,
|
|
||||||
/** 是否已有历史对话(决定深链进入后默认开最新还是走新建闸门)。 */
|
|
||||||
hasThreads: threads.length > 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* 脱敏词「种子」映射表(前端内置)。
|
* 脱敏词映射表
|
||||||
* key: 原始词(支持正则特殊字符,会被转义)
|
* key: 原始词(支持正则特殊字符,会被转义)
|
||||||
* value: 脱敏后替换词
|
* value: 脱敏后替换词
|
||||||
*
|
|
||||||
* 这份常量是**部署种子**:新机器首次启动、后台还没有任何敏感词时,运行时直接用它;
|
|
||||||
* 管理员也可在「敏感词管理」页一键「导入种子词」把它写入后台。线上以后台配置为准
|
|
||||||
* (见 {@link replaceDesensitizeMap}),后台为空时回退到这份种子。
|
|
||||||
*
|
|
||||||
* 注意:请勿在运行时修改本对象——它要保持与「出厂种子」一致。运行时可变映射见
|
|
||||||
* {@link DESENSITIZE_MAP}。
|
|
||||||
*/
|
*/
|
||||||
export const SEED_DESENSITIZE_MAP: Readonly<Record<string, string>> = Object.freeze({
|
export const DESENSITIZE_MAP: Record<string, string> = {
|
||||||
// 任务工作区业务名 → 业务码(脱敏展示)。整词在前,优先于下面更短的「任务」「行动」匹配。
|
|
||||||
任务分析: "rwfx",
|
|
||||||
三情分析: "3qfx",
|
|
||||||
行动分析: "xdfx",
|
|
||||||
方案: "FA",
|
方案: "FA",
|
||||||
设计: "SJ",
|
设计: "SJ",
|
||||||
任务: "RW",
|
任务: "RW",
|
||||||
@@ -55,15 +44,8 @@ export const SEED_DESENSITIZE_MAP: Readonly<Record<string, string>> = Object.fre
|
|||||||
军: "J",
|
军: "J",
|
||||||
美军: "MJ",
|
美军: "MJ",
|
||||||
台军: "TJ",
|
台军: "TJ",
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
};
|
||||||
* 运行时实际生效的脱敏词映射表(可变)。
|
|
||||||
*
|
|
||||||
* 初始为 {@link SEED_DESENSITIZE_MAP} 的浅拷贝(保证后台数据加载前 `desensitize`
|
|
||||||
* 立即可用);应用启动后由 {@link replaceDesensitizeMap} 用后台配置整体替换。
|
|
||||||
*/
|
|
||||||
export const DESENSITIZE_MAP: Record<string, string> = { ...SEED_DESENSITIZE_MAP };
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将 DESENSITIZE_MAP 编译为单个正则,避免多次遍历字符串。
|
* 将 DESENSITIZE_MAP 编译为单个正则,避免多次遍历字符串。
|
||||||
@@ -93,22 +75,6 @@ export function desensitize(text: string): string {
|
|||||||
return text.replace(_regex, (matched) => DESENSITIZE_MAP[matched] ?? matched);
|
return text.replace(_regex, (matched) => DESENSITIZE_MAP[matched] ?? matched);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 用**指定映射**(而非全局 {@link DESENSITIZE_MAP})构造一个脱敏函数。
|
|
||||||
*
|
|
||||||
* 适用于「数据加载完就要立即用其结果脱敏、不能依赖全局 map 的异步回灌时序」的场景
|
|
||||||
* (如侧边栏/导航栏菜单:直接用 `/api/sensitive-words` 查询结果计算标签,避免与
|
|
||||||
* {@link replaceDesensitizeMap} 的 effect 时序竞态)。正则在构造时编译一次,可缓存复用。
|
|
||||||
*
|
|
||||||
* @param map 原始词 → 替换词
|
|
||||||
* @returns `(text) => 脱敏后文本`;map 为空时返回恒等函数
|
|
||||||
*/
|
|
||||||
export function makeDesensitizer(map: Record<string, string>): (text: string) => string {
|
|
||||||
const regex = buildRegex(map);
|
|
||||||
if (!regex) return (text) => text;
|
|
||||||
return (text) => text.replace(regex, (matched) => map[matched] ?? matched);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 深度脱敏:递归遍历对象 / 数组,对其中所有字符串值做 {@link desensitize},
|
* 深度脱敏:递归遍历对象 / 数组,对其中所有字符串值做 {@link desensitize},
|
||||||
* 其余类型原样保留。返回**新值**(不修改入参),用于对结构化数据(如大屏 report-json
|
* 其余类型原样保留。返回**新值**(不修改入参),用于对结构化数据(如大屏 report-json
|
||||||
@@ -141,18 +107,3 @@ export function addDesensitizeEntries(entries: Record<string, string>): void {
|
|||||||
Object.assign(DESENSITIZE_MAP, entries);
|
Object.assign(DESENSITIZE_MAP, entries);
|
||||||
_regex = buildRegex(DESENSITIZE_MAP);
|
_regex = buildRegex(DESENSITIZE_MAP);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 用后台配置**整体替换**运行时脱敏词映射表,替换后自动重编译正则。
|
|
||||||
*
|
|
||||||
* 与 {@link addDesensitizeEntries} 不同,本函数会先清空现有词条,因此后台里被
|
|
||||||
* 删除的词不会因为还残留在种子里而继续生效。应用启动时拉取
|
|
||||||
* `/api/sensitive-words` 后调用;若后台为空则不调用,保持使用种子。
|
|
||||||
*
|
|
||||||
* @param entries 后台返回的「启用」词条,格式同 {@link DESENSITIZE_MAP}
|
|
||||||
*/
|
|
||||||
export function replaceDesensitizeMap(entries: Record<string, string>): void {
|
|
||||||
for (const key of Object.keys(DESENSITIZE_MAP)) delete DESENSITIZE_MAP[key];
|
|
||||||
Object.assign(DESENSITIZE_MAP, entries);
|
|
||||||
_regex = buildRegex(DESENSITIZE_MAP);
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,15 @@
|
|||||||
import "@fontsource/noto-sans-sc/chinese-simplified-400.css";
|
import "@fontsource/noto-sans-sc/chinese-simplified-400.css";
|
||||||
import "@fontsource/noto-sans-sc/chinese-simplified-500.css";
|
import "@fontsource/noto-sans-sc/chinese-simplified-500.css";
|
||||||
import "@fontsource/noto-sans-sc/chinese-simplified-600.css";
|
import "@fontsource/noto-sans-sc/chinese-simplified-600.css";
|
||||||
import "@fontsource/noto-sans-sc/chinese-simplified-700.css";
|
import "@fontsource/noto-sans-sc/chinese-simplified-700.css";
|
||||||
import "./styles/globals.css";
|
import "./styles/globals.css";
|
||||||
import "tdesign-react/es/style/index.css";
|
import "tdesign-react/es/style/index.css";
|
||||||
import "katex/dist/katex.min.css";
|
import "katex/dist/katex.min.css";
|
||||||
|
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import ReactDOM from "react-dom/client";
|
import ReactDOM from "react-dom/client";
|
||||||
|
|
||||||
import { App } from "./App";
|
import { App } from "./App";
|
||||||
import { syncEmbedSessionFromCurrentUrl } from "@/core/embed/embed-session";
|
|
||||||
|
|
||||||
// 渲染前同步启用「iframe 嵌入会话」(按标签页 sessionStorage):必须早于任何鉴权写入,
|
|
||||||
// 使 iframe 嵌入态的登录走 sessionStorage、与同浏览器正常登录(localStorage)完全隔离。
|
|
||||||
syncEmbedSessionFromCurrentUrl();
|
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById("root")!).render(
|
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
|
|||||||
@@ -87,50 +87,6 @@ export async function deleteAIWritingSession(id: string): Promise<void> {
|
|||||||
if (!resp.ok) throw new Error(`删除失败: ${resp.status}`);
|
if (!resp.ok) throw new Error(`删除失败: ${resp.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 把一篇写作转入「后台挂起」:后端自动驱动剩余流程到定稿(离页/刷新/切号不打断)。
|
|
||||||
*
|
|
||||||
* 幂等——同一会话已在后台跑则后端直接返回 ``started:false``。
|
|
||||||
*/
|
|
||||||
export async function suspendAIWritingToBackground(
|
|
||||||
id: string,
|
|
||||||
): Promise<{ started: boolean; status: string }> {
|
|
||||||
const resp = await apiFetch(`${BASE()}/${id}/background`, { method: 'POST' });
|
|
||||||
if (!resp.ok) throw new Error(`后台挂起失败: ${resp.status}`);
|
|
||||||
return resp.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 一篇写作的实际进度(供「查看进度」流程图弹窗轮询)。 */
|
|
||||||
export interface AIWritingProgress {
|
|
||||||
sessionStatus: string;
|
|
||||||
/** 规范化阶段 key(与流程图阶段一一对应);null = 还没建 checkpoint。 */
|
|
||||||
stage: string | null;
|
|
||||||
note: string | null;
|
|
||||||
revisionCount: number;
|
|
||||||
maxRevisions: number;
|
|
||||||
reviewVerdict: string | null;
|
|
||||||
isRunning: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAIWritingProgress(id: string): Promise<AIWritingProgress> {
|
|
||||||
const resp = await apiFetch(`${BASE()}/${id}/progress`);
|
|
||||||
if (!resp.ok) throw new Error(`获取进度失败: ${resp.status}`);
|
|
||||||
return resp.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* beforeunload 兜底:离开/刷新页面时用 keepalive 发起后台挂起,
|
|
||||||
* 保证浏览器卸载页面后请求仍能发完。fire-and-forget,不读响应;
|
|
||||||
* 重复触发由后端「同会话已在后台跑」幂等兜住。
|
|
||||||
*/
|
|
||||||
export function suspendAIWritingToBackgroundKeepalive(id: string): void {
|
|
||||||
try {
|
|
||||||
void apiFetch(`${BASE()}/${id}/background`, { method: 'POST', keepalive: true }).catch(() => {});
|
|
||||||
} catch {
|
|
||||||
/* 卸载阶段尽力而为,忽略一切异常 */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 保存会话的完整对话时间线,供历史回显出与实时对话一致的富时间线。
|
* 保存会话的完整对话时间线,供历史回显出与实时对话一致的富时间线。
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,138 +0,0 @@
|
|||||||
/**
|
|
||||||
* AI 写作流程图(竖向固定流水线)。
|
|
||||||
*
|
|
||||||
* 写作流程是固定线性流水线:意图理解 → 素材搜集 → 素材确认 → 大纲规划 → 大纲确认 →
|
|
||||||
* 写作 → 草稿确认 → 编辑审核 → 定稿。按传入的 ``activeKey``(后端从 graph checkpoint
|
|
||||||
* 推导的当前阶段 key)点亮:已过=done 打钩、当前=active 转圈、未到=灰。
|
|
||||||
*
|
|
||||||
* 纯展示组件,无弹窗/无窗口 chrome —— 由 ``AIWritingFlowDialog`` 套在弹窗里使用。
|
|
||||||
*/
|
|
||||||
import { CheckIcon, Loader2Icon } from 'lucide-react';
|
|
||||||
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
export interface FlowStage {
|
|
||||||
key: string;
|
|
||||||
label: string;
|
|
||||||
emoji: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 固定流水线阶段(key 与后端 ai_writing_job_executor 的 stage key 一致)。 */
|
|
||||||
export const FLOW_STAGES: readonly FlowStage[] = [
|
|
||||||
{ key: 'intent', label: '意图理解', emoji: '🧭' },
|
|
||||||
{ key: 'research', label: '素材搜集', emoji: '🔍' },
|
|
||||||
{ key: 'material_confirm', label: '素材确认', emoji: '📚' },
|
|
||||||
{ key: 'outline', label: '大纲规划', emoji: '🗂️' },
|
|
||||||
{ key: 'outline_confirm', label: '大纲确认', emoji: '🧩' },
|
|
||||||
{ key: 'draft', label: '写作', emoji: '✍️' },
|
|
||||||
{ key: 'draft_confirm', label: '草稿确认', emoji: '📝' },
|
|
||||||
{ key: 'review', label: '编辑审核', emoji: '🧐' },
|
|
||||||
{ key: 'done', label: '定稿', emoji: '🏁' },
|
|
||||||
];
|
|
||||||
|
|
||||||
export const FLOW_STAGE_LABEL: Record<string, string> = Object.fromEntries(
|
|
||||||
FLOW_STAGES.map((s) => [s.key, s.label]),
|
|
||||||
);
|
|
||||||
|
|
||||||
type StageState = 'pending' | 'active' | 'done' | 'error';
|
|
||||||
|
|
||||||
const LINE = 'bg-slate-300 dark:bg-border';
|
|
||||||
|
|
||||||
function StageNode({
|
|
||||||
label,
|
|
||||||
emoji,
|
|
||||||
state,
|
|
||||||
note,
|
|
||||||
}: {
|
|
||||||
label: string;
|
|
||||||
emoji: string;
|
|
||||||
state: StageState;
|
|
||||||
note?: string | null;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div className="flex shrink-0 flex-col items-center gap-1 px-0.5 text-center">
|
|
||||||
<div className="relative flex size-11 items-center justify-center">
|
|
||||||
{state === 'active' && <span className="absolute inset-0 animate-ping rounded-full bg-primary/25" />}
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'relative flex size-11 items-center justify-center rounded-full border-2 bg-white text-lg transition-all dark:bg-card',
|
|
||||||
state === 'active' && 'border-primary shadow-[0_0_0_3px_rgba(22,119,255,0.12)]',
|
|
||||||
state === 'done' && 'border-emerald-400/70',
|
|
||||||
state === 'error' && 'border-destructive',
|
|
||||||
state === 'pending' && 'border-border opacity-45 grayscale',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{emoji}
|
|
||||||
{state === 'done' && (
|
|
||||||
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-emerald-500 text-white shadow">
|
|
||||||
<CheckIcon className="size-2.5" />
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{state === 'active' && (
|
|
||||||
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-primary text-primary-foreground shadow">
|
|
||||||
<Loader2Icon className="size-2.5 animate-spin" />
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'whitespace-nowrap rounded border px-1 py-px text-[10px] font-medium leading-tight',
|
|
||||||
state === 'active' && 'border-primary/40 bg-primary/10 text-primary',
|
|
||||||
state === 'done' && 'border-emerald-400/40 bg-emerald-50 text-emerald-600 dark:bg-emerald-950/30',
|
|
||||||
state === 'error' && 'border-destructive/40 bg-destructive/10 text-destructive',
|
|
||||||
state === 'pending' && 'border-border bg-muted text-muted-foreground',
|
|
||||||
)}
|
|
||||||
title={label}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</span>
|
|
||||||
{note && state === 'active' && (
|
|
||||||
<span className="rounded bg-amber-100 px-1 py-px text-[9px] font-medium text-amber-600 dark:bg-amber-950/30">
|
|
||||||
{note}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function AIWritingFlowChart({
|
|
||||||
activeKey,
|
|
||||||
isError = false,
|
|
||||||
note,
|
|
||||||
className,
|
|
||||||
}: {
|
|
||||||
/** 当前阶段 key(null = 还没开始 / 准备中,全部置灰)。 */
|
|
||||||
activeKey: string | null;
|
|
||||||
isError?: boolean;
|
|
||||||
note?: string | null;
|
|
||||||
className?: string;
|
|
||||||
}) {
|
|
||||||
const allDone = activeKey === 'done';
|
|
||||||
const activeIdx = activeKey ? FLOW_STAGES.findIndex((s) => s.key === activeKey) : -1;
|
|
||||||
const stateOf = (idx: number): StageState => {
|
|
||||||
if (allDone) return 'done';
|
|
||||||
if (activeIdx < 0) return 'pending';
|
|
||||||
if (idx < activeIdx) return 'done';
|
|
||||||
if (idx === activeIdx) return isError ? 'error' : 'active';
|
|
||||||
return 'pending';
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
// 横向流水线:左→右排列,节点间用横向连线(对齐到圆形头像竖直中心 ≈ 22px)。
|
|
||||||
// w-max 保持内容固有宽度,由外层 overflow-x-auto 在放不下时横向滚动。
|
|
||||||
<div className={cn('flex w-max flex-row items-start', className)}>
|
|
||||||
{FLOW_STAGES.map((stage, idx) => (
|
|
||||||
<div className="contents" key={stage.key}>
|
|
||||||
{idx > 0 && <div className={cn('mt-[22px] h-px w-5 shrink-0', LINE)} />}
|
|
||||||
<StageNode
|
|
||||||
label={stage.label}
|
|
||||||
emoji={stage.emoji}
|
|
||||||
state={stateOf(idx)}
|
|
||||||
note={stage.key === activeKey ? note : undefined}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
/**
|
|
||||||
* 「查看进度」流程图弹窗。
|
|
||||||
*
|
|
||||||
* 在历史记录里点击一条**后台挂起中**的写作 → 弹出本弹窗,里面是写作流程图,
|
|
||||||
* 实时(轮询)反映该会话后端的实际推进位置,让用户看到「跑到哪一步了」。
|
|
||||||
*/
|
|
||||||
import { useEffect, useRef, useState } from 'react';
|
|
||||||
import { Loader2 } from 'lucide-react';
|
|
||||||
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
|
|
||||||
import {
|
|
||||||
getAIWritingProgress,
|
|
||||||
type AIWritingProgress,
|
|
||||||
type AIWritingSessionSummary,
|
|
||||||
} from '../../api/ai-writing-sessions';
|
|
||||||
import { AIWritingFlowChart, FLOW_STAGE_LABEL } from './AIWritingFlowChart';
|
|
||||||
|
|
||||||
const POLL_MS = 2500;
|
|
||||||
|
|
||||||
function isTerminal(p: AIWritingProgress | null): boolean {
|
|
||||||
if (!p) return false;
|
|
||||||
return p.sessionStatus === 'done' || p.sessionStatus === 'error' || p.stage === 'done';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function AIWritingFlowDialog({
|
|
||||||
session,
|
|
||||||
open,
|
|
||||||
onOpenChange,
|
|
||||||
}: {
|
|
||||||
session: AIWritingSessionSummary | null;
|
|
||||||
open: boolean;
|
|
||||||
onOpenChange: (open: boolean) => void;
|
|
||||||
}) {
|
|
||||||
const [progress, setProgress] = useState<AIWritingProgress | null>(null);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [fetchError, setFetchError] = useState(false);
|
|
||||||
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!open || !session) return;
|
|
||||||
let cancelled = false;
|
|
||||||
setProgress(null);
|
|
||||||
setFetchError(false);
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
const tick = async () => {
|
|
||||||
try {
|
|
||||||
const p = await getAIWritingProgress(session.id);
|
|
||||||
if (cancelled) return;
|
|
||||||
setProgress(p);
|
|
||||||
setFetchError(false);
|
|
||||||
setLoading(false);
|
|
||||||
// 终态停止轮询,否则继续。
|
|
||||||
if (!isTerminal(p)) {
|
|
||||||
timerRef.current = setTimeout(tick, POLL_MS);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
if (cancelled) return;
|
|
||||||
setFetchError(true);
|
|
||||||
setLoading(false);
|
|
||||||
timerRef.current = setTimeout(tick, POLL_MS);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
void tick();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
if (timerRef.current) clearTimeout(timerRef.current);
|
|
||||||
timerRef.current = null;
|
|
||||||
};
|
|
||||||
}, [open, session]);
|
|
||||||
|
|
||||||
const terminal = isTerminal(progress);
|
|
||||||
const isError = progress?.sessionStatus === 'error';
|
|
||||||
const stage = progress?.stage ?? null;
|
|
||||||
|
|
||||||
let caption: string;
|
|
||||||
if (loading && !progress) {
|
|
||||||
caption = '加载进度中…';
|
|
||||||
} else if (isError) {
|
|
||||||
caption = '后台执行出错,请重新发起写作';
|
|
||||||
} else if (progress?.sessionStatus === 'done' || stage === 'done') {
|
|
||||||
caption = '✓ 写作已完成,点开这条记录即可查看成稿';
|
|
||||||
} else {
|
|
||||||
const stageLabel = stage ? (FLOW_STAGE_LABEL[stage] ?? '准备中') : '准备中';
|
|
||||||
let text = `后台运行中 · 当前:${stageLabel}`;
|
|
||||||
if (progress?.note) text += `(${progress.note})`;
|
|
||||||
if (stage === 'review' && (progress?.revisionCount ?? 0) > 0) {
|
|
||||||
text += ` · 第 ${progress!.revisionCount}/${progress!.maxRevisions} 轮修改`;
|
|
||||||
}
|
|
||||||
caption = text;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
||||||
<DialogContent className="sm:max-w-2xl">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle className="truncate pr-6 text-sm" title={session?.title}>
|
|
||||||
写作进度 · {session?.draft_title || session?.title || '后台写作'}
|
|
||||||
</DialogTitle>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<div className="flex flex-col items-center gap-3 py-1">
|
|
||||||
<div className="w-full overflow-x-auto py-2">
|
|
||||||
<AIWritingFlowChart className="mx-auto" activeKey={stage} isError={isError} note={progress?.note} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-center gap-1.5 text-center text-xs text-muted-foreground">
|
|
||||||
{!terminal && !isError && <Loader2 className="size-3 shrink-0 animate-spin text-sky-500" />}
|
|
||||||
<span className={fetchError ? 'text-amber-500' : undefined}>
|
|
||||||
{fetchError ? '获取进度失败,重试中…' : caption}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useRef, useEffect } from 'react';
|
import { useState, useRef, useEffect } from 'react';
|
||||||
import { History, Trash2, Check, X, RefreshCw, Loader2 } from 'lucide-react';
|
import { History, Trash2, Check, X, RefreshCw } from 'lucide-react';
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
@@ -7,8 +7,6 @@ import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions';
|
|||||||
|
|
||||||
export const STATUS_LABELS: Record<string, { label: string; color: string }> = {
|
export const STATUS_LABELS: Record<string, { label: string; color: string }> = {
|
||||||
in_progress: { label: '进行中', color: 'text-blue-500' },
|
in_progress: { label: '进行中', color: 'text-blue-500' },
|
||||||
// 后台挂起中:后端正自动驱动到定稿(离页/刷新/切号不打断)。
|
|
||||||
background: { label: '挂起中', color: 'text-sky-500' },
|
|
||||||
draft_ready: { label: '草稿', color: 'text-amber-500' },
|
draft_ready: { label: '草稿', color: 'text-amber-500' },
|
||||||
review_ready: { label: '审核', color: 'text-purple-500' },
|
review_ready: { label: '审核', color: 'text-purple-500' },
|
||||||
done: { label: '完成', color: 'text-green-500' },
|
done: { label: '完成', color: 'text-green-500' },
|
||||||
@@ -31,15 +29,11 @@ export interface SessionItemProps {
|
|||||||
session: AIWritingSessionSummary;
|
session: AIWritingSessionSummary;
|
||||||
isSelected: boolean;
|
isSelected: boolean;
|
||||||
onSelect: () => void;
|
onSelect: () => void;
|
||||||
/** 「挂起中」记录点击时改为查看进度(流程图弹窗),不直接打开会话。 */
|
|
||||||
onShowProgress?: () => void;
|
|
||||||
onDelete: () => void;
|
onDelete: () => void;
|
||||||
onRename: (title: string) => void;
|
onRename: (title: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SessionItem({ session, isSelected, onSelect, onShowProgress, onDelete, onRename }: SessionItemProps) {
|
export function SessionItem({ session, isSelected, onSelect, onDelete, onRename }: SessionItemProps) {
|
||||||
const isBackground = session.status === 'background';
|
|
||||||
const handleRowClick = isBackground && onShowProgress ? onShowProgress : onSelect;
|
|
||||||
const [editing, setEditing] = useState(false);
|
const [editing, setEditing] = useState(false);
|
||||||
const [editValue, setEditValue] = useState(session.title);
|
const [editValue, setEditValue] = useState(session.title);
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
@@ -66,7 +60,7 @@ export function SessionItem({ session, isSelected, onSelect, onShowProgress, onD
|
|||||||
'group relative flex items-start gap-2 px-3 py-2.5 cursor-pointer transition-colors',
|
'group relative flex items-start gap-2 px-3 py-2.5 cursor-pointer transition-colors',
|
||||||
isSelected ? 'bg-accent' : 'hover:bg-accent/60',
|
isSelected ? 'bg-accent' : 'hover:bg-accent/60',
|
||||||
)}
|
)}
|
||||||
onClick={!editing ? handleRowClick : undefined}
|
onClick={!editing ? onSelect : undefined}
|
||||||
>
|
>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
{editing ? (
|
{editing ? (
|
||||||
@@ -95,10 +89,7 @@ export function SessionItem({ session, isSelected, onSelect, onShowProgress, onD
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<div className="flex items-center gap-1.5 mt-0.5">
|
<div className="flex items-center gap-1.5 mt-0.5">
|
||||||
<span className={cn('flex items-center gap-0.5 text-[10px] font-medium', color)}>
|
<span className={cn('text-[10px] font-medium', color)}>{label}</span>
|
||||||
{session.status === 'background' && <Loader2 className="w-2.5 h-2.5 animate-spin" />}
|
|
||||||
{label}
|
|
||||||
</span>
|
|
||||||
<span className="text-[10px] text-muted-foreground">·</span>
|
<span className="text-[10px] text-muted-foreground">·</span>
|
||||||
<span className="text-[10px] text-muted-foreground">{formatRelative(session.updated_at)}</span>
|
<span className="text-[10px] text-muted-foreground">{formatRelative(session.updated_at)}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -123,8 +114,6 @@ interface AIWritingHistoryDropdownProps {
|
|||||||
selectedId: string | null;
|
selectedId: string | null;
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
onSelect: (session: AIWritingSessionSummary) => void;
|
onSelect: (session: AIWritingSessionSummary) => void;
|
||||||
/** 点击「挂起中」记录时查看进度(流程图弹窗),不直接打开会话。 */
|
|
||||||
onShowProgress?: (session: AIWritingSessionSummary) => void;
|
|
||||||
onDelete: (id: string) => void;
|
onDelete: (id: string) => void;
|
||||||
onRename: (id: string, title: string) => void;
|
onRename: (id: string, title: string) => void;
|
||||||
onRefresh: () => void;
|
onRefresh: () => void;
|
||||||
@@ -135,7 +124,6 @@ export function AIWritingHistoryDropdown({
|
|||||||
selectedId,
|
selectedId,
|
||||||
loading,
|
loading,
|
||||||
onSelect,
|
onSelect,
|
||||||
onShowProgress,
|
|
||||||
onDelete,
|
onDelete,
|
||||||
onRename,
|
onRename,
|
||||||
onRefresh,
|
onRefresh,
|
||||||
@@ -201,7 +189,6 @@ export function AIWritingHistoryDropdown({
|
|||||||
session={s}
|
session={s}
|
||||||
isSelected={s.id === selectedId}
|
isSelected={s.id === selectedId}
|
||||||
onSelect={() => { onSelect(s); setOpen(false); }}
|
onSelect={() => { onSelect(s); setOpen(false); }}
|
||||||
onShowProgress={onShowProgress ? () => { onShowProgress(s); setOpen(false); } : undefined}
|
|
||||||
onDelete={() => onDelete(s.id)}
|
onDelete={() => onDelete(s.id)}
|
||||||
onRename={(title) => onRename(s.id, title)}
|
onRename={(title) => onRename(s.id, title)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,34 +1,8 @@
|
|||||||
import { useMemo } from 'react';
|
|
||||||
import { CheckCircle2, ChevronRight, FileText, Search, PenLine, ClipboardEdit, Star } from 'lucide-react';
|
import { CheckCircle2, ChevronRight, FileText, Search, PenLine, ClipboardEdit, Star } from 'lucide-react';
|
||||||
|
|
||||||
import type { AIWritingSessionSummary, CompletedInterventionRecord } from '../../api/ai-writing-sessions';
|
import type { AIWritingSessionSummary, CompletedInterventionRecord } from '../../api/ai-writing-sessions';
|
||||||
import {
|
|
||||||
normalizeProgressDict,
|
|
||||||
normalizeMaterial,
|
|
||||||
normalizeOutline,
|
|
||||||
normalizeReviewResult,
|
|
||||||
} from '../../hooks/useAIWritingStream';
|
|
||||||
import type { CompletedIntervention } from '../../types/ai-writing';
|
|
||||||
import { AIWritingTimeline } from './AIWritingTimeline';
|
import { AIWritingTimeline } from './AIWritingTimeline';
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化一条 completedIntervention(后台挂起重建的干预记录里素材/大纲/审核数据是
|
|
||||||
* snake_case,前端干预卡期望 camelCase)。对前端实时存的 camelCase 记录幂等。
|
|
||||||
*/
|
|
||||||
function normalizeCompletedIntervention(rec: Record<string, unknown>): CompletedIntervention {
|
|
||||||
const out: Record<string, unknown> = { ...rec };
|
|
||||||
out.pausePoint = rec.pausePoint ?? rec.pause_point;
|
|
||||||
if (Array.isArray(rec.materials)) {
|
|
||||||
out.materials = (rec.materials as Record<string, unknown>[]).map(normalizeMaterial);
|
|
||||||
}
|
|
||||||
if (rec.outline) out.outline = normalizeOutline(rec.outline);
|
|
||||||
const rr = rec.reviewResult ?? rec.review_result;
|
|
||||||
if (rr) out.reviewResult = normalizeReviewResult(rr);
|
|
||||||
if (out.draftTitle == null && rec.draft_title != null) out.draftTitle = rec.draft_title;
|
|
||||||
if (out.draftWordCount == null && rec.draft_word_count != null) out.draftWordCount = rec.draft_word_count;
|
|
||||||
return out as unknown as CompletedIntervention;
|
|
||||||
}
|
|
||||||
|
|
||||||
const PAUSE_LABELS: Record<string, string> = {
|
const PAUSE_LABELS: Record<string, string> = {
|
||||||
material_confirm: '素材确认',
|
material_confirm: '素材确认',
|
||||||
outline_confirm: '大纲确认',
|
outline_confirm: '大纲确认',
|
||||||
@@ -93,22 +67,6 @@ export function AIWritingHistoryView({ session }: AIWritingHistoryViewProps) {
|
|||||||
const transcript = session.transcript;
|
const transcript = session.transcript;
|
||||||
// 有完整时间线快照时,复用实时对话的 AIWritingTimeline 渲染,保证回显与实时一致
|
// 有完整时间线快照时,复用实时对话的 AIWritingTimeline 渲染,保证回显与实时一致
|
||||||
const hasTranscript = !!transcript && (transcript.progressEvents?.length ?? 0) > 0;
|
const hasTranscript = !!transcript && (transcript.progressEvents?.length ?? 0) > 0;
|
||||||
// 归一化 transcript 事件:后台挂起跑出的事件是 raw(snake_case),前端实时存的是
|
|
||||||
// camelCase——统一过一遍 normalizeProgressDict(幂等),两种来源回显都正确一致。
|
|
||||||
const normalizedEvents = useMemo(
|
|
||||||
() => (transcript?.progressEvents ?? []).map(
|
|
||||||
(e) => normalizeProgressDict(e as unknown as Record<string, unknown>, session.id),
|
|
||||||
),
|
|
||||||
[transcript, session.id],
|
|
||||||
);
|
|
||||||
// 干预记录同样归一化(后台重建的素材/大纲/审核数据为 snake_case;前端实时记录已是
|
|
||||||
// camelCase,归一化幂等),保证素材列表/大纲/编辑审核卡片正确渲染。
|
|
||||||
const normalizedInterventions = useMemo(
|
|
||||||
() => (transcript?.completedInterventions ?? []).map(
|
|
||||||
(rec) => normalizeCompletedIntervention(rec as unknown as Record<string, unknown>),
|
|
||||||
),
|
|
||||||
[transcript],
|
|
||||||
);
|
|
||||||
const createdAt = session.created_at
|
const createdAt = session.created_at
|
||||||
? new Date(session.created_at).toLocaleString('zh-CN', {
|
? new Date(session.created_at).toLocaleString('zh-CN', {
|
||||||
year: 'numeric', month: 'short', day: 'numeric',
|
year: 'numeric', month: 'short', day: 'numeric',
|
||||||
@@ -136,8 +94,8 @@ export function AIWritingHistoryView({ session }: AIWritingHistoryViewProps) {
|
|||||||
{hasTranscript ? (
|
{hasTranscript ? (
|
||||||
/* 完整对话时间线回显 */
|
/* 完整对话时间线回显 */
|
||||||
<AIWritingTimeline
|
<AIWritingTimeline
|
||||||
events={normalizedEvents}
|
events={transcript!.progressEvents}
|
||||||
completedInterventions={normalizedInterventions}
|
completedInterventions={transcript!.completedInterventions ?? []}
|
||||||
currentPause={null}
|
currentPause={null}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
import { ChevronsDown, CloudUpload, PanelRightClose, Play, Plus, RotateCcw, Settings2, Square, Trash2 } from 'lucide-react';
|
import { ChevronsDown, PanelRightClose, Play, Plus, RotateCcw, Settings2, Square, Trash2 } from 'lucide-react';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@@ -17,12 +17,7 @@ import { useAIWriting } from '../../contexts/AIWritingContext';
|
|||||||
import { useAIWritingHistory } from '../../contexts/AIWritingHistoryContext';
|
import { useAIWritingHistory } from '../../contexts/AIWritingHistoryContext';
|
||||||
import { useWritingFormOptional } from '../../contexts/WritingFormContext';
|
import { useWritingFormOptional } from '../../contexts/WritingFormContext';
|
||||||
import { useAIWritingSessions } from '../../hooks/useAIWritingSessions';
|
import { useAIWritingSessions } from '../../hooks/useAIWritingSessions';
|
||||||
import {
|
import { adminCleanupAIWritingSessions, getAIWritingSession } from '../../api/ai-writing-sessions';
|
||||||
adminCleanupAIWritingSessions,
|
|
||||||
getAIWritingSession,
|
|
||||||
suspendAIWritingToBackground,
|
|
||||||
suspendAIWritingToBackgroundKeepalive,
|
|
||||||
} from '../../api/ai-writing-sessions';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 暂停 / 继续功能开关(默认 false = 关)。
|
* 暂停 / 继续功能开关(默认 false = 关)。
|
||||||
@@ -56,7 +51,6 @@ import { ReviewStreamingView } from './ReviewStreamingView';
|
|||||||
import { RevisionSummaryCard } from './RevisionSummaryCard';
|
import { RevisionSummaryCard } from './RevisionSummaryCard';
|
||||||
import { AIWritingHistoryDropdown } from './AIWritingHistoryDropdown';
|
import { AIWritingHistoryDropdown } from './AIWritingHistoryDropdown';
|
||||||
import { AIWritingHistoryView } from './AIWritingHistoryView';
|
import { AIWritingHistoryView } from './AIWritingHistoryView';
|
||||||
import { AIWritingFlowDialog } from './AIWritingFlowDialog';
|
|
||||||
import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions';
|
import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions';
|
||||||
|
|
||||||
const STATUS_LABEL: Record<string, string> = {
|
const STATUS_LABEL: Record<string, string> = {
|
||||||
@@ -97,8 +91,6 @@ export function AIWritingPanel({
|
|||||||
useEffect(() => { refreshArticleTypes(); }, [refreshArticleTypes]);
|
useEffect(() => { refreshArticleTypes(); }, [refreshArticleTypes]);
|
||||||
|
|
||||||
const [reqDialogOpen, setReqDialogOpen] = useState(false);
|
const [reqDialogOpen, setReqDialogOpen] = useState(false);
|
||||||
// 「查看进度」流程图弹窗当前展示的会话(点击历史里的「挂起中」记录时打开)。
|
|
||||||
const [progressSession, setProgressSession] = useState<AIWritingSessionSummary | null>(null);
|
|
||||||
|
|
||||||
const isIdle = state.status === 'idle';
|
const isIdle = state.status === 'idle';
|
||||||
const isDone = state.status === 'done';
|
const isDone = state.status === 'done';
|
||||||
@@ -196,57 +188,11 @@ export function AIWritingPanel({
|
|||||||
void openHistory(session);
|
void openHistory(session);
|
||||||
}, [openHistory]);
|
}, [openHistory]);
|
||||||
|
|
||||||
// 点击历史里的「挂起中」记录 → 打开流程图弹窗看实际进度(而非直接打开会话)。
|
|
||||||
const handleShowProgress = useCallback((session: AIWritingSessionSummary) => {
|
|
||||||
setProgressSession(session);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleNewSession = useCallback(() => {
|
const handleNewSession = useCallback(() => {
|
||||||
closeHistory();
|
closeHistory();
|
||||||
reset();
|
reset();
|
||||||
}, [closeHistory, reset]);
|
}, [closeHistory, reset]);
|
||||||
|
|
||||||
// ── 后台挂起:把当前写作转后台,后端自动驱动到定稿(离页/刷新/切号不打断) ──
|
|
||||||
const handleBackgroundSuspend = useCallback(async () => {
|
|
||||||
const sid = state.sessionId;
|
|
||||||
if (!sid) {
|
|
||||||
toast.error('当前没有可挂起的写作会话');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await suspendAIWritingToBackground(sid);
|
|
||||||
} catch (e) {
|
|
||||||
toast.error(e instanceof Error ? e.message : '后台挂起失败');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
toast.success('已转入后台自动完成,稍后可在「历史记录」查看进度与结果');
|
|
||||||
// reset() 会 stop 客户端 SSE 订阅并回到 idle —— 后端驱动器接管续跑,不冲突。
|
|
||||||
reset();
|
|
||||||
// 刷新历史列表,让「挂起中」徽标立刻出现。
|
|
||||||
refresh();
|
|
||||||
}, [state.sessionId, reset, refresh]);
|
|
||||||
|
|
||||||
// 离页 / 刷新 / 关标签页时,若写作仍在进行中则自动转后台(与圆桌「自动挂起」一致)。
|
|
||||||
// 用 ref 持有最新的「是否在跑 + 会话 id」,让卸载/卸载前回调读到即时值。
|
|
||||||
const suspendRef = useRef<{ running: boolean; sid: string | null }>({ running: false, sid: null });
|
|
||||||
useEffect(() => {
|
|
||||||
suspendRef.current = { running: isRunning, sid: state.sessionId ?? null };
|
|
||||||
}, [isRunning, state.sessionId]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const onBeforeUnload = () => {
|
|
||||||
const { running, sid } = suspendRef.current;
|
|
||||||
if (running && sid) suspendAIWritingToBackgroundKeepalive(sid);
|
|
||||||
};
|
|
||||||
window.addEventListener('beforeunload', onBeforeUnload);
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('beforeunload', onBeforeUnload);
|
|
||||||
// 组件卸载(路由离开本页 / 切换工作区标签):写作未完成则自动转后台。
|
|
||||||
const { running, sid } = suspendRef.current;
|
|
||||||
if (running && sid) suspendAIWritingToBackgroundKeepalive(sid);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// ── 侧边栏"最近写作"通信:两种路径 ────────────────────────────────────────
|
// ── 侧边栏"最近写作"通信:两种路径 ────────────────────────────────────────
|
||||||
// 用 ref 包住 handler,保证事件监听器始终能拿到最新版本
|
// 用 ref 包住 handler,保证事件监听器始终能拿到最新版本
|
||||||
const handleSelectHistoryRef = useRef(handleSelectHistory);
|
const handleSelectHistoryRef = useRef(handleSelectHistory);
|
||||||
@@ -353,19 +299,6 @@ export function AIWritingPanel({
|
|||||||
新建
|
新建
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{/* 后台挂起:写作进行中(含等待干预)时出现,点击后由后端自动跑完剩余流程 */}
|
|
||||||
{isRunning && !isHistoryMode && state.sessionId && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-7 px-2 text-xs gap-1 text-sky-500 hover:text-sky-600 hover:bg-sky-50 dark:hover:bg-sky-950/30"
|
|
||||||
onClick={handleBackgroundSuspend}
|
|
||||||
title="转入后台:自动确认素材/大纲、写作、编辑审核直至定稿,离开页面也不中断"
|
|
||||||
>
|
|
||||||
<CloudUpload className="size-3" />
|
|
||||||
后台挂起
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{/* ⏸️/▶️ "停止 / 继续" 由 ENABLE_PAUSE_RESUME_UI 控制(默认 false 隐藏)。
|
{/* ⏸️/▶️ "停止 / 继续" 由 ENABLE_PAUSE_RESUME_UI 控制(默认 false 隐藏)。
|
||||||
后期把 flag 翻成 true 即可恢复,UI / hook 全套代码都已就位。 */}
|
后期把 flag 翻成 true 即可恢复,UI / hook 全套代码都已就位。 */}
|
||||||
{ENABLE_PAUSE_RESUME_UI && isRunning && !state.isPaused && (
|
{ENABLE_PAUSE_RESUME_UI && isRunning && !state.isPaused && (
|
||||||
@@ -407,7 +340,6 @@ export function AIWritingPanel({
|
|||||||
selectedId={historySession?.id ?? null}
|
selectedId={historySession?.id ?? null}
|
||||||
loading={sessionsLoading}
|
loading={sessionsLoading}
|
||||||
onSelect={handleSelectHistory}
|
onSelect={handleSelectHistory}
|
||||||
onShowProgress={handleShowProgress}
|
|
||||||
onDelete={remove}
|
onDelete={remove}
|
||||||
onRename={rename}
|
onRename={rename}
|
||||||
onRefresh={refresh}
|
onRefresh={refresh}
|
||||||
@@ -523,15 +455,9 @@ export function AIWritingPanel({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 技能检索过程实时展示:
|
{/* 技能检索 pending:用户点击瞬间到 awaiting 之间,始终显示 SkillStepsCard 占位
|
||||||
① skillSearchPending —— PAUSE-1 用户点"重新搜索/按输入追加"瞬间到 awaiting
|
steps.length === 0 时 SkillStepsCard 内部会渲染骨架行,不让用户干等空白 */}
|
||||||
之间的占位(steps 为空时 SkillStepsCard 内部渲染骨架行,不让用户干等空白);
|
{state.skillSearchPending && (
|
||||||
② 首次素材收集(researching 且已有 skill_search_step)—— 让"调用了哪个技能 /
|
|
||||||
检索到多少条 / 检索完成"像智能体问答一样边搜边显示,而不是搜完才在素材确认
|
|
||||||
卡里一次性看到。素材确认(awaiting_material_confirm)时由 InterventionCard
|
|
||||||
接管展示同一份 steps,这里 researching 条件自动失效,不会重复。 */}
|
|
||||||
{(state.skillSearchPending
|
|
||||||
|| (state.status === 'researching' && state.skillSearchSteps.length > 0)) && (
|
|
||||||
<div className="px-4 pb-2">
|
<div className="px-4 pb-2">
|
||||||
<SkillStepsCard steps={state.skillSearchSteps} inProgress />
|
<SkillStepsCard steps={state.skillSearchSteps} inProgress />
|
||||||
</div>
|
</div>
|
||||||
@@ -541,11 +467,8 @@ export function AIWritingPanel({
|
|||||||
state.status !== 'writing_draft' &&
|
state.status !== 'writing_draft' &&
|
||||||
!(state.status === 'writing_outline' && (state.outlineStreamingText || state.outlineThinkingText)) &&
|
!(state.status === 'writing_outline' && (state.outlineStreamingText || state.outlineThinkingText)) &&
|
||||||
!(state.status === 'reviewing' && state.streamingReviewItems.length > 0) &&
|
!(state.status === 'reviewing' && state.streamingReviewItems.length > 0) &&
|
||||||
/* 技能检索占位卡 / 选择打字机 / 已流式的技能步骤 已经在展示,不再叠加 skeleton。
|
/* 技能检索占位卡 / 选择打字机 已经在流式展示,不再叠加 skeleton */
|
||||||
(研究阶段一旦有 skill_search_step,就改由上面的 SkillStepsCard 实时呈现进度,
|
|
||||||
研究词生成阶段 steps 还为空时仍走 skeleton 透传 researchProgress 文案。) */
|
|
||||||
!state.skillSearchPending &&
|
!state.skillSearchPending &&
|
||||||
!(state.status === 'researching' && state.skillSearchSteps.length > 0) &&
|
|
||||||
!(state.status === 'researching' && (state.skillSelectStreamingText || state.skillSelectThinkingText)) &&
|
!(state.status === 'researching' && (state.skillSelectStreamingText || state.skillSelectThinkingText)) &&
|
||||||
/* 意图解析流式过程中(LLM 还在吐 JSON)不要显示 skeleton */
|
/* 意图解析流式过程中(LLM 还在吐 JSON)不要显示 skeleton */
|
||||||
!state.intentStreamingText && !state.intentThinkingText && (
|
!state.intentStreamingText && !state.intentThinkingText && (
|
||||||
@@ -601,13 +524,6 @@ export function AIWritingPanel({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 查看进度流程图弹窗:点击历史里的「挂起中」记录时打开 */}
|
|
||||||
<AIWritingFlowDialog
|
|
||||||
session={progressSession}
|
|
||||||
open={progressSession !== null}
|
|
||||||
onOpenChange={(o) => { if (!o) setProgressSession(null); }}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* 写作参数查看弹窗 */}
|
{/* 写作参数查看弹窗 */}
|
||||||
{state.request && (
|
{state.request && (
|
||||||
<Dialog open={reqDialogOpen} onOpenChange={setReqDialogOpen}>
|
<Dialog open={reqDialogOpen} onOpenChange={setReqDialogOpen}>
|
||||||
|
|||||||
@@ -1,22 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import { BookOpen, FileText, LayoutGrid, Loader2, Plus, Settings2 } from "lucide-react";
|
||||||
BarChart3,
|
import { useEffect, useState } from "react";
|
||||||
BookOpen,
|
|
||||||
FileText,
|
|
||||||
Globe2,
|
|
||||||
LayoutGrid,
|
|
||||||
Loader2,
|
|
||||||
Newspaper,
|
|
||||||
Plus,
|
|
||||||
Search,
|
|
||||||
Settings2,
|
|
||||||
SlidersHorizontal,
|
|
||||||
Sparkles,
|
|
||||||
TrendingUp,
|
|
||||||
} from "lucide-react";
|
|
||||||
import type { LucideIcon } from "lucide-react";
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
@@ -37,62 +22,23 @@ import type { ResearchTemplate } from "../../api/ai-writing-research-templates";
|
|||||||
import { useWritingForm } from "../../contexts/WritingFormContext";
|
import { useWritingForm } from "../../contexts/WritingFormContext";
|
||||||
import { useAIWriting } from "../../contexts/AIWritingContext";
|
import { useAIWriting } from "../../contexts/AIWritingContext";
|
||||||
|
|
||||||
type TemplateVisual = {
|
/**
|
||||||
Icon: LucideIcon;
|
* 课题研究左栏(需求 0616 #5)。
|
||||||
iconClass: string;
|
* - 上半「研究模板」= 研究模板实体(``useResearchTemplates``);点击一键预填整张写作表单
|
||||||
accentClass: string;
|
* (文章类型 / 大纲 / 搜索来源 / 字数 / 受众 / 严格模式 / 主题)并展开配置。顶部「配置」
|
||||||
};
|
* 入口进入模板配置页维护这些模板。
|
||||||
|
* - 下半「笔记本」= 我的空间(``useStudioNotebooks``);点击在右侧内嵌打开该笔记本页。
|
||||||
const TEMPLATE_VISUALS: TemplateVisual[] = [
|
*/
|
||||||
{
|
|
||||||
Icon: Globe2,
|
|
||||||
iconClass: "bg-blue-50 text-blue-600",
|
|
||||||
accentClass: "bg-blue-500",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Icon: Newspaper,
|
|
||||||
iconClass: "bg-amber-50 text-amber-600",
|
|
||||||
accentClass: "bg-amber-500",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Icon: Sparkles,
|
|
||||||
iconClass: "bg-violet-50 text-violet-600",
|
|
||||||
accentClass: "bg-violet-500",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Icon: TrendingUp,
|
|
||||||
iconClass: "bg-rose-50 text-rose-600",
|
|
||||||
accentClass: "bg-rose-500",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Icon: BookOpen,
|
|
||||||
iconClass: "bg-emerald-50 text-emerald-600",
|
|
||||||
accentClass: "bg-emerald-500",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Icon: BarChart3,
|
|
||||||
iconClass: "bg-cyan-50 text-cyan-600",
|
|
||||||
accentClass: "bg-cyan-500",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
function getTemplateVisual(tpl: ResearchTemplate, index: number): TemplateVisual {
|
|
||||||
const text = `${tpl.name} ${tpl.description ?? ""} ${tpl.article_type_key ?? ""}`;
|
|
||||||
if (/网摘|网络|热点|摘/.test(text)) return TEMPLATE_VISUALS[0];
|
|
||||||
if (/周报|周刊|日报|月报/.test(text)) return TEMPLATE_VISUALS[1];
|
|
||||||
if (/要讯|资讯|快讯|简报/.test(text)) return TEMPLATE_VISUALS[2];
|
|
||||||
if (/行业|分析|市场|竞争/.test(text)) return TEMPLATE_VISUALS[3];
|
|
||||||
if (/政策|解读|法规/.test(text)) return TEMPLATE_VISUALS[4];
|
|
||||||
return TEMPLATE_VISUALS[index % TEMPLATE_VISUALS.length];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ResearchSidebar({
|
export function ResearchSidebar({
|
||||||
viewingNotebookId,
|
viewingNotebookId,
|
||||||
onOpenNotebook,
|
onOpenNotebook,
|
||||||
onOpenAllSpaces,
|
onOpenAllSpaces,
|
||||||
}: {
|
}: {
|
||||||
|
/** 当前在右侧查看的笔记本 id(高亮用)。 */
|
||||||
viewingNotebookId?: number | null;
|
viewingNotebookId?: number | null;
|
||||||
|
/** 点击笔记本 → 在右侧内嵌打开该笔记本页(替换右侧内容)。 */
|
||||||
onOpenNotebook: (notebookId: number) => void;
|
onOpenNotebook: (notebookId: number) => void;
|
||||||
|
/** 点击「所有空间」→ 在右侧内嵌打开空间列表页。 */
|
||||||
onOpenAllSpaces: () => void;
|
onOpenAllSpaces: () => void;
|
||||||
}) {
|
}) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -116,7 +62,7 @@ export function ResearchSidebar({
|
|||||||
} = useWritingForm();
|
} = useWritingForm();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const [templateSearch, setTemplateSearch] = useState("");
|
// 新建空间弹窗(与 workspace-nav-studio 同款)。
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [creating, setCreating] = useState(false);
|
const [creating, setCreating] = useState(false);
|
||||||
@@ -126,16 +72,6 @@ export function ResearchSidebar({
|
|||||||
void refresh();
|
void refresh();
|
||||||
}, [refresh]);
|
}, [refresh]);
|
||||||
|
|
||||||
const filteredTemplates = useMemo(() => {
|
|
||||||
const keyword = templateSearch.trim().toLowerCase();
|
|
||||||
if (!keyword) return templates;
|
|
||||||
return templates.filter((tpl) =>
|
|
||||||
[tpl.name, tpl.description, tpl.article_type_key]
|
|
||||||
.filter(Boolean)
|
|
||||||
.some((value) => String(value).toLowerCase().includes(keyword)),
|
|
||||||
);
|
|
||||||
}, [templates, templateSearch]);
|
|
||||||
|
|
||||||
const handleCreate = async () => {
|
const handleCreate = async () => {
|
||||||
const trimmed = name.trim();
|
const trimmed = name.trim();
|
||||||
if (!trimmed) return;
|
if (!trimmed) return;
|
||||||
@@ -156,6 +92,8 @@ export function ResearchSidebar({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 点击研究模板 → ①回填整张写作表单(保持写作态左栏显示与运行配置一致)
|
||||||
|
// ②直接以模板预设进入 AI 写作流程(startWriting)。
|
||||||
const handleTemplateClick = (tpl: ResearchTemplate) => {
|
const handleTemplateClick = (tpl: ResearchTemplate) => {
|
||||||
const intent = tpl.topic?.trim() ?? "";
|
const intent = tpl.topic?.trim() ?? "";
|
||||||
const articleType = tpl.article_type_key || "analysis";
|
const articleType = tpl.article_type_key || "analysis";
|
||||||
@@ -164,6 +102,7 @@ export function ResearchSidebar({
|
|||||||
const wordCount = tpl.word_count > 0 ? tpl.word_count : 800;
|
const wordCount = tpl.word_count > 0 ? tpl.word_count : 800;
|
||||||
const writingMode = tpl.strict_mode ? "strict" : "loose";
|
const writingMode = tpl.strict_mode ? "strict" : "loose";
|
||||||
|
|
||||||
|
// 回填表单上下文(写作态左栏据此展示)。
|
||||||
if (intent) setIntent(intent);
|
if (intent) setIntent(intent);
|
||||||
if (tpl.article_type_key) setArticleType(tpl.article_type_key);
|
if (tpl.article_type_key) setArticleType(tpl.article_type_key);
|
||||||
if (outline) {
|
if (outline) {
|
||||||
@@ -176,6 +115,7 @@ export function ResearchSidebar({
|
|||||||
setStrictMode(tpl.strict_mode);
|
setStrictMode(tpl.strict_mode);
|
||||||
setFormExpanded(true);
|
setFormExpanded(true);
|
||||||
|
|
||||||
|
// 无主题/意图无法发起写作 → 仅回填表单,由用户补充后手动开始。
|
||||||
if (!intent) return;
|
if (!intent) return;
|
||||||
void startWriting({
|
void startWriting({
|
||||||
userIntent: intent,
|
userIntent: intent,
|
||||||
@@ -190,191 +130,116 @@ export function ResearchSidebar({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside className="ai-research-sidebar flex h-full w-[320px] shrink-0 flex-col overflow-hidden border-r border-slate-100 bg-white text-slate-700 shadow-[1px_0_18px_rgba(15,23,42,0.03)]">
|
<aside className="flex h-full w-64 shrink-0 flex-col overflow-hidden border-r border-border/70 bg-card/60 backdrop-blur-sm">
|
||||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden px-3 py-4">
|
{/* 上半:研究模板 */}
|
||||||
<section className="mb-5">
|
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-2 py-3">
|
||||||
<div className="mb-3 flex items-center justify-between gap-3 px-1">
|
<div className="px-2 mb-1.5 flex items-center justify-between">
|
||||||
<button
|
<h2 className="text-muted-foreground/70 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
|
||||||
type="button"
|
研究模板
|
||||||
onClick={() => navigate("/page/canvas/research-templates")}
|
</h2>
|
||||||
title="配置研究模板"
|
<button
|
||||||
aria-label="配置研究模板"
|
type="button"
|
||||||
className="group flex items-center gap-2 rounded-lg text-[16px] font-bold text-slate-500 transition-colors hover:text-slate-800"
|
onClick={() => navigate("/page/canvas/research-templates")}
|
||||||
>
|
title="配置研究模板"
|
||||||
<SlidersHorizontal className="size-4 text-slate-400" />
|
aria-label="配置研究模板"
|
||||||
<span>研究模板</span>
|
className="text-muted-foreground/70 hover:text-foreground rounded p-0.5 transition-colors"
|
||||||
<Settings2 className="size-3.5 text-slate-300 opacity-0 transition-opacity group-hover:opacity-100" />
|
>
|
||||||
</button>
|
<Settings2 className="size-3.5" />
|
||||||
<div className="relative w-[150px]">
|
</button>
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-slate-400" />
|
</div>
|
||||||
<input
|
{templates.length === 0 ? (
|
||||||
type="text"
|
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">
|
||||||
value={templateSearch}
|
暂无研究模板,点右上角配置
|
||||||
onChange={(event) => setTemplateSearch(event.target.value)}
|
</p>
|
||||||
placeholder="搜索写作模板..."
|
) : (
|
||||||
className="h-8 w-full rounded-lg border border-slate-200 bg-slate-50/80 pl-8 pr-3 text-[12px] text-slate-600 outline-none transition focus:border-blue-200 focus:bg-white focus:ring-2 focus:ring-blue-100"
|
<div className="flex flex-col gap-1">
|
||||||
/>
|
{templates.map((tpl) => (
|
||||||
</div>
|
<button
|
||||||
</div>
|
key={tpl.id}
|
||||||
|
type="button"
|
||||||
{templates.length === 0 ? (
|
onClick={() => handleTemplateClick(tpl)}
|
||||||
<p className="rounded-xl border border-dashed border-slate-200 px-3 py-5 text-center text-xs text-slate-400">
|
title={tpl.description ?? tpl.name}
|
||||||
暂无研究模板,点击标题配置
|
className="flex items-start gap-2 rounded-lg px-2.5 py-1.5 text-left text-muted-foreground transition-colors hover:bg-sidebar-accent/60 hover:text-foreground"
|
||||||
</p>
|
>
|
||||||
) : filteredTemplates.length === 0 ? (
|
<FileText className="mt-0.5 size-3.5 shrink-0 text-muted-foreground/70" />
|
||||||
<p className="rounded-xl border border-dashed border-slate-200 px-3 py-5 text-center text-xs text-slate-400">
|
<span className="min-w-0">
|
||||||
暂无匹配模板
|
<span className="block truncate text-[13px] font-medium">{tpl.name}</span>
|
||||||
</p>
|
{tpl.description && (
|
||||||
) : (
|
<span className="text-muted-foreground/70 line-clamp-1 block text-[11px]">
|
||||||
<div className="space-y-3">
|
{tpl.description}
|
||||||
{filteredTemplates.map((tpl, index) => {
|
|
||||||
const visual = getTemplateVisual(tpl, index);
|
|
||||||
const Icon = visual.Icon;
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={tpl.id}
|
|
||||||
type="button"
|
|
||||||
onClick={() => handleTemplateClick(tpl)}
|
|
||||||
title={tpl.description ?? tpl.name}
|
|
||||||
className="group relative flex w-full items-start gap-3 overflow-hidden rounded-[5px] bg-white px-4 py-4 text-left shadow-[0_8px_24px_rgba(15,23,42,0.04)] transition-all hover:-translate-y-0.5 hover:shadow-[0_14px_30px_rgba(30,64,175,0.08)] active:translate-y-0"
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"flex size-12 shrink-0 items-center justify-center rounded-xl transition-colors",
|
|
||||||
visual.iconClass,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Icon className="size-6 stroke-[2.2]" />
|
|
||||||
</span>
|
</span>
|
||||||
<span className="min-w-0 flex-1 pt-0.5">
|
)}
|
||||||
<span className="block truncate text-[16px] font-bold leading-5 text-slate-900 transition-colors group-hover:text-blue-700">
|
</span>
|
||||||
{tpl.name}
|
</button>
|
||||||
</span>
|
))}
|
||||||
{tpl.description && (
|
|
||||||
<span
|
|
||||||
className="mt-1.5 overflow-hidden text-[13px] leading-6 text-slate-500"
|
|
||||||
style={{
|
|
||||||
display: "-webkit-box",
|
|
||||||
WebkitBoxOrient: "vertical",
|
|
||||||
WebkitLineClamp: 2,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{tpl.description}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"absolute bottom-4 left-0 top-4 w-1 rounded-r-full opacity-0 transition-opacity group-hover:opacity-100",
|
|
||||||
visual.accentClass,
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="flex min-h-0 flex-1 flex-col border-t border-slate-100 pt-5">
|
|
||||||
<div className="mb-3 flex items-center justify-between px-2">
|
|
||||||
<h2 className="text-[15px] font-bold tracking-wide text-slate-400">
|
|
||||||
笔记本
|
|
||||||
</h2>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
setName("");
|
|
||||||
setCreateError("");
|
|
||||||
setCreateOpen(true);
|
|
||||||
}}
|
|
||||||
title="新建写作空间"
|
|
||||||
aria-label="新建写作空间"
|
|
||||||
className="rounded-md p-1 text-slate-400 transition-colors hover:bg-rose-50 hover:text-rose-600"
|
|
||||||
>
|
|
||||||
<Plus className="size-4 stroke-[2.5]" />
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto px-1 pb-3">
|
|
||||||
{notebooksLoading ? (
|
|
||||||
<p className="px-3 py-2 text-xs text-slate-400">加载中...</p>
|
|
||||||
) : notebooksError ? (
|
|
||||||
<p className="rounded-xl bg-amber-50 px-3 py-2 text-xs leading-5 text-amber-700">
|
|
||||||
笔记本服务暂不可用,请检查空间服务地址或账号
|
|
||||||
</p>
|
|
||||||
) : notebooks.length === 0 ? (
|
|
||||||
<p className="px-3 py-2 text-xs text-slate-400">暂无笔记本</p>
|
|
||||||
) : (
|
|
||||||
notebooks.map((nb) => {
|
|
||||||
const active = viewingNotebookId === nb.id;
|
|
||||||
const sourceCount = Math.max(0, nb.source_count ?? 0);
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={nb.id}
|
|
||||||
type="button"
|
|
||||||
onClick={() => onOpenNotebook(nb.id)}
|
|
||||||
title={nb.description || nb.name}
|
|
||||||
className={cn(
|
|
||||||
"group relative flex min-h-14 w-full items-center gap-3 rounded-xl border bg-white px-3 py-2 text-left transition-all",
|
|
||||||
active
|
|
||||||
? "border-rose-100 bg-rose-50/35 text-slate-900 shadow-[0_6px_18px_rgba(244,63,94,0.06)]"
|
|
||||||
: "border-slate-100/80 text-slate-600 hover:border-slate-200 hover:bg-slate-50/70",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{active && (
|
|
||||||
<span className="absolute bottom-4 left-0 top-4 w-1 rounded-r-full bg-rose-500" />
|
|
||||||
)}
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"flex size-8 shrink-0 items-center justify-center rounded-lg",
|
|
||||||
active ? "bg-rose-50 text-rose-600" : "bg-slate-100 text-slate-500",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<BookOpen className="size-4 stroke-[2.2]" />
|
|
||||||
</span>
|
|
||||||
<span className="min-w-0 flex-1">
|
|
||||||
<span className="block truncate text-[15px] font-medium leading-5">
|
|
||||||
{nb.name}
|
|
||||||
</span>
|
|
||||||
{sourceCount > 0 && (
|
|
||||||
<span className="mt-1 flex items-center gap-1 text-[11px] text-slate-400">
|
|
||||||
<FileText className="size-3" />
|
|
||||||
已有 {sourceCount} 篇排版
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
{sourceCount > 0 && (
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"flex size-7 shrink-0 items-center justify-center rounded-full border text-[12px] font-semibold",
|
|
||||||
active
|
|
||||||
? "border-rose-100 bg-rose-50 text-rose-600"
|
|
||||||
: "border-slate-100 bg-slate-50 text-slate-400",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{sourceCount}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="border-t border-slate-100 px-1 pt-3">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onOpenAllSpaces}
|
|
||||||
className="flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left text-[14px] font-bold text-slate-700 transition-colors hover:bg-slate-50 hover:text-slate-950"
|
|
||||||
>
|
|
||||||
<LayoutGrid className="size-4 text-rose-500 stroke-[2.3]" />
|
|
||||||
<span>所有空间</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* 下半:笔记本(我的空间) */}
|
||||||
|
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto border-t border-border/60 px-2 py-3">
|
||||||
|
<h2 className="text-muted-foreground/70 px-2 mb-1.5 text-[10px] font-semibold tracking-[0.12em] uppercase select-none">
|
||||||
|
笔记本
|
||||||
|
</h2>
|
||||||
|
<div className="flex flex-col gap-0.5">
|
||||||
|
{/* 新建空间 */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setName("");
|
||||||
|
setCreateError("");
|
||||||
|
setCreateOpen(true);
|
||||||
|
}}
|
||||||
|
className="flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] text-muted-foreground transition-colors hover:bg-sidebar-accent/60 hover:text-foreground"
|
||||||
|
>
|
||||||
|
<Plus className="size-3.5 shrink-0 text-muted-foreground/70" />
|
||||||
|
<span>新建空间</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{notebooksLoading ? (
|
||||||
|
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">加载中…</p>
|
||||||
|
) : notebooksError ? (
|
||||||
|
<p className="px-2 py-1.5 text-xs text-amber-600">
|
||||||
|
笔记本服务暂不可用(检查空间服务地址 / 账号)
|
||||||
|
</p>
|
||||||
|
) : notebooks.length === 0 ? (
|
||||||
|
<p className="px-2 py-1.5 text-xs text-muted-foreground/70">暂无笔记本</p>
|
||||||
|
) : (
|
||||||
|
notebooks.map((nb) => {
|
||||||
|
const active = viewingNotebookId === nb.id;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={nb.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onOpenNotebook(nb.id)}
|
||||||
|
title={nb.description || nb.name}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] transition-colors",
|
||||||
|
active
|
||||||
|
? "bg-primary/10 text-primary"
|
||||||
|
: "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<BookOpen className="size-3.5 shrink-0 text-muted-foreground/70" />
|
||||||
|
<span className="truncate">{nb.name}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 所有空间 */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onOpenAllSpaces}
|
||||||
|
className="flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] text-muted-foreground transition-colors hover:bg-sidebar-accent/60 hover:text-foreground"
|
||||||
|
>
|
||||||
|
<LayoutGrid className="size-3.5 shrink-0 text-muted-foreground/70" />
|
||||||
|
<span>所有空间</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 新建空间弹窗 */}
|
||||||
<Dialog open={createOpen} onOpenChange={(v) => !creating && setCreateOpen(v)}>
|
<Dialog open={createOpen} onOpenChange={(v) => !creating && setCreateOpen(v)}>
|
||||||
<DialogContent className="sm:max-w-md">
|
<DialogContent className="sm:max-w-md">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
|
|||||||
@@ -15,11 +15,6 @@ import {
|
|||||||
import { useStream } from '@langchain/langgraph-sdk/react';
|
import { useStream } from '@langchain/langgraph-sdk/react';
|
||||||
|
|
||||||
import { getAPIClient } from '@/core/api';
|
import { getAPIClient } from '@/core/api';
|
||||||
import {
|
|
||||||
getStreamErrorMessage,
|
|
||||||
isThreadNotAccessibleError,
|
|
||||||
notifyThreadAccessChangedAndReload,
|
|
||||||
} from '@/core/threads/thread-access-error';
|
|
||||||
|
|
||||||
import { useCanvasGraphContext } from '../contexts/CanvasGraphContext';
|
import { useCanvasGraphContext } from '../contexts/CanvasGraphContext';
|
||||||
import { saveAIWritingTranscript } from '../api/ai-writing-sessions';
|
import { saveAIWritingTranscript } from '../api/ai-writing-sessions';
|
||||||
@@ -191,18 +186,10 @@ const AIWritingStreamHost = memo(function AIWritingStreamHost({
|
|||||||
},
|
},
|
||||||
onError(err: unknown) {
|
onError(err: unknown) {
|
||||||
eventBatcherRef.current?.cancel();
|
eventBatcherRef.current?.cancel();
|
||||||
const message = getStreamErrorMessage(err);
|
dispatchRef.current?.({
|
||||||
// A "thread not accessible/not found" 404 almost always means the writing
|
type: 'set_error',
|
||||||
// thread belongs to a previous login session — the user switched accounts
|
message: err instanceof Error ? err.message : String(err),
|
||||||
// (or this tab outlived a re-login), so the current account legitimately
|
});
|
||||||
// can't access the old thread. Instead of dumping the raw HTTP 404 into
|
|
||||||
// the panel, re-frame it around the current identity and reload — same UX
|
|
||||||
// the chat stream gives (see core/threads/hooks.ts).
|
|
||||||
if (isThreadNotAccessibleError(message)) {
|
|
||||||
notifyThreadAccessChangedAndReload();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
dispatchRef.current?.({ type: 'set_error', message });
|
|
||||||
},
|
},
|
||||||
onFinish(finishState) {
|
onFinish(finishState) {
|
||||||
eventBatcherRef.current?.cancel();
|
eventBatcherRef.current?.cancel();
|
||||||
@@ -304,12 +291,7 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = getStreamErrorMessage(err);
|
dispatch({ type: 'set_error', message: err instanceof Error ? err.message : String(err) });
|
||||||
if (isThreadNotAccessibleError(message)) {
|
|
||||||
notifyThreadAccessChangedAndReload();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
dispatch({ type: 'set_error', message });
|
|
||||||
}
|
}
|
||||||
}, [state.status]);
|
}, [state.status]);
|
||||||
|
|
||||||
@@ -385,24 +367,12 @@ export function AIWritingProvider({ children }: { children: ReactNode }) {
|
|||||||
dispatch({ type: 'intervention_submitted', record, nextStatus, pendingRevisionContext });
|
dispatch({ type: 'intervention_submitted', record, nextStatus, pendingRevisionContext });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// resume 是新 invocation,其 config 默认不带最初的 model_name;而写作/审核节点
|
|
||||||
// 在 resume 后才运行,若首轮 intent 未把模型存进 state(历史会话 / 捕获为空),
|
|
||||||
// 后端就只能回退默认模型。这里把表单选定的模型随每次 resume 一并回传,
|
|
||||||
// 让后端(get_writing_model / resolve_agent_model_name 的 configurable 兜底)
|
|
||||||
// 始终用上用户真正选的模型。
|
|
||||||
const resumeModelName = state.request?.modelName;
|
|
||||||
await stream.submit(undefined, {
|
await stream.submit(undefined, {
|
||||||
command: { resume: resumePayload },
|
command: { resume: resumePayload },
|
||||||
streamMode: ['values', 'updates', 'custom', 'messages-tuple'],
|
streamMode: ['values', 'updates', 'custom', 'messages-tuple'],
|
||||||
...(resumeModelName ? { config: { configurable: { model_name: resumeModelName } } } : {}),
|
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = getStreamErrorMessage(err);
|
dispatch({ type: 'set_error', message: err instanceof Error ? err.message : String(err) });
|
||||||
if (isThreadNotAccessibleError(message)) {
|
|
||||||
notifyThreadAccessChangedAndReload();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
dispatch({ type: 'set_error', message });
|
|
||||||
}
|
}
|
||||||
}, [state.sessionId, state.currentPause, state.materials, state.outline,
|
}, [state.sessionId, state.currentPause, state.materials, state.outline,
|
||||||
state.currentDraftTitle, state.currentDraftMarkdown, state.reviewResult,
|
state.currentDraftTitle, state.currentDraftMarkdown, state.reviewResult,
|
||||||
|
|||||||
@@ -395,7 +395,7 @@ function handleEvent(prev: AIWritingState, event: ProgressEvent): AIWritingState
|
|||||||
|
|
||||||
// ── snake_case ↔ camelCase 归一化(custom 通道事件 + interrupt payload) ──────
|
// ── snake_case ↔ camelCase 归一化(custom 通道事件 + interrupt payload) ──────
|
||||||
|
|
||||||
export function normalizeMaterial(m: Record<string, unknown>): AIMaterial {
|
function normalizeMaterial(m: Record<string, unknown>): AIMaterial {
|
||||||
const extra = (m.extra_metadata ?? m.extraMetadata) as Record<string, unknown> | undefined;
|
const extra = (m.extra_metadata ?? m.extraMetadata) as Record<string, unknown> | undefined;
|
||||||
return {
|
return {
|
||||||
id: String(m.id ?? ''),
|
id: String(m.id ?? ''),
|
||||||
@@ -430,7 +430,7 @@ function normalizeOutlineSection(s: Record<string, unknown>) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeOutline(o: unknown): AIOutline | null {
|
function normalizeOutline(o: unknown): AIOutline | null {
|
||||||
if (!o || typeof o !== 'object') return null;
|
if (!o || typeof o !== 'object') return null;
|
||||||
const obj = o as Record<string, unknown>;
|
const obj = o as Record<string, unknown>;
|
||||||
return {
|
return {
|
||||||
@@ -449,7 +449,7 @@ function normalizeReviewIssue(i: Record<string, unknown>): ReviewIssue {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeReviewResult(r: unknown): ReviewResult | null {
|
function normalizeReviewResult(r: unknown): ReviewResult | null {
|
||||||
if (!r || typeof r !== 'object') return null;
|
if (!r || typeof r !== 'object') return null;
|
||||||
const o = r as Record<string, unknown>;
|
const o = r as Record<string, unknown>;
|
||||||
return {
|
return {
|
||||||
@@ -472,12 +472,8 @@ function normalizeBlockedSection(b: Record<string, unknown>): BlockedSection {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 把后端节点 ``progress_events`` 数组里的一条 dict 翻译成前端 ProgressEvent。
|
/** 把后端节点 ``progress_events`` 数组里的一条 dict 翻译成前端 ProgressEvent。 */
|
||||||
*
|
function normalizeProgressDict(parsed: Record<string, unknown>, sessionId: string): ProgressEvent {
|
||||||
* 幂等:对已是 camelCase 的前端事件再跑一遍基本不变(snake_case 键不存在即跳过),
|
|
||||||
* 所以历史回显时可无脑对**整条** transcript 跑一遍——既归一后台存的 raw 事件,又
|
|
||||||
* 不破坏前端实时存的事件。 */
|
|
||||||
export function normalizeProgressDict(parsed: Record<string, unknown>, sessionId: string): ProgressEvent {
|
|
||||||
const out: Record<string, unknown> = { ...parsed, sessionId };
|
const out: Record<string, unknown> = { ...parsed, sessionId };
|
||||||
|
|
||||||
if ('agent_name' in out) out.agentName = out.agent_name;
|
if ('agent_name' in out) out.agentName = out.agent_name;
|
||||||
|
|||||||
@@ -2,13 +2,11 @@
|
|||||||
|
|
||||||
import { BotIcon, PlusSquare } from "lucide-react";
|
import { BotIcon, PlusSquare } from "lucide-react";
|
||||||
import { useParams, useRouter } from "next/navigation";
|
import { useParams, useRouter } from "next/navigation";
|
||||||
import { useLocation } from "react-router-dom";
|
|
||||||
import { useRouteBase } from "@/core/route-base";
|
import { useRouteBase } from "@/core/route-base";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
|
||||||
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { AgentChatSidebar } from "@/components/workspace/agents/agent-chat-sidebar";
|
|
||||||
import { AgentDetailPanel } from "@/components/workspace/agents/agent-detail-panel";
|
import { AgentDetailPanel } from "@/components/workspace/agents/agent-detail-panel";
|
||||||
import { AgentQuestionChips } from "@/components/workspace/agents/agent-question-chips";
|
import { AgentQuestionChips } from "@/components/workspace/agents/agent-question-chips";
|
||||||
import { AgentWelcome } from "@/components/workspace/agent-welcome";
|
import { AgentWelcome } from "@/components/workspace/agent-welcome";
|
||||||
@@ -28,20 +26,14 @@ import { useI18n } from "@/core/i18n/hooks";
|
|||||||
import { useModels } from "@/core/models/hooks";
|
import { useModels } from "@/core/models/hooks";
|
||||||
import { useNotification } from "@/core/notification/hooks";
|
import { useNotification } from "@/core/notification/hooks";
|
||||||
import { saveLastAgentId, useThreadSettings } from "@/core/settings";
|
import { saveLastAgentId, useThreadSettings } from "@/core/settings";
|
||||||
import { stopThreadRun, useThreadStream } from "@/core/threads/hooks";
|
import { useThreadStream } from "@/core/threads/hooks";
|
||||||
import { textOfMessage } from "@/core/threads/utils";
|
import { textOfMessage } from "@/core/threads/utils";
|
||||||
import { env } from "@/env";
|
import { env } from "@/env";
|
||||||
import { readTaskContext } from "@/core/auth/task-purpose";
|
|
||||||
import { TaskPurposePanel } from "@/strategy-components/components/task-components/TaskPurposePanel";
|
|
||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
|
|
||||||
export default function AgentChatPage({
|
export default function AgentChatPage({
|
||||||
embeddedAgentId,
|
embeddedAgentId,
|
||||||
chatBasePath,
|
chatBasePath,
|
||||||
taskGate,
|
|
||||||
taskBind,
|
|
||||||
autoStartWhenPurposeEmpty,
|
|
||||||
showAgentList,
|
|
||||||
}: {
|
}: {
|
||||||
/** 当作为「通用问答右侧嵌入」渲染时由父组件传入的 agent id(替代路由参数)。
|
/** 当作为「通用问答右侧嵌入」渲染时由父组件传入的 agent id(替代路由参数)。
|
||||||
* 传入即视为嵌入态:路由仍停留在 /chats/new,仅右侧问答区换成该智能体的对话。 */
|
* 传入即视为嵌入态:路由仍停留在 /chats/new,仅右侧问答区换成该智能体的对话。 */
|
||||||
@@ -51,17 +43,6 @@ export default function AgentChatPage({
|
|||||||
* 传入如 `/page/strategy/task-management/plan-task-sentiment/agent/${id}/chats`,
|
* 传入如 `/page/strategy/task-management/plan-task-sentiment/agent/${id}/chats`,
|
||||||
* 使开新会话 / 首条消息后的 URL 改写都停留在任务管理上下文(侧边栏保持对应业务高亮)。 */
|
* 使开新会话 / 首条消息后的 URL 改写都停留在任务管理上下文(侧边栏保持对应业务高亮)。 */
|
||||||
chatBasePath?: string;
|
chatBasePath?: string;
|
||||||
/** rwfx 任务深链闸门:新建对话时顶部展示目的树面板(覆盖确认后才开始问答),
|
|
||||||
* 并给新建 thread 打 `metadata.taskId` 标签(任务↔对话 1:N)。见 task-purpose。 */
|
|
||||||
taskGate?: boolean;
|
|
||||||
/** 3qfx / xdfx 任务深链:仅做任务↔对话 1:N 绑定(打 `metadata.taskId` 标签 + 切换会话停旧 run),
|
|
||||||
* 不展示目的树闸门;新建对话直接把任务开场信息自动发出。与 `taskGate` 互斥使用。 */
|
|
||||||
taskBind?: boolean;
|
|
||||||
/** rwfx:查询任务目的为空数据时,自动开始第一次问答(跳过手动点「开始问答」)。 */
|
|
||||||
autoStartWhenPurposeEmpty?: boolean;
|
|
||||||
/** 是否在最左侧展示「智能体列表」栏(顶部下拉切换 我的/广场,点击进入该智能体对话)。
|
|
||||||
* 仅独立的智能体问答整页开启;任务工作区 / 模块页 / 嵌入态不传(各有自己的左栏)。 */
|
|
||||||
showAgentList?: boolean;
|
|
||||||
} = {}) {
|
} = {}) {
|
||||||
const routeBase = useRouteBase();
|
const routeBase = useRouteBase();
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
@@ -76,29 +57,6 @@ export default function AgentChatPage({
|
|||||||
// 对话路由前缀:调用方可覆盖(任务深链嵌入态),否则用当前 routeBase 下的独立智能体对话路径。
|
// 对话路由前缀:调用方可覆盖(任务深链嵌入态),否则用当前 routeBase 下的独立智能体对话路径。
|
||||||
const agentChatsBase = chatBasePath ?? `${routeBase}/agents/${agent_id}/chats`;
|
const agentChatsBase = chatBasePath ?? `${routeBase}/agents/${agent_id}/chats`;
|
||||||
|
|
||||||
// 任务深链上下文(taskId + 开场信息):闸门(rwfx)与纯绑定(3qfx/xdfx)都要读取。
|
|
||||||
const taskCtxOn = !!(taskGate || taskBind);
|
|
||||||
const taskContext = useMemo(
|
|
||||||
() => (taskCtxOn ? readTaskContext() : null),
|
|
||||||
[taskCtxOn],
|
|
||||||
);
|
|
||||||
const taskId =
|
|
||||||
taskCtxOn && taskContext && taskContext.agentId === agent_id
|
|
||||||
? taskContext.taskId
|
|
||||||
: "";
|
|
||||||
// 纯绑定(taskBind,无闸门,3qfx/xdfx):新建对话进问答页后,右上角「开始回答」按钮点击时
|
|
||||||
// 发出的任务开场信息。不再自动发(避免新建对话竞态重复发送),改由用户手动点按钮触发。
|
|
||||||
// rwfx 走目的树闸门「开始问答」,不在此列。
|
|
||||||
const taskStartText =
|
|
||||||
taskBind && !taskGate && taskContext && taskContext.agentId === agent_id
|
|
||||||
? (taskContext.openingText?.trim() ?? "")
|
|
||||||
: "";
|
|
||||||
// 「首次进入且该任务无历史」信号:由 TaskFxIndexResolver 在「无聊天对话 → /new」时注入
|
|
||||||
// (用户主动点「新建对话」不带)。3qfx/xdfx 据此自动发出开场词、跳过「开始回答」按钮;
|
|
||||||
// rwfx 据此决定目的树为空时是否自动开始(仍由 TaskPurposePanel 在有数据时弹覆盖确认)。
|
|
||||||
const location = useLocation();
|
|
||||||
const taskAutoStart = !!(location.state as { taskAutoStart?: boolean } | null)?.taskAutoStart;
|
|
||||||
|
|
||||||
// If ChatPage stashed an opening message for this agent, skip the landing
|
// If ChatPage stashed an opening message for this agent, skip the landing
|
||||||
// screen on first render so the user doesn't see a flash of the welcome UI
|
// screen on first render so the user doesn't see a flash of the welcome UI
|
||||||
// before the auto-sent message takes over.
|
// before the auto-sent message takes over.
|
||||||
@@ -114,7 +72,7 @@ export default function AgentChatPage({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const [hasStartedConversation, setHasStartedConversation] = useState(
|
const [hasStartedConversation, setHasStartedConversation] = useState(
|
||||||
() => hasPendingForThisAgent(),
|
hasPendingForThisAgent,
|
||||||
);
|
);
|
||||||
|
|
||||||
const { agent, isLoading: isAgentLoading } = useAgent(agent_id);
|
const { agent, isLoading: isAgentLoading } = useAgent(agent_id);
|
||||||
@@ -143,8 +101,6 @@ export default function AgentChatPage({
|
|||||||
threadId: isNewThread ? undefined : threadId,
|
threadId: isNewThread ? undefined : threadId,
|
||||||
assistantId: agent_id,
|
assistantId: agent_id,
|
||||||
context: { ...settings.context, agent_id },
|
context: { ...settings.context, agent_id },
|
||||||
// 任务闸门:新建 thread 打 metadata.taskId 标签,供任务对话列表(1:N)按任务过滤。
|
|
||||||
threadMetadata: taskId ? { taskId } : undefined,
|
|
||||||
onStart: (createdThreadId) => {
|
onStart: (createdThreadId) => {
|
||||||
setThreadId(createdThreadId);
|
setThreadId(createdThreadId);
|
||||||
setIsNewThread(false);
|
setIsNewThread(false);
|
||||||
@@ -187,30 +143,6 @@ export default function AgentChatPage({
|
|||||||
[sendMessage, threadId, agent_id],
|
[sendMessage, threadId, agent_id],
|
||||||
);
|
);
|
||||||
|
|
||||||
// 任务流程:切换 / 新建会话时,停掉「上一会话服务端在跑」的 run(老对话要停止)。
|
|
||||||
// 任务工作区(rwfx 闸门 + 3qfx/xdfx 纯绑定)启用——普通问答页保留后台续跑行为不变。
|
|
||||||
const prevTaskThreadRef = useRef<string | null>(null);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!taskCtxOn) return;
|
|
||||||
const prev = prevTaskThreadRef.current;
|
|
||||||
if (prev && prev !== threadId) void stopThreadRun(prev);
|
|
||||||
prevTaskThreadRef.current = threadId ?? null;
|
|
||||||
}, [taskCtxOn, threadId]);
|
|
||||||
useEffect(() => {
|
|
||||||
// 离开任务问答页(卸载)时也停掉当前会话的服务端 run。
|
|
||||||
return () => {
|
|
||||||
if (taskCtxOn) void stopThreadRun(prevTaskThreadRef.current);
|
|
||||||
};
|
|
||||||
}, [taskCtxOn]);
|
|
||||||
|
|
||||||
// 任务闸门通过(无目的数据 / 覆盖成功):发出开场信息开始问答;无开场信息则
|
|
||||||
// 仅切到对话态(隐藏面板),让用户手动输入。
|
|
||||||
const handleGateStart = useCallback(() => {
|
|
||||||
const text = taskContext?.openingText?.trim();
|
|
||||||
if (text) handleSubmit({ text, files: [] });
|
|
||||||
else setHasStartedConversation(true);
|
|
||||||
}, [handleSubmit, taskContext]);
|
|
||||||
|
|
||||||
// ChatPage stashes the opening message in sessionStorage when the user picks
|
// ChatPage stashes the opening message in sessionStorage when the user picks
|
||||||
// an agent on the landing screen, then redirects here. Replay it once so the
|
// an agent on the landing screen, then redirects here. Replay it once so the
|
||||||
// user doesn't have to re-type the question on the agent chat page.
|
// user doesn't have to re-type the question on the agent chat page.
|
||||||
@@ -236,24 +168,6 @@ export default function AgentChatPage({
|
|||||||
handleSubmit({ text: pending.text, files: [] });
|
handleSubmit({ text: pending.text, files: [] });
|
||||||
}, [agent_id, threadId, isNewThread, handleSubmit]);
|
}, [agent_id, threadId, isNewThread, handleSubmit]);
|
||||||
|
|
||||||
// 纯绑定任务深链(3qfx/xdfx):用户主动「新建对话」进 landing 后,由 header 右上角「开始回答」
|
|
||||||
// 按钮手动触发发出开场信息(见下方 header)。手动场景不自动发,避免新建对话竞态导致的重复发送。
|
|
||||||
const handleTaskStart = useCallback(() => {
|
|
||||||
if (taskStartText) handleSubmit({ text: taskStartText, files: [] });
|
|
||||||
}, [handleSubmit, taskStartText]);
|
|
||||||
|
|
||||||
// 首次进入且该任务无历史(taskAutoStart):3qfx/xdfx 直接自动发出开场信息,无需手动点「开始回答」。
|
|
||||||
// autoStartedRef 一次性、不随 threadId 抖动重置,故只发一次(首次进入是干净 mount,无上一会话之忧)。
|
|
||||||
const autoStartedRef = useRef(false);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!taskAutoStart) return;
|
|
||||||
if (!taskStartText) return;
|
|
||||||
if (!isNewThread) return;
|
|
||||||
if (autoStartedRef.current) return;
|
|
||||||
autoStartedRef.current = true;
|
|
||||||
handleSubmit({ text: taskStartText, files: [] });
|
|
||||||
}, [taskAutoStart, taskStartText, isNewThread, handleSubmit]);
|
|
||||||
|
|
||||||
const handleClarificationSubmit = useCallback(
|
const handleClarificationSubmit = useCallback(
|
||||||
(answer: string) => {
|
(answer: string) => {
|
||||||
setHasStartedConversation(true);
|
setHasStartedConversation(true);
|
||||||
@@ -267,9 +181,6 @@ export default function AgentChatPage({
|
|||||||
}, [thread]);
|
}, [thread]);
|
||||||
|
|
||||||
const isLandingState = isNewThread && !hasStartedConversation;
|
const isLandingState = isNewThread && !hasStartedConversation;
|
||||||
// 任务闸门面板:仅 rwfx(taskGate)在新建对话且尚未开始时,于问答页顶部展示目的树 + 覆盖确认。
|
|
||||||
// 3qfx/xdfx(taskBind)不展示闸门,新建对话进问答页后由右上角「开始回答」按钮手动发出开场信息。
|
|
||||||
const showTaskGate = !!taskGate && !!taskId && isNewThread && !hasStartedConversation;
|
|
||||||
const isDemoMode = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
|
const isDemoMode = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
|
||||||
|
|
||||||
const status = thread.error
|
const status = thread.error
|
||||||
@@ -286,8 +197,6 @@ export default function AgentChatPage({
|
|||||||
always opens between the chat and the detail panel — the detail
|
always opens between the chat and the detail panel — the detail
|
||||||
panel stays rightmost. */}
|
panel stays rightmost. */}
|
||||||
<div className="flex size-full min-h-0 overflow-hidden workspace-chat-bg">
|
<div className="flex size-full min-h-0 overflow-hidden workspace-chat-bg">
|
||||||
{/* 最左:智能体列表栏(仅独立整页问答开启)。顶部下拉切换 我的/广场。 */}
|
|
||||||
{showAgentList && <AgentChatSidebar activeAgentId={agent_id} />}
|
|
||||||
<div className="min-h-0 min-w-0 flex-1">
|
<div className="min-h-0 min-w-0 flex-1">
|
||||||
<ChatBox threadId={threadId}>
|
<ChatBox threadId={threadId}>
|
||||||
{/* Main conversation column. `relative` hosts the floating
|
{/* Main conversation column. `relative` hosts the floating
|
||||||
@@ -310,18 +219,6 @@ export default function AgentChatPage({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
{/* 3qfx/xdfx 任务深链:用户主动「新建对话」进问答页后,点此发出任务开场信息开始问答。
|
|
||||||
首次进入且无历史(taskAutoStart)会自动发,不显示此按钮。 */}
|
|
||||||
{taskStartText && isLandingState && !taskAutoStart && (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
className="mr-1 bg-[var(--color-main)] text-white shadow-sm hover:bg-[var(--brand-950)]"
|
|
||||||
onClick={handleTaskStart}
|
|
||||||
disabled={isDemoMode}
|
|
||||||
>
|
|
||||||
开始回答
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Tooltip content={t.agents.newChat}>
|
<Tooltip content={t.agents.newChat}>
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
@@ -348,16 +245,6 @@ export default function AgentChatPage({
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{showTaskGate && (
|
|
||||||
<TaskPurposePanel
|
|
||||||
taskId={taskId}
|
|
||||||
onStart={handleGateStart}
|
|
||||||
// rwfx:仅「首次进入且无聊天对话历史」(taskAutoStart) 时,目的树为空才自动开始;
|
|
||||||
// 用户主动新建对话则需手动点「开始问答」。目的树有数据始终弹「覆盖并开始问答」确认。
|
|
||||||
autoStartWhenEmpty={!!autoStartWhenPurposeEmpty && taskAutoStart}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isLandingState ? (
|
{isLandingState ? (
|
||||||
/* Home: centered hero, suggested questions, and input.
|
/* Home: centered hero, suggested questions, and input.
|
||||||
Everything lives inside the scrollable main column. No fixed,
|
Everything lives inside the scrollable main column. No fixed,
|
||||||
@@ -468,7 +355,6 @@ export default function AgentChatPage({
|
|||||||
agentName={agentDisplayName}
|
agentName={agentDisplayName}
|
||||||
disabled={thread.isLoading || isDemoMode}
|
disabled={thread.isLoading || isDemoMode}
|
||||||
onAskQuestion={(text) => handleSubmit({ text, files: [] })}
|
onAskQuestion={(text) => handleSubmit({ text, files: [] })}
|
||||||
defaultCollapsed={taskCtxOn}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</ThreadContext.Provider>
|
</ThreadContext.Provider>
|
||||||
|
|||||||
@@ -75,9 +75,7 @@ function ModuleChatShell({ module }: { module: AgentModuleConfig }) {
|
|||||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// 外壳挂 workspace-chat-bg:深色下整片用同一张深蓝主题底图(fixed),作为左栏半透明
|
<div className="flex size-full min-h-0 overflow-hidden">
|
||||||
// 玻璃面板透出的「底色」;浅色透明无影响。右侧对话区自带同款底图,左右底色一致。
|
|
||||||
<div className="workspace-chat-bg flex size-full min-h-0 overflow-hidden">
|
|
||||||
<AgentModuleSidebar
|
<AgentModuleSidebar
|
||||||
moduleKey={module.key}
|
moduleKey={module.key}
|
||||||
activeAgentId={agent_id}
|
activeAgentId={agent_id}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { motion } from "motion/react";
|
|||||||
import { Select } from "tdesign-react";
|
import { Select } from "tdesign-react";
|
||||||
import {
|
import {
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
ArrowLeft,
|
|
||||||
HelpCircle,
|
HelpCircle,
|
||||||
Info,
|
Info,
|
||||||
Link2,
|
Link2,
|
||||||
@@ -22,7 +21,6 @@ import {
|
|||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
import { useTheme } from "@/contexts/ThemeContext";
|
||||||
import { useRouteNavigate } from "@/core/route-base";
|
|
||||||
import { listAgents } from "@/core/agents/api";
|
import { listAgents } from "@/core/agents/api";
|
||||||
import type { Agent } from "@/core/agents/types";
|
import type { Agent } from "@/core/agents/types";
|
||||||
import { listChains } from "@/roundtable-planning/api/chains";
|
import { listChains } from "@/roundtable-planning/api/chains";
|
||||||
@@ -36,7 +34,6 @@ import { cn } from "@/lib/utils";
|
|||||||
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
|
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
|
||||||
|
|
||||||
export default function BusinessChainMappingPage() {
|
export default function BusinessChainMappingPage() {
|
||||||
const navigate = useRouteNavigate();
|
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const isDark = theme === "dark";
|
const isDark = theme === "dark";
|
||||||
// 整片脱敏:业务链条映射页展示文本(链条名/描述/席位名/标题)。输入框 Hook 自动跳过。
|
// 整片脱敏:业务链条映射页展示文本(链条名/描述/席位名/标题)。输入框 Hook 自动跳过。
|
||||||
@@ -145,8 +142,8 @@ export default function BusinessChainMappingPage() {
|
|||||||
|
|
||||||
/* ── 样式 ── */
|
/* ── 样式 ── */
|
||||||
const shellClass = isDark
|
const shellClass = isDark
|
||||||
? "size-full min-h-0 overflow-y-auto text-slate-100 workspace-chat-bg"
|
? "h-full overflow-y-auto text-slate-100 workspace-chat-bg"
|
||||||
: "size-full min-h-0 overflow-y-auto bg-white text-[#222]";
|
: "h-full overflow-y-auto bg-white text-[#222]";
|
||||||
|
|
||||||
// 卡片:无边框,纯阴影
|
// 卡片:无边框,纯阴影
|
||||||
const cardClass = isDark
|
const cardClass = isDark
|
||||||
@@ -236,20 +233,6 @@ export default function BusinessChainMappingPage() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => navigate("/page/strategy/business-chains")}
|
|
||||||
className={cn(
|
|
||||||
"relative z-10 inline-flex shrink-0 items-center gap-1.5 rounded-[5px] border px-3.5 py-2 text-xs font-semibold transition-all active:scale-95",
|
|
||||||
isDark
|
|
||||||
? "border-white/10 bg-white/5 text-slate-300 hover:bg-white/10 hover:text-slate-100"
|
|
||||||
: "border-slate-200 bg-white text-slate-600 hover:bg-slate-50 hover:text-slate-900",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<ArrowLeft className="size-3.5" />
|
|
||||||
返回业务链条
|
|
||||||
</button>
|
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
{/* ── 表格区 ── */}
|
{/* ── 表格区 ── */}
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ import { QuestionNavigator } from "@/components/workspace/question-navigator";
|
|||||||
import { ThreadTitle } from "@/components/workspace/thread-title";
|
import { ThreadTitle } from "@/components/workspace/thread-title";
|
||||||
import { TodoList } from "@/components/workspace/todo-list";
|
import { TodoList } from "@/components/workspace/todo-list";
|
||||||
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
|
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
|
||||||
import { UserIdentityBadge } from "@/components/workspace/user-identity-badge";
|
|
||||||
import { Welcome } from "@/components/workspace/welcome";
|
import { Welcome } from "@/components/workspace/welcome";
|
||||||
import { CompactWelcome } from "@/components/workspace/compact-welcome";
|
import { CompactWelcome } from "@/components/workspace/compact-welcome";
|
||||||
import { readSidebarEnabled } from "@/core/page-layout/sidebar-enabled";
|
import { readSidebarEnabled } from "@/core/page-layout/sidebar-enabled";
|
||||||
@@ -482,17 +481,6 @@ export default function ChatPage() {
|
|||||||
<ExportTrigger threadId={threadId} />
|
<ExportTrigger threadId={threadId} />
|
||||||
<KnowledgeSaveTrigger threadId={threadId} />
|
<KnowledgeSaveTrigger threadId={threadId} />
|
||||||
<ArtifactTrigger />
|
<ArtifactTrigger />
|
||||||
{/* 不带全局顶栏(紧凑模式)时,名称+岗位回落到聊天页顶栏右侧,
|
|
||||||
与全量模式 Header 右上角保持一致。全量模式已有顶栏则不重复展示。 */}
|
|
||||||
{!compactChrome && (
|
|
||||||
<>
|
|
||||||
<div
|
|
||||||
className="bg-border/70 mx-1 h-6 w-px shrink-0"
|
|
||||||
aria-hidden
|
|
||||||
/>
|
|
||||||
<UserIdentityBadge />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<main className="flex min-h-0 max-w-full grow flex-col">
|
<main className="flex min-h-0 max-w-full grow flex-col">
|
||||||
|
|||||||
@@ -3,16 +3,13 @@
|
|||||||
*
|
*
|
||||||
* 深蓝主题适配见 `./light-app-management.css`(《深蓝色 UI 规范》tokens.css)。
|
* 深蓝主题适配见 `./light-app-management.css`(《深蓝色 UI 规范》tokens.css)。
|
||||||
*/
|
*/
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
AlignLeft,
|
AlignLeft,
|
||||||
ArrowDown,
|
|
||||||
ArrowUp,
|
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ChevronUp,
|
ChevronUp,
|
||||||
Copy,
|
Copy,
|
||||||
GripVertical,
|
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
FolderTree,
|
FolderTree,
|
||||||
Globe,
|
Globe,
|
||||||
@@ -242,68 +239,6 @@ export default function LightAppManagementPage() {
|
|||||||
[apps, categoryFilter, mountFilter],
|
[apps, categoryFilter, mountFilter],
|
||||||
);
|
);
|
||||||
|
|
||||||
// ── 排序调整:仅当「iframe 嵌套 + 指定某个挂载菜单」时开启 ──
|
|
||||||
// 同一菜单下的多个 iframe 子项可拖拽 / 上下移调整顺序;调整即写回各应用的 sortOrder,
|
|
||||||
// 侧栏(use-sidebar-menu 按列表顺序注入,后端按 sort_order 升序返回)随之同步。
|
|
||||||
const reorderable = categoryFilter === "iframe" && !!mountFilter && viewMode === "table";
|
|
||||||
// 乐观顺序覆盖(保存期间稳定显示,刷新回来与服务端一致);切换筛选/搜索即清空,回落服务端顺序。
|
|
||||||
const [orderIds, setOrderIds] = useState<string[] | null>(null);
|
|
||||||
const [reordering, setReordering] = useState(false);
|
|
||||||
const dragIndexRef = useRef<number | null>(null);
|
|
||||||
useEffect(() => {
|
|
||||||
setOrderIds(null);
|
|
||||||
}, [categoryFilter, mountFilter, search]);
|
|
||||||
|
|
||||||
const displayApps = useMemo(() => {
|
|
||||||
if (!reorderable || !orderIds) return tableApps;
|
|
||||||
const pos = new Map(orderIds.map((id, i) => [id, i] as const));
|
|
||||||
return [...tableApps].sort(
|
|
||||||
(a, b) => (pos.get(a.appId) ?? 1e9) - (pos.get(b.appId) ?? 1e9),
|
|
||||||
);
|
|
||||||
}, [reorderable, orderIds, tableApps]);
|
|
||||||
|
|
||||||
// 把整组按新顺序重排 sortOrder(组内 0-based;只 PUT 顺序变了的项),乐观先行。
|
|
||||||
const persistOrder = async (ordered: LightApp[]) => {
|
|
||||||
setOrderIds(ordered.map((a) => a.appId));
|
|
||||||
const changed = ordered.filter((a, i) => a.sortOrder !== i);
|
|
||||||
if (changed.length === 0) return;
|
|
||||||
setReordering(true);
|
|
||||||
try {
|
|
||||||
await Promise.all(
|
|
||||||
ordered.map((a, i) =>
|
|
||||||
a.sortOrder === i
|
|
||||||
? Promise.resolve()
|
|
||||||
: actions.update.mutateAsync({ appId: a.appId, patch: { sortOrder: i } }),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
toast.error((err as Error).message || "排序保存失败");
|
|
||||||
setOrderIds(null);
|
|
||||||
} finally {
|
|
||||||
setReordering(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const moveApp = (index: number, dir: -1 | 1) => {
|
|
||||||
if (reordering) return;
|
|
||||||
const target = index + dir;
|
|
||||||
if (target < 0 || target >= displayApps.length) return;
|
|
||||||
const next = [...displayApps];
|
|
||||||
[next[index], next[target]] = [next[target]!, next[index]!];
|
|
||||||
void persistOrder(next);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRowDrop = (toIndex: number) => {
|
|
||||||
const from = dragIndexRef.current;
|
|
||||||
dragIndexRef.current = null;
|
|
||||||
if (from === null || from === toIndex || reordering) return;
|
|
||||||
const next = [...displayApps];
|
|
||||||
const [moved] = next.splice(from, 1);
|
|
||||||
if (!moved) return;
|
|
||||||
next.splice(toIndex, 0, moved);
|
|
||||||
void persistOrder(next);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="light-app-management-page h-full overflow-y-auto bg-neutral-50 dark:bg-[#0C1836] dark:text-[#C5CFE0]">
|
<div className="light-app-management-page h-full overflow-y-auto bg-neutral-50 dark:bg-[#0C1836] dark:text-[#C5CFE0]">
|
||||||
<div className="mx-auto flex min-h-full w-full max-w-7xl flex-col space-y-7 px-8 py-8">
|
<div className="mx-auto flex min-h-full w-full max-w-7xl flex-col space-y-7 px-8 py-8">
|
||||||
@@ -414,18 +349,9 @@ export default function LightAppManagementPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="lam-count flex flex-wrap items-center gap-x-3 gap-y-1 text-xs font-medium text-neutral-500">
|
<div className="lam-count text-xs font-medium text-neutral-500">
|
||||||
<span>
|
搜寻到 <strong className="font-bold text-[#F5222D]">{tableApps.length}</strong>{" "}
|
||||||
搜寻到 <strong className="font-bold text-[#F5222D]">{tableApps.length}</strong>{" "}
|
个注册完成的子模块轻应用
|
||||||
个注册完成的子模块轻应用
|
|
||||||
</span>
|
|
||||||
{reorderable && (
|
|
||||||
<span className="inline-flex items-center gap-1 text-[11px] text-sky-600">
|
|
||||||
<GripVertical className="h-3.5 w-3.5" />
|
|
||||||
拖拽行或用上 / 下按钮调整「{mountLabel(mountFilter)}」下的菜单顺序,调整即生效
|
|
||||||
{reordering && <span className="text-neutral-400">· 保存中…</span>}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{viewMode === "table" ? (
|
{viewMode === "table" ? (
|
||||||
@@ -433,7 +359,6 @@ export default function LightAppManagementPage() {
|
|||||||
<table className="lam-table w-full table-fixed border-collapse text-left">
|
<table className="lam-table w-full table-fixed border-collapse text-left">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="select-none border-b border-neutral-100/80 bg-neutral-50/40 text-[12.5px] font-semibold text-neutral-500">
|
<tr className="select-none border-b border-neutral-100/80 bg-neutral-50/40 text-[12.5px] font-semibold text-neutral-500">
|
||||||
{reorderable && <th className="w-[44px] px-2 py-4" aria-label="拖拽排序" />}
|
|
||||||
<th className="w-[15%] px-6 py-4">名称</th>
|
<th className="w-[15%] px-6 py-4">名称</th>
|
||||||
<th className="w-[14%] px-4 py-4">类型</th>
|
<th className="w-[14%] px-4 py-4">类型</th>
|
||||||
<th className="w-[27%] px-4 py-4">地址</th>
|
<th className="w-[27%] px-4 py-4">地址</th>
|
||||||
@@ -444,32 +369,8 @@ export default function LightAppManagementPage() {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-neutral-100">
|
<tbody className="divide-y divide-neutral-100">
|
||||||
{displayApps.map((app, index) => (
|
{tableApps.map((app) => (
|
||||||
<tr
|
<tr key={app.appId} className="group align-middle transition-colors hover:bg-neutral-50/40">
|
||||||
key={app.appId}
|
|
||||||
className={`group align-middle transition-colors hover:bg-neutral-50/40 ${
|
|
||||||
reorderable ? "lam-reorder-row" : ""
|
|
||||||
}`}
|
|
||||||
draggable={reorderable}
|
|
||||||
onDragStart={
|
|
||||||
reorderable
|
|
||||||
? (e) => {
|
|
||||||
dragIndexRef.current = index;
|
|
||||||
e.dataTransfer.effectAllowed = "move";
|
|
||||||
}
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
onDragOver={reorderable ? (e) => e.preventDefault() : undefined}
|
|
||||||
onDrop={reorderable ? () => handleRowDrop(index) : undefined}
|
|
||||||
>
|
|
||||||
{reorderable && (
|
|
||||||
<td className="px-2 py-[18px] text-center">
|
|
||||||
<GripVertical
|
|
||||||
className="lam-drag-handle mx-auto h-4 w-4 cursor-grab text-neutral-300"
|
|
||||||
aria-hidden
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
)}
|
|
||||||
<td className="px-6 py-[18px]">
|
<td className="px-6 py-[18px]">
|
||||||
<span className="lam-row-name text-[14px] font-bold text-neutral-800 transition-colors group-hover:text-[#F5222D]">
|
<span className="lam-row-name text-[14px] font-bold text-neutral-800 transition-colors group-hover:text-[#F5222D]">
|
||||||
{app.name}
|
{app.name}
|
||||||
@@ -604,29 +505,6 @@ export default function LightAppManagementPage() {
|
|||||||
|
|
||||||
<td className="px-4 py-[18px] pr-6 text-center">
|
<td className="px-4 py-[18px] pr-6 text-center">
|
||||||
<div className="flex items-center justify-center space-x-1">
|
<div className="flex items-center justify-center space-x-1">
|
||||||
{reorderable && (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
disabled={index === 0 || reordering}
|
|
||||||
onClick={() => moveApp(index, -1)}
|
|
||||||
className="lam-icon-btn cursor-pointer rounded-[5px] p-1 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-[#F5222D] disabled:cursor-not-allowed disabled:opacity-30"
|
|
||||||
title="上移"
|
|
||||||
>
|
|
||||||
<ArrowUp className="h-3.5 w-3.5" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
disabled={index === displayApps.length - 1 || reordering}
|
|
||||||
onClick={() => moveApp(index, 1)}
|
|
||||||
className="lam-icon-btn cursor-pointer rounded-[5px] p-1 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-[#F5222D] disabled:cursor-not-allowed disabled:opacity-30"
|
|
||||||
title="下移"
|
|
||||||
>
|
|
||||||
<ArrowDown className="h-3.5 w-3.5" />
|
|
||||||
</button>
|
|
||||||
<span className="mx-0.5 h-4 w-px shrink-0 bg-neutral-200" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<button
|
<button
|
||||||
onClick={() => openEdit(app)}
|
onClick={() => openEdit(app)}
|
||||||
className="lam-icon-btn cursor-pointer rounded-[5px] p-1.5 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-emerald-600"
|
className="lam-icon-btn cursor-pointer rounded-[5px] p-1.5 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-emerald-600"
|
||||||
@@ -646,9 +524,9 @@ export default function LightAppManagementPage() {
|
|||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{displayApps.length === 0 && (
|
{tableApps.length === 0 && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={reorderable ? 8 : 7} className="py-12 text-center">
|
<td colSpan={7} className="py-12 text-center">
|
||||||
<div className="flex flex-col items-center justify-center space-y-3">
|
<div className="flex flex-col items-center justify-center space-y-3">
|
||||||
<div className="lam-empty-icon flex h-12 w-12 items-center justify-center rounded-full bg-neutral-100 text-neutral-300">
|
<div className="lam-empty-icon flex h-12 w-12 items-center justify-center rounded-full bg-neutral-100 text-neutral-300">
|
||||||
<Info className="h-6 w-6" />
|
<Info className="h-6 w-6" />
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
|
||||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { ToolMetricsPanel } from "@/components/workspace/admin/tool-metrics-panel";
|
import { ToolMetricsPanel } from "@/components/workspace/admin/tool-metrics-panel";
|
||||||
import {
|
import {
|
||||||
@@ -495,18 +494,14 @@ function Td({
|
|||||||
export default function LlmMetricsPage() {
|
export default function LlmMetricsPage() {
|
||||||
const [tab, setTab] = useState<"llm" | "tool">("llm");
|
const [tab, setTab] = useState<"llm" | "tool">("llm");
|
||||||
return (
|
return (
|
||||||
<div className="flex size-full min-h-0 w-full">
|
<div className="mx-auto flex w-full max-w-6xl flex-col gap-4 px-6 py-8">
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
<Tabs value={tab} onValueChange={(v) => setTab(v as "llm" | "tool")}>
|
||||||
<div className="mx-auto flex w-full max-w-6xl flex-col gap-4 px-6 py-8">
|
<TabsList>
|
||||||
<Tabs value={tab} onValueChange={(v) => setTab(v as "llm" | "tool")}>
|
<TabsTrigger value="llm">大模型调用</TabsTrigger>
|
||||||
<TabsList>
|
<TabsTrigger value="tool">工具调用</TabsTrigger>
|
||||||
<TabsTrigger value="llm">大模型调用</TabsTrigger>
|
</TabsList>
|
||||||
<TabsTrigger value="tool">工具调用</TabsTrigger>
|
</Tabs>
|
||||||
</TabsList>
|
{tab === "llm" ? <LlmMetricsPanel /> : <ToolMetricsPanel />}
|
||||||
</Tabs>
|
|
||||||
{tab === "llm" ? <LlmMetricsPanel /> : <ToolMetricsPanel />}
|
|
||||||
</div>
|
|
||||||
</ScrollArea>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -15,12 +15,10 @@ import {
|
|||||||
import {
|
import {
|
||||||
fetchCopTaskDetail,
|
fetchCopTaskDetail,
|
||||||
persistCopTaskDetail,
|
persistCopTaskDetail,
|
||||||
resolveDeeplinkTaskId,
|
|
||||||
resolveTaskDeeplinkTarget,
|
resolveTaskDeeplinkTarget,
|
||||||
} from '@/core/auth/task-deeplink';
|
} from '@/core/auth/task-deeplink';
|
||||||
import { resolveUsernameByOnlineTicket } from '@/core/auth/wujie-ticket-login';
|
import { resolveUsernameByOnlineTicket } from '@/core/auth/wujie-ticket-login';
|
||||||
import { isWujieEnv, useWujieProps } from '@/core/embed/wujie';
|
import { isWujieEnv, useWujieProps } from '@/core/embed/wujie';
|
||||||
import { readEmbedParam } from '@/core/embed/embed-session';
|
|
||||||
import {
|
import {
|
||||||
GENERAL_QA_ROUTE,
|
GENERAL_QA_ROUTE,
|
||||||
loginByYUserId,
|
loginByYUserId,
|
||||||
@@ -49,13 +47,6 @@ export default function LoginPage() {
|
|||||||
() => isSidebarEnabledFromSearch(searchParams.toString()),
|
() => isSidebarEnabledFromSearch(searchParams.toString()),
|
||||||
[searchParams],
|
[searchParams],
|
||||||
);
|
);
|
||||||
// iframe 嵌入模式(外部系统 `&embed=1`):去 chrome + 按标签页强制主题。嵌入侧**不**走
|
|
||||||
// setTheme / persistSidebarEnabled(那俩落 localStorage、会跨标签污染正常系统页),改用
|
|
||||||
// sessionStorage 嵌入会话(见 embed-session.ts)。`embed=0` 显式关闭。
|
|
||||||
const isEmbed = useMemo(
|
|
||||||
() => readEmbedParam(searchParams.toString()) === 'on',
|
|
||||||
[searchParams],
|
|
||||||
);
|
|
||||||
const redirectPath = useMemo(
|
const redirectPath = useMemo(
|
||||||
() =>
|
() =>
|
||||||
searchParams.get('from') === IFRAME_LOGIN_SOURCE
|
searchParams.get('from') === IFRAME_LOGIN_SOURCE
|
||||||
@@ -113,14 +104,11 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
// 主题切换:无界 props.theme 优先,其次 URL query theme。两者取值约定一致
|
// 主题切换:无界 props.theme 优先,其次 URL query theme。两者取值约定一致
|
||||||
// (dark-blue → 深色;red → 浅色;blue 暂无该主题,先用浅色代替),统一走 resolveThemeFromQuery。
|
// (dark-blue → 深色;red → 浅色;blue 暂无该主题,先用浅色代替),统一走 resolveThemeFromQuery。
|
||||||
// **嵌入模式跳过**:setTheme 会写 localStorage `strategy-theme`,跨标签污染正常系统页;
|
|
||||||
// 嵌入主题改由 forcedTheme(按标签页、不持久化)接管。
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isEmbed) return;
|
|
||||||
const themeValue = wujieProps.theme || externalParams.theme;
|
const themeValue = wujieProps.theme || externalParams.theme;
|
||||||
if (!themeValue) return;
|
if (!themeValue) return;
|
||||||
setTheme(resolveThemeFromQuery(themeValue));
|
setTheme(resolveThemeFromQuery(themeValue));
|
||||||
}, [isEmbed, wujieProps.theme, externalParams.theme, setTheme]);
|
}, [wujieProps.theme, externalParams.theme, setTheme]);
|
||||||
|
|
||||||
// ticket / userId / env 持久化(与 login 请求并行做,互不阻塞)
|
// ticket / userId / env 持久化(与 login 请求并行做,互不阻塞)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -165,23 +153,18 @@ export default function LoginPage() {
|
|||||||
// 内网透传的 access_token 合并进 userInfo(在 loginByYUserId 覆盖之后),
|
// 内网透传的 access_token 合并进 userInfo(在 loginByYUserId 覆盖之后),
|
||||||
// XK/PG 中任务 iframe 据此取 accessToken
|
// XK/PG 中任务 iframe 据此取 accessToken
|
||||||
persistAccessToken(accessToken);
|
persistAccessToken(accessToken);
|
||||||
// 嵌入模式不写 sidebarEnabled(localStorage 的「简洁/全量」偏好会跨标签污染正常页);
|
persistSidebarEnabled(sidebarEnabled);
|
||||||
// 去 chrome 由按标签页的嵌入会话(isEmbedActive)驱动,见 PageLayout。
|
|
||||||
if (!isEmbed) persistSidebarEnabled(sidebarEnabled);
|
|
||||||
setStatus('success');
|
setStatus('success');
|
||||||
|
|
||||||
// 任务深链:带 taskId + goPath 时拉任务详情并直送对应问答/会商页;
|
// 任务深链:带 taskId + goPath 时拉任务详情并直送对应问答/会商页;
|
||||||
// 任一环节失败(无地址/拉取失败/未配置智能体/goPath 无法识别)都回退默认首页。
|
// 任一环节失败(无地址/拉取失败/未配置智能体/goPath 无法识别)都回退默认首页。
|
||||||
if (taskId && goPath) {
|
if (taskId && goPath) {
|
||||||
try {
|
try {
|
||||||
// xdfx 深链 ?taskId= 传入的是「行动id」,先换成真正的「任务id」;其它业务原样。
|
const detail = await fetchCopTaskDetail(taskId);
|
||||||
const realTaskId = await resolveDeeplinkTaskId(goPath, taskId);
|
|
||||||
if (cancelled) return;
|
|
||||||
const detail = await fetchCopTaskDetail(realTaskId);
|
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
if (detail) {
|
if (detail) {
|
||||||
persistCopTaskDetail(detail);
|
persistCopTaskDetail(detail);
|
||||||
const target = await resolveTaskDeeplinkTarget(goPath, detail, realTaskId, taskId);
|
const target = await resolveTaskDeeplinkTarget(goPath, detail);
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
if (target) {
|
if (target) {
|
||||||
navigate(target.path, { replace: true, state: target.state });
|
navigate(target.path, { replace: true, state: target.state });
|
||||||
@@ -222,7 +205,6 @@ export default function LoginPage() {
|
|||||||
gatePassword,
|
gatePassword,
|
||||||
taskId,
|
taskId,
|
||||||
goPath,
|
goPath,
|
||||||
isEmbed,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { MemorySettingsPage } from "@/components/workspace/settings/memory-setti
|
|||||||
|
|
||||||
export default function MemoryPage() {
|
export default function MemoryPage() {
|
||||||
return (
|
return (
|
||||||
<div className="flex size-full min-h-0 flex-col overflow-auto p-6">
|
<div className="flex flex-col h-full overflow-auto p-6">
|
||||||
<MemorySettingsPage />
|
<MemorySettingsPage />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,895 +0,0 @@
|
|||||||
/**
|
|
||||||
* 菜单管理页(仅管理员)。
|
|
||||||
*
|
|
||||||
* 管理整棵侧边栏菜单(一级 / 二级 / 三级),含通过「应用管理」注入的 iframe 轻应用节点。
|
|
||||||
* 编辑结果以「覆盖层」形式保存到后端 `/api/menu-overrides`,不改动代码里的静态菜单。
|
|
||||||
*
|
|
||||||
* 支持:
|
|
||||||
* - 改名 / 停用 / 启用(编辑弹窗)
|
|
||||||
* - 同级上下移动(↑ ↓ 箭头)
|
|
||||||
* - 拖拽调整顺序 + 跨层级移动(横向拖动改变层级,严格 ≤ 3 级)
|
|
||||||
* - 「移动到」父级选择器(拖拽之外的第二种调层级方式,键盘可达)
|
|
||||||
* - 保存 / 重置全部
|
|
||||||
*/
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
|
||||||
import { Navigate } from "react-router-dom";
|
|
||||||
import {
|
|
||||||
DndContext,
|
|
||||||
DragOverlay,
|
|
||||||
PointerSensor,
|
|
||||||
closestCenter,
|
|
||||||
useSensor,
|
|
||||||
useSensors,
|
|
||||||
type DragEndEvent,
|
|
||||||
type DragMoveEvent,
|
|
||||||
type DragStartEvent,
|
|
||||||
} from "@dnd-kit/core";
|
|
||||||
import {
|
|
||||||
SortableContext,
|
|
||||||
arrayMove,
|
|
||||||
useSortable,
|
|
||||||
verticalListSortingStrategy,
|
|
||||||
} from "@dnd-kit/sortable";
|
|
||||||
import { CSS } from "@dnd-kit/utilities";
|
|
||||||
import {
|
|
||||||
ChevronDown,
|
|
||||||
ChevronRight,
|
|
||||||
ChevronsLeft,
|
|
||||||
ChevronsRight,
|
|
||||||
ChevronUp,
|
|
||||||
GripVertical,
|
|
||||||
Info,
|
|
||||||
Menu,
|
|
||||||
Pencil,
|
|
||||||
RotateCcw,
|
|
||||||
Save,
|
|
||||||
Search,
|
|
||||||
Sparkles,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Switch } from "@/components/ui/switch";
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
|
||||||
import {
|
|
||||||
MAX_MENU_DEPTH,
|
|
||||||
diffOverrides,
|
|
||||||
flattenMenu,
|
|
||||||
isDescendant,
|
|
||||||
mergeFlatNodes,
|
|
||||||
wouldExceedDepth,
|
|
||||||
type MenuOverride,
|
|
||||||
type MergedMenuNode,
|
|
||||||
} from "@/core/page-layout/menu-overrides";
|
|
||||||
import { sidebarMenuItems, type MenuItem } from "@/core/page-layout/sidebar-menu";
|
|
||||||
import { injectLightApps } from "@/core/page-layout/use-sidebar-menu";
|
|
||||||
import { useLightApps } from "@/strategy-components/api/light-apps";
|
|
||||||
import {
|
|
||||||
useMenuOverrideActions,
|
|
||||||
useMenuOverrides,
|
|
||||||
} from "@/strategy-components/api/menu-overrides";
|
|
||||||
|
|
||||||
const INDENT = 22;
|
|
||||||
|
|
||||||
/** 编辑器内部的扁平行(数组顺序 = DFS 显示顺序,同级连续)。 */
|
|
||||||
interface FlatRow {
|
|
||||||
id: string;
|
|
||||||
parentId: string | null;
|
|
||||||
label: string;
|
|
||||||
disabled: boolean;
|
|
||||||
source: MenuItem;
|
|
||||||
defaultLabel: string;
|
|
||||||
defaultParentId: string | null;
|
|
||||||
defaultIndex: number;
|
|
||||||
isLightApp: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 扁平行工具 ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/** 按 parentId 分组、DFS 重排,使每个节点的子节点紧跟其后(同级保持相遇顺序)。 */
|
|
||||||
function normalizeDfs(list: FlatRow[]): FlatRow[] {
|
|
||||||
const childrenOf = new Map<string | null, FlatRow[]>();
|
|
||||||
for (const r of list) {
|
|
||||||
const key = r.parentId ?? null;
|
|
||||||
const arr = childrenOf.get(key) ?? [];
|
|
||||||
arr.push(r);
|
|
||||||
childrenOf.set(key, arr);
|
|
||||||
}
|
|
||||||
const out: FlatRow[] = [];
|
|
||||||
const walk = (pid: string | null) => {
|
|
||||||
for (const node of childrenOf.get(pid) ?? []) {
|
|
||||||
out.push(node);
|
|
||||||
walk(node.id);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
walk(null);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergedToRows(merged: MergedMenuNode[]): FlatRow[] {
|
|
||||||
const childrenOf = new Map<string | null, MergedMenuNode[]>();
|
|
||||||
for (const n of merged) {
|
|
||||||
const key = n.parentId ?? null;
|
|
||||||
const arr = childrenOf.get(key) ?? [];
|
|
||||||
arr.push(n);
|
|
||||||
childrenOf.set(key, arr);
|
|
||||||
}
|
|
||||||
const rows: FlatRow[] = [];
|
|
||||||
const walk = (pid: string | null) => {
|
|
||||||
(childrenOf.get(pid) ?? [])
|
|
||||||
.slice()
|
|
||||||
.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
|
|
||||||
.forEach((n) => {
|
|
||||||
rows.push({
|
|
||||||
id: n.id,
|
|
||||||
parentId: n.parentId ?? null,
|
|
||||||
label: n.label,
|
|
||||||
disabled: n.disabled,
|
|
||||||
source: n.source,
|
|
||||||
defaultLabel: n.defaultLabel,
|
|
||||||
defaultParentId: n.defaultParentId,
|
|
||||||
defaultIndex: n.defaultIndex,
|
|
||||||
isLightApp: n.isLightApp,
|
|
||||||
});
|
|
||||||
walk(n.id);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
walk(null);
|
|
||||||
return rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 扁平行 → 合并节点(order = 同级内位置),供 diff / 深度校验复用。 */
|
|
||||||
function rowsToMerged(rows: FlatRow[]): MergedMenuNode[] {
|
|
||||||
const counter = new Map<string | null, number>();
|
|
||||||
return rows.map((r) => {
|
|
||||||
const key = r.parentId ?? null;
|
|
||||||
const order = counter.get(key) ?? 0;
|
|
||||||
counter.set(key, order + 1);
|
|
||||||
return {
|
|
||||||
id: r.id,
|
|
||||||
defaultLabel: r.defaultLabel,
|
|
||||||
defaultParentId: r.defaultParentId,
|
|
||||||
defaultIndex: r.defaultIndex,
|
|
||||||
source: r.source,
|
|
||||||
isLightApp: r.isLightApp,
|
|
||||||
label: r.label,
|
|
||||||
parentId: r.parentId ?? null,
|
|
||||||
order,
|
|
||||||
disabled: r.disabled,
|
|
||||||
hasOverride: false,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function depthByIdOf(rows: FlatRow[]): Map<string, number> {
|
|
||||||
const parentOf = new Map(rows.map((r) => [r.id, r.parentId]));
|
|
||||||
const cache = new Map<string, number>();
|
|
||||||
const compute = (id: string): number => {
|
|
||||||
if (cache.has(id)) return cache.get(id)!;
|
|
||||||
const pid = parentOf.get(id) ?? null;
|
|
||||||
const d = pid == null ? 1 : compute(pid) + 1;
|
|
||||||
cache.set(id, d);
|
|
||||||
return d;
|
|
||||||
};
|
|
||||||
for (const r of rows) compute(r.id);
|
|
||||||
return cache;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 可排序行 ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
interface SortableRowProps {
|
|
||||||
row: FlatRow;
|
|
||||||
depth: number;
|
|
||||||
canUp: boolean;
|
|
||||||
canDown: boolean;
|
|
||||||
canIndent: boolean;
|
|
||||||
canOutdent: boolean;
|
|
||||||
dragEnabled: boolean;
|
|
||||||
onUp: () => void;
|
|
||||||
onDown: () => void;
|
|
||||||
onIndent: () => void;
|
|
||||||
onOutdent: () => void;
|
|
||||||
onToggle: () => void;
|
|
||||||
onEdit: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 一级 / 二级 / 三级 的层级色标。 */
|
|
||||||
const LEVEL_BADGE = [
|
|
||||||
"bg-blue-50 text-blue-600 border border-blue-100",
|
|
||||||
"bg-purple-50 text-purple-600 border border-purple-100",
|
|
||||||
"bg-indigo-50 text-indigo-600 border border-indigo-100",
|
|
||||||
];
|
|
||||||
|
|
||||||
function SortableRow({
|
|
||||||
row,
|
|
||||||
depth,
|
|
||||||
canUp,
|
|
||||||
canDown,
|
|
||||||
canIndent,
|
|
||||||
canOutdent,
|
|
||||||
dragEnabled,
|
|
||||||
onUp,
|
|
||||||
onDown,
|
|
||||||
onIndent,
|
|
||||||
onOutdent,
|
|
||||||
onToggle,
|
|
||||||
onEdit,
|
|
||||||
}: SortableRowProps) {
|
|
||||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
|
||||||
id: row.id,
|
|
||||||
});
|
|
||||||
const Icon = row.source.icon;
|
|
||||||
const levelLabel = ["一级", "二级", "三级"][depth - 1] ?? `${depth}级`;
|
|
||||||
const typeLabel = row.isLightApp ? "应用" : "内置";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
ref={setNodeRef}
|
|
||||||
style={{
|
|
||||||
transform: CSS.Transform.toString(transform),
|
|
||||||
transition,
|
|
||||||
marginLeft: (depth - 1) * INDENT,
|
|
||||||
opacity: isDragging ? 0.4 : 1,
|
|
||||||
}}
|
|
||||||
className={`group relative flex flex-col gap-3 rounded-2xl border p-3.5 transition-all md:flex-row md:items-center md:justify-between ${
|
|
||||||
row.disabled
|
|
||||||
? "border-slate-100 bg-slate-50/40"
|
|
||||||
: "border-slate-200/70 bg-white shadow-[0_1px_4px_-1px_rgba(0,0,0,0.04)] hover:border-slate-300 hover:shadow-[0_4px_16px_-4px_rgba(0,0,0,0.08)]"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{/* 左侧:拖拽柄 + 图标 + 名称/路径 */}
|
|
||||||
<div className="flex min-w-0 items-center gap-3">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`shrink-0 rounded p-1 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600 ${
|
|
||||||
dragEnabled ? "cursor-grab touch-none active:cursor-grabbing" : "cursor-not-allowed opacity-40"
|
|
||||||
}`}
|
|
||||||
title={dragEnabled ? "拖动调整顺序与层级" : "筛选状态下不可拖动"}
|
|
||||||
{...(dragEnabled ? attributes : {})}
|
|
||||||
{...(dragEnabled ? listeners : {})}
|
|
||||||
>
|
|
||||||
<GripVertical className="size-4" />
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{depth > 1 && (
|
|
||||||
<ChevronRight className="hidden size-3.5 shrink-0 stroke-[2.5] text-slate-300 sm:block" />
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onEdit}
|
|
||||||
className={`shrink-0 rounded-xl p-2.5 transition-all ${
|
|
||||||
row.disabled
|
|
||||||
? "bg-slate-100 text-slate-400"
|
|
||||||
: "bg-red-50 text-red-600 hover:scale-105 hover:bg-red-100"
|
|
||||||
}`}
|
|
||||||
title="点击修改菜单详情"
|
|
||||||
>
|
|
||||||
<Icon className="size-[18px]" />
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onEdit}
|
|
||||||
className={`truncate text-sm font-semibold transition-colors hover:text-red-600 ${
|
|
||||||
row.disabled ? "text-slate-400 line-through" : "text-slate-800"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{row.label}
|
|
||||||
</button>
|
|
||||||
<span
|
|
||||||
className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${LEVEL_BADGE[depth - 1] ?? LEVEL_BADGE[2]}`}
|
|
||||||
>
|
|
||||||
{levelLabel}
|
|
||||||
</span>
|
|
||||||
<span className="rounded border border-slate-200/60 bg-slate-100 px-1.5 py-0.5 font-mono text-[10px] font-medium text-slate-500">
|
|
||||||
{typeLabel}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 右侧:层级/排序按钮组 + 状态 + 编辑 */}
|
|
||||||
<div className="flex items-center justify-between gap-2.5 border-t border-slate-100 pt-2.5 md:justify-end md:border-t-0 md:pt-0">
|
|
||||||
<div className="flex items-center rounded-xl border border-slate-200/70 bg-slate-50/80 p-0.5 text-slate-500">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onOutdent}
|
|
||||||
disabled={!canOutdent}
|
|
||||||
className="rounded-lg p-1.5 transition-colors hover:bg-white hover:text-slate-800 disabled:opacity-20 disabled:hover:bg-transparent"
|
|
||||||
title="升一级"
|
|
||||||
>
|
|
||||||
<ChevronsLeft className="size-3.5" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onIndent}
|
|
||||||
disabled={!canIndent}
|
|
||||||
className="rounded-lg p-1.5 transition-colors hover:bg-white hover:text-slate-800 disabled:opacity-20 disabled:hover:bg-transparent"
|
|
||||||
title="降一级"
|
|
||||||
>
|
|
||||||
<ChevronsRight className="size-3.5" />
|
|
||||||
</button>
|
|
||||||
<div className="mx-1 h-4 w-px bg-slate-200" />
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onUp}
|
|
||||||
disabled={!canUp}
|
|
||||||
className="rounded-lg p-1.5 transition-colors hover:bg-white hover:text-slate-800 disabled:opacity-20 disabled:hover:bg-transparent"
|
|
||||||
title="上移"
|
|
||||||
>
|
|
||||||
<ChevronUp className="size-3.5" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onDown}
|
|
||||||
disabled={!canDown}
|
|
||||||
className="rounded-lg p-1.5 transition-colors hover:bg-white hover:text-slate-800 disabled:opacity-20 disabled:hover:bg-transparent"
|
|
||||||
title="下移"
|
|
||||||
>
|
|
||||||
<ChevronDown className="size-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onToggle}
|
|
||||||
className={`inline-flex select-none items-center gap-1.5 rounded-xl px-3 py-1.5 text-xs font-semibold transition-all ${
|
|
||||||
row.disabled
|
|
||||||
? "bg-slate-100 text-slate-400 hover:bg-slate-200 hover:text-slate-600"
|
|
||||||
: "border border-emerald-200/50 bg-emerald-50 text-emerald-600 hover:bg-emerald-100"
|
|
||||||
}`}
|
|
||||||
title="点击切换启用 / 停用"
|
|
||||||
>
|
|
||||||
<span className={`size-1.5 shrink-0 rounded-full ${row.disabled ? "bg-slate-400" : "bg-emerald-500"}`} />
|
|
||||||
{row.disabled ? "停用中" : "启用中"}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onEdit}
|
|
||||||
className="rounded-lg p-1.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-700"
|
|
||||||
title="编辑"
|
|
||||||
>
|
|
||||||
<Pencil className="size-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 主页面 ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export default function MenuManagementPage() {
|
|
||||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
|
||||||
// 与侧边栏一致:只取「启用的 iframe 轻应用」作为合并基树,避免管理树与实际渲染脱节。
|
|
||||||
const { data: iframeApps = [] } = useLightApps({ appType: "iframe", enabledOnly: true });
|
|
||||||
const { data: overrides = [], isLoading } = useMenuOverrides();
|
|
||||||
const { save } = useMenuOverrideActions();
|
|
||||||
|
|
||||||
const baseTree = useMemo(() => injectLightApps(sidebarMenuItems, iframeApps), [iframeApps]);
|
|
||||||
|
|
||||||
// 初始扁平行(套用已保存覆盖层,含停用项)。
|
|
||||||
const initialRows = useMemo(
|
|
||||||
() => mergedToRows(mergeFlatNodes(flattenMenu(baseTree), overrides)),
|
|
||||||
[baseTree, overrides],
|
|
||||||
);
|
|
||||||
|
|
||||||
const [rows, setRows] = useState<FlatRow[]>(initialRows);
|
|
||||||
const [loadedKey, setLoadedKey] = useState("");
|
|
||||||
const [editId, setEditId] = useState<string | null>(null);
|
|
||||||
const [activeId, setActiveId] = useState<string | null>(null);
|
|
||||||
const [offsetX, setOffsetX] = useState(0);
|
|
||||||
const [query, setQuery] = useState("");
|
|
||||||
const [statusFilter, setStatusFilter] = useState<"all" | "active" | "inactive">("all");
|
|
||||||
|
|
||||||
// 数据首次/变化加载时,用服务端值重置工作副本(避免覆盖用户未保存的编辑:以来源 key 判定)。
|
|
||||||
const sourceKey = useMemo(
|
|
||||||
() => JSON.stringify({ a: iframeApps.map((x) => x.appId), o: overrides }),
|
|
||||||
[iframeApps, overrides],
|
|
||||||
);
|
|
||||||
useEffect(() => {
|
|
||||||
if (sourceKey !== loadedKey) {
|
|
||||||
setRows(initialRows);
|
|
||||||
setLoadedKey(sourceKey);
|
|
||||||
}
|
|
||||||
}, [sourceKey, loadedKey, initialRows]);
|
|
||||||
|
|
||||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
|
|
||||||
|
|
||||||
const depthById = useMemo(() => depthByIdOf(rows), [rows]);
|
|
||||||
const mergedNow = useMemo(() => rowsToMerged(rows), [rows]);
|
|
||||||
const currentOverrides = useMemo(() => diffOverrides(mergedNow), [mergedNow]);
|
|
||||||
|
|
||||||
const dirty = useMemo(() => {
|
|
||||||
const norm = (list: MenuOverride[]) =>
|
|
||||||
JSON.stringify(
|
|
||||||
list
|
|
||||||
.map((o) => ({ ...o, label: o.label ?? null, parentId: o.parentId ?? null }))
|
|
||||||
.sort((a, b) => a.nodeId.localeCompare(b.nodeId)),
|
|
||||||
);
|
|
||||||
return norm(currentOverrides) !== norm(overrides);
|
|
||||||
}, [currentOverrides, overrides]);
|
|
||||||
|
|
||||||
const editingRow = rows.find((r) => r.id === editId) ?? null;
|
|
||||||
|
|
||||||
const isFiltering = query.trim() !== "" || statusFilter !== "all";
|
|
||||||
const visibleRows = useMemo(() => {
|
|
||||||
const q = query.trim().toLowerCase();
|
|
||||||
return rows.filter((r) => {
|
|
||||||
const matchQ = !q || r.label.toLowerCase().includes(q);
|
|
||||||
const matchS =
|
|
||||||
statusFilter === "all" ||
|
|
||||||
(statusFilter === "active" && !r.disabled) ||
|
|
||||||
(statusFilter === "inactive" && r.disabled);
|
|
||||||
return matchQ && matchS;
|
|
||||||
});
|
|
||||||
}, [rows, query, statusFilter]);
|
|
||||||
|
|
||||||
// ── 行操作 ──
|
|
||||||
const siblingsOf = (parentId: string | null) => rows.filter((r) => (r.parentId ?? null) === (parentId ?? null));
|
|
||||||
|
|
||||||
const reorderBefore = (moveId: string, beforeId: string) => {
|
|
||||||
setRows((prev) => {
|
|
||||||
const from = prev.findIndex((r) => r.id === moveId);
|
|
||||||
const to = prev.findIndex((r) => r.id === beforeId);
|
|
||||||
if (from < 0 || to < 0) return prev;
|
|
||||||
return normalizeDfs(arrayMove(prev, from, to));
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const moveUp = (row: FlatRow) => {
|
|
||||||
const sibs = siblingsOf(row.parentId);
|
|
||||||
const i = sibs.findIndex((s) => s.id === row.id);
|
|
||||||
if (i > 0) reorderBefore(row.id, sibs[i - 1].id);
|
|
||||||
};
|
|
||||||
const moveDown = (row: FlatRow) => {
|
|
||||||
const sibs = siblingsOf(row.parentId);
|
|
||||||
const i = sibs.findIndex((s) => s.id === row.id);
|
|
||||||
if (i >= 0 && i < sibs.length - 1) reorderBefore(sibs[i + 1].id, row.id);
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 降一级(缩进):成为「上一个同级兄弟」的末位子节点。 */
|
|
||||||
const indentRow = (row: FlatRow) => {
|
|
||||||
const sibs = siblingsOf(row.parentId);
|
|
||||||
const i = sibs.findIndex((s) => s.id === row.id);
|
|
||||||
if (i <= 0) return;
|
|
||||||
const newParent = sibs[i - 1].id;
|
|
||||||
if (wouldExceedDepth(row.id, newParent, mergedNow)) {
|
|
||||||
toast.error(`移动后将超过 ${MAX_MENU_DEPTH} 级,已阻止`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setRows((prev) => {
|
|
||||||
const next = prev.map((r) => (r.id === row.id ? { ...r, parentId: newParent } : r));
|
|
||||||
const idx = next.findIndex((r) => r.id === row.id);
|
|
||||||
const [moved] = next.splice(idx, 1);
|
|
||||||
next.push(moved);
|
|
||||||
return normalizeDfs(next);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 升一级(移位):移动到「父级的父级」下,紧跟原父级之后。 */
|
|
||||||
const outdentRow = (row: FlatRow) => {
|
|
||||||
if (row.parentId == null) return;
|
|
||||||
const parentRow = rows.find((r) => r.id === row.parentId);
|
|
||||||
if (!parentRow) return;
|
|
||||||
const newParent = parentRow.parentId ?? null;
|
|
||||||
setRows((prev) => {
|
|
||||||
const next = prev.map((r) => (r.id === row.id ? { ...r, parentId: newParent } : r));
|
|
||||||
const idx = next.findIndex((r) => r.id === row.id);
|
|
||||||
const [moved] = next.splice(idx, 1);
|
|
||||||
const pIdx = next.findIndex((r) => r.id === parentRow.id);
|
|
||||||
next.splice(pIdx + 1, 0, moved);
|
|
||||||
return normalizeDfs(next);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const toggleRow = (row: FlatRow) =>
|
|
||||||
setRows((prev) => prev.map((r) => (r.id === row.id ? { ...r, disabled: !r.disabled } : r)));
|
|
||||||
|
|
||||||
const applyEdit = (label: string, disabled: boolean, newParentId: string | null) => {
|
|
||||||
if (!editingRow) return;
|
|
||||||
const id = editingRow.id;
|
|
||||||
if ((newParentId ?? null) !== (editingRow.parentId ?? null)) {
|
|
||||||
if (newParentId && (newParentId === id || isDescendant(id, newParentId, mergedNow))) {
|
|
||||||
toast.error("不能移动到自身或其子菜单下");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (wouldExceedDepth(id, newParentId ?? null, mergedNow)) {
|
|
||||||
toast.error(`移动后将超过 ${MAX_MENU_DEPTH} 级,已阻止`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setRows((prev) => {
|
|
||||||
let next = prev.map((r) =>
|
|
||||||
r.id === id ? { ...r, label, disabled, parentId: newParentId ?? null } : r,
|
|
||||||
);
|
|
||||||
// 改了父级:把该行挪到数组末尾,规范化后成为新父级的末位子节点。
|
|
||||||
if ((newParentId ?? null) !== (editingRow.parentId ?? null)) {
|
|
||||||
const idx = next.findIndex((r) => r.id === id);
|
|
||||||
const [moved] = next.splice(idx, 1);
|
|
||||||
next.push(moved);
|
|
||||||
}
|
|
||||||
return normalizeDfs(next);
|
|
||||||
});
|
|
||||||
setEditId(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
// ── 拖拽 ──
|
|
||||||
const flattenedDepths = depthById;
|
|
||||||
|
|
||||||
const computeProjection = (overId: string) => {
|
|
||||||
const activeIndex = rows.findIndex((r) => r.id === activeId);
|
|
||||||
const overIndex = rows.findIndex((r) => r.id === overId);
|
|
||||||
if (activeIndex < 0 || overIndex < 0) return null;
|
|
||||||
const moved = arrayMove(rows, activeIndex, overIndex);
|
|
||||||
const prev = moved[overIndex - 1];
|
|
||||||
const next = moved[overIndex + 1];
|
|
||||||
const activeDepth = flattenedDepths.get(activeId!) ?? 1;
|
|
||||||
const dragDepth = Math.round(offsetX / INDENT);
|
|
||||||
const projected = activeDepth + dragDepth;
|
|
||||||
|
|
||||||
// 被移动子树的高度 → 其根可落的最大深度。
|
|
||||||
const childrenMap = new Map<string | null, string[]>();
|
|
||||||
for (const r of rows) {
|
|
||||||
const k = r.parentId ?? null;
|
|
||||||
const arr = childrenMap.get(k) ?? [];
|
|
||||||
arr.push(r.id);
|
|
||||||
childrenMap.set(k, arr);
|
|
||||||
}
|
|
||||||
const heightOf = (id: string): number => {
|
|
||||||
const kids = childrenMap.get(id) ?? [];
|
|
||||||
return kids.length ? 1 + Math.max(...kids.map(heightOf)) : 1;
|
|
||||||
};
|
|
||||||
const activeCap = MAX_MENU_DEPTH - (heightOf(activeId!) - 1);
|
|
||||||
|
|
||||||
const maxDepth = Math.min(prev ? (flattenedDepths.get(prev.id) ?? 1) + 1 : 1, activeCap);
|
|
||||||
const minDepth = next ? flattenedDepths.get(next.id) ?? 1 : 1;
|
|
||||||
let depth = Math.max(minDepth, Math.min(projected, maxDepth));
|
|
||||||
depth = Math.max(1, depth);
|
|
||||||
|
|
||||||
const parentId = (() => {
|
|
||||||
if (depth <= 1 || !prev) return null;
|
|
||||||
const prevDepth = flattenedDepths.get(prev.id) ?? 1;
|
|
||||||
if (depth === prevDepth) return prev.parentId ?? null;
|
|
||||||
if (depth > prevDepth) return prev.id;
|
|
||||||
const back = moved
|
|
||||||
.slice(0, overIndex)
|
|
||||||
.reverse()
|
|
||||||
.find((r) => (flattenedDepths.get(r.id) ?? 1) === depth);
|
|
||||||
return back ? back.parentId ?? null : null;
|
|
||||||
})();
|
|
||||||
|
|
||||||
return { depth, parentId };
|
|
||||||
};
|
|
||||||
|
|
||||||
const onDragStart = (e: DragStartEvent) => {
|
|
||||||
setActiveId(String(e.active.id));
|
|
||||||
setOffsetX(0);
|
|
||||||
};
|
|
||||||
const onDragMove = (e: DragMoveEvent) => {
|
|
||||||
setOffsetX(e.delta.x);
|
|
||||||
};
|
|
||||||
const onDragEnd = (e: DragEndEvent) => {
|
|
||||||
const aId = activeId;
|
|
||||||
setActiveId(null);
|
|
||||||
setOffsetX(0);
|
|
||||||
const overId = e.over ? String(e.over.id) : null;
|
|
||||||
if (!aId || !overId) return;
|
|
||||||
const proj = computeProjection(overId);
|
|
||||||
if (!proj) return;
|
|
||||||
const parentId = proj.parentId;
|
|
||||||
if (parentId && (parentId === aId || isDescendant(aId, parentId, mergedNow))) {
|
|
||||||
return; // 落到自身子树,忽略
|
|
||||||
}
|
|
||||||
if (wouldExceedDepth(aId, parentId, mergedNow)) {
|
|
||||||
toast.error(`移动后将超过 ${MAX_MENU_DEPTH} 级,已阻止`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setRows((prev) => {
|
|
||||||
const activeIndex = prev.findIndex((r) => r.id === aId);
|
|
||||||
const overIndex = prev.findIndex((r) => r.id === overId);
|
|
||||||
if (activeIndex < 0 || overIndex < 0) return prev;
|
|
||||||
const clone = prev.map((r) => ({ ...r }));
|
|
||||||
clone[activeIndex].parentId = parentId;
|
|
||||||
return normalizeDfs(arrayMove(clone, activeIndex, overIndex));
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
try {
|
|
||||||
await save.mutateAsync(currentOverrides);
|
|
||||||
toast.success("菜单配置已保存");
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "保存失败");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleReset = () => {
|
|
||||||
if (!confirm("确定要重置全部菜单为默认布局吗?保存后将清除所有自定义配置。")) return;
|
|
||||||
setRows(mergedToRows(mergeFlatNodes(flattenMenu(baseTree), [])));
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!isAdmin) return <Navigate to="/page/workspace/chats/new" replace />;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="h-full overflow-auto bg-slate-50/60 px-4 py-6 sm:px-6 lg:px-8">
|
|
||||||
<div className="mx-auto max-w-4xl">
|
|
||||||
{/* 顶部信息卡 */}
|
|
||||||
<div className="relative mb-6 overflow-hidden rounded-3xl border border-slate-200/60 bg-white p-6 shadow-sm md:p-8">
|
|
||||||
<div className="pointer-events-none absolute right-0 top-0 select-none p-8 opacity-[0.03]">
|
|
||||||
<Menu className="size-44 text-slate-900" />
|
|
||||||
</div>
|
|
||||||
<div className="relative">
|
|
||||||
<div className="mb-4 flex flex-col justify-between gap-4 md:flex-row md:items-center">
|
|
||||||
<div>
|
|
||||||
<span className="mb-3 inline-flex select-none items-center gap-1.5 rounded-full border border-red-100 bg-red-50 px-3 py-1 text-xs font-semibold text-red-600">
|
|
||||||
<Sparkles className="size-3" />
|
|
||||||
系统集成版
|
|
||||||
</span>
|
|
||||||
<h1 className="flex items-center gap-3 text-2xl font-bold tracking-tight text-slate-800 md:text-3xl">
|
|
||||||
菜单管理
|
|
||||||
<span className="rounded-lg border border-slate-200/60 bg-slate-100 px-2.5 py-0.5 font-mono text-xs font-medium text-slate-500">
|
|
||||||
{rows.length} 个项目
|
|
||||||
</span>
|
|
||||||
</h1>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleReset}
|
|
||||||
className="inline-flex cursor-pointer items-center gap-2 rounded-xl border border-slate-200 bg-white px-3.5 py-2 text-sm font-semibold text-slate-600 shadow-sm transition-all hover:border-slate-300 hover:bg-slate-50 hover:text-slate-800"
|
|
||||||
title="恢复为默认菜单布局"
|
|
||||||
>
|
|
||||||
<RotateCcw className="size-[15px]" />
|
|
||||||
重置全部
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={!dirty || save.isPending}
|
|
||||||
className="inline-flex cursor-pointer items-center gap-2 rounded-xl border border-red-600 bg-red-600 px-5 py-2 text-sm font-semibold text-white shadow-sm transition-all hover:bg-red-700 active:scale-95 disabled:cursor-not-allowed disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{save.isPending ? (
|
|
||||||
<>
|
|
||||||
<div className="size-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
|
||||||
保存中…
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Save className="size-[15px]" />
|
|
||||||
保存修改
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p className="flex max-w-2xl items-start gap-2.5 rounded-2xl border border-slate-200/50 bg-slate-50/70 p-3.5 text-sm leading-relaxed text-slate-600">
|
|
||||||
<Info className="mt-0.5 size-4 shrink-0 text-slate-400" />
|
|
||||||
<span>
|
|
||||||
<strong>拖拽调整</strong> 菜单顺序与层级(按住拖拽地标 <span className="font-mono">::</span>{" "}
|
|
||||||
上下排序,横向拖动改变层级);也可点击卡片上的<strong> 缩进 / 移位按钮 </strong>
|
|
||||||
精确调整层级(最多 {MAX_MENU_DEPTH} 级)、启停与编辑。
|
|
||||||
</span>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 搜索 + 状态筛选栏 */}
|
|
||||||
<div className="mb-6 flex flex-col items-center justify-between gap-4 rounded-2xl border border-slate-200/60 bg-white p-4 shadow-sm md:flex-row md:p-5">
|
|
||||||
<div className="relative w-full md:w-80">
|
|
||||||
<Search className="absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
placeholder="搜索菜单名称…"
|
|
||||||
value={query}
|
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
|
||||||
className="w-full rounded-xl border border-slate-200 bg-slate-50/50 py-2 pl-10 pr-4 text-sm transition-all hover:border-slate-300 focus:border-red-500 focus:outline-none focus:ring-4 focus:ring-red-500/5"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="inline-flex items-center rounded-xl border border-slate-200/40 bg-slate-100/80 p-1 text-xs font-medium">
|
|
||||||
{(
|
|
||||||
[
|
|
||||||
["all", "全部"],
|
|
||||||
["active", "已启用"],
|
|
||||||
["inactive", "已停用"],
|
|
||||||
] as const
|
|
||||||
).map(([key, label]) => (
|
|
||||||
<button
|
|
||||||
key={key}
|
|
||||||
type="button"
|
|
||||||
onClick={() => setStatusFilter(key)}
|
|
||||||
className={`cursor-pointer rounded-lg px-3.5 py-1.5 transition-all ${
|
|
||||||
statusFilter === key
|
|
||||||
? "bg-white font-semibold text-slate-800 shadow-sm"
|
|
||||||
: "text-slate-500 hover:text-slate-800"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 菜单列表卡 */}
|
|
||||||
<div className="min-h-[400px] rounded-3xl border border-slate-200/60 bg-white p-4 shadow-sm md:p-6">
|
|
||||||
{isLoading ? (
|
|
||||||
<p className="py-20 text-center text-sm text-slate-400">加载中…</p>
|
|
||||||
) : visibleRows.length === 0 ? (
|
|
||||||
<div className="flex flex-col items-center justify-center py-20 text-center">
|
|
||||||
<div className="mb-4 rounded-full bg-slate-100 p-4 text-slate-400">
|
|
||||||
<Menu className="size-8" />
|
|
||||||
</div>
|
|
||||||
<h4 className="mb-1 text-base font-semibold text-slate-700">无符合条件的菜单项</h4>
|
|
||||||
<p className="max-w-xs text-sm text-slate-400">尝试清空搜索或筛选条件以查看全部菜单。</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<DndContext
|
|
||||||
sensors={sensors}
|
|
||||||
collisionDetection={closestCenter}
|
|
||||||
onDragStart={onDragStart}
|
|
||||||
onDragMove={onDragMove}
|
|
||||||
onDragEnd={onDragEnd}
|
|
||||||
onDragCancel={() => {
|
|
||||||
setActiveId(null);
|
|
||||||
setOffsetX(0);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<SortableContext
|
|
||||||
items={visibleRows.map((r) => r.id)}
|
|
||||||
strategy={verticalListSortingStrategy}
|
|
||||||
>
|
|
||||||
<div className="flex flex-col gap-3">
|
|
||||||
{visibleRows.map((row) => {
|
|
||||||
const sibs = siblingsOf(row.parentId);
|
|
||||||
const i = sibs.findIndex((s) => s.id === row.id);
|
|
||||||
const canIndent = i > 0 && !wouldExceedDepth(row.id, sibs[i - 1].id, mergedNow);
|
|
||||||
return (
|
|
||||||
<SortableRow
|
|
||||||
key={row.id}
|
|
||||||
row={row}
|
|
||||||
depth={depthById.get(row.id) ?? 1}
|
|
||||||
canUp={i > 0}
|
|
||||||
canDown={i >= 0 && i < sibs.length - 1}
|
|
||||||
canIndent={canIndent}
|
|
||||||
canOutdent={row.parentId != null}
|
|
||||||
dragEnabled={!isFiltering}
|
|
||||||
onUp={() => moveUp(row)}
|
|
||||||
onDown={() => moveDown(row)}
|
|
||||||
onIndent={() => indentRow(row)}
|
|
||||||
onOutdent={() => outdentRow(row)}
|
|
||||||
onToggle={() => toggleRow(row)}
|
|
||||||
onEdit={() => setEditId(row.id)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</SortableContext>
|
|
||||||
<DragOverlay>
|
|
||||||
{activeId ? (
|
|
||||||
<div className="rounded-2xl border border-red-200 bg-white px-3.5 py-2 text-sm font-semibold text-slate-800 shadow-lg">
|
|
||||||
{rows.find((r) => r.id === activeId)?.label}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</DragOverlay>
|
|
||||||
</DndContext>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{editingRow && (
|
|
||||||
<EditMenuDialog
|
|
||||||
key={editingRow.id}
|
|
||||||
row={editingRow}
|
|
||||||
rows={rows}
|
|
||||||
merged={mergedNow}
|
|
||||||
depthById={depthById}
|
|
||||||
onClose={() => setEditId(null)}
|
|
||||||
onApply={applyEdit}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 编辑弹窗 ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
interface EditMenuDialogProps {
|
|
||||||
row: FlatRow;
|
|
||||||
rows: FlatRow[];
|
|
||||||
merged: MergedMenuNode[];
|
|
||||||
depthById: Map<string, number>;
|
|
||||||
onClose: () => void;
|
|
||||||
onApply: (label: string, disabled: boolean, parentId: string | null) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ROOT_OPTION = "__root__";
|
|
||||||
|
|
||||||
function EditMenuDialog({ row, rows, merged, depthById, onClose, onApply }: EditMenuDialogProps) {
|
|
||||||
const [label, setLabel] = useState(row.label);
|
|
||||||
const [disabled, setDisabled] = useState(row.disabled);
|
|
||||||
const [parentValue, setParentValue] = useState(row.parentId ?? ROOT_OPTION);
|
|
||||||
|
|
||||||
// 合法的「移动到」父级:非自身、非自身子树、移动后不超 3 级。
|
|
||||||
const parentOptions = useMemo(() => {
|
|
||||||
const opts: { value: string; label: string }[] = [{ value: ROOT_OPTION, label: "(设为一级菜单)" }];
|
|
||||||
for (const r of rows) {
|
|
||||||
if (r.id === row.id) continue;
|
|
||||||
if (isDescendant(row.id, r.id, merged)) continue;
|
|
||||||
if (wouldExceedDepth(row.id, r.id, merged)) continue;
|
|
||||||
const depth = depthById.get(r.id) ?? 1;
|
|
||||||
opts.push({ value: r.id, label: `${" ".repeat(depth - 1)}${r.label}` });
|
|
||||||
}
|
|
||||||
return opts;
|
|
||||||
}, [row.id, rows, merged, depthById]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open onOpenChange={(o) => !o && onClose()}>
|
|
||||||
<DialogContent className="sm:max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>编辑菜单</DialogTitle>
|
|
||||||
</DialogHeader>
|
|
||||||
<div className="flex flex-col gap-4 py-2">
|
|
||||||
<div className="flex flex-col gap-1.5">
|
|
||||||
<label className="text-sm font-medium">名称</label>
|
|
||||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="菜单显示名称" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium">启用</p>
|
|
||||||
<p className="text-xs text-muted-foreground">停用后该菜单(及其子菜单)对所有用户隐藏</p>
|
|
||||||
</div>
|
|
||||||
<Switch checked={!disabled} onCheckedChange={(v) => setDisabled(!v)} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-1.5">
|
|
||||||
<label className="text-sm font-medium">移动到(父级)</label>
|
|
||||||
<Select value={parentValue} onValueChange={setParentValue}>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent className="max-h-72">
|
|
||||||
{parentOptions.map((o) => (
|
|
||||||
<SelectItem key={o.value} value={o.value}>
|
|
||||||
{o.label}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<p className="text-xs text-muted-foreground">选择目标父级即可调整层级(拖拽之外的方式),最多 {MAX_MENU_DEPTH} 级。</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<DialogFooter>
|
|
||||||
<Button variant="outline" onClick={onClose}>
|
|
||||||
取消
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() =>
|
|
||||||
onApply(label.trim() || row.label, disabled, parentValue === ROOT_OPTION ? null : parentValue)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
确定
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -83,8 +83,6 @@ export default function NewAgentPage() {
|
|||||||
const [modelInput, setModelInput] = useState<string>("");
|
const [modelInput, setModelInput] = useState<string>("");
|
||||||
const [chatModelInput, setChatModelInput] = useState<string>("");
|
const [chatModelInput, setChatModelInput] = useState<string>("");
|
||||||
const [templateNameInput, setTemplateNameInput] = useState("");
|
const [templateNameInput, setTemplateNameInput] = useState("");
|
||||||
// 会商席位「技能识别强化」开关(弱模型补偿)。默认关。
|
|
||||||
const [seatSkillDirectiveInput, setSeatSkillDirectiveInput] = useState(false);
|
|
||||||
const [formError, setFormError] = useState("");
|
const [formError, setFormError] = useState("");
|
||||||
const [agentId, setAgentId] = useState("");
|
const [agentId, setAgentId] = useState("");
|
||||||
const [agent, setAgent] = useState<Agent | null>(null);
|
const [agent, setAgent] = useState<Agent | null>(null);
|
||||||
@@ -232,7 +230,6 @@ export default function NewAgentPage() {
|
|||||||
skills: selectedSkills,
|
skills: selectedSkills,
|
||||||
model: modelOverride,
|
model: modelOverride,
|
||||||
template_name: templateNameInput.trim(),
|
template_name: templateNameInput.trim(),
|
||||||
seat_skill_directive: seatSkillDirectiveInput,
|
|
||||||
});
|
});
|
||||||
setAgent(updated);
|
setAgent(updated);
|
||||||
return updated;
|
return updated;
|
||||||
@@ -254,7 +251,6 @@ export default function NewAgentPage() {
|
|||||||
skills: selectedSkills,
|
skills: selectedSkills,
|
||||||
model: modelOverride,
|
model: modelOverride,
|
||||||
template_name: templateNameInput.trim(),
|
template_name: templateNameInput.trim(),
|
||||||
seat_skill_directive: seatSkillDirectiveInput,
|
|
||||||
});
|
});
|
||||||
setAgentId(created.id);
|
setAgentId(created.id);
|
||||||
setAgent(created);
|
setAgent(created);
|
||||||
@@ -285,7 +281,6 @@ export default function NewAgentPage() {
|
|||||||
selectedSkills,
|
selectedSkills,
|
||||||
soulInput,
|
soulInput,
|
||||||
templateNameInput,
|
templateNameInput,
|
||||||
seatSkillDirectiveInput,
|
|
||||||
t.agents.nameStepCheckError,
|
t.agents.nameStepCheckError,
|
||||||
t.agents.nameStepNetworkError,
|
t.agents.nameStepNetworkError,
|
||||||
validateForm,
|
validateForm,
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ import { useEffect, useState } from 'react';
|
|||||||
import { useSearchParams } from 'react-router-dom';
|
import { useSearchParams } from 'react-router-dom';
|
||||||
import AIWritingPage from '@/open-canvas/pages/AIWritingPage';
|
import AIWritingPage from '@/open-canvas/pages/AIWritingPage';
|
||||||
import { getNotebookApiBaseURL } from '@/core/config';
|
import { getNotebookApiBaseURL } from '@/core/config';
|
||||||
|
import { useTheme, type ThemeType } from '@/contexts/ThemeContext';
|
||||||
|
|
||||||
|
const VALID_THEMES: ThemeType[] = ['dark', 'light', 'lightblue'];
|
||||||
|
|
||||||
interface NotebookTokenData {
|
interface NotebookTokenData {
|
||||||
doc_ids: number[];
|
doc_ids: number[];
|
||||||
@@ -13,6 +16,17 @@ interface NotebookTokenData {
|
|||||||
export default function NotebookAIWritingPage() {
|
export default function NotebookAIWritingPage() {
|
||||||
const [searchParams] = useSearchParams();
|
const [searchParams] = useSearchParams();
|
||||||
const token = searchParams.get('token');
|
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 [data, setData] = useState<NotebookTokenData | null>(null);
|
||||||
const [spaceName, setSpaceName] = useState<string | null>(null);
|
const [spaceName, setSpaceName] = useState<string | null>(null);
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { PageSidebarDark } from "@/components/page-sidebar-dark";
|
|||||||
import { isChatsIframeWorkspacePath } from "@/core/page-layout/chats-iframe-route";
|
import { isChatsIframeWorkspacePath } from "@/core/page-layout/chats-iframe-route";
|
||||||
import { readSidebarEnabled } from "@/core/page-layout/sidebar-enabled";
|
import { readSidebarEnabled } from "@/core/page-layout/sidebar-enabled";
|
||||||
import { isWujieEnv } from "@/core/embed/wujie";
|
import { isWujieEnv } from "@/core/embed/wujie";
|
||||||
import { isEmbedActive, readEmbedParam } from "@/core/embed/embed-session";
|
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
import { useTheme } from "@/contexts/ThemeContext";
|
||||||
import { useLocation } from "react-router-dom";
|
import { useLocation } from "react-router-dom";
|
||||||
import { useActiveThirdLevel } from "@/core/page-layout/use-sidebar-menu";
|
import { useActiveThirdLevel } from "@/core/page-layout/use-sidebar-menu";
|
||||||
@@ -38,14 +37,8 @@ function PageLayout() {
|
|||||||
const [layoutMode] = useLayoutMode();
|
const [layoutMode] = useLayoutMode();
|
||||||
const chromeByPreference =
|
const chromeByPreference =
|
||||||
layoutMode === "full" ? true : layoutMode === "compact" ? false : sidebarEnabled;
|
layoutMode === "full" ? true : layoutMode === "compact" ? false : sidebarEnabled;
|
||||||
// iframe 嵌入模式(外部系统 `&embed=1`,按标签页 sessionStorage):去掉全局导航栏 + 侧边栏,
|
|
||||||
// 只留问答/会商工作区本体。按 location 重算以跟随页内导航;非嵌入标签页恒为 false,不受影响。
|
|
||||||
const embedActive = useMemo(
|
|
||||||
() => isEmbedActive() || readEmbedParam(location.search) === "on",
|
|
||||||
[location.pathname, location.search],
|
|
||||||
);
|
|
||||||
const pageSidebarAllowed =
|
const pageSidebarAllowed =
|
||||||
chromeByPreference && !isChatsIframeWorkspacePath(location.pathname) && !embedActive;
|
chromeByPreference && !isChatsIframeWorkspacePath(location.pathname);
|
||||||
|
|
||||||
// h-full(100%)而非 h-screen(100vh):配合 globals.css 的 html/body/#root height:100%
|
// h-full(100%)而非 h-screen(100vh):配合 globals.css 的 html/body/#root height:100%
|
||||||
// 高度链,根布局跟随容器高度。全屏下 100% 解析到视口,与 h-screen 等价;无界等嵌套
|
// 高度链,根布局跟随容器高度。全屏下 100% 解析到视口,与 h-screen 等价;无界等嵌套
|
||||||
|
|||||||
@@ -34,7 +34,6 @@ import {
|
|||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Pagination } from "@/components/ui/pagination";
|
import { Pagination } from "@/components/ui/pagination";
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
|
||||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import type {
|
import type {
|
||||||
AdminLeaderboardDimension,
|
AdminLeaderboardDimension,
|
||||||
@@ -226,11 +225,7 @@ export default function PublicLeaderboardPage() {
|
|||||||
}, [userPageCount]);
|
}, [userPageCount]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div className="min-h-screen w-full bg-[#FFF7F7] text-[#231815] dark:bg-[#011226] dark:text-white" style={pageBg}>
|
||||||
className="flex size-full min-h-0 w-full bg-[#FFF7F7] text-[#231815] dark:bg-[#011226] dark:text-white"
|
|
||||||
style={pageBg}
|
|
||||||
>
|
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
|
||||||
<div className="mx-auto w-full max-w-6xl px-4 py-8 sm:px-6 sm:py-10">
|
<div className="mx-auto w-full max-w-6xl px-4 py-8 sm:px-6 sm:py-10">
|
||||||
{/* 标题区:仅展示,不含任何操作按钮 */}
|
{/* 标题区:仅展示,不含任何操作按钮 */}
|
||||||
<header className="mb-6">
|
<header className="mb-6">
|
||||||
@@ -377,7 +372,6 @@ export default function PublicLeaderboardPage() {
|
|||||||
{data?.generated_at ? `数据生成于 ${fmtDate(data.generated_at)}` : "仅供查看"}
|
{data?.generated_at ? `数据生成于 ${fmtDate(data.generated_at)}` : "仅供查看"}
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
</ScrollArea>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,333 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 会商诊断日志(仅 admin):展示多智能体会商全流程(第一步意图 / 第二步研讨 /
|
|
||||||
* 第三步报告 + 后台挂起执行器 / 进程内网关)各处的报错与关键事件,支持按
|
|
||||||
* scope(前台/后台)、阶段、级别、事件码、作业/任务/草稿 id、关键词筛选 + 分页。
|
|
||||||
*
|
|
||||||
* 数据源:`GET /api/roundtable-diagnostics`(admin-gated)。入口:多智能体会商页右上角
|
|
||||||
* 设置按钮(admin)。见 [[roundtable-diagnostics]]。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { useMemo, useState } from "react";
|
|
||||||
import { Navigate, useNavigate } from "react-router-dom";
|
|
||||||
import { ArrowLeft, RefreshCw, Search } from "lucide-react";
|
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Pagination } from "@/components/ui/pagination";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
|
||||||
import {
|
|
||||||
type DiagnosticFilters,
|
|
||||||
type DiagnosticItem,
|
|
||||||
useRoundtableDiagnosticFacets,
|
|
||||||
useRoundtableDiagnostics,
|
|
||||||
} from "@/strategy-components/api/roundtable-diagnostics";
|
|
||||||
|
|
||||||
const PAGE_SIZE = 50;
|
|
||||||
|
|
||||||
const ALL = "__all__";
|
|
||||||
|
|
||||||
// 阶段中文名(已知集合;未知阶段原样显示)。
|
|
||||||
const STAGE_LABELS: Record<string, string> = {
|
|
||||||
step1_intent: "第一步 · 意图",
|
|
||||||
step2_init: "第二步 · 初始化",
|
|
||||||
step2_leader: "第二步 · 总控",
|
|
||||||
step2_seat: "第二步 · 席位",
|
|
||||||
step2_recommend: "第二步 · 推荐",
|
|
||||||
step2_orchestration: "第二步 · 编排",
|
|
||||||
step3_summary: "第三步 · 总结报告",
|
|
||||||
step3_report: "第三步 · 结果绘制",
|
|
||||||
step3_dashboard: "第三步 · 大屏数据",
|
|
||||||
step3_structure: "第三步 · 数据入库",
|
|
||||||
upstream: "回环代理",
|
|
||||||
job: "后台作业",
|
|
||||||
};
|
|
||||||
|
|
||||||
const SCOPE_LABELS: Record<string, string> = {
|
|
||||||
background: "后台挂起",
|
|
||||||
foreground: "前台实时(服务端)",
|
|
||||||
client: "前端上报",
|
|
||||||
};
|
|
||||||
|
|
||||||
// 范围切换:后台挂起(background) / 前台调用(foreground 服务端观测 + client 前端上报)。
|
|
||||||
type ScopeCategory = "background" | "frontend";
|
|
||||||
|
|
||||||
// 每个范围下可选的阶段(按用户要求:后台挂起只到第二/三步;前台调用含第一步)。
|
|
||||||
const STAGE_OPTIONS: Record<ScopeCategory, string[]> = {
|
|
||||||
background: [
|
|
||||||
"step2_init",
|
|
||||||
"step2_leader",
|
|
||||||
"step2_seat",
|
|
||||||
"step2_orchestration",
|
|
||||||
"step3_summary",
|
|
||||||
"step3_report",
|
|
||||||
"step3_dashboard",
|
|
||||||
"step3_structure",
|
|
||||||
"job",
|
|
||||||
],
|
|
||||||
frontend: [
|
|
||||||
"step1_intent",
|
|
||||||
"step2_init",
|
|
||||||
"step2_leader",
|
|
||||||
"step2_seat",
|
|
||||||
"step2_recommend",
|
|
||||||
"step3_summary",
|
|
||||||
"step3_report",
|
|
||||||
"step3_dashboard",
|
|
||||||
"step3_structure",
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const LEVEL_STYLES: Record<string, string> = {
|
|
||||||
error: "bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300",
|
|
||||||
warning: "bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300",
|
|
||||||
info: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300",
|
|
||||||
};
|
|
||||||
|
|
||||||
function stageLabel(stage: string): string {
|
|
||||||
return STAGE_LABELS[stage] ?? stage;
|
|
||||||
}
|
|
||||||
|
|
||||||
function fmtTime(iso: string | null): string {
|
|
||||||
if (!iso) return "";
|
|
||||||
try {
|
|
||||||
const d = new Date(iso);
|
|
||||||
return d.toLocaleString("zh-CN", { hour12: false });
|
|
||||||
} catch {
|
|
||||||
return iso;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function DiagnosticRow({ item }: { item: DiagnosticItem }) {
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const hasDetail = item.detail != null && Object.keys(item.detail as object).length > 0;
|
|
||||||
return (
|
|
||||||
<div className="rounded-lg border border-slate-200 dark:border-border bg-white dark:bg-card px-3 py-2 text-sm">
|
|
||||||
<div className="flex items-start gap-2">
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"shrink-0 rounded px-1.5 py-0.5 text-xs font-medium uppercase",
|
|
||||||
LEVEL_STYLES[item.level] ?? LEVEL_STYLES.info,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{item.level}
|
|
||||||
</span>
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
|
||||||
<Badge variant="secondary" className="text-xs">
|
|
||||||
{stageLabel(item.stage)}
|
|
||||||
</Badge>
|
|
||||||
<code className="text-xs text-slate-500 dark:text-muted-foreground">{item.event}</code>
|
|
||||||
{item.agentName ? (
|
|
||||||
<span className="text-xs text-slate-500 dark:text-muted-foreground">· {item.agentName}</span>
|
|
||||||
) : null}
|
|
||||||
{item.userName ? (
|
|
||||||
<span className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300">
|
|
||||||
👤 {item.userName}
|
|
||||||
</span>
|
|
||||||
) : null}
|
|
||||||
<span className="ml-auto text-xs text-slate-400 dark:text-muted-foreground">{fmtTime(item.createdAt)}</span>
|
|
||||||
</div>
|
|
||||||
<p className="mt-1 whitespace-pre-wrap break-words text-slate-700 dark:text-foreground">
|
|
||||||
{item.message || <span className="text-slate-400">(无说明)</span>}
|
|
||||||
</p>
|
|
||||||
<div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-slate-400 dark:text-muted-foreground">
|
|
||||||
<span>{SCOPE_LABELS[item.scope] ?? item.scope}</span>
|
|
||||||
{item.jobId ? <span>job: {item.jobId.slice(0, 8)}</span> : null}
|
|
||||||
{item.taskId ? <span>task: {item.taskId}</span> : null}
|
|
||||||
{item.draftId ? <span>draft: {item.draftId.slice(0, 8)}</span> : null}
|
|
||||||
{item.cycle != null ? <span>cycle: {item.cycle}</span> : null}
|
|
||||||
{hasDetail ? (
|
|
||||||
<button type="button" className="text-blue-500 hover:underline" onClick={() => setOpen((v) => !v)}>
|
|
||||||
{open ? "收起详情" : "展开详情"}
|
|
||||||
</button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
{open && hasDetail ? (
|
|
||||||
<pre className="mt-2 max-h-64 overflow-auto rounded bg-slate-50 dark:bg-muted p-2 text-xs text-slate-600 dark:text-muted-foreground">
|
|
||||||
{JSON.stringify(item.detail, null, 2)}
|
|
||||||
</pre>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function RoundtableDiagnosticsPage() {
|
|
||||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const [scopeCategory, setScopeCategory] = useState<ScopeCategory>("background");
|
|
||||||
const [stage, setStage] = useState<string>(ALL);
|
|
||||||
const [level, setLevel] = useState<string>(ALL);
|
|
||||||
const [event, setEvent] = useState<string>(ALL);
|
|
||||||
const [qInput, setQInput] = useState("");
|
|
||||||
const [q, setQ] = useState("");
|
|
||||||
const [page, setPage] = useState(1);
|
|
||||||
|
|
||||||
// 「前台调用」= 服务端观测(foreground) + 前端上报(client) 两种 scope 合并查(后端按逗号分隔多值)。
|
|
||||||
const scopeParam = scopeCategory === "background" ? "background" : "foreground,client";
|
|
||||||
|
|
||||||
const filters: DiagnosticFilters = useMemo(
|
|
||||||
() => ({
|
|
||||||
scope: scopeParam,
|
|
||||||
stage: stage === ALL ? undefined : stage,
|
|
||||||
level: level === ALL ? undefined : level,
|
|
||||||
event: event === ALL ? undefined : event,
|
|
||||||
q: q || undefined,
|
|
||||||
limit: PAGE_SIZE,
|
|
||||||
offset: (page - 1) * PAGE_SIZE,
|
|
||||||
}),
|
|
||||||
[scopeParam, stage, level, event, q, page],
|
|
||||||
);
|
|
||||||
|
|
||||||
const { data, isLoading, isFetching, refetch } = useRoundtableDiagnostics(filters, isAdmin);
|
|
||||||
const { data: facets } = useRoundtableDiagnosticFacets(isAdmin);
|
|
||||||
|
|
||||||
if (!isAdmin) {
|
|
||||||
return <Navigate to="/page/workspace/chats/new" replace />;
|
|
||||||
}
|
|
||||||
|
|
||||||
const items = data?.items ?? [];
|
|
||||||
const total = data?.total ?? 0;
|
|
||||||
|
|
||||||
const resetPageAnd = (fn: () => void) => {
|
|
||||||
fn();
|
|
||||||
setPage(1);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 切换范围时清空阶段筛选(两种范围的阶段选项不同)+ 回到第一页。
|
|
||||||
const switchScope = (next: ScopeCategory) => {
|
|
||||||
setScopeCategory(next);
|
|
||||||
setStage(ALL);
|
|
||||||
setPage(1);
|
|
||||||
};
|
|
||||||
|
|
||||||
const applySearch = () => resetPageAnd(() => setQ(qInput.trim()));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex h-full flex-col bg-slate-50 dark:bg-background">
|
|
||||||
{/* Header */}
|
|
||||||
<header className="flex items-center gap-3 border-b border-slate-200 dark:border-border bg-white dark:bg-card px-4 py-3">
|
|
||||||
<Button variant="ghost" size="sm" onClick={() => navigate(-1)} className="gap-1">
|
|
||||||
<ArrowLeft className="h-4 w-4" />
|
|
||||||
返回
|
|
||||||
</Button>
|
|
||||||
<div>
|
|
||||||
<h1 className="text-base font-semibold text-slate-800 dark:text-foreground">会商诊断日志</h1>
|
|
||||||
<p className="text-xs text-slate-400 dark:text-muted-foreground">
|
|
||||||
多智能体会商全流程报错与关键事件(含后台挂起卡死、超时、产物缺失等)
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => refetch()}
|
|
||||||
className="ml-auto gap-1"
|
|
||||||
disabled={isFetching}
|
|
||||||
>
|
|
||||||
<RefreshCw className={cn("h-4 w-4", isFetching && "animate-spin")} />
|
|
||||||
刷新
|
|
||||||
</Button>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{/* Filters */}
|
|
||||||
<div className="flex flex-wrap items-center gap-2 border-b border-slate-200 dark:border-border bg-white dark:bg-card px-4 py-2">
|
|
||||||
{/* 范围切换:后台挂起 / 前台调用 */}
|
|
||||||
<div className="inline-flex rounded-lg border border-slate-200 dark:border-border p-0.5">
|
|
||||||
{(["background", "frontend"] as ScopeCategory[]).map((c) => (
|
|
||||||
<button
|
|
||||||
key={c}
|
|
||||||
type="button"
|
|
||||||
onClick={() => switchScope(c)}
|
|
||||||
className={cn(
|
|
||||||
"rounded-md px-3 py-1 text-xs font-medium transition-colors",
|
|
||||||
scopeCategory === c
|
|
||||||
? "bg-slate-800 text-white dark:bg-primary dark:text-primary-foreground"
|
|
||||||
: "text-slate-500 hover:text-slate-700 dark:text-muted-foreground dark:hover:text-foreground",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{c === "background" ? "后台挂起" : "前台调用"}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<FilterSelect label="阶段" value={stage} onChange={(v) => resetPageAnd(() => setStage(v))}
|
|
||||||
options={STAGE_OPTIONS[scopeCategory]} labels={STAGE_LABELS} />
|
|
||||||
<FilterSelect label="级别" value={level} onChange={(v) => resetPageAnd(() => setLevel(v))}
|
|
||||||
options={facets?.level ?? []} />
|
|
||||||
<FilterSelect label="事件" value={event} onChange={(v) => resetPageAnd(() => setEvent(v))}
|
|
||||||
options={facets?.event ?? []} />
|
|
||||||
<div className="flex items-center gap-1">
|
|
||||||
<Input
|
|
||||||
value={qInput}
|
|
||||||
onChange={(e) => setQInput(e.target.value)}
|
|
||||||
onKeyDown={(e) => e.key === "Enter" && applySearch()}
|
|
||||||
placeholder="搜索报错说明…"
|
|
||||||
className="h-8 w-48"
|
|
||||||
/>
|
|
||||||
<Button variant="secondary" size="sm" onClick={applySearch} className="gap-1">
|
|
||||||
<Search className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<span className="ml-auto text-xs text-slate-400 dark:text-muted-foreground">共 {total} 条</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* List */}
|
|
||||||
<div className="flex-1 overflow-auto px-4 py-3">
|
|
||||||
{isLoading ? (
|
|
||||||
<p className="py-10 text-center text-sm text-slate-400">加载中…</p>
|
|
||||||
) : items.length === 0 ? (
|
|
||||||
<p className="py-10 text-center text-sm text-slate-400">暂无诊断记录</p>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
{items.map((it) => (
|
|
||||||
<DiagnosticRow key={it.id} item={it} />
|
|
||||||
))}
|
|
||||||
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} className="pt-2" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FilterSelect({
|
|
||||||
label,
|
|
||||||
value,
|
|
||||||
onChange,
|
|
||||||
options,
|
|
||||||
labels,
|
|
||||||
}: {
|
|
||||||
label: string;
|
|
||||||
value: string;
|
|
||||||
onChange: (v: string) => void;
|
|
||||||
options: string[];
|
|
||||||
labels?: Record<string, string>;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<Select value={value} onValueChange={onChange}>
|
|
||||||
<SelectTrigger className="h-8 w-auto min-w-[120px] text-xs">
|
|
||||||
<SelectValue placeholder={label} />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value={ALL}>{label}:全部</SelectItem>
|
|
||||||
{options.map((o) => (
|
|
||||||
<SelectItem key={o} value={o}>
|
|
||||||
{labels?.[o] ?? o}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,273 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
|
||||||
import { Navigate } from "react-router-dom";
|
|
||||||
import { Download, Info, Plus, Save, Search, ShieldAlert, Sparkles, Trash2 } from "lucide-react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
|
|
||||||
import { Switch } from "@/components/ui/switch";
|
|
||||||
import { getAccountDisplayName } from "@/core/auth";
|
|
||||||
import { SEED_DESENSITIZE_MAP } from "@/lib/desensitize";
|
|
||||||
import {
|
|
||||||
type SensitiveWord,
|
|
||||||
useSensitiveWordActions,
|
|
||||||
useSensitiveWords,
|
|
||||||
} from "@/strategy-components/api/sensitive-words";
|
|
||||||
|
|
||||||
interface EditRow {
|
|
||||||
/** 稳定的行 key(编辑原始词时不丢焦点) */
|
|
||||||
key: number;
|
|
||||||
word: string;
|
|
||||||
replacement: string;
|
|
||||||
enabled: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
let _seq = 1;
|
|
||||||
const nextKey = () => _seq++;
|
|
||||||
|
|
||||||
function toRows(words: SensitiveWord[]): EditRow[] {
|
|
||||||
return words.map((w) => ({ key: nextKey(), word: w.word, replacement: w.replacement, enabled: w.enabled }));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 归一化用于「脏」判断与重复检测(按原始词去空白后比较)。 */
|
|
||||||
function serialize(rows: { word: string; replacement: string; enabled: boolean }[]): string {
|
|
||||||
return JSON.stringify(
|
|
||||||
rows
|
|
||||||
.map((r) => ({ w: r.word.trim(), r: r.replacement, e: r.enabled }))
|
|
||||||
.filter((r) => r.w !== "")
|
|
||||||
.sort((a, b) => a.w.localeCompare(b.w)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function SensitiveWordsPage() {
|
|
||||||
// 仅用户名为 lqq 的账号可访问(用户名 = 设置→个人信息页展示名)。
|
|
||||||
const canManage = getAccountDisplayName().toLowerCase() === "lqq";
|
|
||||||
const { data: serverWords = [], isLoading } = useSensitiveWords();
|
|
||||||
const { save } = useSensitiveWordActions();
|
|
||||||
|
|
||||||
const [rows, setRows] = useState<EditRow[]>([]);
|
|
||||||
const [loadedKey, setLoadedKey] = useState<string | null>(null);
|
|
||||||
const [query, setQuery] = useState("");
|
|
||||||
|
|
||||||
// 服务端数据首次/变化时回填工作副本(以序列化值判定,避免覆盖未保存编辑)。
|
|
||||||
const sourceKey = useMemo(() => serialize(serverWords), [serverWords]);
|
|
||||||
useEffect(() => {
|
|
||||||
if (sourceKey !== loadedKey) {
|
|
||||||
setRows(toRows(serverWords));
|
|
||||||
setLoadedKey(sourceKey);
|
|
||||||
}
|
|
||||||
}, [sourceKey, loadedKey, serverWords]);
|
|
||||||
|
|
||||||
const dirty = useMemo(() => serialize(rows) !== serialize(serverWords), [rows, serverWords]);
|
|
||||||
|
|
||||||
const q = query.trim().toLowerCase();
|
|
||||||
const visibleRows = useMemo(
|
|
||||||
() =>
|
|
||||||
!q
|
|
||||||
? rows
|
|
||||||
: rows.filter(
|
|
||||||
(r) => r.word.toLowerCase().includes(q) || r.replacement.toLowerCase().includes(q),
|
|
||||||
),
|
|
||||||
[rows, q],
|
|
||||||
);
|
|
||||||
|
|
||||||
const enabledCount = rows.filter((r) => r.enabled && r.word.trim()).length;
|
|
||||||
|
|
||||||
// ── 行操作 ──
|
|
||||||
const patchRow = (key: number, patch: Partial<EditRow>) =>
|
|
||||||
setRows((prev) => prev.map((r) => (r.key === key ? { ...r, ...patch } : r)));
|
|
||||||
const removeRow = (key: number) => setRows((prev) => prev.filter((r) => r.key !== key));
|
|
||||||
const addRow = () => setRows((prev) => [{ key: nextKey(), word: "", replacement: "", enabled: true }, ...prev]);
|
|
||||||
|
|
||||||
/** 用前端内置种子补齐当前没有的词(已存在的词不动)。 */
|
|
||||||
const importSeed = () => {
|
|
||||||
const have = new Set(rows.map((r) => r.word.trim()).filter(Boolean));
|
|
||||||
const added: EditRow[] = [];
|
|
||||||
for (const [word, replacement] of Object.entries(SEED_DESENSITIZE_MAP)) {
|
|
||||||
if (!have.has(word)) added.push({ key: nextKey(), word, replacement, enabled: true });
|
|
||||||
}
|
|
||||||
if (added.length === 0) {
|
|
||||||
toast.info("种子词已全部存在,无需导入");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setRows((prev) => [...added, ...prev]);
|
|
||||||
toast.success(`已导入 ${added.length} 个种子词(保存后生效)`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
// 校验:去空白、丢弃空原始词、检测重复。
|
|
||||||
const cleaned = rows
|
|
||||||
.map((r) => ({ ...r, word: r.word.trim() }))
|
|
||||||
.filter((r) => r.word !== "");
|
|
||||||
const seen = new Set<string>();
|
|
||||||
for (const r of cleaned) {
|
|
||||||
if (seen.has(r.word)) {
|
|
||||||
toast.error(`原始词「${r.word}」重复,请合并后再保存`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
seen.add(r.word);
|
|
||||||
}
|
|
||||||
const payload: SensitiveWord[] = cleaned.map((r, i) => ({
|
|
||||||
word: r.word,
|
|
||||||
replacement: r.replacement,
|
|
||||||
enabled: r.enabled,
|
|
||||||
sortOrder: i,
|
|
||||||
}));
|
|
||||||
try {
|
|
||||||
await save.mutateAsync(payload);
|
|
||||||
toast.success("敏感词已保存");
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "保存失败");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!canManage) return <Navigate to="/page/workspace/chats/new" replace />;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="h-full overflow-auto bg-slate-50/60 px-4 py-6 sm:px-6 lg:px-8">
|
|
||||||
<div className="mx-auto max-w-4xl">
|
|
||||||
{/* 顶部信息卡 */}
|
|
||||||
<div className="relative mb-6 overflow-hidden rounded-3xl border border-slate-200/60 bg-white p-6 shadow-sm md:p-8">
|
|
||||||
<div className="pointer-events-none absolute right-0 top-0 select-none p-8 opacity-[0.03]">
|
|
||||||
<ShieldAlert className="size-44 text-slate-900" />
|
|
||||||
</div>
|
|
||||||
<div className="relative">
|
|
||||||
<div className="mb-4 flex flex-col justify-between gap-4 md:flex-row md:items-center">
|
|
||||||
<div>
|
|
||||||
<span className="mb-3 inline-flex select-none items-center gap-1.5 rounded-full border border-red-100 bg-red-50 px-3 py-1 text-xs font-semibold text-red-600">
|
|
||||||
<Sparkles className="size-3" />
|
|
||||||
系统集成版
|
|
||||||
</span>
|
|
||||||
<h1 className="flex items-center gap-3 text-2xl font-bold tracking-tight text-slate-800 md:text-3xl">
|
|
||||||
敏感词管理
|
|
||||||
<span className="rounded-lg border border-slate-200/60 bg-slate-100 px-2.5 py-0.5 font-mono text-xs font-medium text-slate-500">
|
|
||||||
{rows.length} 词 / {enabledCount} 启用
|
|
||||||
</span>
|
|
||||||
</h1>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={importSeed}
|
|
||||||
className="inline-flex cursor-pointer items-center gap-2 rounded-xl border border-slate-200 bg-white px-3.5 py-2 text-sm font-semibold text-slate-600 shadow-sm transition-all hover:border-slate-300 hover:bg-slate-50 hover:text-slate-800"
|
|
||||||
title="用前端内置种子词补齐当前缺失的词"
|
|
||||||
>
|
|
||||||
<Download className="size-[15px]" />
|
|
||||||
导入种子词
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={!dirty || save.isPending}
|
|
||||||
className="inline-flex cursor-pointer items-center gap-2 rounded-xl border border-red-600 bg-red-600 px-5 py-2 text-sm font-semibold text-white shadow-sm transition-all hover:bg-red-700 active:scale-95 disabled:cursor-not-allowed disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{save.isPending ? (
|
|
||||||
<>
|
|
||||||
<div className="size-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
|
||||||
保存中…
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Save className="size-[15px]" />
|
|
||||||
保存修改
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p className="flex max-w-2xl items-start gap-2.5 rounded-2xl border border-slate-200/50 bg-slate-50/70 p-3.5 text-sm leading-relaxed text-slate-600">
|
|
||||||
<Info className="mt-0.5 size-4 shrink-0 text-slate-400" />
|
|
||||||
<span>
|
|
||||||
配置展示层<strong> 脱敏词映射</strong>(原始词 → 替换词)。保存后全站脱敏即时生效;
|
|
||||||
<strong> 停用 </strong>的词会保留但不参与替换。前端内置的种子词仅用于全新机器首次部署,
|
|
||||||
可用<strong>「导入种子词」</strong>一键写入后台。
|
|
||||||
</span>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 搜索 + 新增栏 */}
|
|
||||||
<div className="mb-6 flex flex-col items-center justify-between gap-4 rounded-2xl border border-slate-200/60 bg-white p-4 shadow-sm md:flex-row md:p-5">
|
|
||||||
<div className="relative w-full md:w-80">
|
|
||||||
<Search className="absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
placeholder="搜索原始词 / 替换词…"
|
|
||||||
value={query}
|
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
|
||||||
className="w-full rounded-xl border border-slate-200 bg-slate-50/50 py-2 pl-10 pr-4 text-sm transition-all hover:border-slate-300 focus:border-red-500 focus:outline-none focus:ring-4 focus:ring-red-500/5"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={addRow}
|
|
||||||
className="inline-flex w-full cursor-pointer items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:border-red-300 hover:bg-red-50 hover:text-red-600 md:w-auto"
|
|
||||||
>
|
|
||||||
<Plus className="size-[15px]" />
|
|
||||||
新增敏感词
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 列表 */}
|
|
||||||
<div className="overflow-hidden rounded-2xl border border-slate-200/60 bg-white shadow-sm">
|
|
||||||
<div className="grid grid-cols-[1fr_1fr_auto_auto] items-center gap-3 border-b border-slate-200/60 bg-slate-50/70 px-4 py-2.5 text-xs font-semibold text-slate-500">
|
|
||||||
<span>原始词</span>
|
|
||||||
<span>替换词</span>
|
|
||||||
<span className="px-1 text-center">启用</span>
|
|
||||||
<span className="w-8" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="px-4 py-12 text-center text-sm text-slate-400">加载中…</div>
|
|
||||||
) : visibleRows.length === 0 ? (
|
|
||||||
<div className="px-4 py-12 text-center text-sm text-slate-400">
|
|
||||||
{rows.length === 0 ? "暂无敏感词,点击「新增」或「导入种子词」开始配置" : "没有匹配的词"}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<ul className="divide-y divide-slate-100">
|
|
||||||
{visibleRows.map((row) => (
|
|
||||||
<li
|
|
||||||
key={row.key}
|
|
||||||
className={`grid grid-cols-[1fr_1fr_auto_auto] items-center gap-3 px-4 py-2.5 transition-colors hover:bg-slate-50/60 ${
|
|
||||||
row.enabled ? "" : "opacity-55"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={row.word}
|
|
||||||
placeholder="原始词"
|
|
||||||
onChange={(e) => patchRow(row.key, { word: e.target.value })}
|
|
||||||
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm transition-all focus:border-red-500 focus:outline-none focus:ring-2 focus:ring-red-500/10"
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={row.replacement}
|
|
||||||
placeholder="替换词"
|
|
||||||
onChange={(e) => patchRow(row.key, { replacement: e.target.value })}
|
|
||||||
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm transition-all focus:border-red-500 focus:outline-none focus:ring-2 focus:ring-red-500/10"
|
|
||||||
/>
|
|
||||||
<div className="px-1">
|
|
||||||
<Switch
|
|
||||||
checked={row.enabled}
|
|
||||||
onCheckedChange={(v) => patchRow(row.key, { enabled: v })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => removeRow(row.key)}
|
|
||||||
title="删除"
|
|
||||||
className="flex size-8 items-center justify-center rounded-lg text-slate-400 transition-colors hover:bg-red-50 hover:text-red-600"
|
|
||||||
>
|
|
||||||
<Trash2 className="size-4" />
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,7 @@ import { SkillEvolutionPanel } from "@/components/workspace/skills/skill-evoluti
|
|||||||
|
|
||||||
export default function SkillEvolutionPage() {
|
export default function SkillEvolutionPage() {
|
||||||
return (
|
return (
|
||||||
<div className="flex size-full min-h-0 flex-col overflow-auto p-6">
|
<div className="flex h-full flex-col overflow-auto p-6">
|
||||||
<SkillEvolutionPanel />
|
<SkillEvolutionPanel />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { SkillSettingsPage } from "@/components/workspace/settings/skill-setting
|
|||||||
|
|
||||||
export default function SkillsPage() {
|
export default function SkillsPage() {
|
||||||
return (
|
return (
|
||||||
<div className="flex size-full min-h-0 flex-col overflow-auto p-6">
|
<div className="flex flex-col h-full overflow-auto p-6">
|
||||||
<SkillSettingsPage />
|
<SkillSettingsPage />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Navigate, Route, Routes } from "react-router-dom";
|
import { Navigate, Route, Routes, useParams } from "react-router-dom";
|
||||||
import { Toaster } from "sonner";
|
import { Toaster } from "sonner";
|
||||||
|
|
||||||
import { SidebarProvider } from "@/components/ui/sidebar";
|
import { SidebarProvider } from "@/components/ui/sidebar";
|
||||||
import { getAccountDisplayName, getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { RouteBaseProvider } from "@/core/route-base";
|
import { RouteBaseProvider } from "@/core/route-base";
|
||||||
import GeneralQA from "@/strategy-components/components/chat-qa/GeneralQA";
|
import GeneralQA from "@/strategy-components/components/chat-qa/GeneralQA";
|
||||||
import SentimentAnalyzes from "@/strategy-components/components/task-components/SentimentAnalyzes";
|
import SentimentAnalyzes from "@/strategy-components/components/task-components/SentimentAnalyzes";
|
||||||
@@ -11,17 +11,10 @@ import TaskPgFrom from "@/strategy-components/components/task-components/TaskPgF
|
|||||||
import TaskTyFrom from "@/strategy-components/components/task-components/TaskTyFrom";
|
import TaskTyFrom from "@/strategy-components/components/task-components/TaskTyFrom";
|
||||||
import TaskXkFrom from "@/strategy-components/components/task-components/TaskXkFrom";
|
import TaskXkFrom from "@/strategy-components/components/task-components/TaskXkFrom";
|
||||||
import TaskAnalyzes from "@/strategy-components/components/task-components/TaskAnalyzes";
|
import TaskAnalyzes from "@/strategy-components/components/task-components/TaskAnalyzes";
|
||||||
import {
|
|
||||||
TaskBindChat,
|
|
||||||
TaskFxChat,
|
|
||||||
TaskFxIndexResolver,
|
|
||||||
TaskFxWorkspace,
|
|
||||||
} from "@/strategy-components/components/task-components/TaskFxWorkspace";
|
|
||||||
import { ActionAnalyzes } from "@/strategy-components/components/task-components/ActionAnalyzes";
|
import { ActionAnalyzes } from "@/strategy-components/components/task-components/ActionAnalyzes";
|
||||||
import KnowledgeBaseResourceManagement from "@/strategy-components/components/resource-management/KnowledgeBaseResourceManagement";
|
import KnowledgeBaseResourceManagement from "@/strategy-components/components/resource-management/KnowledgeBaseResourceManagement";
|
||||||
import NetworkActorResourceManagement from "@/strategy-components/components/resource-management/NetworkActorResourceManagement";
|
import NetworkActorResourceManagement from "@/strategy-components/components/resource-management/NetworkActorResourceManagement";
|
||||||
import RoundtablePlanningPage from "@/roundtable-planning/pages/RoundtablePlanningPage";
|
import RoundtablePlanningPage from "@/roundtable-planning/pages/RoundtablePlanningPage";
|
||||||
import DashboardAgentPage from "@/roundtable-planning/pages/DashboardAgentPage";
|
|
||||||
import BusinessChainListPage from "@/roundtable-planning/pages/BusinessChainListPage";
|
import BusinessChainListPage from "@/roundtable-planning/pages/BusinessChainListPage";
|
||||||
import BusinessChainEditorPage from "@/roundtable-planning/pages/BusinessChainEditorPage";
|
import BusinessChainEditorPage from "@/roundtable-planning/pages/BusinessChainEditorPage";
|
||||||
import "@/roundtable-planning/styles/roundtable-planning.css";
|
import "@/roundtable-planning/styles/roundtable-planning.css";
|
||||||
@@ -38,10 +31,6 @@ import PublicLeaderboardPage from "./PublicLeaderboardPage";
|
|||||||
import LightAppIframeView from "./LightAppIframeView";
|
import LightAppIframeView from "./LightAppIframeView";
|
||||||
import LightAppListPage from "./LightAppListPage";
|
import LightAppListPage from "./LightAppListPage";
|
||||||
import LightAppManagementPage from "./LightAppManagementPage";
|
import LightAppManagementPage from "./LightAppManagementPage";
|
||||||
import MenuManagementPage from "./MenuManagementPage";
|
|
||||||
import SensitiveWordsPage from "./SensitiveWordsPage";
|
|
||||||
import TaskButtonsPage from "./TaskButtonsPage";
|
|
||||||
import RoundtableDiagnosticsPage from "./RoundtableDiagnosticsPage";
|
|
||||||
import LightAppNewNotePage from "./LightAppNewNotePage";
|
import LightAppNewNotePage from "./LightAppNewNotePage";
|
||||||
import LightAppNoteListPage from "./LightAppNoteListPage";
|
import LightAppNoteListPage from "./LightAppNoteListPage";
|
||||||
import LightAppNoteQAPage from "./LightAppNoteQAPage";
|
import LightAppNoteQAPage from "./LightAppNoteQAPage";
|
||||||
@@ -62,6 +51,20 @@ import AdminScheduledTasksPage from "./AdminScheduledTasksPage";
|
|||||||
import AdminUserActivityPage from "./AdminUserActivityPage";
|
import AdminUserActivityPage from "./AdminUserActivityPage";
|
||||||
import { ChatRuntime } from "./WorkspaceRoutes";
|
import { ChatRuntime } from "./WorkspaceRoutes";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 任务深链:把智能体问答嵌进「任务管理」布局。读路由参数 agent_id,给 AgentChatPage
|
||||||
|
* 传入以 taskBase 为前缀的对话路由(开新会话 / URL 改写都停留在任务管理上下文,
|
||||||
|
* 侧边栏保持对应业务高亮)。
|
||||||
|
*/
|
||||||
|
function TaskEmbeddedAgentChat({ taskBase }: { taskBase: string }) {
|
||||||
|
const { agent_id } = useParams<{ agent_id: string }>();
|
||||||
|
return (
|
||||||
|
<ChatRuntime>
|
||||||
|
<AgentChatPage chatBasePath={`${taskBase}/agent/${agent_id}/chats`} />
|
||||||
|
</ChatRuntime>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default function StrategyRoutes() {
|
export default function StrategyRoutes() {
|
||||||
return (
|
return (
|
||||||
<RouteBaseProvider value="/page/strategy">
|
<RouteBaseProvider value="/page/strategy">
|
||||||
@@ -89,16 +92,6 @@ export default function StrategyRoutes() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 大屏绘制智能体独立页面(按 taskId 存取;ChatRuntime 提供 ArtifactsProvider 给沙箱预览) */}
|
|
||||||
<Route
|
|
||||||
path="dashboard-agent"
|
|
||||||
element={
|
|
||||||
<ChatRuntime>
|
|
||||||
<DashboardAgentPage />
|
|
||||||
</ChatRuntime>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* 需求 0616 #3/#4:zzJC / zzXD 「按类型聚合」模块页(重做,独立路由)。 */}
|
{/* 需求 0616 #3/#4:zzJC / zzXD 「按类型聚合」模块页(重做,独立路由)。 */}
|
||||||
<Route path="qa/zzjc/*" element={<AgentModuleRoutes module={AGENT_MODULES.zzjc} />} />
|
<Route path="qa/zzjc/*" element={<AgentModuleRoutes module={AGENT_MODULES.zzjc} />} />
|
||||||
<Route path="qa/zzxd/*" element={<AgentModuleRoutes module={AGENT_MODULES.zzxd} />} />
|
<Route path="qa/zzxd/*" element={<AgentModuleRoutes module={AGENT_MODULES.zzxd} />} />
|
||||||
@@ -144,26 +137,12 @@ export default function StrategyRoutes() {
|
|||||||
</ChatRuntime>
|
</ChatRuntime>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{/* 三情分析:任务工作区(左对话列表 1:N,无目的树闸门;新建对话直接带开场信息)。 */}
|
|
||||||
<Route
|
<Route
|
||||||
path="plan-task-sentiment/agent/:agent_id/chats"
|
path="plan-task-sentiment/agent/:agent_id/chats/:thread_id"
|
||||||
element={
|
element={
|
||||||
<TaskFxWorkspace taskBase="/page/strategy/task-management/plan-task-sentiment" business="3qfx" lite />
|
<TaskEmbeddedAgentChat taskBase="/page/strategy/task-management/plan-task-sentiment" />
|
||||||
}
|
}
|
||||||
>
|
/>
|
||||||
<Route
|
|
||||||
index
|
|
||||||
element={
|
|
||||||
<TaskFxIndexResolver taskBase="/page/strategy/task-management/plan-task-sentiment" />
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Route
|
|
||||||
path=":thread_id"
|
|
||||||
element={
|
|
||||||
<TaskBindChat taskBase="/page/strategy/task-management/plan-task-sentiment" />
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</Route>
|
|
||||||
<Route
|
<Route
|
||||||
path="plan-task/plan-task-fx"
|
path="plan-task/plan-task-fx"
|
||||||
element={
|
element={
|
||||||
@@ -183,29 +162,12 @@ export default function StrategyRoutes() {
|
|||||||
</ChatRuntime>
|
</ChatRuntime>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{/* 任务FX:任务工作区(左对话列表 1:N + 右问答;新建对话顶部目的树闸门)。 */}
|
|
||||||
<Route
|
<Route
|
||||||
path="plan-task/plan-task-fx/agent/:agent_id/chats"
|
path="plan-task/plan-task-fx/agent/:agent_id/chats/:thread_id"
|
||||||
element={
|
element={
|
||||||
<TaskFxWorkspace taskBase="/page/strategy/task-management/plan-task/plan-task-fx" business="rwfx" />
|
<TaskEmbeddedAgentChat taskBase="/page/strategy/task-management/plan-task/plan-task-fx" />
|
||||||
}
|
}
|
||||||
>
|
/>
|
||||||
<Route
|
|
||||||
index
|
|
||||||
element={
|
|
||||||
<TaskFxIndexResolver taskBase="/page/strategy/task-management/plan-task/plan-task-fx" />
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Route
|
|
||||||
path=":thread_id"
|
|
||||||
element={
|
|
||||||
<TaskFxChat
|
|
||||||
taskBase="/page/strategy/task-management/plan-task/plan-task-fx"
|
|
||||||
autoStartWhenPurposeEmpty
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</Route>
|
|
||||||
<Route
|
<Route
|
||||||
path="plan-task/plan-task-action"
|
path="plan-task/plan-task-action"
|
||||||
element={
|
element={
|
||||||
@@ -225,28 +187,12 @@ export default function StrategyRoutes() {
|
|||||||
</ChatRuntime>
|
</ChatRuntime>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{/* 行动分析:任务工作区(左对话列表 1:N 精简版 + 左上行动详情卡片;直接问答,
|
|
||||||
右上角「开始回答」按钮手动发出开场信息,不走目的树闸门/覆盖确认)。
|
|
||||||
注意:xdfx 深链传入的是「行动id」,登录时已先经 resolveDeeplinkTaskId 换成任务id。 */}
|
|
||||||
<Route
|
<Route
|
||||||
path="plan-task/plan-task-action/agent/:agent_id/chats"
|
path="plan-task/plan-task-action/agent/:agent_id/chats/:thread_id"
|
||||||
element={
|
element={
|
||||||
<TaskFxWorkspace taskBase="/page/strategy/task-management/plan-task/plan-task-action" business="xdfx" lite />
|
<TaskEmbeddedAgentChat taskBase="/page/strategy/task-management/plan-task/plan-task-action" />
|
||||||
}
|
}
|
||||||
>
|
/>
|
||||||
<Route
|
|
||||||
index
|
|
||||||
element={
|
|
||||||
<TaskFxIndexResolver taskBase="/page/strategy/task-management/plan-task/plan-task-action" />
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Route
|
|
||||||
path=":thread_id"
|
|
||||||
element={
|
|
||||||
<TaskBindChat taskBase="/page/strategy/task-management/plan-task/plan-task-action" />
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</Route>
|
|
||||||
<Route path="mnty-task-mechanism" element={<TaskTyFrom defaultPage="iframeXdty" title="XDTY任务" />} />
|
<Route path="mnty-task-mechanism" element={<TaskTyFrom defaultPage="iframeXdty" title="XDTY任务" />} />
|
||||||
<Route path="mnty-task-plan" element={<TaskTyFrom defaultPage="iframeFaty" title="方案TY任务" />} />
|
<Route path="mnty-task-plan" element={<TaskTyFrom defaultPage="iframeFaty" title="方案TY任务" />} />
|
||||||
<Route path="mnty-task-zsty" element={<TaskTyFrom defaultPage="iframeSysystem" title="XXTY任务" />} />
|
<Route path="mnty-task-zsty" element={<TaskTyFrom defaultPage="iframeSysystem" title="XXTY任务" />} />
|
||||||
@@ -292,7 +238,7 @@ export default function StrategyRoutes() {
|
|||||||
path="agents/:agent_id/chats/:thread_id"
|
path="agents/:agent_id/chats/:thread_id"
|
||||||
element={
|
element={
|
||||||
<ChatRuntime>
|
<ChatRuntime>
|
||||||
<AgentChatPage showAgentList />
|
<AgentChatPage />
|
||||||
</ChatRuntime>
|
</ChatRuntime>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -364,46 +310,6 @@ export default function StrategyRoutes() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
|
||||||
path="admin/menu-management"
|
|
||||||
element={
|
|
||||||
getStoredAuth()?.system_role === "admin" ? (
|
|
||||||
<MenuManagementPage />
|
|
||||||
) : (
|
|
||||||
<Navigate to="/page/workspace/chats/new" replace />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Route
|
|
||||||
path="admin/sensitive-words"
|
|
||||||
element={
|
|
||||||
getAccountDisplayName().toLowerCase() === "lqq" ? (
|
|
||||||
<SensitiveWordsPage />
|
|
||||||
) : (
|
|
||||||
<Navigate to="/page/workspace/chats/new" replace />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Route
|
|
||||||
path="admin/task-buttons"
|
|
||||||
element={
|
|
||||||
getStoredAuth()?.system_role === "admin" ? (
|
|
||||||
<TaskButtonsPage />
|
|
||||||
) : (
|
|
||||||
<Navigate to="/page/workspace/chats/new" replace />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Route
|
|
||||||
path="admin/roundtable-diagnostics"
|
|
||||||
element={
|
|
||||||
getStoredAuth()?.system_role === "admin" ? (
|
|
||||||
<RoundtableDiagnosticsPage />
|
|
||||||
) : (
|
|
||||||
<Navigate to="/page/workspace/chats/new" replace />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Route
|
<Route
|
||||||
path="admin/scheduled-tasks"
|
path="admin/scheduled-tasks"
|
||||||
element={
|
element={
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import { fetchDocumentByChunk } from "@/core/studio/api";
|
|||||||
import type { DocumentWithChunks } from "@/core/studio/api";
|
import type { DocumentWithChunks } from "@/core/studio/api";
|
||||||
import type { SourceItem } from "@/core/studio/types";
|
import type { SourceItem } from "@/core/studio/types";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
|
import { useTheme } from "@/contexts/ThemeContext";
|
||||||
import { useModels } from "@/core/models/hooks";
|
import { useModels } from "@/core/models/hooks";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
@@ -218,6 +219,7 @@ export default function StudioNotebookDetailPage({
|
|||||||
const params = useParams<{ notebookId: string }>();
|
const params = useParams<{ notebookId: string }>();
|
||||||
const notebookId =
|
const notebookId =
|
||||||
notebookIdProp != null ? String(notebookIdProp) : params.notebookId;
|
notebookIdProp != null ? String(notebookIdProp) : params.notebookId;
|
||||||
|
const { theme } = useTheme(); // 跳转「我的空间」时带上当前主题 key
|
||||||
const { notebooks, isLoading, token: studioToken } = useStudioNotebooks(); // token 用于跳转 callback
|
const { notebooks, isLoading, token: studioToken } = useStudioNotebooks(); // token 用于跳转 callback
|
||||||
const { models } = useModels();
|
const { models } = useModels();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
@@ -508,7 +510,7 @@ export default function StudioNotebookDetailPage({
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<a
|
<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"
|
target="_blank"
|
||||||
rel="noreferrer"
|
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"
|
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 +534,7 @@ export default function StudioNotebookDetailPage({
|
|||||||
<div className="relative z-10 flex flex-1 flex-col overflow-hidden">
|
<div className="relative z-10 flex flex-1 flex-col overflow-hidden">
|
||||||
{/* 右上角跳转按钮 */}
|
{/* 右上角跳转按钮 */}
|
||||||
<a
|
<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"
|
target="_blank"
|
||||||
rel="noreferrer"
|
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"
|
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"
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { useQueryClient } from "@tanstack/react-query";
|
|||||||
import { useStudioNotebooks } from "@/core/studio/hooks";
|
import { useStudioNotebooks } from "@/core/studio/hooks";
|
||||||
import { createSearchSpace, deleteSearchSpace, renameSearchSpace } from "@/core/studio/api";
|
import { createSearchSpace, deleteSearchSpace, renameSearchSpace } from "@/core/studio/api";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
|
import { useTheme } from "@/contexts/ThemeContext";
|
||||||
import type { StudioNotebook } from "@/core/studio/types";
|
import type { StudioNotebook } from "@/core/studio/types";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
@@ -23,13 +24,16 @@ import {
|
|||||||
} from "@/components/ui/dropdown-menu";
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
function NotebookCardSkeleton() {
|
function NotebookCardSkeleton({ isDark }: { isDark: boolean }) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col rounded-[20px] bg-[#f2f2f2] p-5" style={{ minHeight: 180 }}>
|
<div
|
||||||
<div className="size-10 animate-pulse rounded-xl bg-[#e0e0e0]" />
|
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="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-4 w-3/4 animate-pulse rounded ${isDark ? "bg-[#2c3346]" : "bg-[#e0e0e0]"}`} />
|
||||||
<div className="h-3 w-1/3 animate-pulse rounded bg-[#e0e0e0]" />
|
<div className={`h-3 w-1/3 animate-pulse rounded ${isDark ? "bg-[#2c3346]" : "bg-[#e0e0e0]"}`} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -37,11 +41,13 @@ function NotebookCardSkeleton() {
|
|||||||
|
|
||||||
function NotebookCard({
|
function NotebookCard({
|
||||||
nb,
|
nb,
|
||||||
|
isDark,
|
||||||
onRename,
|
onRename,
|
||||||
onDelete,
|
onDelete,
|
||||||
onOpen,
|
onOpen,
|
||||||
}: {
|
}: {
|
||||||
nb: StudioNotebook;
|
nb: StudioNotebook;
|
||||||
|
isDark: boolean;
|
||||||
onRename: (nb: StudioNotebook) => void;
|
onRename: (nb: StudioNotebook) => void;
|
||||||
onDelete: (nb: StudioNotebook) => void;
|
onDelete: (nb: StudioNotebook) => void;
|
||||||
/** 传入则点击卡片回调(内嵌打开),不再路由跳转。 */
|
/** 传入则点击卡片回调(内嵌打开),不再路由跳转。 */
|
||||||
@@ -61,16 +67,16 @@ function NotebookCard({
|
|||||||
<div className="size-7" />
|
<div className="size-7" />
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-auto flex flex-col gap-1 pt-8">
|
<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}
|
{nb.name}
|
||||||
</span>
|
</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>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
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 ? (
|
{onOpen ? (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -125,6 +131,8 @@ export default function StudioNotebooksPage({
|
|||||||
onOpenNotebook?: (id: number) => void;
|
onOpenNotebook?: (id: number) => void;
|
||||||
} = {}) {
|
} = {}) {
|
||||||
const { notebooks, isLoading, isError } = useStudioNotebooks();
|
const { notebooks, isLoading, isError } = useStudioNotebooks();
|
||||||
|
const { theme } = useTheme();
|
||||||
|
const isDark = theme === "dark";
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
// ── 新建 ──
|
// ── 新建 ──
|
||||||
@@ -221,11 +229,12 @@ export default function StudioNotebooksPage({
|
|||||||
{/* Grid */}
|
{/* Grid */}
|
||||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
|
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
|
||||||
{isLoading
|
{isLoading
|
||||||
? Array.from({ length: 8 }).map((_, i) => <NotebookCardSkeleton key={i} />)
|
? Array.from({ length: 8 }).map((_, i) => <NotebookCardSkeleton key={i} isDark={isDark} />)
|
||||||
: notebooks.map((nb) => (
|
: notebooks.map((nb) => (
|
||||||
<NotebookCard
|
<NotebookCard
|
||||||
key={nb.id}
|
key={nb.id}
|
||||||
nb={nb}
|
nb={nb}
|
||||||
|
isDark={isDark}
|
||||||
onRename={(nb) => { setRenameTarget(nb); setRenameName(nb.name); setRenameError(""); }}
|
onRename={(nb) => { setRenameTarget(nb); setRenameName(nb.name); setRenameError(""); }}
|
||||||
onDelete={(nb) => { setDeleteTarget(nb); setDeleteError(""); }}
|
onDelete={(nb) => { setDeleteTarget(nb); setDeleteError(""); }}
|
||||||
onOpen={onOpenNotebook}
|
onOpen={onOpenNotebook}
|
||||||
|
|||||||
@@ -1,389 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按钮管理(仅 admin):配置任务工作区(rwfx / 3qfx / xdfx,见 ``TaskFxWorkspace``)
|
|
||||||
* 左侧栏的可配置跳转按钮——改名称、改跳转方式与地址、启停、排序、增删。
|
|
||||||
*
|
|
||||||
* 全局共享、整体替换保存(``PUT /api/task-buttons``)。后端整张表为空时回退代码种子默认
|
|
||||||
* (rwfx 的 4 个历史按钮),此页首次进入也以种子回填工作副本,便于从当前行为起步。
|
|
||||||
* 见 [[task-buttons]]。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
|
||||||
import { Navigate } from "react-router-dom";
|
|
||||||
import { ArrowDown, ArrowUp, Download, MousePointerClick, Plus, Save, Trash2 } from "lucide-react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Switch } from "@/components/ui/switch";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
|
||||||
import {
|
|
||||||
DEFAULT_TASK_DEEPLINK_CONFIG,
|
|
||||||
fetchTaskDeeplinkConfig,
|
|
||||||
type TaskDeeplinkConfig,
|
|
||||||
} from "@/core/auth/task-deeplink-config";
|
|
||||||
import {
|
|
||||||
TASK_BUSINESSES,
|
|
||||||
TASK_BUSINESS_TARGETS,
|
|
||||||
defaultTaskButtons,
|
|
||||||
type TaskBusiness,
|
|
||||||
type TaskButton,
|
|
||||||
} from "@/core/auth/task-buttons";
|
|
||||||
import { useTaskButtonActions, useTaskButtons } from "@/strategy-components/api/task-buttons";
|
|
||||||
|
|
||||||
let _seq = 1;
|
|
||||||
const newId = (b: TaskBusiness) => `${b}-custom-${Date.now()}-${_seq++}`;
|
|
||||||
|
|
||||||
/** 归一化用于「脏」判断(按 id 排序后整体比较)。 */
|
|
||||||
function serialize(rows: TaskButton[]): string {
|
|
||||||
return JSON.stringify([...rows].sort((a, b) => a.id.localeCompare(b.id)));
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function TaskButtonsPage() {
|
|
||||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
|
||||||
const { data: serverButtons = [], isLoading } = useTaskButtons();
|
|
||||||
const { save } = useTaskButtonActions();
|
|
||||||
|
|
||||||
const [cfg, setCfg] = useState<TaskDeeplinkConfig>(() => DEFAULT_TASK_DEEPLINK_CONFIG);
|
|
||||||
useEffect(() => {
|
|
||||||
let alive = true;
|
|
||||||
void fetchTaskDeeplinkConfig().then((c) => {
|
|
||||||
if (alive) setCfg(c);
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
alive = false;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const [rows, setRows] = useState<TaskButton[]>([]);
|
|
||||||
const [loadedKey, setLoadedKey] = useState<string | null>(null);
|
|
||||||
const [tab, setTab] = useState<TaskBusiness>("rwfx");
|
|
||||||
|
|
||||||
// 服务端首次/变化时回填工作副本(空表回填种子默认)。以序列化值判定,避免覆盖未保存编辑。
|
|
||||||
const sourceKey = useMemo(() => serialize(serverButtons), [serverButtons]);
|
|
||||||
useEffect(() => {
|
|
||||||
if (sourceKey !== loadedKey) {
|
|
||||||
setRows(serverButtons.length > 0 ? serverButtons : defaultTaskButtons(cfg));
|
|
||||||
setLoadedKey(sourceKey);
|
|
||||||
}
|
|
||||||
}, [sourceKey, loadedKey, serverButtons, cfg]);
|
|
||||||
|
|
||||||
const tabRows = useMemo(
|
|
||||||
() => rows.filter((r) => r.business === tab).sort((a, b) => a.sortOrder - b.sortOrder),
|
|
||||||
[rows, tab],
|
|
||||||
);
|
|
||||||
|
|
||||||
const dirty = useMemo(() => serialize(rows) !== sourceKey, [rows, sourceKey]);
|
|
||||||
|
|
||||||
if (!isAdmin) return <Navigate to="/page/workspace/chats/new" replace />;
|
|
||||||
|
|
||||||
const update = (id: string, patch: Partial<TaskButton>) =>
|
|
||||||
setRows((rs) => rs.map((r) => (r.id === id ? { ...r, ...patch } : r)));
|
|
||||||
|
|
||||||
const removeRow = (id: string) => setRows((rs) => rs.filter((r) => r.id !== id));
|
|
||||||
|
|
||||||
const addRow = () => {
|
|
||||||
const maxSort = tabRows.reduce((m, r) => Math.max(m, r.sortOrder), -1);
|
|
||||||
setRows((rs) => [
|
|
||||||
...rs,
|
|
||||||
{
|
|
||||||
id: newId(tab),
|
|
||||||
business: tab,
|
|
||||||
label: "新按钮",
|
|
||||||
linkType: "url",
|
|
||||||
target: "",
|
|
||||||
appendTaskId: true,
|
|
||||||
idParam: "id",
|
|
||||||
idKind: "task",
|
|
||||||
openMode: "blank",
|
|
||||||
enabled: true,
|
|
||||||
sortOrder: maxSort + 1,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
};
|
|
||||||
|
|
||||||
const moveRow = (id: string, dir: "up" | "down") => {
|
|
||||||
const list = [...tabRows];
|
|
||||||
const i = list.findIndex((r) => r.id === id);
|
|
||||||
const j = dir === "up" ? i - 1 : i + 1;
|
|
||||||
if (i < 0 || j < 0 || j >= list.length) return;
|
|
||||||
[list[i], list[j]] = [list[j], list[i]];
|
|
||||||
const reordered = list.map((r, idx) => ({ ...r, sortOrder: idx }));
|
|
||||||
setRows((rs) => [...rs.filter((r) => r.business !== tab), ...reordered]);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
const payload = rows.map((r) => ({ ...r, label: r.label.trim() }));
|
|
||||||
try {
|
|
||||||
await save.mutateAsync(payload);
|
|
||||||
toast.success("已保存按钮配置");
|
|
||||||
} catch (e) {
|
|
||||||
toast.error(e instanceof Error ? e.message : "保存失败");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const importDefaults = (business?: TaskBusiness) => {
|
|
||||||
const have = new Set(rows.map((r) => r.id));
|
|
||||||
const adds = defaultTaskButtons(cfg)
|
|
||||||
.filter((d) => !business || d.business === business)
|
|
||||||
.filter((d) => !have.has(d.id));
|
|
||||||
if (!adds.length) {
|
|
||||||
toast.info("没有可导入的默认按钮");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setRows((rs) => [...rs, ...adds]);
|
|
||||||
toast.success(`已导入 ${adds.length} 个默认按钮`);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex size-full min-h-0 flex-col overflow-hidden bg-background">
|
|
||||||
<div className="border-border/70 flex items-center justify-between gap-3 border-b px-5 py-4">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<MousePointerClick className="h-5 w-5 text-[var(--color-main,#0062D9)]" />
|
|
||||||
<div>
|
|
||||||
<div className="text-foreground text-base font-semibold">按钮管理</div>
|
|
||||||
<div className="text-muted-foreground text-xs">
|
|
||||||
配置任务工作区底部「快捷跳转」栏的按钮(名称 / 跳转方式 / 地址 / 启停 / 排序)
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Button variant="outline" size="sm" onClick={() => importDefaults()}>
|
|
||||||
<Download className="h-4 w-4" /> 导入全部默认
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" onClick={handleSave} disabled={!dirty || save.isPending}>
|
|
||||||
<Save className="h-4 w-4" /> {save.isPending ? "保存中…" : "保存"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 业务 tab:每个 tab = 一个任务深链页面,明确区分三种页面的按钮 */}
|
|
||||||
<div className="border-border/70 flex items-stretch gap-2 border-b px-5 pt-3">
|
|
||||||
{TASK_BUSINESSES.map((b) => {
|
|
||||||
const count = rows.filter((r) => r.business === b.code).length;
|
|
||||||
const active = tab === b.code;
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={b.code}
|
|
||||||
type="button"
|
|
||||||
onClick={() => setTab(b.code)}
|
|
||||||
className={cn(
|
|
||||||
"flex min-w-[8.5rem] flex-col gap-0.5 rounded-t-lg border border-b-0 px-4 py-2 text-left transition-colors",
|
|
||||||
active
|
|
||||||
? "border-[var(--color-main,#0062D9)] bg-[var(--color-main,#0062D9)] text-white"
|
|
||||||
: "border-border/70 text-muted-foreground hover:bg-muted bg-transparent",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span className="flex items-center gap-1.5 text-sm font-semibold">
|
|
||||||
{b.name}
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"rounded px-1.5 text-[11px] tabular-nums",
|
|
||||||
active ? "bg-white/20" : "bg-muted-foreground/15",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{count}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
<span className={cn("text-[11px]", active ? "text-white/80" : "opacity-70")}>
|
|
||||||
?goPath={b.goPath}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 当前页面说明 */}
|
|
||||||
{(() => {
|
|
||||||
const meta = TASK_BUSINESSES.find((b) => b.code === tab)!;
|
|
||||||
return (
|
|
||||||
<div className="border-border/70 bg-muted/40 text-muted-foreground border-b px-5 py-2 text-xs">
|
|
||||||
正在编辑「<span className="text-foreground font-medium">{meta.name}</span>
|
|
||||||
」页面的按钮 · {meta.desc} 下方按钮会显示在该页面底部的「快捷跳转」栏,从上到下对应栏内从左到右的顺序。
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
|
|
||||||
<div className="min-h-0 flex-1 overflow-y-auto p-5">
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="text-muted-foreground text-sm">加载中…</div>
|
|
||||||
) : tabRows.length === 0 ? (
|
|
||||||
<div className="text-muted-foreground flex flex-col items-center gap-3 rounded-md border border-dashed p-6 text-center text-sm">
|
|
||||||
该页面暂无按钮。可「导入该页面默认按钮」一键填充,或点下方「添加按钮」自定义。
|
|
||||||
<Button variant="outline" size="sm" onClick={() => importDefaults(tab)}>
|
|
||||||
<Download className="h-4 w-4" /> 导入该页面默认按钮
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-col gap-3">
|
|
||||||
{tabRows.map((r, idx) => (
|
|
||||||
<div
|
|
||||||
key={r.id}
|
|
||||||
className="border-border/70 grid grid-cols-[1fr_auto] items-start gap-3 rounded-lg border bg-card/60 p-3"
|
|
||||||
>
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<label className="text-muted-foreground w-16 shrink-0 text-xs">名称</label>
|
|
||||||
<Input
|
|
||||||
value={r.label}
|
|
||||||
onChange={(e) => update(r.id, { label: e.target.value })}
|
|
||||||
placeholder="按钮名称"
|
|
||||||
className="h-8 max-w-xs"
|
|
||||||
/>
|
|
||||||
<label className="text-muted-foreground ml-2 shrink-0 text-xs">类型</label>
|
|
||||||
<Select
|
|
||||||
value={r.linkType}
|
|
||||||
onValueChange={(v) => update(r.id, { linkType: v as TaskButton["linkType"] })}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="h-8 w-36">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="url">外部链接</SelectItem>
|
|
||||||
<SelectItem value="business">切换业务</SelectItem>
|
|
||||||
<SelectItem value="purpose">目的树弹框</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<label className="text-muted-foreground w-16 shrink-0 text-xs">目标</label>
|
|
||||||
{r.linkType === "purpose" ? (
|
|
||||||
<span className="text-muted-foreground text-xs">
|
|
||||||
点击弹出当前任务的「任务目的」表格,无需配置目标。
|
|
||||||
</span>
|
|
||||||
) : r.linkType === "url" ? (
|
|
||||||
<>
|
|
||||||
<Input
|
|
||||||
value={r.target}
|
|
||||||
onChange={(e) => update(r.id, { target: e.target.value })}
|
|
||||||
placeholder="https://…(跳转地址)"
|
|
||||||
className="h-8 flex-1 min-w-[16rem]"
|
|
||||||
/>
|
|
||||||
<label className="text-muted-foreground ml-2 flex shrink-0 items-center gap-1.5 text-xs">
|
|
||||||
<Switch
|
|
||||||
checked={r.appendTaskId}
|
|
||||||
onCheckedChange={(v) => update(r.id, { appendTaskId: v })}
|
|
||||||
/>
|
|
||||||
追加参数
|
|
||||||
</label>
|
|
||||||
{r.appendTaskId && (
|
|
||||||
<div className="flex shrink-0 items-center gap-1 text-xs">
|
|
||||||
<span className="text-muted-foreground">?</span>
|
|
||||||
<Input
|
|
||||||
value={r.idParam}
|
|
||||||
onChange={(e) => update(r.id, { idParam: e.target.value })}
|
|
||||||
placeholder="id"
|
|
||||||
className="h-8 w-24"
|
|
||||||
title="查询参数名(如 id / task_id)"
|
|
||||||
/>
|
|
||||||
<span className="text-muted-foreground">=</span>
|
|
||||||
{/* 行动分析(xdfx):行动id 与任务id 不同,可选追加哪种;其它业务固定任务id */}
|
|
||||||
{tab === "xdfx" ? (
|
|
||||||
<Select
|
|
||||||
value={r.idKind}
|
|
||||||
onValueChange={(v) => update(r.id, { idKind: v as TaskButton["idKind"] })}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="h-8 w-24">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="task">任务id</SelectItem>
|
|
||||||
<SelectItem value="action">行动id</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
) : (
|
|
||||||
<span className="text-muted-foreground">任务id</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<label className="text-muted-foreground ml-2 shrink-0 text-xs">打开方式</label>
|
|
||||||
<Select
|
|
||||||
value={r.openMode}
|
|
||||||
onValueChange={(v) => update(r.id, { openMode: v as TaskButton["openMode"] })}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="h-8 w-32" title="外链打开方式">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="blank">新窗口</SelectItem>
|
|
||||||
<SelectItem value="self">当前窗口</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Select value={r.target} onValueChange={(v) => update(r.id, { target: v })}>
|
|
||||||
<SelectTrigger className="h-8 w-48">
|
|
||||||
<SelectValue placeholder="选择目标业务" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{TASK_BUSINESS_TARGETS.map((t) => (
|
|
||||||
<SelectItem key={t.code} value={t.code}>
|
|
||||||
{t.label}({t.code})
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-1">
|
|
||||||
<label className="text-muted-foreground mr-1 flex items-center gap-1.5 text-xs">
|
|
||||||
<Switch
|
|
||||||
checked={r.enabled}
|
|
||||||
onCheckedChange={(v) => update(r.id, { enabled: v })}
|
|
||||||
/>
|
|
||||||
启用
|
|
||||||
</label>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-8 w-8"
|
|
||||||
disabled={idx === 0}
|
|
||||||
onClick={() => moveRow(r.id, "up")}
|
|
||||||
title="上移"
|
|
||||||
>
|
|
||||||
<ArrowUp className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-8 w-8"
|
|
||||||
disabled={idx === tabRows.length - 1}
|
|
||||||
onClick={() => moveRow(r.id, "down")}
|
|
||||||
title="下移"
|
|
||||||
>
|
|
||||||
<ArrowDown className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="text-muted-foreground hover:text-destructive h-8 w-8"
|
|
||||||
onClick={() => removeRow(r.id)}
|
|
||||||
title="删除"
|
|
||||||
>
|
|
||||||
<Trash2 className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Button variant="outline" size="sm" className="mt-4" onClick={addRow}>
|
|
||||||
<Plus className="h-4 w-4" /> 添加按钮
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -288,7 +288,7 @@ export default function WorkspaceRoutes({
|
|||||||
element={
|
element={
|
||||||
<WorkspaceLayout {...layoutProps}>
|
<WorkspaceLayout {...layoutProps}>
|
||||||
<ChatRuntime>
|
<ChatRuntime>
|
||||||
<AgentChatPage showAgentList />
|
<AgentChatPage />
|
||||||
</ChatRuntime>
|
</ChatRuntime>
|
||||||
</WorkspaceLayout>
|
</WorkspaceLayout>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -678,18 +678,3 @@
|
|||||||
[data-theme="lightblue"] .light-app-management-page .lam-dialog-save:active {
|
[data-theme="lightblue"] .light-app-management-page .lam-dialog-save:active {
|
||||||
background-color: #0056C6;
|
background-color: #0056C6;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── iframe 菜单排序:拖拽行 + 拖拽手柄 ───────────────────────────────── */
|
|
||||||
.light-app-management-page .lam-reorder-row {
|
|
||||||
cursor: grab;
|
|
||||||
}
|
|
||||||
.light-app-management-page .lam-reorder-row:active {
|
|
||||||
cursor: grabbing;
|
|
||||||
}
|
|
||||||
/* 深蓝主题下手柄/箭头用次级文字色,避免在深底上发灰看不清 */
|
|
||||||
.dark .light-app-management-page .lam-drag-handle {
|
|
||||||
color: #4A6491;
|
|
||||||
}
|
|
||||||
.dark .light-app-management-page .lam-reorder-row:hover .lam-drag-handle {
|
|
||||||
color: #6E88B0;
|
|
||||||
}
|
|
||||||
@@ -31,8 +31,6 @@ export interface ChainCreatePayload {
|
|||||||
coordinatorPrompt?: string | null;
|
coordinatorPrompt?: string | null;
|
||||||
/** 默认席位执行模式(flash/thinking/pro/ultra);null = 未设。 */
|
/** 默认席位执行模式(flash/thinking/pro/ultra);null = 未设。 */
|
||||||
seatMode?: SeatMode | null;
|
seatMode?: SeatMode | null;
|
||||||
/** 研讨前并行取数开关(逐条 opt-in);缺省 false。 */
|
|
||||||
gatherFirst?: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Partial update — send only what changed. */
|
/** Partial update — send only what changed. */
|
||||||
@@ -48,19 +46,12 @@ export interface ChainUpdatePayload {
|
|||||||
coordinatorPrompt?: string | null;
|
coordinatorPrompt?: string | null;
|
||||||
/** 默认席位执行模式;send `null` to clear, omit to leave. */
|
/** 默认席位执行模式;send `null` to clear, omit to leave. */
|
||||||
seatMode?: SeatMode | null;
|
seatMode?: SeatMode | null;
|
||||||
/** 研讨前并行取数开关;send true/false 改,omit 不改。 */
|
|
||||||
gatherFirst?: boolean;
|
|
||||||
/** 发布开关:true 发布为公共 / false 取消发布;omit 不改。仅 owner 生效。 */
|
/** 发布开关:true 发布为公共 / false 取消发布;omit 不改。仅 owner 生效。 */
|
||||||
isPublic?: boolean;
|
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`;
|
const BASE = () => `${getBackendBaseURL()}/api/roundtable-chains`;
|
||||||
|
|
||||||
@@ -85,7 +76,6 @@ interface ServerChain {
|
|||||||
stage_goals?: (string | null)[] | null;
|
stage_goals?: (string | null)[] | null;
|
||||||
coordinator_prompt?: string | null;
|
coordinator_prompt?: string | null;
|
||||||
seat_mode?: string | null;
|
seat_mode?: string | null;
|
||||||
gather_first?: boolean;
|
|
||||||
is_public?: boolean;
|
is_public?: boolean;
|
||||||
is_mine?: boolean;
|
is_mine?: boolean;
|
||||||
owner_name?: string | null;
|
owner_name?: string | null;
|
||||||
@@ -103,7 +93,6 @@ function toChain(s: ServerChain): BusinessChain {
|
|||||||
stageGoals: Array.isArray(s.stage_goals) ? s.stage_goals : null,
|
stageGoals: Array.isArray(s.stage_goals) ? s.stage_goals : null,
|
||||||
coordinatorPrompt: s.coordinator_prompt ?? null,
|
coordinatorPrompt: s.coordinator_prompt ?? null,
|
||||||
seatMode: (s.seat_mode as SeatMode | null) ?? undefined,
|
seatMode: (s.seat_mode as SeatMode | null) ?? undefined,
|
||||||
gatherFirst: s.gather_first ?? false,
|
|
||||||
isPublic: s.is_public ?? false,
|
isPublic: s.is_public ?? false,
|
||||||
// 后端缺省时按「我的」处理(向后兼容旧响应)。
|
// 后端缺省时按「我的」处理(向后兼容旧响应)。
|
||||||
isMine: s.is_mine ?? true,
|
isMine: s.is_mine ?? true,
|
||||||
@@ -123,7 +112,6 @@ function fromCreate(p: ChainCreatePayload) {
|
|||||||
...(p.stageGoals !== undefined ? { stage_goals: p.stageGoals } : {}),
|
...(p.stageGoals !== undefined ? { stage_goals: p.stageGoals } : {}),
|
||||||
...(p.coordinatorPrompt !== undefined ? { coordinator_prompt: p.coordinatorPrompt } : {}),
|
...(p.coordinatorPrompt !== undefined ? { coordinator_prompt: p.coordinatorPrompt } : {}),
|
||||||
...(p.seatMode !== undefined ? { seat_mode: p.seatMode } : {}),
|
...(p.seatMode !== undefined ? { seat_mode: p.seatMode } : {}),
|
||||||
...(p.gatherFirst !== undefined ? { gather_first: p.gatherFirst } : {}),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +126,6 @@ function fromUpdate(p: ChainUpdatePayload) {
|
|||||||
if (p.stageGoals !== undefined) out.stage_goals = p.stageGoals;
|
if (p.stageGoals !== undefined) out.stage_goals = p.stageGoals;
|
||||||
if (p.coordinatorPrompt !== undefined) out.coordinator_prompt = p.coordinatorPrompt;
|
if (p.coordinatorPrompt !== undefined) out.coordinator_prompt = p.coordinatorPrompt;
|
||||||
if (p.seatMode !== undefined) out.seat_mode = p.seatMode;
|
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;
|
if (p.isPublic !== undefined) out.is_public = p.isPublic;
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
@@ -151,7 +138,7 @@ function fromUpdate(p: ChainUpdatePayload) {
|
|||||||
* - `"public"`:所有已发布的公共链条(任何账号可见 / 可选入研讨)。
|
* - `"public"`:所有已发布的公共链条(任何账号可见 / 可选入研讨)。
|
||||||
*/
|
*/
|
||||||
export async function listChains(scope: ChainScope = "mine"): Promise<BusinessChain[]> {
|
export async function listChains(scope: ChainScope = "mine"): Promise<BusinessChain[]> {
|
||||||
const url = scope === "mine" ? BASE() : `${BASE()}?scope=${scope}`;
|
const url = scope === "public" ? `${BASE()}?scope=public` : BASE();
|
||||||
const res = await apiFetch(url, { method: "GET" });
|
const res = await apiFetch(url, { method: "GET" });
|
||||||
const data = await readJson<{ chains: ServerChain[] }>(res, "list chains");
|
const data = await readJson<{ chains: ServerChain[] }>(res, "list chains");
|
||||||
return (data.chains ?? []).map(toChain);
|
return (data.chains ?? []).map(toChain);
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
/**
|
|
||||||
* 大屏绘制智能体「独立页面」会话持久化 —— 按外部 taskId 存取(后端不按 user 分权)。
|
|
||||||
*
|
|
||||||
* 一个 taskId 一条会话:聊天记录(transcript)+ 最新结构化数据(reportJson)。
|
|
||||||
* 后端 `/api/dashboard-sessions/by-task/{taskId}`(GET 取 / PUT upsert)。
|
|
||||||
* 详见后端 `app/gateway/routers/dashboard_sessions.py`。
|
|
||||||
*/
|
|
||||||
import { apiFetch } from "@/core/api/fetch-client";
|
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
|
||||||
|
|
||||||
export interface DashboardSession {
|
|
||||||
taskId: string;
|
|
||||||
/** 聊天记录(大屏绘制智能体对话气泡数组;形状与 Step2Dialogue 一致,宽松存取)。 */
|
|
||||||
transcript: unknown[] | null;
|
|
||||||
/** 最新结构化数据(report-json 字符串);可被 parseReportJson 解析则视为「有效结果」。 */
|
|
||||||
reportJson: string | null;
|
|
||||||
updatedAt: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ServerDashboardSession {
|
|
||||||
task_id: string;
|
|
||||||
transcript: unknown[] | null;
|
|
||||||
report_json: string | null;
|
|
||||||
created_at?: string | null;
|
|
||||||
updated_at?: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const BASE = () => `${getBackendBaseURL()}/api/dashboard-sessions`;
|
|
||||||
|
|
||||||
function toClient(s: ServerDashboardSession): DashboardSession {
|
|
||||||
return {
|
|
||||||
taskId: s.task_id,
|
|
||||||
transcript: Array.isArray(s.transcript) ? s.transcript : null,
|
|
||||||
reportJson: s.report_json ?? null,
|
|
||||||
updatedAt: s.updated_at ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 取该 taskId 的会话;无(404)返回 null。 */
|
|
||||||
export async function getDashboardSessionByTask(taskId: string): Promise<DashboardSession | null> {
|
|
||||||
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}`, { method: "GET" });
|
|
||||||
if (res.status === 404) return null;
|
|
||||||
if (!res.ok) {
|
|
||||||
const text = await res.text().catch(() => "");
|
|
||||||
throw new Error(`get dashboard session failed (${res.status}): ${text}`);
|
|
||||||
}
|
|
||||||
return toClient((await res.json()) as ServerDashboardSession);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** upsert 该 taskId 的会话(只传需要更新的字段)。 */
|
|
||||||
export async function putDashboardSessionByTask(
|
|
||||||
taskId: string,
|
|
||||||
patch: { transcript?: unknown[]; reportJson?: string | null },
|
|
||||||
): Promise<DashboardSession | null> {
|
|
||||||
const body: Record<string, unknown> = {};
|
|
||||||
if (patch.transcript !== undefined) body.transcript = patch.transcript;
|
|
||||||
if (patch.reportJson !== undefined) body.report_json = patch.reportJson;
|
|
||||||
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}`, {
|
|
||||||
method: "PUT",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const text = await res.text().catch(() => "");
|
|
||||||
throw new Error(`put dashboard session failed (${res.status}): ${text}`);
|
|
||||||
}
|
|
||||||
return toClient((await res.json()) as ServerDashboardSession);
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
/**
|
|
||||||
* 会商「前端调用报错」上报器。
|
|
||||||
*
|
|
||||||
* 服务端诊断只能记到「处理函数跑起来后抛的错」;而用户实际遇到的很多报错(nginx/网关
|
|
||||||
* 返回 502、网络中断、fetch 直接失败、SSE 里收到的 error 帧)发生在**客户端**侧。这里把
|
|
||||||
* 这些前端可观测到的报错 best-effort 上报到 `POST /api/roundtable-diagnostics/report`
|
|
||||||
* (scope="client",非 admin 接口),便于管理员在诊断页统一筛选用户使用时的报错。
|
|
||||||
*
|
|
||||||
* 设计:fire-and-forget + `keepalive`(页面跳转也能发出去)+ 绝不抛错(上报失败就算了,
|
|
||||||
* 不能让「报错上报」本身再影响会商流程)。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { apiFetch } from "@/core/api/fetch-client";
|
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
|
||||||
|
|
||||||
export interface RoundtableErrorReport {
|
|
||||||
stage: string;
|
|
||||||
event: string;
|
|
||||||
message: string;
|
|
||||||
level?: "error" | "warning" | "info";
|
|
||||||
detail?: unknown;
|
|
||||||
agentId?: string;
|
|
||||||
agentName?: string;
|
|
||||||
cycle?: number;
|
|
||||||
draftId?: string;
|
|
||||||
taskId?: string;
|
|
||||||
jobId?: string;
|
|
||||||
httpStatus?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 页面级上下文(draftId / taskId),由会商页设置,使每条上报都能归属到草稿/任务,
|
|
||||||
// 而无需把它们穿进每个底层 api 调用。
|
|
||||||
let _ctx: { draftId?: string; taskId?: string } = {};
|
|
||||||
|
|
||||||
export function setRoundtableErrorContext(ctx: { draftId?: string; taskId?: string }): void {
|
|
||||||
_ctx = { ..._ctx, ...ctx };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 据 agentType + agentName 推断诊断 stage(与后端 `_stage_for_agent` 对齐)。 */
|
|
||||||
export function stageForRoundtableAgent(
|
|
||||||
agentType: string | undefined,
|
|
||||||
agentName: string | null | undefined,
|
|
||||||
): string {
|
|
||||||
switch (agentName) {
|
|
||||||
case "roundtable-report":
|
|
||||||
return "step3_report";
|
|
||||||
case "roundtable-summary":
|
|
||||||
return "step3_summary";
|
|
||||||
case "roundtable-dashboard":
|
|
||||||
return "step3_dashboard";
|
|
||||||
case "roundtable-structure":
|
|
||||||
return "step3_structure";
|
|
||||||
default:
|
|
||||||
return agentType === "leader" ? "step2_leader" : "step2_seat";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function reportRoundtableError(input: RoundtableErrorReport): void {
|
|
||||||
try {
|
|
||||||
const detail =
|
|
||||||
input.httpStatus != null && typeof input.detail !== "object"
|
|
||||||
? { httpStatus: input.httpStatus, raw: input.detail }
|
|
||||||
: input.httpStatus != null
|
|
||||||
? { httpStatus: input.httpStatus, ...(input.detail as Record<string, unknown>) }
|
|
||||||
: input.detail;
|
|
||||||
const body = JSON.stringify({
|
|
||||||
stage: input.stage,
|
|
||||||
event: input.event,
|
|
||||||
level: input.level ?? "error",
|
|
||||||
message: (input.message ?? "").slice(0, 2000),
|
|
||||||
detail,
|
|
||||||
jobId: input.jobId,
|
|
||||||
draftId: input.draftId ?? _ctx.draftId,
|
|
||||||
taskId: input.taskId ?? _ctx.taskId,
|
|
||||||
agentId: input.agentId,
|
|
||||||
agentName: input.agentName,
|
|
||||||
cycle: input.cycle,
|
|
||||||
});
|
|
||||||
void apiFetch(`${getBackendBaseURL()}/api/roundtable-diagnostics/report`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body,
|
|
||||||
keepalive: true,
|
|
||||||
}).catch(() => {
|
|
||||||
/* 上报失败静默 */
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
/* 绝不抛错 */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -133,18 +133,6 @@ export interface DraftStep3Snapshot {
|
|||||||
* 与经典 `html`(模式一)并存互不覆盖。后台挂起与手动并行绘制都写这里。Optional.
|
* 与经典 `html`(模式一)并存互不覆盖。后台挂起与手动并行绘制都写这里。Optional.
|
||||||
*/
|
*/
|
||||||
dashboardJson?: string | null;
|
dashboardJson?: string | null;
|
||||||
/**
|
|
||||||
* 第三步「结果绘制(经典 HTML 看板)」生成过程的完整对话气泡(中间文字 + 步骤条),与第二步
|
|
||||||
* `step2RoundtableDialogues` 同形(`Step2Dialogue[]`)。存它使加载后能回显整段绘制过程,而非
|
|
||||||
* 只有最终 HTML。Optional —— 旧草稿没有该字段,恢复时回退为重建单条「历史记录」气泡。
|
|
||||||
*/
|
|
||||||
reportDialogues?: unknown[];
|
|
||||||
/** 经典看板各席位 write_file 调用重建的 stub(threadId → [stub ai message]),供加载后点开产物预览。 */
|
|
||||||
reportSeatStubMessages?: Record<string, unknown[]>;
|
|
||||||
/** 第三步「大屏多页」生成过程的完整对话气泡(中间文字 + 步骤条),同 `reportDialogues`。Optional。 */
|
|
||||||
dashboardDialogues?: unknown[];
|
|
||||||
/** 大屏各席位 write_file 调用重建的 stub。Optional。 */
|
|
||||||
dashboardSeatStubMessages?: Record<string, unknown[]>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -164,20 +152,6 @@ export interface DraftStep3SummarySnapshot {
|
|||||||
model: string;
|
model: string;
|
||||||
/** The agent's closing chat text (the report body it echoed into the conversation). */
|
/** The agent's closing chat text (the report body it echoed into the conversation). */
|
||||||
closing?: string;
|
closing?: string;
|
||||||
/**
|
|
||||||
* 第三步「总结报告」生成过程的**完整对话气泡**(含中间文字内容 + 每条气泡的步骤条
|
|
||||||
* `steps`),与第二步 `step2RoundtableDialogues` 同形(`Step2Dialogue[]`)。存它使加载
|
|
||||||
* 草稿后能像第二步一样回显整段研讨过程,而不只是最终 md / 流程图。Optional —— 此前
|
|
||||||
* 的草稿没有该字段,恢复时回退为重建单条「历史记录」气泡。
|
|
||||||
*/
|
|
||||||
dialogues?: unknown[];
|
|
||||||
/** 各席位 write_file 调用重建的 stub(threadId → [stub ai message]),供加载后点开产物的虚拟预览。 */
|
|
||||||
seatStubMessages?: Record<string, unknown[]>;
|
|
||||||
/**
|
|
||||||
* 入库状态(idle/asking/running/done/later/declined)。存它使重载草稿后不重复询问
|
|
||||||
* 已入库/已选稍后的会商;恢复展示用。Optional —— 旧草稿无该字段。
|
|
||||||
*/
|
|
||||||
ingestStatus?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Lightweight metadata row returned by the list endpoint. */
|
/** Lightweight metadata row returned by the list endpoint. */
|
||||||
@@ -232,7 +206,7 @@ export interface DraftUpdatePayload {
|
|||||||
|
|
||||||
const BASE = () => `${getBackendBaseURL()}/api/roundtable-drafts`;
|
const BASE = () => `${getBackendBaseURL()}/api/roundtable-drafts`;
|
||||||
|
|
||||||
export async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text().catch(() => "");
|
const text = await res.text().catch(() => "");
|
||||||
throw new Error(`${ctx} failed (${res.status}): ${text}`);
|
throw new Error(`${ctx} failed (${res.status}): ${text}`);
|
||||||
@@ -243,9 +217,8 @@ export async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
|||||||
// ── server ⇄ client field mapping ──────────────────────────────────────────
|
// ── server ⇄ client field mapping ──────────────────────────────────────────
|
||||||
// Backend uses snake_case (furthest_step / created_at / updated_at); the rest
|
// Backend uses snake_case (furthest_step / created_at / updated_at); the rest
|
||||||
// of the frontend reads camelCase. Map at this boundary so callers stay clean.
|
// of the frontend reads camelCase. Map at this boundary so callers stay clean.
|
||||||
// Shared with the task-scoped client (`task-drafts.ts`) — same wire shape.
|
|
||||||
|
|
||||||
export interface ServerDraftMeta {
|
interface ServerDraftMeta {
|
||||||
id: string;
|
id: string;
|
||||||
task_id?: string | null;
|
task_id?: string | null;
|
||||||
title: string;
|
title: string;
|
||||||
@@ -256,13 +229,13 @@ export interface ServerDraftMeta {
|
|||||||
job_id?: string | null;
|
job_id?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ServerDraftFull extends ServerDraftMeta {
|
interface ServerDraftFull extends ServerDraftMeta {
|
||||||
step1: DraftStep1Snapshot | null;
|
step1: DraftStep1Snapshot | null;
|
||||||
step2: DraftStep2Snapshot | null;
|
step2: DraftStep2Snapshot | null;
|
||||||
step3: DraftStep3Snapshot | null;
|
step3: DraftStep3Snapshot | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toMeta(s: ServerDraftMeta): DraftMeta {
|
function toMeta(s: ServerDraftMeta): DraftMeta {
|
||||||
const step = Math.min(3, Math.max(1, s.furthest_step || 1)) as 1 | 2 | 3;
|
const step = Math.min(3, Math.max(1, s.furthest_step || 1)) as 1 | 2 | 3;
|
||||||
return {
|
return {
|
||||||
id: s.id,
|
id: s.id,
|
||||||
@@ -276,7 +249,7 @@ export function toMeta(s: ServerDraftMeta): DraftMeta {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toRecord(s: ServerDraftFull): DraftRecord {
|
function toRecord(s: ServerDraftFull): DraftRecord {
|
||||||
return {
|
return {
|
||||||
...toMeta(s),
|
...toMeta(s),
|
||||||
step1: s.step1 ?? null,
|
step1: s.step1 ?? null,
|
||||||
@@ -285,7 +258,7 @@ export function toRecord(s: ServerDraftFull): DraftRecord {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function fromCreate(p: DraftCreatePayload) {
|
function fromCreate(p: DraftCreatePayload) {
|
||||||
return {
|
return {
|
||||||
...(p.id ? { id: p.id } : {}),
|
...(p.id ? { id: p.id } : {}),
|
||||||
...(p.taskId ? { task_id: p.taskId } : {}),
|
...(p.taskId ? { task_id: p.taskId } : {}),
|
||||||
@@ -297,7 +270,7 @@ export function fromCreate(p: DraftCreatePayload) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function fromUpdate(p: DraftUpdatePayload) {
|
function fromUpdate(p: DraftUpdatePayload) {
|
||||||
const out: Record<string, unknown> = {};
|
const out: Record<string, unknown> = {};
|
||||||
if (p.title !== undefined) out.title = p.title;
|
if (p.title !== undefined) out.title = p.title;
|
||||||
if (p.furthestStep !== undefined) out.furthest_step = p.furthestStep;
|
if (p.furthestStep !== undefined) out.furthest_step = p.furthestStep;
|
||||||
@@ -325,6 +298,17 @@ export async function getDraft(id: string): Promise<DraftRecord | null> {
|
|||||||
return toRecord(data);
|
return toRecord(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按外部任务 id 取最新一条草稿(后端忽略 user,不分权)。无则返回 null(404)。
|
||||||
|
* 无界嵌入抽屉打开时用于「该任务有聊天记录则回显最新一条」。
|
||||||
|
*/
|
||||||
|
export async function getLatestDraftByTask(taskId: string): Promise<DraftRecord | null> {
|
||||||
|
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}/latest`, { method: "GET" });
|
||||||
|
if (res.status === 404) return null;
|
||||||
|
const data = await readJson<ServerDraftFull>(res, "get latest draft by task");
|
||||||
|
return toRecord(data);
|
||||||
|
}
|
||||||
|
|
||||||
export async function createDraft(payload: DraftCreatePayload): Promise<DraftRecord> {
|
export async function createDraft(payload: DraftCreatePayload): Promise<DraftRecord> {
|
||||||
const res = await apiFetch(BASE(), {
|
const res = await apiFetch(BASE(), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|||||||
@@ -1,188 +0,0 @@
|
|||||||
/**
|
|
||||||
* Step3 流程图「后端抽取 + 校验」SSE 客户端。
|
|
||||||
*
|
|
||||||
* 对应后端 `POST /api/flow-extract/stream`:后端独立调模型(不走总结线程,避开 coordinatorPrompt
|
|
||||||
* 的报告锚定)两段式产图——①流式抽取 flow-json(实时吐回,前端原样显示给用户看)→ ②模型校验/修复
|
|
||||||
* → 返回校验后的结构化图数据 `{title, nodes, edges}`。
|
|
||||||
*
|
|
||||||
* 这样把不稳定的「文本→结构」抽取 + 校验放后端,前端只负责实时显示抽取过程 + 拿最终图绘制。
|
|
||||||
*/
|
|
||||||
import { apiFetch } from "@/core/api/fetch-client";
|
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
|
||||||
import type { FlowGraphData } from "@/roundtable-planning/lib/flow-graph";
|
|
||||||
|
|
||||||
/** 第三步输入框意图分类结果(与后端 /intent 对应)。 */
|
|
||||||
export type FlowIntent = "regenerate_report" | "modify_flow" | "regenerate_flow" | "ingest" | "qa" | "unclear";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 识别第三步输入框消息的意图(一次模型调用)。失败回退 "unclear"(前端发起澄清)。
|
|
||||||
* 参考 ai_writing 的一次性 JSON 意图识别范式。
|
|
||||||
*/
|
|
||||||
export async function classifyFlowIntent(req: {
|
|
||||||
message: string;
|
|
||||||
hasReport: boolean;
|
|
||||||
hasFlow: boolean;
|
|
||||||
/** 当前是否可入库(入库按钮已出现、未入库);为真才允许识别出 ingest 意图。 */
|
|
||||||
canIngest?: boolean;
|
|
||||||
model?: string;
|
|
||||||
signal?: AbortSignal;
|
|
||||||
}): Promise<{ intent: FlowIntent; reason: string }> {
|
|
||||||
try {
|
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/intent`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
message: req.message,
|
|
||||||
has_report: req.hasReport,
|
|
||||||
has_flow: req.hasFlow,
|
|
||||||
can_ingest: req.canIngest ?? false,
|
|
||||||
model: req.model,
|
|
||||||
}),
|
|
||||||
signal: req.signal,
|
|
||||||
});
|
|
||||||
if (!res.ok) return { intent: "unclear", reason: "" };
|
|
||||||
const data = (await res.json()) as { intent?: string; reason?: string };
|
|
||||||
const intent = (data.intent ?? "unclear") as FlowIntent;
|
|
||||||
return { intent, reason: data.reason ?? "" };
|
|
||||||
} catch {
|
|
||||||
return { intent: "unclear", reason: "" };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 「稍后入库」待命时输入框消息的入库意图(与后端 /ingest-intent 对应)。 */
|
|
||||||
export type IngestIntent = "start_ingest" | "add_data" | "other" | "unclear";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 识别「稍后入库」后用户在输入框的入库意图(一次模型调用)。
|
|
||||||
* 失败回退 "unclear"(前端发起协助让用户自己选)。
|
|
||||||
*/
|
|
||||||
export async function classifyIngestIntent(req: {
|
|
||||||
message: string;
|
|
||||||
model?: string;
|
|
||||||
signal?: AbortSignal;
|
|
||||||
}): Promise<{ intent: IngestIntent; reason: string }> {
|
|
||||||
try {
|
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/ingest-intent`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ message: req.message, model: req.model }),
|
|
||||||
signal: req.signal,
|
|
||||||
});
|
|
||||||
if (!res.ok) return { intent: "unclear", reason: "" };
|
|
||||||
const data = (await res.json()) as { intent?: string; reason?: string };
|
|
||||||
return { intent: (data.intent ?? "unclear") as IngestIntent, reason: data.reason ?? "" };
|
|
||||||
} catch {
|
|
||||||
return { intent: "unclear", reason: "" };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface FlowExtractRequest {
|
|
||||||
/** 报告 Markdown(优先数据来源)。 */
|
|
||||||
reportMd?: string | null;
|
|
||||||
/** 各席位交付(无报告时的数据来源)。 */
|
|
||||||
seatDeliveries?: Array<{ sender: string; content: string }>;
|
|
||||||
/** 业务链层级(stages 的 goal)。 */
|
|
||||||
chainLevels?: string[];
|
|
||||||
/** 业务链总控编排提示(写明层级时优先用它)。 */
|
|
||||||
coordinatorPrompt?: string | null;
|
|
||||||
/** 深链接业务码(rwfx→6BF 等)。非空 → 后端按业务链抽取规范强制注入完整层级。 */
|
|
||||||
businessCode?: string | null;
|
|
||||||
/** 根节点 label 强制值(xdfx:本次行动名称)。非空 → 根节点 n1 用它,不用任务名当根。 */
|
|
||||||
rootLabel?: string | null;
|
|
||||||
/** 推理模型名(沿用第三步所选)。 */
|
|
||||||
model?: string;
|
|
||||||
/** Phase 2 问答修改:当前流程图 + 指令 → 按指令改图(其余不变)。 */
|
|
||||||
currentGraph?: FlowGraphData | null;
|
|
||||||
instruction?: string;
|
|
||||||
signal?: AbortSignal;
|
|
||||||
/** 抽取流式增量(含 `<think>` 思考 + 正文 + JSON,前端原样渲染:思考块 + 代码块)。 */
|
|
||||||
onExtractDelta?: (text: string) => void;
|
|
||||||
/** 抽取结束、进入校验阶段。 */
|
|
||||||
onValidating?: () => void;
|
|
||||||
/** 校验/修复流式增量(同样含思考 + 正文,前端实时显示校验过程)。 */
|
|
||||||
onValidateDelta?: (text: string) => void;
|
|
||||||
/**
|
|
||||||
* 模型自动容错:后端某模型抽取失败,已切到下一个模型重抽。上层据此**清空已累计的抽取增量**
|
|
||||||
* (`onExtractDelta` 之前吐出的半截内容)并提示用户。`failedModel`/`nextModel`/`reason` 描述切换。
|
|
||||||
*/
|
|
||||||
onModelSwitch?: (info: { failedModel: string; nextModel: string; reason: string }) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 消费 SSE,返回校验后的最终图。抽取阶段通过 `onExtractDelta` 实时回吐;
|
|
||||||
* 出错(后端 error 帧 / 网络)抛异常。
|
|
||||||
*/
|
|
||||||
export async function streamFlowExtract(req: FlowExtractRequest): Promise<FlowGraphData> {
|
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/stream`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
report_md: req.reportMd ?? null,
|
|
||||||
seat_deliveries: (req.seatDeliveries ?? []).map((s) => ({ sender: s.sender, content: s.content })),
|
|
||||||
chain_levels: req.chainLevels ?? [],
|
|
||||||
coordinator_prompt: req.coordinatorPrompt ?? null,
|
|
||||||
business_code: req.businessCode ?? null,
|
|
||||||
root_label: req.rootLabel ?? null,
|
|
||||||
model: req.model,
|
|
||||||
current_graph: req.currentGraph ?? null,
|
|
||||||
instruction: req.instruction ?? null,
|
|
||||||
}),
|
|
||||||
signal: req.signal,
|
|
||||||
});
|
|
||||||
if (!res.ok || !res.body) {
|
|
||||||
const text = await res.text().catch(() => "");
|
|
||||||
throw new Error(`flow-extract failed (${res.status}): ${text}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const reader = res.body.getReader();
|
|
||||||
const decoder = new TextDecoder();
|
|
||||||
let buffer = "";
|
|
||||||
let graph: FlowGraphData | null = null;
|
|
||||||
let errored: string | null = null;
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const { done, value } = await reader.read();
|
|
||||||
if (done) break;
|
|
||||||
buffer += decoder.decode(value, { stream: true });
|
|
||||||
const lines = buffer.split("\n");
|
|
||||||
buffer = lines.pop() ?? "";
|
|
||||||
for (const rawLine of lines) {
|
|
||||||
const line = rawLine.trimEnd();
|
|
||||||
if (!line.startsWith("data:")) continue;
|
|
||||||
const data = line.slice(5).trim();
|
|
||||||
if (!data) continue;
|
|
||||||
let frame: Record<string, unknown>;
|
|
||||||
try {
|
|
||||||
frame = JSON.parse(data) as Record<string, unknown>;
|
|
||||||
} catch {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const event = typeof frame.event === "string" ? frame.event : "";
|
|
||||||
if (event === "extract_delta") {
|
|
||||||
const c = typeof frame.content === "string" ? frame.content : "";
|
|
||||||
if (c) req.onExtractDelta?.(c);
|
|
||||||
} else if (event === "validating") {
|
|
||||||
req.onValidating?.();
|
|
||||||
} else if (event === "validate_delta") {
|
|
||||||
const c = typeof frame.content === "string" ? frame.content : "";
|
|
||||||
if (c) req.onValidateDelta?.(c);
|
|
||||||
} else if (event === "model_switch") {
|
|
||||||
req.onModelSwitch?.({
|
|
||||||
failedModel: typeof frame.failed_model === "string" ? frame.failed_model : "",
|
|
||||||
nextModel: typeof frame.next_model === "string" ? frame.next_model : "",
|
|
||||||
reason: typeof frame.reason === "string" ? frame.reason : "",
|
|
||||||
});
|
|
||||||
} else if (event === "final") {
|
|
||||||
graph = (frame.graph as FlowGraphData) ?? null;
|
|
||||||
} else if (event === "error") {
|
|
||||||
errored = typeof frame.detail === "string" ? frame.detail : "未知错误";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (errored) throw new Error(errored);
|
|
||||||
if (!graph || !Array.isArray(graph.nodes) || graph.nodes.length === 0) {
|
|
||||||
throw new Error("flow-extract 未返回有效流程图");
|
|
||||||
}
|
|
||||||
return graph;
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
/**
|
|
||||||
* 第三步「入库」功能门控 + 入库执行客户端。
|
|
||||||
*
|
|
||||||
* 入库不再由前端硬编码「有没有含『入库』关键字的技能」判定,而是让**结构化输出智能体**
|
|
||||||
* (`roundtable-structure`)读它挂载的入库技能 + 当前业务场景,**自行判断**是否有适合本
|
|
||||||
* 场景的入库技能(技能名可能含「六步法」等场景线索)。判定为可入库才显示「入库」按钮。
|
|
||||||
*
|
|
||||||
* 真正入库时,由结构化输出智能体走**完整 agent 运行时**(`POST /api/multi-agent/run/stream`,
|
|
||||||
* role=ingest)**自己挑技能、读 SKILL.md 并调用**完成入库——而不是前端代它调技能。
|
|
||||||
*/
|
|
||||||
import { apiFetch } from "@/core/api/fetch-client";
|
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
|
||||||
|
|
||||||
/** `/ingest-eligibility` 返回:是否可入库 + 选中的技能名 + 一句话依据。 */
|
|
||||||
export interface IngestEligibility {
|
|
||||||
canIngest: boolean;
|
|
||||||
skill: string;
|
|
||||||
reason: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 让结构化输出智能体判断「当前业务场景**是否有合适的入库技能**」(决定是否显示入库按钮)。
|
|
||||||
*
|
|
||||||
* 入参为业务场景线索(业务码 / 业务链名 / 总控编排提示 / 方案标题)+ taskId,由后端把挂在
|
|
||||||
* `roundtable-structure` 上、且已启用的技能交给模型对照判断。失败 / 未配置入库技能 → 不可入库。
|
|
||||||
*/
|
|
||||||
export async function checkIngestEligibility(req: {
|
|
||||||
taskId?: string | null;
|
|
||||||
businessCode?: string | null;
|
|
||||||
chainName?: string | null;
|
|
||||||
coordinatorPrompt?: string | null;
|
|
||||||
reportTitle?: string | null;
|
|
||||||
model?: string;
|
|
||||||
}): Promise<IngestEligibility> {
|
|
||||||
try {
|
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/flow-extract/ingest-eligibility`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
task_id: req.taskId ?? null,
|
|
||||||
business_code: req.businessCode ?? null,
|
|
||||||
chain_name: req.chainName ?? null,
|
|
||||||
coordinator_prompt: req.coordinatorPrompt ?? null,
|
|
||||||
report_title: req.reportTitle ?? null,
|
|
||||||
model: req.model,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
if (!res.ok) return { canIngest: false, skill: "", reason: "" };
|
|
||||||
const data = (await res.json()) as { can_ingest?: boolean; skill?: string; reason?: string };
|
|
||||||
return {
|
|
||||||
canIngest: !!data.can_ingest,
|
|
||||||
skill: data.skill ?? "",
|
|
||||||
reason: data.reason ?? "",
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return { canIngest: false, skill: "", reason: "" };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,6 @@ import { apiFetch } from "@/core/api/fetch-client";
|
|||||||
import { getBackendBaseURL } from "@/core/config";
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
|
|
||||||
import type { ClarificationPayload } from "./multi-agent";
|
import type { ClarificationPayload } from "./multi-agent";
|
||||||
import { reportRoundtableError } from "./diagnostics-report";
|
|
||||||
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
||||||
|
|
||||||
export type { ClarificationPayload };
|
export type { ClarificationPayload };
|
||||||
@@ -341,11 +340,6 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
|||||||
|
|
||||||
if (!res.ok || !res.body) {
|
if (!res.ok || !res.body) {
|
||||||
const text = await res.text().catch(() => "");
|
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}`);
|
throw new Error(`intent/stream failed (${res.status}): ${text}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -431,11 +425,6 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
|||||||
}
|
}
|
||||||
if (parsed.status === "error") {
|
if (parsed.status === "error") {
|
||||||
result.errorDetail = parseIntentErrorDetail(parsed.error_detail);
|
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) {
|
if (parsed.status === "clarification" && result.clarifications.length === 0) {
|
||||||
// Fallback path: no live `type:"tool"` clarification frames were seen
|
// Fallback path: no live `type:"tool"` clarification frames were seen
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { apiFetch } from "@/core/api/fetch-client";
|
|||||||
import { getBackendBaseURL } from "@/core/config";
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
|
|
||||||
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
||||||
import { reportRoundtableError, stageForRoundtableAgent } from "@/roundtable-planning/api/diagnostics-report";
|
|
||||||
|
|
||||||
export type ThreadIdMap = Record<string, string>;
|
export type ThreadIdMap = Record<string, string>;
|
||||||
|
|
||||||
@@ -75,12 +74,6 @@ export async function initMultiAgent(
|
|||||||
tlog(`fetch.headers status=${res.status}`);
|
tlog(`fetch.headers status=${res.status}`);
|
||||||
if (!res.ok || !res.body) {
|
if (!res.ok || !res.body) {
|
||||||
const text = await res.text().catch(() => "");
|
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}`);
|
throw new Error(`init multi-agent failed (${res.status}): ${text}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,34 +150,18 @@ export async function initMultiAgent(
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
aborted = (err as Error)?.name === "AbortError" || payload.signal?.aborted === true;
|
aborted = (err as Error)?.name === "AbortError" || payload.signal?.aborted === true;
|
||||||
if (!aborted) {
|
if (!aborted) throw err;
|
||||||
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})`);
|
tlog(`total ${(performance.now() - t0).toFixed(0)}ms (seats=${seatCount})`);
|
||||||
|
|
||||||
if (errorDetail) {
|
if (errorDetail) {
|
||||||
reportRoundtableError({
|
|
||||||
stage: "step2_init", event: "init_error_frame",
|
|
||||||
message: `第二步会商初始化报错:${errorDetail.slice(0, 800)}`,
|
|
||||||
});
|
|
||||||
throw new Error(`init multi-agent failed: ${errorDetail}`);
|
throw new Error(`init multi-agent failed: ${errorDetail}`);
|
||||||
}
|
}
|
||||||
if (aborted) {
|
if (aborted) {
|
||||||
throw new DOMException("init aborted", "AbortError");
|
throw new DOMException("init aborted", "AbortError");
|
||||||
}
|
}
|
||||||
if (!threadIds || !mainAgentName) {
|
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");
|
throw new Error("init multi-agent stream ended without init_done");
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
@@ -234,17 +211,6 @@ export interface StreamMultiAgentRequest {
|
|||||||
reasoningEffort?: "minimal" | "low" | "medium" | "high";
|
reasoningEffort?: "minimal" | "low" | "medium" | "high";
|
||||||
/** 仅 special 用;ultra 档置真,给席位解锁 `task` 子代理工具。 */
|
/** 仅 special 用;ultra 档置真,给席位解锁 `task` 子代理工具。 */
|
||||||
subagentEnabled?: boolean;
|
subagentEnabled?: boolean;
|
||||||
/**
|
|
||||||
* 仅 special 用。会商席位「技能识别强化」开关(沿用所选业务链条配置)。置 true 时后端把该
|
|
||||||
* 席位配置的技能(含 SKILL.md 路径 + 必须先 read_file 的硬指令)拼进本轮任务,补偿弱模型。
|
|
||||||
* 与该席位 agent 自身 config.yaml 的同名开关取 OR。省略 = false(关)。
|
|
||||||
*/
|
|
||||||
seatSkillDirective?: boolean;
|
|
||||||
/**
|
|
||||||
* 深链接业务码(rwfx→6BF 等)。**仅方案总结报告(summary)单例消费**:非空 → 后端按业务链抽取规范
|
|
||||||
* 强制注入「完整性核对」指令,让总结核对产出相对业务链完不完整。普通会商省略 = 不注入。
|
|
||||||
*/
|
|
||||||
businessCode?: string | null;
|
|
||||||
skillStopNames?: string[];
|
skillStopNames?: string[];
|
||||||
/**
|
/**
|
||||||
* 仅 leader 用。置 true 表示这是「派活后让总控判断继续/综合」的轮次:后端会把各已交付
|
* 仅 leader 用。置 true 表示这是「派活后让总控判断继续/综合」的轮次:后端会把各已交付
|
||||||
@@ -297,27 +263,6 @@ export interface StreamMultiAgentRequest {
|
|||||||
name?: string,
|
name?: string,
|
||||||
args?: Record<string, unknown>,
|
args?: Record<string, unknown>,
|
||||||
) => void;
|
) => 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 {
|
export interface ClarificationPayload {
|
||||||
@@ -351,8 +296,6 @@ export interface StreamMultiAgentResult {
|
|||||||
content: string;
|
content: string;
|
||||||
/** Echoed agent_name of the agent that produced this run. */
|
/** Echoed agent_name of the agent that produced this run. */
|
||||||
agentName: string | null;
|
agentName: string | null;
|
||||||
/** 实际产出本轮结果的模型(发生模型自动容错时即最终切换到的模型);后端未下发时为 null。 */
|
|
||||||
modelUsed?: string | null;
|
|
||||||
/**
|
/**
|
||||||
* Populated when the leader called ask_clarification — the run ended without
|
* Populated when the leader called ask_clarification — the run ended without
|
||||||
* dispatching, and the model is asking the user a question instead. When
|
* dispatching, and the model is asking the user a question instead. When
|
||||||
@@ -499,11 +442,6 @@ function extractAiTextDelta(parsed: unknown): { text: string; id: string } | nul
|
|||||||
export async function streamMultiAgent(
|
export async function streamMultiAgent(
|
||||||
req: StreamMultiAgentRequest,
|
req: StreamMultiAgentRequest,
|
||||||
): Promise<StreamMultiAgentResult> {
|
): Promise<StreamMultiAgentResult> {
|
||||||
// 整段包一层兜底:除已在具体分支上报的(HTTP 错误 / error 帧 / worker error 事件)外,
|
|
||||||
// 再兜住 fetch 直接 reject(网络不可达 / 连接被拒)与流式中途中断(连接重置 / 超时),
|
|
||||||
// 做到「能收集到的报错越全越好」。`reported` 防止与具体分支重复上报。
|
|
||||||
let reported = false;
|
|
||||||
try {
|
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/run/stream`, {
|
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/run/stream`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -519,10 +457,6 @@ export async function streamMultiAgent(
|
|||||||
thinking_enabled: req.thinkingEnabled,
|
thinking_enabled: req.thinkingEnabled,
|
||||||
reasoning_effort: req.reasoningEffort,
|
reasoning_effort: req.reasoningEffort,
|
||||||
subagent_enabled: req.subagentEnabled,
|
subagent_enabled: req.subagentEnabled,
|
||||||
// 仅 special 用;会商技能识别强化(沿用所选业务链条开关)。省略 → 后端按 false(关)处理。
|
|
||||||
seat_skill_directive: req.seatSkillDirective ?? false,
|
|
||||||
// 仅 summary 单例用;深链接业务码 → 后端注入业务链完整性核对。省略/空 → 不注入。
|
|
||||||
business_code: req.businessCode ?? null,
|
|
||||||
skill_stop_names: req.skillStopNames ?? [],
|
skill_stop_names: req.skillStopNames ?? [],
|
||||||
// 仅 leader 用;综合轮让后端注入各席位完整交付正文。省略 → 后端按 false 处理。
|
// 仅 leader 用;综合轮让后端注入各席位完整交付正文。省略 → 后端按 false 处理。
|
||||||
synthesis_mode: req.synthesisMode ?? false,
|
synthesis_mode: req.synthesisMode ?? false,
|
||||||
@@ -540,17 +474,6 @@ export async function streamMultiAgent(
|
|||||||
|
|
||||||
if (!res.ok || !res.body) {
|
if (!res.ok || !res.body) {
|
||||||
const text = await res.text().catch(() => "");
|
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}`);
|
throw new Error(`run/stream failed (${res.status}): ${text}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -578,7 +501,6 @@ export async function streamMultiAgent(
|
|||||||
content: "",
|
content: "",
|
||||||
agentName: null,
|
agentName: null,
|
||||||
clarification: null,
|
clarification: null,
|
||||||
modelUsed: null,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Inferred SSE phase + a tiny helper so we only fire onPhaseChange when the
|
// Inferred SSE phase + a tiny helper so we only fire onPhaseChange when the
|
||||||
@@ -689,43 +611,6 @@ export async function streamMultiAgent(
|
|||||||
frameSeq += 1;
|
frameSeq += 1;
|
||||||
if (debugEnabled) console.debug(debugLabel, `frame#${frameSeq} event=${lastEvent}`, parsed);
|
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
|
// Phase inference from LangGraph messages-tuple frames. We only flip
|
||||||
// to tool_calling/tool_result on chunks that clearly indicate them;
|
// to tool_calling/tool_result on chunks that clearly indicate them;
|
||||||
// everything else with non-empty AI text means we're streaming.
|
// everything else with non-empty AI text means we're streaming.
|
||||||
@@ -826,22 +711,6 @@ export async function streamMultiAgent(
|
|||||||
if (typeof parsed.agent_name === "string") {
|
if (typeof parsed.agent_name === "string") {
|
||||||
result.agentName = parsed.agent_name;
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -859,19 +728,6 @@ export async function streamMultiAgent(
|
|||||||
console.debug(debugLabel, `stream ended after ${frameSeq} frames; final content length=${result.content.length}`);
|
console.debug(debugLabel, `stream ended after ${frameSeq} frames; final content length=${result.content.length}`);
|
||||||
}
|
}
|
||||||
return result;
|
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 {
|
export interface SessionArtifactFile {
|
||||||
@@ -973,48 +829,12 @@ export async function initReportThread(
|
|||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text().catch(() => "");
|
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}`);
|
throw new Error(`init report thread failed (${res.status}): ${text}`);
|
||||||
}
|
}
|
||||||
const json = (await res.json()) as { agent_name: string; thread_id: string };
|
const json = (await res.json()) as { agent_name: string; thread_id: string };
|
||||||
return { agentName: json.agent_name, threadId: json.thread_id };
|
return { agentName: json.agent_name, threadId: json.thread_id };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a thread for the Step 3「大屏多页」dashboard-data agent
|
|
||||||
* (`roundtable-dashboard`, a built-in singleton — distinct from `roundtable-report`;
|
|
||||||
* its run policy disables ALL tools so it only emits a ```report-json block). Run it
|
|
||||||
* with {@link streamMultiAgent} (`agentType: "special"`, `agentName: "roundtable-dashboard"`,
|
|
||||||
* `dAgentThreadId: { [agentName]: threadId }`); the frontend then `extractReportData`s
|
|
||||||
* the streamed text. Follow-up Q&A / refinements reuse the SAME thread (do not re-init)
|
|
||||||
* so the agent keeps the prior dashboard context.
|
|
||||||
*/
|
|
||||||
export async function initDashboardThread(
|
|
||||||
options: { signal?: AbortSignal } = {},
|
|
||||||
): Promise<ReportThreadResponse> {
|
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/dashboard/init`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: "{}",
|
|
||||||
signal: options.signal,
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const text = await res.text().catch(() => "");
|
|
||||||
reportRoundtableError({
|
|
||||||
stage: "step3_dashboard", event: "init_thread_http_error",
|
|
||||||
message: `大屏页面线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
|
|
||||||
httpStatus: res.status, agentId: "roundtable-dashboard", agentName: "大屏页面",
|
|
||||||
});
|
|
||||||
throw new Error(`init dashboard thread failed (${res.status}): ${text}`);
|
|
||||||
}
|
|
||||||
const json = (await res.json()) as { agent_name: string; thread_id: string };
|
|
||||||
return { agentName: json.agent_name, threadId: json.thread_id };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a thread for the Step 3「总结报告」summary agent (`roundtable-summary`,
|
* Create a thread for the Step 3「总结报告」summary agent (`roundtable-summary`,
|
||||||
* a built-in singleton — distinct from `roundtable-report`; this only spins up a
|
* a built-in singleton — distinct from `roundtable-report`; this only spins up a
|
||||||
@@ -1034,44 +854,8 @@ export async function initSummaryThread(
|
|||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text().catch(() => "");
|
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}`);
|
throw new Error(`init summary thread failed (${res.status}): ${text}`);
|
||||||
}
|
}
|
||||||
const json = (await res.json()) as { agent_name: string; thread_id: string };
|
const json = (await res.json()) as { agent_name: string; thread_id: string };
|
||||||
return { agentName: json.agent_name, threadId: json.thread_id };
|
return { agentName: json.agent_name, threadId: json.thread_id };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a thread for the Step 3「入库」structure agent (`roundtable-structure`,
|
|
||||||
* a built-in singleton — the same agent that extracts the flowchart, but this run
|
|
||||||
* uses the `ingest` run policy so its attached ingest skill actually executes).
|
|
||||||
* Run it afterwards with {@link streamMultiAgent} (`agentType: "special"`,
|
|
||||||
* `agentName: "roundtable-structure"`, `dAgentThreadId: { [agentName]: threadId }`):
|
|
||||||
* the agent picks the suitable ingest skill (its name may contain「六步法」), reads
|
|
||||||
* its SKILL.md and calls it — passing the taskId + summary report + structured flow.
|
|
||||||
*/
|
|
||||||
export async function initStructureThread(
|
|
||||||
options: { signal?: AbortSignal } = {},
|
|
||||||
): Promise<ReportThreadResponse> {
|
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/structure/init`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: "{}",
|
|
||||||
signal: options.signal,
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const text = await res.text().catch(() => "");
|
|
||||||
reportRoundtableError({
|
|
||||||
stage: "step3_structure", event: "init_thread_http_error",
|
|
||||||
message: `结构化输出线程创建失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
|
|
||||||
httpStatus: res.status, agentId: "roundtable-structure", agentName: "结构化输出",
|
|
||||||
});
|
|
||||||
throw new Error(`init structure thread failed (${res.status}): ${text}`);
|
|
||||||
}
|
|
||||||
const json = (await res.json()) as { agent_name: string; thread_id: string };
|
|
||||||
return { agentName: json.agent_name, threadId: json.thread_id };
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ import { getBackendBaseURL } from "@/core/config";
|
|||||||
import type { Agent } from "@/core/agents";
|
import type { Agent } from "@/core/agents";
|
||||||
|
|
||||||
import type { IntentSummary } from "./intent";
|
import type { IntentSummary } from "./intent";
|
||||||
import { reportRoundtableError } from "./diagnostics-report";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Agent-recommendation API. Sits between Step 1 (intent clarification) and
|
* Agent-recommendation API. Sits between Step 1 (intent clarification) and
|
||||||
@@ -319,11 +318,6 @@ export async function streamRecommend(req: StreamRecommendRequest): Promise<Stre
|
|||||||
|
|
||||||
if (!res.ok || !res.body) {
|
if (!res.ok || !res.body) {
|
||||||
const text = await res.text().catch(() => "");
|
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}`);
|
throw new Error(`recommend/stream failed (${res.status}): ${text}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,12 +373,6 @@ export async function streamRecommend(req: StreamRecommendRequest): Promise<Stre
|
|||||||
if (Array.isArray(parsed.picks)) {
|
if (Array.isArray(parsed.picks)) {
|
||||||
result.picks = parsed.picks as RecommendPick[];
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import { apiFetch } from "@/core/api/fetch-client";
|
|||||||
import { getBackendBaseURL } from "@/core/config";
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
|
|
||||||
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
||||||
import { reportRoundtableError } from "./diagnostics-report";
|
|
||||||
import { seatModeToRunParams } from "../lib/seat-mode";
|
import { seatModeToRunParams } from "../lib/seat-mode";
|
||||||
import {
|
import {
|
||||||
isTerminalJobStatus,
|
isTerminalJobStatus,
|
||||||
@@ -30,11 +29,6 @@ const BASE = () => `${getBackendBaseURL()}/api/roundtable-jobs`;
|
|||||||
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text().catch(() => "");
|
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}`);
|
throw new Error(`${ctx} failed (${res.status}): ${text}`);
|
||||||
}
|
}
|
||||||
return (await res.json()) as T;
|
return (await res.json()) as T;
|
||||||
@@ -87,8 +81,6 @@ function toStartBody(p: StartJobPayload) {
|
|||||||
const seat = p.seatMode ? seatModeToRunParams(p.seatMode) : null;
|
const seat = p.seatMode ? seatModeToRunParams(p.seatMode) : null;
|
||||||
return {
|
return {
|
||||||
draftId: p.draftId ?? null,
|
draftId: p.draftId ?? null,
|
||||||
// taskId 非空 → task 作业(按 task 共享、不分权,报告写回独立 task-draft 存储)。
|
|
||||||
...(p.taskId ? { taskId: p.taskId } : {}),
|
|
||||||
intent: p.intent,
|
intent: p.intent,
|
||||||
agents: p.agents,
|
agents: p.agents,
|
||||||
model: p.model,
|
model: p.model,
|
||||||
@@ -98,18 +90,6 @@ function toStartBody(p: StartJobPayload) {
|
|||||||
seedMessage: p.seedMessage,
|
seedMessage: p.seedMessage,
|
||||||
threadIds: p.threadIds ?? null,
|
threadIds: p.threadIds ?? null,
|
||||||
coordinatorName: p.coordinatorName ?? "roundtable-coordinator",
|
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
|
...(seat
|
||||||
? {
|
? {
|
||||||
thinking_enabled: seat.thinking_enabled,
|
thinking_enabled: seat.thinking_enabled,
|
||||||
@@ -151,31 +131,23 @@ export function startJobKeepalive(payload: StartJobPayload): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** taskId 非空 → 追加 `task_id` 查询参(task 作业按 task 共享、不分权读取/控制)。 */
|
/** 查作业快照。404 → null。 */
|
||||||
function taskQuery(taskId: string | null | undefined, sep: "?" | "&"): string {
|
export async function getJob(jobId: string): Promise<RoundtableJob | null> {
|
||||||
return taskId ? `${sep}task_id=${encodeURIComponent(taskId)}` : "";
|
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}`, { method: "GET" });
|
||||||
}
|
|
||||||
|
|
||||||
/** 查作业快照。404 → null。`taskId` 非空走 task 共享读取(不分权)。 */
|
|
||||||
export async function getJob(jobId: string, taskId?: string | null): Promise<RoundtableJob | null> {
|
|
||||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}${taskQuery(taskId, "?")}`, { method: "GET" });
|
|
||||||
if (res.status === 404) return null;
|
if (res.status === 404) return null;
|
||||||
return mapJob(await readJson<Record<string, unknown>>(res, "get job"));
|
return mapJob(await readJson<Record<string, unknown>>(res, "get job"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 查某草稿最近一个作业。无 → null。`taskId` 非空走 task 共享读取(不分权)。 */
|
/** 查某草稿最近一个作业。无 → null。 */
|
||||||
export async function getJobByDraft(draftId: string, taskId?: string | null): Promise<RoundtableJob | null> {
|
export async function getJobByDraft(draftId: string): Promise<RoundtableJob | null> {
|
||||||
const res = await apiFetch(
|
const res = await apiFetch(`${BASE()}?draft_id=${encodeURIComponent(draftId)}`, { method: "GET" });
|
||||||
`${BASE()}?draft_id=${encodeURIComponent(draftId)}${taskQuery(taskId, "&")}`,
|
|
||||||
{ method: "GET" },
|
|
||||||
);
|
|
||||||
const data = await readJson<Record<string, unknown> | null>(res, "get job by draft");
|
const data = await readJson<Record<string, unknown> | null>(res, "get job by draft");
|
||||||
return data ? mapJob(data) : null;
|
return data ? mapJob(data) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 回答澄清后续跑。`taskId` 非空 → task 共享续跑(不分权)。 */
|
/** 回答澄清后续跑。 */
|
||||||
export async function resumeJob(jobId: string, answer: string, taskId?: string | null): Promise<RoundtableJob> {
|
export async function resumeJob(jobId: string, answer: string): Promise<RoundtableJob> {
|
||||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/resume${taskQuery(taskId, "?")}`, {
|
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/resume`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ answer }),
|
body: JSON.stringify({ answer }),
|
||||||
@@ -183,9 +155,9 @@ export async function resumeJob(jobId: string, answer: string, taskId?: string |
|
|||||||
return mapJob(await readJson<Record<string, unknown>>(res, "resume job"));
|
return mapJob(await readJson<Record<string, unknown>>(res, "resume job"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 取消作业。`taskId` 非空 → task 共享取消(不分权)。 */
|
/** 取消作业。 */
|
||||||
export async function cancelJob(jobId: string, taskId?: string | null): Promise<RoundtableJob> {
|
export async function cancelJob(jobId: string): Promise<RoundtableJob> {
|
||||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/cancel${taskQuery(taskId, "?")}`, { method: "POST" });
|
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/cancel`, { method: "POST" });
|
||||||
return mapJob(await readJson<Record<string, unknown>>(res, "cancel job"));
|
return mapJob(await readJson<Record<string, unknown>>(res, "cancel job"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,12 +177,12 @@ export interface StreamJobHandlers {
|
|||||||
*
|
*
|
||||||
* 终态帧后后端会主动关闭流;本函数也在收到终态快照时调 onDone,调用方可据此 unsubscribe。
|
* 终态帧后后端会主动关闭流;本函数也在收到终态快照时调 onDone,调用方可据此 unsubscribe。
|
||||||
*/
|
*/
|
||||||
export function streamJob(jobId: string, handlers: StreamJobHandlers, taskId?: string | null): () => void {
|
export function streamJob(jobId: string, handlers: StreamJobHandlers): () => void {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/stream${taskQuery(taskId, "?")}`, {
|
const res = await apiFetch(`${BASE()}/${encodeURIComponent(jobId)}/stream`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
@@ -239,13 +211,7 @@ export function streamJob(jobId: string, handlers: StreamJobHandlers, taskId?: s
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (frame.event === "error") {
|
if (frame.event === "error") {
|
||||||
const detail = String(frame.detail ?? "unknown stream error");
|
handlers.onError?.(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;
|
continue;
|
||||||
}
|
}
|
||||||
const job = mapJob(frame);
|
const job = mapJob(frame);
|
||||||
|
|||||||
@@ -1,83 +0,0 @@
|
|||||||
/**
|
|
||||||
* **Task-scoped** roundtable draft storage (taskId 深链聊天记录).
|
|
||||||
*
|
|
||||||
* Separate from the per-user `drafts.ts` client: records here are keyed **only by
|
|
||||||
* `taskId`** and are **not partitioned by user** (the deep-link audience shares
|
|
||||||
* them). Hits `/api/roundtable-task-drafts` (table `roundtable_task_drafts`),
|
|
||||||
* physically distinct from the personal `roundtable_drafts` store so the two
|
|
||||||
* never mix.
|
|
||||||
*
|
|
||||||
* The wire shape matches the personal store, so we reuse its types + mappers.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { apiFetch } from "@/core/api/fetch-client";
|
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
|
||||||
|
|
||||||
import {
|
|
||||||
fromCreate,
|
|
||||||
fromUpdate,
|
|
||||||
readJson,
|
|
||||||
toMeta,
|
|
||||||
toRecord,
|
|
||||||
type DraftCreatePayload,
|
|
||||||
type DraftMeta,
|
|
||||||
type DraftRecord,
|
|
||||||
type DraftUpdatePayload,
|
|
||||||
type ServerDraftFull,
|
|
||||||
type ServerDraftMeta,
|
|
||||||
} from "@/roundtable-planning/api/drafts";
|
|
||||||
|
|
||||||
const BASE = () => `${getBackendBaseURL()}/api/roundtable-task-drafts`;
|
|
||||||
|
|
||||||
/** 按外部任务 id 列出该任务全部聊天记录(轻量 meta,newest first;不分权)。 */
|
|
||||||
export async function listTaskDraftsByTask(taskId: string): Promise<DraftMeta[]> {
|
|
||||||
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}`, { method: "GET" });
|
|
||||||
const data = await readJson<{ drafts: ServerDraftMeta[] }>(res, "list task drafts");
|
|
||||||
return (data.drafts ?? []).map(toMeta);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 按外部任务 id 取最新一条聊天记录(不分权)。无则 null(404)。 */
|
|
||||||
export async function getLatestTaskDraftByTask(taskId: string): Promise<DraftRecord | null> {
|
|
||||||
const res = await apiFetch(`${BASE()}/by-task/${encodeURIComponent(taskId)}/latest`, { method: "GET" });
|
|
||||||
if (res.status === 404) return null;
|
|
||||||
const data = await readJson<ServerDraftFull>(res, "get latest task draft");
|
|
||||||
return toRecord(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Full task draft by id (不分权). Returns null on 404. */
|
|
||||||
export async function getTaskDraft(id: string): Promise<DraftRecord | null> {
|
|
||||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "GET" });
|
|
||||||
if (res.status === 404) return null;
|
|
||||||
const data = await readJson<ServerDraftFull>(res, "get task draft");
|
|
||||||
return toRecord(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Create a task draft. `payload.taskId` is required. */
|
|
||||||
export async function createTaskDraft(payload: DraftCreatePayload): Promise<DraftRecord> {
|
|
||||||
const res = await apiFetch(BASE(), {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(fromCreate(payload)),
|
|
||||||
});
|
|
||||||
const data = await readJson<ServerDraftFull>(res, "create task draft");
|
|
||||||
return toRecord(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateTaskDraft(id: string, patch: DraftUpdatePayload): Promise<DraftRecord | null> {
|
|
||||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, {
|
|
||||||
method: "PUT",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(fromUpdate(patch)),
|
|
||||||
});
|
|
||||||
if (res.status === 404) return null;
|
|
||||||
const data = await readJson<ServerDraftFull>(res, "update task draft");
|
|
||||||
return toRecord(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function deleteTaskDraft(id: string): Promise<void> {
|
|
||||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "DELETE" });
|
|
||||||
if (!res.ok && res.status !== 404) {
|
|
||||||
const text = await res.text().catch(() => "");
|
|
||||||
throw new Error(`delete task draft failed (${res.status}): ${text}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { createPortal } from "react-dom";
|
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
import remarkGfm from "remark-gfm";
|
import remarkGfm from "remark-gfm";
|
||||||
@@ -215,9 +214,7 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
|
|||||||
[content],
|
[content],
|
||||||
);
|
);
|
||||||
|
|
||||||
// 经 portal 挂到 body:脱离会商页 <main>(`relative z-0`) 的层叠上下文,
|
return (
|
||||||
// 否则 fixed 弹窗会被会商页头(z-40)/全局顶栏(z-45)盖住顶部。
|
|
||||||
return createPortal(
|
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-6"
|
className="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-6"
|
||||||
onMouseDown={(e) => {
|
onMouseDown={(e) => {
|
||||||
@@ -290,7 +287,6 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</div>
|
||||||
document.body,
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -31,7 +31,6 @@ import {
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
|
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
|
||||||
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
|
||||||
import { listAgents } from "@/core/agents";
|
import { listAgents } from "@/core/agents";
|
||||||
|
|
||||||
import { listChains, setChainPublic, type ChainScope } from "../api/chains";
|
import { listChains, setChainPublic, type ChainScope } from "../api/chains";
|
||||||
@@ -72,9 +71,7 @@ export function BusinessChainListBody({
|
|||||||
const [chains, setChains] = useState<BusinessChain[]>([]);
|
const [chains, setChains] = useState<BusinessChain[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
// 管理员:额外多一个「全部」筛选,且可编辑 / 发布任意账号的链条。
|
// 筛选:我的 / 公共(已发布)。
|
||||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
|
||||||
// 筛选:我的 / 公共(已发布)/(管理员)全部。
|
|
||||||
const [scope, setScope] = useState<ChainScope>("mine");
|
const [scope, setScope] = useState<ChainScope>("mine");
|
||||||
const [publishingId, setPublishingId] = useState<string | null>(null);
|
const [publishingId, setPublishingId] = useState<string | null>(null);
|
||||||
// 实时名称表(id 小写 → 最新 name):用于把席位的落库快照名刷新成最新(agent 改名同步)。
|
// 实时名称表(id 小写 → 最新 name):用于把席位的落库快照名刷新成最新(agent 改名同步)。
|
||||||
@@ -150,9 +147,9 @@ export function BusinessChainListBody({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* 筛选:我的 / 公共 /(管理员)全部 */}
|
{/* 筛选:我的 / 公共 */}
|
||||||
<div className="shrink-0 flex items-center gap-1 rounded-lg border border-border bg-muted/40 p-0.5 self-start">
|
<div className="shrink-0 flex items-center gap-1 rounded-lg border border-border bg-muted/40 p-0.5 self-start">
|
||||||
{((isAdmin ? ["mine", "public", "all"] : ["mine", "public"]) as ChainScope[]).map((s) => (
|
{(["mine", "public"] as const).map((s) => (
|
||||||
<button
|
<button
|
||||||
key={s}
|
key={s}
|
||||||
type="button"
|
type="button"
|
||||||
@@ -164,7 +161,7 @@ export function BusinessChainListBody({
|
|||||||
: "text-muted-foreground hover:text-foreground",
|
: "text-muted-foreground hover:text-foreground",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{s === "mine" ? "我的" : s === "public" ? "公共" : "全部"}
|
{s === "mine" ? "我的" : "公共"}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -198,7 +195,6 @@ export function BusinessChainListBody({
|
|||||||
<ChainRow
|
<ChainRow
|
||||||
key={chain.id}
|
key={chain.id}
|
||||||
chain={chain}
|
chain={chain}
|
||||||
canManage={isAdmin || chain.isMine !== false}
|
|
||||||
nameById={nameById}
|
nameById={nameById}
|
||||||
publishing={publishingId === chain.id}
|
publishing={publishingId === chain.id}
|
||||||
onSettings={() => onConfigure(chain.id)}
|
onSettings={() => onConfigure(chain.id)}
|
||||||
@@ -249,20 +245,18 @@ export function BusinessChainListDialog({
|
|||||||
|
|
||||||
function ChainRow({
|
function ChainRow({
|
||||||
chain,
|
chain,
|
||||||
canManage,
|
|
||||||
nameById,
|
nameById,
|
||||||
publishing,
|
publishing,
|
||||||
onSettings,
|
onSettings,
|
||||||
onTogglePublic,
|
onTogglePublic,
|
||||||
}: {
|
}: {
|
||||||
chain: BusinessChain;
|
chain: BusinessChain;
|
||||||
/** 能否编辑 / 发布(本人链条 或 管理员)。 */
|
|
||||||
canManage: boolean;
|
|
||||||
nameById: Map<string, string>;
|
nameById: Map<string, string>;
|
||||||
publishing: boolean;
|
publishing: boolean;
|
||||||
onSettings: () => void;
|
onSettings: () => void;
|
||||||
onTogglePublic: () => void;
|
onTogglePublic: () => void;
|
||||||
}) {
|
}) {
|
||||||
|
const isMine = chain.isMine !== false;
|
||||||
// 配置者用户名:后端返回 email,展示时取 @ 前的本地部分更像「用户名」。
|
// 配置者用户名:后端返回 email,展示时取 @ 前的本地部分更像「用户名」。
|
||||||
const ownerName = chain.ownerName ? chain.ownerName.split("@")[0] : "";
|
const ownerName = chain.ownerName ? chain.ownerName.split("@")[0] : "";
|
||||||
return (
|
return (
|
||||||
@@ -280,8 +274,8 @@ function ChainRow({
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||||
{/* 发布 / 取消发布:本人的链条或管理员可操作。 */}
|
{/* 发布 / 取消发布:仅本人的链条可操作。 */}
|
||||||
{canManage && (
|
{isMine && (
|
||||||
<Button
|
<Button
|
||||||
variant={chain.isPublic ? "secondary" : "outline"}
|
variant={chain.isPublic ? "secondary" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
@@ -297,8 +291,8 @@ function ChainRow({
|
|||||||
{chain.isPublic ? "取消发布" : "发布"}
|
{chain.isPublic ? "取消发布" : "发布"}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{/* 设置(编辑):本人的链条或管理员;普通用户看别人的链条只读浏览。 */}
|
{/* 设置(编辑):仅本人的链条;公共里别人的链条只读浏览。 */}
|
||||||
{canManage && (
|
{isMine && (
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -147,28 +147,19 @@ export function BusinessChainPicker({
|
|||||||
const chainMeta = { id: selectedChain.id, title: selectedChain.title };
|
const chainMeta = { id: selectedChain.id, title: selectedChain.title };
|
||||||
const seatNameById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.name]));
|
const seatNameById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.name]));
|
||||||
const nameOf = (id: string) => nameById.get(id) ?? seatNameById.get(id) ?? id;
|
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。
|
// 链条带分层、过滤存活后仍并行 → dag 编排(携带快速/沙箱子模式);否则退回线性 chain。
|
||||||
if (dagPlan) {
|
if (dagPlan) {
|
||||||
// dag:席位顺序按 stage 展平(与 plan 一致)。
|
// dag:席位顺序按 stage 展平(与 plan 一致)。
|
||||||
const agents = dagPlan.stages
|
const agents = dagPlan.stages
|
||||||
.flatMap((st) => st.agentIds)
|
.flatMap((st) => st.agentIds)
|
||||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), seatMode: seatModeOf(id) }));
|
.map((id) => ({ agent_id: id, name: nameOf(id) }));
|
||||||
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode, gatherFirst: selectedChain.gatherFirst ?? false });
|
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
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) }));
|
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id) }));
|
||||||
onConfirm({ agents, mode: "chain", chain: chainMeta, gatherFirst: selectedChain.gatherFirst ?? false });
|
onConfirm({ agents, mode: "chain", chain: chainMeta });
|
||||||
};
|
};
|
||||||
|
|
||||||
// 整片脱敏:链条卡片区(链条名/描述/席位智能体名)。输入框不受影响(Hook 跳过)。
|
// 整片脱敏:链条卡片区(链条名/描述/席位智能体名)。输入框不受影响(Hook 跳过)。
|
||||||
|
|||||||
@@ -1,250 +0,0 @@
|
|||||||
/**
|
|
||||||
* 大屏绘制智能体「交互区」聊天面板(沙箱左 60%;右 40% 是抽取过程代码预览)。
|
|
||||||
*
|
|
||||||
* 从 `Step3DashboardMode` 抽出共享:圆桌 Step3「结果绘制·大屏」与独立大屏页
|
|
||||||
* (`DashboardAgentPage`)都复用同一套聊天 UI(流式气泡 + 模型选择 + 暂停/重画 +
|
|
||||||
* 修改输入框)。消息里不展示 report-json 本体(已在右侧沙箱实时渲染),用
|
|
||||||
* `stripReportFence` 替换成一句提示。
|
|
||||||
*/
|
|
||||||
import { useMemo, useRef, useState, type FormEvent } from "react";
|
|
||||||
import {
|
|
||||||
CheckCircle,
|
|
||||||
Loader2,
|
|
||||||
Pause,
|
|
||||||
RefreshCw,
|
|
||||||
SendHorizontal,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
import { useLocalSettings } from "@/core/settings";
|
|
||||||
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
|
|
||||||
import type { ModelOption } from "@/roundtable-planning/components/Step3ReportMode";
|
|
||||||
import { ScrollToBottomButton } from "@/roundtable-planning/components/ScrollToBottomButton";
|
|
||||||
import { Step2Message } from "@/roundtable-planning/components/Step2Panel";
|
|
||||||
import { useAutoScroll } from "@/roundtable-planning/hooks/useAutoScroll";
|
|
||||||
import { useDialogueSpeedMetrics } from "@/roundtable-planning/hooks/useDialogueSpeedMetrics";
|
|
||||||
import type { UseStep3DashboardReturn } from "@/roundtable-planning/hooks/useStep3Dashboard";
|
|
||||||
import { stripReportFence } from "@/roundtable-planning/lib/report-template";
|
|
||||||
|
|
||||||
export interface DashboardChatPanelProps {
|
|
||||||
phase: UseStep3DashboardReturn["phase"];
|
|
||||||
dialogues: UseStep3DashboardReturn["dialogues"];
|
|
||||||
busy: boolean;
|
|
||||||
error: string | null;
|
|
||||||
onAsk: (message: string) => void;
|
|
||||||
onRedraw: () => void;
|
|
||||||
onPause: () => void;
|
|
||||||
onOpenPreview: () => void;
|
|
||||||
hasResult: boolean;
|
|
||||||
selectedModel: string;
|
|
||||||
availableModels: ReadonlyArray<ModelOption>;
|
|
||||||
modelsLoading: boolean;
|
|
||||||
setSelectedModel: (model: string) => void;
|
|
||||||
/** 面板副标题(默认对齐圆桌 Step3;独立大屏页可自定义说明)。 */
|
|
||||||
subtitle?: string;
|
|
||||||
/** 完成提示语(默认「已切换到大屏页面」;独立页不自动跳,可改文案)。 */
|
|
||||||
doneHint?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DashboardChatPanel({
|
|
||||||
phase,
|
|
||||||
dialogues,
|
|
||||||
busy,
|
|
||||||
error,
|
|
||||||
onAsk,
|
|
||||||
onRedraw,
|
|
||||||
onPause,
|
|
||||||
onOpenPreview,
|
|
||||||
hasResult,
|
|
||||||
selectedModel,
|
|
||||||
availableModels,
|
|
||||||
modelsLoading,
|
|
||||||
setSelectedModel,
|
|
||||||
subtitle = "提炼研讨成果为大屏结构化数据(右侧实时显示抽取过程)",
|
|
||||||
doneHint = "数据已就绪,已切换到大屏页面。",
|
|
||||||
}: DashboardChatPanelProps) {
|
|
||||||
const inputLocked = phase === "creating";
|
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
|
||||||
const { atBottom, scrollToBottom } = useAutoScroll(scrollRef, [dialogues]);
|
|
||||||
const [localSettings] = useLocalSettings();
|
|
||||||
const speedMeterEnabled = localSettings.display.streamSpeedMeterEnabled;
|
|
||||||
const dialogueMetrics = useDialogueSpeedMetrics(dialogues);
|
|
||||||
const [text, setText] = useState("");
|
|
||||||
|
|
||||||
// 消息列表里不展示 report-json 结构化数据本体(它已在右侧沙箱实时渲染),
|
|
||||||
// 把数据块替换成一句「看右侧沙箱」的提示,避免左右两边重复刷整段 JSON。
|
|
||||||
const displayDialogues = useMemo(
|
|
||||||
() =>
|
|
||||||
dialogues.map((d) => {
|
|
||||||
const content = d.content ?? "";
|
|
||||||
if (!content) return d;
|
|
||||||
const stripped = stripReportFence(content, d.streaming === true);
|
|
||||||
return stripped === content ? d : { ...d, content: stripped };
|
|
||||||
}),
|
|
||||||
[dialogues],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
const t = text.trim();
|
|
||||||
if (!t || inputLocked) return;
|
|
||||||
setText("");
|
|
||||||
onAsk(t);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex h-full min-h-0 flex-col bg-slate-50/20">
|
|
||||||
{/* 面板头:智能体名 + 模型选择 + 暂停/重画 */}
|
|
||||||
<div className="shrink-0 flex items-center justify-between gap-2 border-b border-slate-100 bg-white px-4 py-2.5">
|
|
||||||
<div className="flex items-center gap-2 min-w-0">
|
|
||||||
<div className="w-6 h-6 shrink-0 rounded-lg bg-gradient-to-tr from-primary to-[var(--brand-200)] flex items-center justify-center text-white text-xs shadow-sm">
|
|
||||||
📊
|
|
||||||
</div>
|
|
||||||
<div className="leading-tight min-w-0">
|
|
||||||
<div className="text-xs font-bold text-slate-800 truncate">大屏绘制智能体</div>
|
|
||||||
<div className="text-[10px] text-slate-400 truncate">{subtitle}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 shrink-0">
|
|
||||||
<select
|
|
||||||
id="step3-dashboard-model-select"
|
|
||||||
value={selectedModel}
|
|
||||||
onChange={(e) => setSelectedModel(e.target.value)}
|
|
||||||
disabled={busy || modelsLoading || availableModels.length === 0}
|
|
||||||
title={
|
|
||||||
modelsLoading
|
|
||||||
? "正在加载模型列表…"
|
|
||||||
: availableModels.length === 0
|
|
||||||
? "未在 config.yaml 中配置任何模型"
|
|
||||||
: busy
|
|
||||||
? "绘制中不可切换;完成后或重新绘制时生效"
|
|
||||||
: "切换绘制使用的推理模型(下次绘制生效)"
|
|
||||||
}
|
|
||||||
className="max-w-[160px] bg-slate-50/50 border border-slate-200 rounded-xl px-2.5 py-1.5 text-[11px] font-bold text-slate-700 cursor-pointer focus:outline-none focus:border-primary focus:ring-1 focus:ring-[var(--brand-200)]/50 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-secondary dark:text-foreground dark:border-border"
|
|
||||||
>
|
|
||||||
{availableModels.length === 0 && (
|
|
||||||
<option value="">{modelsLoading ? "加载中…" : "未配置模型"}</option>
|
|
||||||
)}
|
|
||||||
{availableModels.map((m) => (
|
|
||||||
<option key={m.name} value={m.name}>
|
|
||||||
{m.display_name && m.display_name !== m.name ? `${m.display_name} (${m.name})` : m.name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
{busy ? (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onPause}
|
|
||||||
title="中止当前绘制"
|
|
||||||
className="bg-white border border-amber-200 text-amber-700 hover:bg-amber-50 text-[10.5px] font-bold px-2.5 py-1.5 rounded-xl flex items-center gap-1 transition"
|
|
||||||
>
|
|
||||||
<Pause className="w-3.5 h-3.5" />
|
|
||||||
中止
|
|
||||||
</button>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onRedraw}
|
|
||||||
title="丢弃上下文,从头重新绘制"
|
|
||||||
className="bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 text-[10.5px] font-bold px-2.5 py-1.5 rounded-xl flex items-center gap-1 transition"
|
|
||||||
>
|
|
||||||
<RefreshCw className="w-3.5 h-3.5 text-slate-500" />
|
|
||||||
重新绘制
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 聊天记录 */}
|
|
||||||
<div className="relative flex-1 min-h-0 flex flex-col">
|
|
||||||
<div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-4 space-y-4 bg-white">
|
|
||||||
{phase === "creating" && dialogues.length === 0 && (
|
|
||||||
<div className="flex items-center gap-2 text-xs text-slate-500">
|
|
||||||
<Loader2 className="w-3.5 h-3.5 animate-spin text-primary" />
|
|
||||||
正在初始化绘制线程…
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{displayDialogues.map((msg) => (
|
|
||||||
<Step2Message
|
|
||||||
key={msg.id}
|
|
||||||
msg={msg}
|
|
||||||
metric={speedMeterEnabled ? dialogueMetrics.get(msg.id) : undefined}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{busy && (
|
|
||||||
<div className="inline-flex items-center gap-2 rounded-full border bg-white px-2.5 py-1 text-[11px] text-slate-500">
|
|
||||||
<span className="bg-primary size-1.5 animate-pulse rounded-full" />
|
|
||||||
右侧沙箱实时显示数据抽取过程
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{phase === "error" && (
|
|
||||||
<div className="rounded-xl border border-rose-200 bg-rose-50 p-3 text-xs text-rose-700">
|
|
||||||
<div className="font-bold mb-1">绘制失败</div>
|
|
||||||
<div className="leading-relaxed break-all">{error}</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onRedraw}
|
|
||||||
className="mt-2 inline-flex items-center gap-1 text-[11px] font-bold text-rose-700 underline hover:text-rose-800"
|
|
||||||
>
|
|
||||||
<RefreshCw className="w-3 h-3" />
|
|
||||||
重试
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{phase === "done" && (
|
|
||||||
<div className="flex items-center gap-2 text-xs font-bold text-emerald-600">
|
|
||||||
<CheckCircle className="w-4 h-4" />
|
|
||||||
{doneHint}
|
|
||||||
{hasResult && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onOpenPreview}
|
|
||||||
className="ml-1 inline-flex items-center gap-1 text-[11px] font-bold text-primary underline hover:opacity-80"
|
|
||||||
>
|
|
||||||
在沙箱打开 HTML 预览
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{!atBottom && <ScrollToBottomButton onClick={scrollToBottom} />}
|
|
||||||
|
|
||||||
{/* 问答修改输入框 */}
|
|
||||||
<form onSubmit={handleSubmit} className="shrink-0 border-t border-slate-100 bg-white px-3 py-3">
|
|
||||||
<div className="flex items-end gap-2 rounded-2xl border border-slate-200 bg-slate-50/70 px-3 py-2 focus-within:border-primary/60 focus-within:bg-white focus-within:ring-2 focus-within:ring-[var(--brand-200)]/40">
|
|
||||||
<AutoGrowTextarea
|
|
||||||
maxHeight={224}
|
|
||||||
value={text}
|
|
||||||
onChange={(e) => setText(e.target.value)}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === "Enter" && !e.shiftKey) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.currentTarget.form?.requestSubmit();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
disabled={inputLocked}
|
|
||||||
rows={1}
|
|
||||||
placeholder={
|
|
||||||
busy
|
|
||||||
? "随时输入修改要求——发送会打断当前绘制并按新要求重出数据"
|
|
||||||
: "输入修改要求,例如:把风险分布换成柱状图,新增一个执行路线席位"
|
|
||||||
}
|
|
||||||
className="min-h-8 max-h-56 flex-1 resize-none bg-transparent py-1.5 text-xs leading-relaxed text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={inputLocked || text.trim().length === 0}
|
|
||||||
title={inputLocked ? "正在初始化线程,请稍候" : "发送修改要求"}
|
|
||||||
className="mb-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary text-white transition hover:bg-[var(--brand-900)] disabled:cursor-not-allowed disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{inputLocked ? <Loader2 className="h-4 w-4 animate-spin" /> : <SendHorizontal className="h-4 w-4" />}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -18,11 +18,6 @@ export interface DispatchChainJobModalProps {
|
|||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
title?: string;
|
title?: string;
|
||||||
onView?: (job: RoundtableJob) => void;
|
onView?: (job: RoundtableJob) => void;
|
||||||
/**
|
|
||||||
* 外部任务 id(taskId 深链会商)。非空 → 按 task 共享读取/控制作业(不分权),
|
|
||||||
* 任何人打开同一 task 都能看在跑的研讨流程图。普通模式留空。
|
|
||||||
*/
|
|
||||||
taskId?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DispatchChainJobModal({
|
export function DispatchChainJobModal({
|
||||||
@@ -31,7 +26,6 @@ export function DispatchChainJobModal({
|
|||||||
onOpenChange,
|
onOpenChange,
|
||||||
title,
|
title,
|
||||||
onView,
|
onView,
|
||||||
taskId = null,
|
|
||||||
}: DispatchChainJobModalProps) {
|
}: DispatchChainJobModalProps) {
|
||||||
const [job, setJob] = useState<RoundtableJob | null>(null);
|
const [job, setJob] = useState<RoundtableJob | null>(null);
|
||||||
|
|
||||||
@@ -42,28 +36,24 @@ export function DispatchChainJobModal({
|
|||||||
}
|
}
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
// 首帧快照:弹窗一打开就有内容,不必等 SSE 第一帧。
|
// 首帧快照:弹窗一打开就有内容,不必等 SSE 第一帧。
|
||||||
void getJob(jobId, taskId)
|
void getJob(jobId)
|
||||||
.then((j) => {
|
.then((j) => {
|
||||||
if (!cancelled && j) setJob(j);
|
if (!cancelled && j) setJob(j);
|
||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
const unsubscribe = streamJob(
|
const unsubscribe = streamJob(jobId, {
|
||||||
jobId,
|
onProgress: (j) => {
|
||||||
{
|
if (!cancelled) setJob(j);
|
||||||
onProgress: (j) => {
|
|
||||||
if (!cancelled) setJob(j);
|
|
||||||
},
|
|
||||||
onError: () => {
|
|
||||||
/* 流错误静默:保留已拿到的最后一帧;可后续加 toast */
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
taskId,
|
onError: () => {
|
||||||
);
|
/* 流错误静默:保留已拿到的最后一帧;可后续加 toast */
|
||||||
|
},
|
||||||
|
});
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
unsubscribe();
|
unsubscribe();
|
||||||
};
|
};
|
||||||
}, [open, jobId, taskId]);
|
}, [open, jobId]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DispatchChainModal
|
<DispatchChainModal
|
||||||
@@ -85,7 +75,7 @@ export function DispatchChainJobModal({
|
|||||||
jobId
|
jobId
|
||||||
? (answer) => {
|
? (answer) => {
|
||||||
// 乐观更新为 running,随后 SSE 会推真状态续上。
|
// 乐观更新为 running,随后 SSE 会推真状态续上。
|
||||||
void resumeJob(jobId, answer, taskId)
|
void resumeJob(jobId, answer)
|
||||||
.then((j) => setJob(j))
|
.then((j) => setJob(j))
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -94,7 +84,7 @@ export function DispatchChainJobModal({
|
|||||||
onCancel={
|
onCancel={
|
||||||
jobId
|
jobId
|
||||||
? () => {
|
? () => {
|
||||||
void cancelJob(jobId, taskId)
|
void cancelJob(jobId)
|
||||||
.then((j) => setJob(j))
|
.then((j) => setJob(j))
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,14 +15,12 @@ import {
|
|||||||
useRef,
|
useRef,
|
||||||
useState,
|
useState,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { createPortal } from "react-dom";
|
|
||||||
import {
|
import {
|
||||||
applyNodeChanges,
|
applyNodeChanges,
|
||||||
Background,
|
Background,
|
||||||
BackgroundVariant,
|
BackgroundVariant,
|
||||||
Handle,
|
Handle,
|
||||||
MarkerType,
|
MarkerType,
|
||||||
MiniMap,
|
|
||||||
Position,
|
Position,
|
||||||
ReactFlow,
|
ReactFlow,
|
||||||
ReactFlowProvider,
|
ReactFlowProvider,
|
||||||
@@ -34,14 +32,11 @@ import {
|
|||||||
} from "@xyflow/react";
|
} from "@xyflow/react";
|
||||||
import "@xyflow/react/dist/style.css";
|
import "@xyflow/react/dist/style.css";
|
||||||
import {
|
import {
|
||||||
Check,
|
|
||||||
FileText,
|
FileText,
|
||||||
Loader2,
|
Loader2,
|
||||||
LocateFixed,
|
LocateFixed,
|
||||||
Maximize2,
|
Maximize2,
|
||||||
Minimize2,
|
Minimize2,
|
||||||
Pencil,
|
|
||||||
Trash2,
|
|
||||||
Workflow,
|
Workflow,
|
||||||
X,
|
X,
|
||||||
ZoomIn,
|
ZoomIn,
|
||||||
@@ -49,36 +44,14 @@ import {
|
|||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
|
||||||
import {
|
import {
|
||||||
applyNodeEdit,
|
FLOW_NODE_TYPE_META,
|
||||||
deleteNodeFromGraph,
|
|
||||||
flowNodeMeta,
|
|
||||||
FLOW_NODE_W,
|
FLOW_NODE_W,
|
||||||
layoutFlowGraph,
|
layoutFlowGraph,
|
||||||
type FlowGraphData,
|
type FlowGraphData,
|
||||||
type FlowGraphNode,
|
type FlowGraphNode,
|
||||||
type FlowOrientation,
|
|
||||||
} from "@/roundtable-planning/lib/flow-graph";
|
} from "@/roundtable-planning/lib/flow-graph";
|
||||||
|
|
||||||
/**
|
|
||||||
* 深蓝主题色板(《深蓝色 UI 规范》ZS-004 / ZS-002)。浅色保持原 slate/white。
|
|
||||||
* 用于流程图弹窗在深色下的容器 / 头部 / 画布 / 连线 / 图例 / 小地图 / 详情弹窗。
|
|
||||||
*/
|
|
||||||
const DARK = {
|
|
||||||
pageBg: "#0C1836", // ZS-004-09 画布底
|
|
||||||
cardBg: "#122347", // ZS-004-08 头部 / 详情卡底
|
|
||||||
border: "#1A2F5A", // ZS-004-07 卡片边框
|
|
||||||
borderStrong: "#2D4473", // ZS-004-06 弱分割
|
|
||||||
text: "#C5CFE0", // ZS-004-02 正文
|
|
||||||
textMuted: "#6E88B0", // ZS-004-04 次级文字
|
|
||||||
primary: "#1677FF", // ZS-002-06 主色
|
|
||||||
link: "#4096FF", // ZS-002-05 链接
|
|
||||||
dots: "#2D4473", // 画布点阵
|
|
||||||
edge: "#4A6491", // ZS-004-05 静态连线
|
|
||||||
edgeActive: "#4096FF", // 活动连线
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
interface FlowGraphPanelProps {
|
interface FlowGraphPanelProps {
|
||||||
data: FlowGraphData;
|
data: FlowGraphData;
|
||||||
/** 流式绘制中(决定蚂蚁线 + 自动 fitView 跟随)。 */
|
/** 流式绘制中(决定蚂蚁线 + 自动 fitView 跟随)。 */
|
||||||
@@ -86,34 +59,17 @@ interface FlowGraphPanelProps {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
/** 沙箱里有 md 报告时提供:工具栏显示「MD 报告」按钮,点击切回 Markdown 预览。 */
|
/** 沙箱里有 md 报告时提供:工具栏显示「MD 报告」按钮,点击切回 Markdown 预览。 */
|
||||||
onSwitchToReport?: () => void;
|
onSwitchToReport?: () => void;
|
||||||
/** Phase 3:画布手动编辑——传入则节点详情弹窗出现「编辑 / 删除」,回写整张新图。 */
|
|
||||||
onChange?: (next: FlowGraphData) => void;
|
|
||||||
/** 布局方向:默认 "vertical"(自上而下);弹窗里用 "horizontal" 横向铺开。 */
|
|
||||||
orientation?: FlowOrientation;
|
|
||||||
/** 右下角缩略图(小地图)—— 弹窗大画布里便于纵览定位。 */
|
|
||||||
miniMap?: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── 自定义节点(按 type 着色的卡片)────────────────────────────────────────
|
// ── 自定义节点(按 type 着色的卡片)────────────────────────────────────────
|
||||||
|
|
||||||
function FlowCardNode({ data }: NodeProps) {
|
function FlowCardNode({ data }: NodeProps) {
|
||||||
const d = data as {
|
const node = (data as { node?: FlowGraphNode; scale?: number }).node;
|
||||||
node?: FlowGraphNode;
|
const scale = (data as { node?: FlowGraphNode; scale?: number }).scale ?? 1;
|
||||||
scale?: number;
|
|
||||||
orientation?: FlowOrientation;
|
|
||||||
dark?: boolean;
|
|
||||||
};
|
|
||||||
const node = d.node;
|
|
||||||
const scale = d.scale ?? 1;
|
|
||||||
if (!node) return null;
|
if (!node) return null;
|
||||||
const meta = flowNodeMeta(d.dark ?? false)[node.type];
|
const meta = FLOW_NODE_TYPE_META[node.type];
|
||||||
// 节点宽度随容器宽度缩放(宽时放大、窄时缩小)。
|
// 节点宽度随容器宽度缩放(宽时放大、窄时缩小)。
|
||||||
const scaledWidth = FLOW_NODE_W * scale;
|
const scaledWidth = FLOW_NODE_W * scale;
|
||||||
// 横向布局连入/连出走左右两侧,纵向走上下。
|
|
||||||
const horizontal = d.orientation === "horizontal";
|
|
||||||
const targetPos = horizontal ? Position.Left : Position.Top;
|
|
||||||
const sourcePos = horizontal ? Position.Right : Position.Bottom;
|
|
||||||
const handleColor = d.dark ? "!bg-[#4A6491]" : "!bg-slate-400";
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -125,15 +81,15 @@ function FlowCardNode({ data }: NodeProps) {
|
|||||||
className="cursor-pointer rounded-xl border-2 px-3 py-2 shadow-sm transition hover:shadow-md"
|
className="cursor-pointer rounded-xl border-2 px-3 py-2 shadow-sm transition hover:shadow-md"
|
||||||
title="点击查看详情"
|
title="点击查看详情"
|
||||||
>
|
>
|
||||||
<Handle type="target" position={targetPos} className={cn("!h-1.5 !w-1.5", handleColor)} />
|
<Handle type="target" position={Position.Top} className="!h-1.5 !w-1.5 !bg-slate-400" />
|
||||||
<div className="mb-0.5 flex items-center gap-1.5">
|
<div className="mb-0.5 flex items-center gap-1.5">
|
||||||
<span style={{ background: meta.dot }} className="size-2 shrink-0 rounded-full" />
|
<span style={{ background: meta.dot }} className="size-2 shrink-0 rounded-full" />
|
||||||
<span className="text-[9px] font-bold uppercase tracking-wider opacity-70" style={{ fontSize: `${9 * scale}px` }}>
|
<span className="text-[9px] font-bold uppercase tracking-wider opacity-70" style={{ fontSize: `${9 * scale}px` }}>
|
||||||
{node.group?.trim() || meta.label}
|
{meta.label}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="break-words font-bold leading-snug" style={{ fontSize: `${11.5 * scale}px` }}>{node.label}</div>
|
<div className="break-words font-bold leading-snug" style={{ fontSize: `${11.5 * scale}px` }}>{node.label}</div>
|
||||||
<Handle type="source" position={sourcePos} className={cn("!h-1.5 !w-1.5", handleColor)} />
|
<Handle type="source" position={Position.Bottom} className="!h-1.5 !w-1.5 !bg-slate-400" />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -150,13 +106,8 @@ function FlowCanvasInner({
|
|||||||
onToggleFullscreen,
|
onToggleFullscreen,
|
||||||
onClose,
|
onClose,
|
||||||
onSwitchToReport,
|
onSwitchToReport,
|
||||||
onChange,
|
|
||||||
orientation = "vertical",
|
|
||||||
miniMap = false,
|
|
||||||
}: FlowGraphPanelProps & { fullscreen: boolean; onToggleFullscreen: () => void }) {
|
}: FlowGraphPanelProps & { fullscreen: boolean; onToggleFullscreen: () => void }) {
|
||||||
const rf = useReactFlow();
|
const rf = useReactFlow();
|
||||||
const { theme } = useTheme();
|
|
||||||
const isDark = theme === "dark";
|
|
||||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||||
const [scale, setScale] = useState(1);
|
const [scale, setScale] = useState(1);
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -185,7 +136,7 @@ function FlowCanvasInner({
|
|||||||
};
|
};
|
||||||
}, [rf]);
|
}, [rf]);
|
||||||
|
|
||||||
const layoutNodes = useMemo(() => layoutFlowGraph(data, orientation), [data, orientation]);
|
const layoutNodes = useMemo(() => layoutFlowGraph(data), [data]);
|
||||||
const derivedNodes: Node[] = useMemo(
|
const derivedNodes: Node[] = useMemo(
|
||||||
() =>
|
() =>
|
||||||
layoutNodes.map((n) => ({
|
layoutNodes.map((n) => ({
|
||||||
@@ -193,9 +144,9 @@ function FlowCanvasInner({
|
|||||||
type: "flowCard",
|
type: "flowCard",
|
||||||
// 节点随 scale 放大 → 布局坐标同步乘 scale,间距一起拉开,避免同层重叠。
|
// 节点随 scale 放大 → 布局坐标同步乘 scale,间距一起拉开,避免同层重叠。
|
||||||
position: manualPosRef.current.get(n.id) ?? { x: n.x * scale, y: n.y * scale },
|
position: manualPosRef.current.get(n.id) ?? { x: n.x * scale, y: n.y * scale },
|
||||||
data: { node: n, scale, orientation, dark: isDark },
|
data: { node: n, scale },
|
||||||
})),
|
})),
|
||||||
[layoutNodes, scale, orientation, isDark],
|
[layoutNodes, scale],
|
||||||
);
|
);
|
||||||
|
|
||||||
const [nodes, setNodes] = useState<Node[]>(derivedNodes);
|
const [nodes, setNodes] = useState<Node[]>(derivedNodes);
|
||||||
@@ -214,13 +165,7 @@ function FlowCanvasInner({
|
|||||||
() =>
|
() =>
|
||||||
data.edges.map((e) => {
|
data.edges.map((e) => {
|
||||||
const active = streaming && (e.to === newestNodeId || e.from === newestNodeId);
|
const active = streaming && (e.to === newestNodeId || e.from === newestNodeId);
|
||||||
const color = active
|
const color = active ? "#3b82f6" : "#94a3b8";
|
||||||
? isDark
|
|
||||||
? DARK.edgeActive
|
|
||||||
: "#3b82f6"
|
|
||||||
: isDark
|
|
||||||
? DARK.edge
|
|
||||||
: "#94a3b8";
|
|
||||||
return {
|
return {
|
||||||
id: `e-${e.from}->${e.to}`,
|
id: `e-${e.from}->${e.to}`,
|
||||||
source: e.from,
|
source: e.from,
|
||||||
@@ -229,11 +174,11 @@ function FlowCanvasInner({
|
|||||||
animated: active,
|
animated: active,
|
||||||
style: { stroke: color, strokeWidth: active ? 2 : 1.5 },
|
style: { stroke: color, strokeWidth: active ? 2 : 1.5 },
|
||||||
markerEnd: { type: MarkerType.ArrowClosed, color, width: 16, height: 16 },
|
markerEnd: { type: MarkerType.ArrowClosed, color, width: 16, height: 16 },
|
||||||
labelStyle: { fontSize: 10, fill: isDark ? DARK.text : "#64748b", fontWeight: 700 },
|
labelStyle: { fontSize: 10, fill: "#64748b", fontWeight: 700 },
|
||||||
labelBgStyle: { fill: isDark ? DARK.cardBg : "#ffffff", fillOpacity: isDark ? 0.9 : 0.85 },
|
labelBgStyle: { fill: "#ffffff", fillOpacity: 0.85 },
|
||||||
} satisfies Edge;
|
} satisfies Edge;
|
||||||
}),
|
}),
|
||||||
[data.edges, streaming, newestNodeId, isDark],
|
[data.edges, streaming, newestNodeId],
|
||||||
);
|
);
|
||||||
|
|
||||||
// 流式中节点增加 → 画布平滑 fitView 跟随生长(用户暂停流后不再打扰)。
|
// 流式中节点增加 → 画布平滑 fitView 跟随生长(用户暂停流后不再打扰)。
|
||||||
@@ -248,30 +193,15 @@ function FlowCanvasInner({
|
|||||||
const selectedNode = selectedId ? data.nodes.find((n) => n.id === selectedId) ?? null : null;
|
const selectedNode = selectedId ? data.nodes.find((n) => n.id === selectedId) ?? null : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div className="flex h-full min-h-0 flex-col">
|
||||||
className="flex h-full min-h-0 flex-col"
|
|
||||||
style={isDark ? { background: DARK.pageBg } : undefined}
|
|
||||||
>
|
|
||||||
{/* 头部:标题 + 工具栏 */}
|
{/* 头部:标题 + 工具栏 */}
|
||||||
<div
|
<div className="shrink-0 flex items-center justify-between gap-2 border-b border-slate-100 bg-white px-4 py-2.5">
|
||||||
className={cn(
|
|
||||||
"shrink-0 flex items-center justify-between gap-2 border-b px-4 py-2.5",
|
|
||||||
isDark ? "" : "border-slate-100 bg-white",
|
|
||||||
)}
|
|
||||||
style={isDark ? { background: DARK.cardBg, borderColor: DARK.border } : undefined}
|
|
||||||
>
|
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
<Workflow className="h-4 w-4 shrink-0 text-primary" />
|
<Workflow className="h-4 w-4 shrink-0 text-primary" />
|
||||||
<span
|
<span className="truncate text-xs font-bold text-slate-800">
|
||||||
className="truncate text-xs font-bold text-slate-800"
|
|
||||||
style={isDark ? { color: DARK.text } : undefined}
|
|
||||||
>
|
|
||||||
{data.title || "方案流程图"}
|
{data.title || "方案流程图"}
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span className="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[10px] text-slate-500">
|
||||||
className="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[10px] text-slate-500"
|
|
||||||
style={isDark ? { background: "rgba(45,68,115,0.5)", color: DARK.textMuted } : undefined}
|
|
||||||
>
|
|
||||||
{data.nodes.length} 节点 · {data.edges.length} 连线
|
{data.nodes.length} 节点 · {data.edges.length} 连线
|
||||||
</span>
|
</span>
|
||||||
{streaming && (
|
{streaming && (
|
||||||
@@ -287,8 +217,7 @@ function FlowCanvasInner({
|
|||||||
type="button"
|
type="button"
|
||||||
title="切回 Markdown 报告预览(流程图可随时再打开)"
|
title="切回 Markdown 报告预览(流程图可随时再打开)"
|
||||||
onClick={onSwitchToReport}
|
onClick={onSwitchToReport}
|
||||||
className="mr-1 inline-flex h-7 items-center gap-1 rounded-lg border border-slate-200/70 bg-white px-2 text-[10.5px] font-bold text-slate-600 transition hover:border-primary/40 hover:text-primary dark:hover:text-primary"
|
className="mr-1 inline-flex h-7 items-center gap-1 rounded-lg border border-slate-200/70 bg-white px-2 text-[10.5px] font-bold text-slate-600 transition hover:border-primary/40 hover:text-primary"
|
||||||
style={isDark ? { background: "transparent", borderColor: DARK.border, color: DARK.text } : undefined}
|
|
||||||
>
|
>
|
||||||
<FileText className="h-3.5 w-3.5" />
|
<FileText className="h-3.5 w-3.5" />
|
||||||
MD 报告
|
MD 报告
|
||||||
@@ -333,50 +262,13 @@ function FlowCanvasInner({
|
|||||||
deleteKeyCode={null}
|
deleteKeyCode={null}
|
||||||
proOptions={{ hideAttribution: true }}
|
proOptions={{ hideAttribution: true }}
|
||||||
>
|
>
|
||||||
<Background
|
<Background variant={BackgroundVariant.Dots} gap={18} size={1} color="#cbd5e1" />
|
||||||
variant={BackgroundVariant.Dots}
|
|
||||||
gap={18}
|
|
||||||
size={1}
|
|
||||||
color={isDark ? DARK.dots : "#cbd5e1"}
|
|
||||||
/>
|
|
||||||
{miniMap && (
|
|
||||||
<MiniMap
|
|
||||||
position="bottom-right"
|
|
||||||
pannable
|
|
||||||
zoomable
|
|
||||||
nodeColor={(n) => {
|
|
||||||
const t = (n.data as { node?: FlowGraphNode }).node?.type;
|
|
||||||
return (t && flowNodeMeta(isDark)[t]?.dot) || (isDark ? DARK.textMuted : "#94a3b8");
|
|
||||||
}}
|
|
||||||
nodeStrokeWidth={2}
|
|
||||||
maskColor={isDark ? "rgba(6,14,36,0.6)" : "rgba(240,240,240,0.6)"}
|
|
||||||
className={cn(
|
|
||||||
"!bottom-2 !right-2 !m-0 overflow-hidden rounded-lg border shadow-sm backdrop-blur-sm",
|
|
||||||
isDark ? "" : "border-slate-200/70 bg-white/90",
|
|
||||||
)}
|
|
||||||
style={
|
|
||||||
isDark
|
|
||||||
? { width: 168, height: 112, background: "rgba(18,35,71,0.9)", borderColor: DARK.border }
|
|
||||||
: { width: 168, height: 112 }
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</ReactFlow>
|
</ReactFlow>
|
||||||
|
|
||||||
{/* 图例 */}
|
{/* 图例 */}
|
||||||
<div
|
<div className="pointer-events-none absolute bottom-2 left-2 flex flex-wrap items-center gap-x-2.5 gap-y-1 rounded-lg border border-slate-200/70 bg-white/85 px-2.5 py-1.5 backdrop-blur-sm">
|
||||||
className={cn(
|
{Object.entries(FLOW_NODE_TYPE_META).map(([type, meta]) => (
|
||||||
"pointer-events-none absolute bottom-2 left-2 flex flex-wrap items-center gap-x-2.5 gap-y-1 rounded-lg border px-2.5 py-1.5 backdrop-blur-sm",
|
<span key={type} className="inline-flex items-center gap-1 text-[9.5px] font-semibold text-slate-500">
|
||||||
isDark ? "" : "border-slate-200/70 bg-white/85",
|
|
||||||
)}
|
|
||||||
style={isDark ? { background: "rgba(18,35,71,0.85)", borderColor: DARK.border } : undefined}
|
|
||||||
>
|
|
||||||
{Object.entries(flowNodeMeta(isDark)).map(([type, meta]) => (
|
|
||||||
<span
|
|
||||||
key={type}
|
|
||||||
className="inline-flex items-center gap-1 text-[9.5px] font-semibold text-slate-500"
|
|
||||||
style={isDark ? { color: DARK.textMuted } : undefined}
|
|
||||||
>
|
|
||||||
<span style={{ background: meta.dot }} className="size-1.5 rounded-full" />
|
<span style={{ background: meta.dot }} className="size-1.5 rounded-full" />
|
||||||
{meta.label}
|
{meta.label}
|
||||||
</span>
|
</span>
|
||||||
@@ -384,15 +276,13 @@ function FlowCanvasInner({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 节点详情弹窗(传入 onChange 时可编辑 / 删除节点) */}
|
{/* 节点详情弹窗 */}
|
||||||
{selectedNode && (
|
{selectedNode && (
|
||||||
<NodeDetailModal
|
<NodeDetailModal
|
||||||
node={selectedNode}
|
node={selectedNode}
|
||||||
data={data}
|
data={data}
|
||||||
dark={isDark}
|
|
||||||
onClose={() => setSelectedId(null)}
|
onClose={() => setSelectedId(null)}
|
||||||
onJump={(id) => setSelectedId(id)}
|
onJump={(id) => setSelectedId(id)}
|
||||||
onChange={onChange}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -408,15 +298,12 @@ function ToolButton({
|
|||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const { theme } = useTheme();
|
|
||||||
const isDark = theme === "dark";
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
title={title}
|
title={title}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
className="flex h-7 w-7 items-center justify-center rounded-lg border border-slate-200/70 bg-white text-slate-500 transition hover:border-primary/40 hover:text-primary"
|
className="flex h-7 w-7 items-center justify-center rounded-lg border border-slate-200/70 bg-white text-slate-500 transition hover:border-primary/40 hover:text-primary"
|
||||||
style={isDark ? { background: "transparent", borderColor: DARK.border, color: DARK.textMuted } : undefined}
|
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</button>
|
</button>
|
||||||
@@ -428,42 +315,19 @@ function ToolButton({
|
|||||||
function NodeDetailModal({
|
function NodeDetailModal({
|
||||||
node,
|
node,
|
||||||
data,
|
data,
|
||||||
dark = false,
|
|
||||||
onClose,
|
onClose,
|
||||||
onJump,
|
onJump,
|
||||||
onChange,
|
|
||||||
}: {
|
}: {
|
||||||
node: FlowGraphNode;
|
node: FlowGraphNode;
|
||||||
data: FlowGraphData;
|
data: FlowGraphData;
|
||||||
dark?: boolean;
|
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onJump: (id: string) => void;
|
onJump: (id: string) => void;
|
||||||
/** Phase 3:传入则可编辑 / 删除该节点(回写整张新图)。 */
|
|
||||||
onChange?: (next: FlowGraphData) => void;
|
|
||||||
}) {
|
}) {
|
||||||
const meta = flowNodeMeta(dark)[node.type];
|
const meta = FLOW_NODE_TYPE_META[node.type];
|
||||||
const labelOf = (id: string) => data.nodes.find((n) => n.id === id)?.label ?? id;
|
const labelOf = (id: string) => data.nodes.find((n) => n.id === id)?.label ?? id;
|
||||||
const incoming = data.edges.filter((e) => e.to === node.id);
|
const incoming = data.edges.filter((e) => e.to === node.id);
|
||||||
const outgoing = data.edges.filter((e) => e.from === node.id);
|
const outgoing = data.edges.filter((e) => e.from === node.id);
|
||||||
|
|
||||||
const [editing, setEditing] = useState(false);
|
|
||||||
const [label, setLabel] = useState(node.label);
|
|
||||||
const [group, setGroup] = useState(node.group ?? "");
|
|
||||||
const [detail, setDetail] = useState(node.detail ?? "");
|
|
||||||
|
|
||||||
const handleSave = () => {
|
|
||||||
onChange?.(applyNodeEdit(data, node.id, { label, group, detail }));
|
|
||||||
setEditing(false);
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
const handleDelete = () => {
|
|
||||||
if (typeof window !== "undefined" && !window.confirm(`删除节点「${node.label}」及其连线?此操作不可撤销。`)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
onChange?.(deleteNodeFromGraph(data, node.id));
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="absolute inset-0 z-30 flex items-center justify-center bg-black/30 p-4 backdrop-blur-[1px]"
|
className="absolute inset-0 z-30 flex items-center justify-center bg-black/30 p-4 backdrop-blur-[1px]"
|
||||||
@@ -471,7 +335,6 @@ function NodeDetailModal({
|
|||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="w-full max-w-md overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-xl"
|
className="w-full max-w-md overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-xl"
|
||||||
style={dark ? { background: DARK.cardBg, borderColor: DARK.border } : undefined}
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
@@ -482,9 +345,9 @@ function NodeDetailModal({
|
|||||||
<span style={{ background: meta.dot }} className="size-2.5 shrink-0 rounded-full" />
|
<span style={{ background: meta.dot }} className="size-2.5 shrink-0 rounded-full" />
|
||||||
<span
|
<span
|
||||||
className="shrink-0 rounded px-1.5 py-0.5 text-[10px] font-bold"
|
className="shrink-0 rounded px-1.5 py-0.5 text-[10px] font-bold"
|
||||||
style={{ background: dark ? "rgba(6,14,36,0.45)" : "#ffffffaa", color: meta.text }}
|
style={{ background: "#ffffffaa", color: meta.text }}
|
||||||
>
|
>
|
||||||
{node.group?.trim() || meta.label}
|
{meta.label}
|
||||||
</span>
|
</span>
|
||||||
<h3 className="min-w-0 truncate text-sm font-bold" style={{ color: meta.text }}>
|
<h3 className="min-w-0 truncate text-sm font-bold" style={{ color: meta.text }}>
|
||||||
{node.label}
|
{node.label}
|
||||||
@@ -494,157 +357,43 @@ function NodeDetailModal({
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="shrink-0 rounded-md p-1 text-slate-500 hover:bg-white/60 hover:text-slate-700"
|
className="shrink-0 rounded-md p-1 text-slate-500 hover:bg-white/60 hover:text-slate-700"
|
||||||
style={dark ? { color: DARK.textMuted } : undefined}
|
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="max-h-[50vh] space-y-3 overflow-y-auto p-4">
|
||||||
{editing ? (
|
<div>
|
||||||
<div className="max-h-[55vh] space-y-3 overflow-y-auto p-4">
|
<div className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400">
|
||||||
<EditField label="节点名称(label)" value={label} onChange={setLabel} dark={dark} />
|
详细说明
|
||||||
<EditField label="所属层级(group,如 目的 / 行为体)" value={group} onChange={setGroup} dark={dark} />
|
|
||||||
<EditField label="详细内容(detail,名称+理由)" value={detail} onChange={setDetail} multiline dark={dark} />
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="max-h-[50vh] space-y-3 overflow-y-auto p-4">
|
|
||||||
<div>
|
|
||||||
<div
|
|
||||||
className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400"
|
|
||||||
style={dark ? { color: DARK.textMuted } : undefined}
|
|
||||||
>
|
|
||||||
详细说明
|
|
||||||
</div>
|
|
||||||
<p
|
|
||||||
className="text-xs leading-relaxed text-slate-700 whitespace-pre-wrap"
|
|
||||||
style={dark ? { color: DARK.text } : undefined}
|
|
||||||
>
|
|
||||||
{node.detail?.trim() || "(该节点未提供详细说明)"}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
{incoming.length > 0 && (
|
<p className="text-xs leading-relaxed text-slate-700">
|
||||||
<ConnectionList title="上游(来自)" entries={incoming.map((e) => ({ id: e.from, label: labelOf(e.from), edgeLabel: e.label }))} onJump={onJump} dark={dark} />
|
{node.detail?.trim() || "(该节点未提供详细说明)"}
|
||||||
)}
|
</p>
|
||||||
{outgoing.length > 0 && (
|
|
||||||
<ConnectionList title="下游(去往)" entries={outgoing.map((e) => ({ id: e.to, label: labelOf(e.to), edgeLabel: e.label }))} onJump={onJump} dark={dark} />
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
{incoming.length > 0 && (
|
||||||
|
<ConnectionList title="上游(来自)" entries={incoming.map((e) => ({ id: e.from, label: labelOf(e.from), edgeLabel: e.label }))} onJump={onJump} />
|
||||||
{/* 编辑 / 删除 操作栏(仅传入 onChange 时显示) */}
|
)}
|
||||||
{onChange && (
|
{outgoing.length > 0 && (
|
||||||
<div
|
<ConnectionList title="下游(去往)" entries={outgoing.map((e) => ({ id: e.to, label: labelOf(e.to), edgeLabel: e.label }))} onJump={onJump} />
|
||||||
className="flex items-center justify-between gap-2 border-t border-slate-100 bg-slate-50/60 px-4 py-2.5"
|
)}
|
||||||
style={dark ? { borderColor: DARK.border, background: "rgba(12,24,54,0.6)" } : undefined}
|
</div>
|
||||||
>
|
|
||||||
{editing ? (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setEditing(false)}
|
|
||||||
className="rounded-lg px-2.5 py-1.5 text-[11px] font-bold text-slate-500 hover:bg-slate-200/60"
|
|
||||||
style={dark ? { color: DARK.textMuted } : undefined}
|
|
||||||
>
|
|
||||||
取消
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleSave}
|
|
||||||
className="inline-flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-[11px] font-bold text-white hover:bg-[var(--brand-900)]"
|
|
||||||
>
|
|
||||||
<Check className="h-3.5 w-3.5" />
|
|
||||||
保存
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleDelete}
|
|
||||||
className="inline-flex items-center gap-1 rounded-lg border border-rose-200 px-2.5 py-1.5 text-[11px] font-bold text-rose-600 hover:bg-rose-50"
|
|
||||||
>
|
|
||||||
<Trash2 className="h-3.5 w-3.5" />
|
|
||||||
删除节点
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setEditing(true)}
|
|
||||||
className="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] font-bold text-slate-700 hover:border-primary/40 hover:text-primary"
|
|
||||||
style={dark ? { borderColor: DARK.border, color: DARK.text } : undefined}
|
|
||||||
>
|
|
||||||
<Pencil className="h-3.5 w-3.5" />
|
|
||||||
编辑
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function EditField({
|
|
||||||
label,
|
|
||||||
value,
|
|
||||||
onChange,
|
|
||||||
multiline,
|
|
||||||
dark = false,
|
|
||||||
}: {
|
|
||||||
label: string;
|
|
||||||
value: string;
|
|
||||||
onChange: (v: string) => void;
|
|
||||||
multiline?: boolean;
|
|
||||||
dark?: boolean;
|
|
||||||
}) {
|
|
||||||
const fieldStyle = dark
|
|
||||||
? { background: "rgba(6,14,36,0.45)", borderColor: DARK.border, color: DARK.text }
|
|
||||||
: undefined;
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<div
|
|
||||||
className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400"
|
|
||||||
style={dark ? { color: DARK.textMuted } : undefined}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</div>
|
|
||||||
{multiline ? (
|
|
||||||
<textarea
|
|
||||||
value={value}
|
|
||||||
onChange={(e) => onChange(e.target.value)}
|
|
||||||
rows={4}
|
|
||||||
className="w-full resize-none rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs leading-relaxed text-slate-800 focus:border-primary focus:outline-none focus:ring-1 focus:ring-[var(--brand-200)]/50"
|
|
||||||
style={fieldStyle}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<input
|
|
||||||
value={value}
|
|
||||||
onChange={(e) => onChange(e.target.value)}
|
|
||||||
className="w-full rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs text-slate-800 focus:border-primary focus:outline-none focus:ring-1 focus:ring-[var(--brand-200)]/50"
|
|
||||||
style={fieldStyle}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ConnectionList({
|
function ConnectionList({
|
||||||
title,
|
title,
|
||||||
entries,
|
entries,
|
||||||
onJump,
|
onJump,
|
||||||
dark = false,
|
|
||||||
}: {
|
}: {
|
||||||
title: string;
|
title: string;
|
||||||
entries: Array<{ id: string; label: string; edgeLabel?: string }>;
|
entries: Array<{ id: string; label: string; edgeLabel?: string }>;
|
||||||
onJump: (id: string) => void;
|
onJump: (id: string) => void;
|
||||||
dark?: boolean;
|
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div
|
<div className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400">
|
||||||
className="mb-1 text-[10px] font-bold uppercase tracking-widest text-slate-400"
|
|
||||||
style={dark ? { color: DARK.textMuted } : undefined}
|
|
||||||
>
|
|
||||||
{title}
|
{title}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-1.5">
|
<div className="flex flex-wrap gap-1.5">
|
||||||
@@ -654,15 +403,11 @@ function ConnectionList({
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={() => onJump(entry.id)}
|
onClick={() => onJump(entry.id)}
|
||||||
className="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-slate-50 px-2 py-1 text-[11px] font-semibold text-slate-700 transition hover:border-primary/40 hover:text-primary"
|
className="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-slate-50 px-2 py-1 text-[11px] font-semibold text-slate-700 transition hover:border-primary/40 hover:text-primary"
|
||||||
style={dark ? { borderColor: DARK.border, background: "rgba(6,14,36,0.4)", color: DARK.text } : undefined}
|
|
||||||
title="查看该节点详情"
|
title="查看该节点详情"
|
||||||
>
|
>
|
||||||
{entry.label}
|
{entry.label}
|
||||||
{entry.edgeLabel && (
|
{entry.edgeLabel && (
|
||||||
<span
|
<span className="rounded bg-slate-200/80 px-1 text-[9px] text-slate-500">
|
||||||
className="rounded bg-slate-200/80 px-1 text-[9px] text-slate-500"
|
|
||||||
style={dark ? { background: "rgba(45,68,115,0.6)", color: DARK.textMuted } : undefined}
|
|
||||||
>
|
|
||||||
{entry.edgeLabel}
|
{entry.edgeLabel}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -675,19 +420,15 @@ function ConnectionList({
|
|||||||
|
|
||||||
// ── 外壳:覆盖右栏 / 全屏切换 ───────────────────────────────────────────────
|
// ── 外壳:覆盖右栏 / 全屏切换 ───────────────────────────────────────────────
|
||||||
|
|
||||||
export function FlowGraphPanel({ data, streaming, onClose, onSwitchToReport, onChange, orientation, miniMap }: FlowGraphPanelProps) {
|
export function FlowGraphPanel({ data, streaming, onClose, onSwitchToReport }: FlowGraphPanelProps) {
|
||||||
const [fullscreen, setFullscreen] = useState(false);
|
const [fullscreen, setFullscreen] = useState(false);
|
||||||
const { theme } = useTheme();
|
return (
|
||||||
const isDark = theme === "dark";
|
|
||||||
const inner = (
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col bg-white",
|
"flex flex-col bg-white",
|
||||||
// 非全屏=填满所在面板(Step3 放在右侧沙箱位,不覆盖左侧消息列表);
|
// 非全屏=填满所在面板(Step3 放在右侧沙箱位,不覆盖左侧消息列表);全屏才整页覆盖。
|
||||||
// 全屏=覆盖整个视口(z 高于 app 顶部导航,保证顶部工具栏可见、可点「退出全屏」)。
|
fullscreen ? "fixed inset-0 z-[80]" : "relative h-full min-h-0 w-full",
|
||||||
fullscreen ? "fixed inset-0 z-[9999]" : "relative h-full min-h-0 w-full",
|
|
||||||
)}
|
)}
|
||||||
style={isDark ? { background: DARK.pageBg } : undefined}
|
|
||||||
>
|
>
|
||||||
<ReactFlowProvider>
|
<ReactFlowProvider>
|
||||||
<FlowCanvasInner
|
<FlowCanvasInner
|
||||||
@@ -697,17 +438,8 @@ export function FlowGraphPanel({ data, streaming, onClose, onSwitchToReport, onC
|
|||||||
onToggleFullscreen={() => setFullscreen((f) => !f)}
|
onToggleFullscreen={() => setFullscreen((f) => !f)}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
onSwitchToReport={onSwitchToReport}
|
onSwitchToReport={onSwitchToReport}
|
||||||
onChange={onChange}
|
|
||||||
orientation={orientation}
|
|
||||||
miniMap={miniMap}
|
|
||||||
/>
|
/>
|
||||||
</ReactFlowProvider>
|
</ReactFlowProvider>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
// 全屏时 portal 到 body:脱离任何带 transform/overflow 的祖先(Step2 沙箱分栏等),
|
|
||||||
// 否则 `fixed` 会被祖先裁剪、顶部工具栏被 app 导航栏盖住(即本次 bug)。
|
|
||||||
if (fullscreen && typeof document !== "undefined") {
|
|
||||||
return createPortal(inner, document.body);
|
|
||||||
}
|
|
||||||
return inner;
|
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,6 @@ function formatFileSize(bytes: number): string {
|
|||||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||||
}
|
}
|
||||||
|
|
||||||
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useLocalSettings } from "@/core/settings";
|
import { useLocalSettings } from "@/core/settings";
|
||||||
import type { MessageMetric } from "@/components/workspace/messages/use-message-metrics";
|
import type { MessageMetric } from "@/components/workspace/messages/use-message-metrics";
|
||||||
@@ -67,11 +66,6 @@ import type { IntentSummary } from "@/roundtable-planning/api/intent";
|
|||||||
|
|
||||||
export interface Step1PanelProps {
|
export interface Step1PanelProps {
|
||||||
// ─── State ────────────────────────────────────────────────────
|
// ─── State ────────────────────────────────────────────────────
|
||||||
/**
|
|
||||||
* 头部左侧自定义内容(深链 taskId 模式:用「策划流程」小图取代默认标题)。
|
|
||||||
* 不传 → 显示默认「任务意图理解 (人机问答)」标题。右侧「问答轮次」始终保留。
|
|
||||||
*/
|
|
||||||
headerLeftSlot?: React.ReactNode;
|
|
||||||
interactiveMessages: InteractiveMessage[];
|
interactiveMessages: InteractiveMessage[];
|
||||||
intentThreadId: string | null;
|
intentThreadId: string | null;
|
||||||
intentReady: object | null;
|
intentReady: object | null;
|
||||||
@@ -98,7 +92,6 @@ export interface Step1PanelProps {
|
|||||||
|
|
||||||
export function Step1Panel(props: Step1PanelProps) {
|
export function Step1Panel(props: Step1PanelProps) {
|
||||||
const {
|
const {
|
||||||
headerLeftSlot,
|
|
||||||
interactiveMessages,
|
interactiveMessages,
|
||||||
intentThreadId,
|
intentThreadId,
|
||||||
intentReady,
|
intentReady,
|
||||||
@@ -163,16 +156,14 @@ export function Step1Panel(props: Step1PanelProps) {
|
|||||||
return (
|
return (
|
||||||
<div className="flex-1 flex flex-col min-h-0">
|
<div className="flex-1 flex flex-col min-h-0">
|
||||||
{/* Dialogue Header */}
|
{/* Dialogue Header */}
|
||||||
<div ref={headerDzRef} className="shrink-0 px-6 py-4.5 border-b border-slate-100 flex items-center justify-between gap-3 bg-slate-50/50">
|
<div ref={headerDzRef} className="shrink-0 px-6 py-4.5 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
|
||||||
{headerLeftSlot ?? (
|
<div className="flex items-center gap-2">
|
||||||
<div className="flex items-center gap-2">
|
<MessageSquare className="w-4.5 h-4.5 text-primary" strokeWidth={2.5} />
|
||||||
<MessageSquare className="w-4.5 h-4.5 text-primary" strokeWidth={2.5} />
|
<h3 className="text-sm font-extrabold text-slate-900">
|
||||||
<h3 className="text-sm font-extrabold text-slate-900">
|
任务意图理解 (人机问答)
|
||||||
任务意图理解 (人机问答)
|
</h3>
|
||||||
</h3>
|
</div>
|
||||||
</div>
|
<span className="text-[11px] font-bold text-slate-400 bg-white border px-2 py-0.5 rounded-md">
|
||||||
)}
|
|
||||||
<span className="shrink-0 text-[11px] font-bold text-slate-400 bg-white border px-2 py-0.5 rounded-md">
|
|
||||||
问答轮次:{interactiveMessages.filter((m) => m.sender === "user").length} 轮
|
问答轮次:{interactiveMessages.filter((m) => m.sender === "user").length} 轮
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -181,8 +172,7 @@ export function Step1Panel(props: Step1PanelProps) {
|
|||||||
<div className="relative flex-1 min-h-0 flex flex-col font-normal">
|
<div className="relative flex-1 min-h-0 flex flex-col font-normal">
|
||||||
<div
|
<div
|
||||||
ref={step1ScrollRef}
|
ref={step1ScrollRef}
|
||||||
// overflow-x-hidden:消息列表只竖向滚(见 Step2Panel 同处注释),避免误触横向拖动抢滑块。
|
className="flex-1 min-h-0 overflow-y-auto p-6 space-y-4 bg-white"
|
||||||
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-6 space-y-4 bg-white"
|
|
||||||
>
|
>
|
||||||
{interactiveMessages.map((msg) => (
|
{interactiveMessages.map((msg) => (
|
||||||
<Step1Message
|
<Step1Message
|
||||||
@@ -231,7 +221,7 @@ export function Step1Panel(props: Step1PanelProps) {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<AutoGrowTextarea
|
<textarea
|
||||||
id="input-text-area"
|
id="input-text-area"
|
||||||
value={inputText}
|
value={inputText}
|
||||||
onChange={(e) => setInputText(e.target.value)}
|
onChange={(e) => setInputText(e.target.value)}
|
||||||
@@ -243,11 +233,10 @@ export function Step1Panel(props: Step1PanelProps) {
|
|||||||
}}
|
}}
|
||||||
placeholder={
|
placeholder={
|
||||||
pendingIntentClarificationMsgId
|
pendingIntentClarificationMsgId
|
||||||
? "也可在此输入自定义回答 (Enter 发送 / Shift+Enter 换行)"
|
? "也可在此输入自定义回答 (Enter 快速发送)"
|
||||||
: "请输入补充信息 / 回答问题 / 继续澄清 (Enter 发送 / Shift+Enter 换行)"
|
: "请输入补充信息 / 回答问题 / 继续澄清 (Enter 快速发送)"
|
||||||
}
|
}
|
||||||
className="w-full text-xs text-slate-700 placeholder:text-slate-400 min-h-[48px] max-h-80 focus:outline-none leading-relaxed font-normal"
|
className="w-full text-xs text-slate-700 placeholder:text-slate-400 resize-none h-[48px] focus:outline-none leading-relaxed font-normal"
|
||||||
maxHeight={320}
|
|
||||||
maxLength={500}
|
maxLength={500}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 253 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user