Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2041c0b07 | ||
|
|
2fa7000ff7 | ||
|
|
760b88d6f1 | ||
|
|
d7ad0624b7 | ||
|
|
27e6b0b23e | ||
|
|
55b5c2cc9f | ||
|
|
d5d5199f6d | ||
|
|
0bd0ac41cd | ||
|
|
b1c396717b | ||
|
|
388a9133fc | ||
|
|
221e947488 | ||
|
|
a1c63a1fe5 | ||
|
|
db2f21191c | ||
|
|
195ef3ee40 | ||
|
|
f3511e5cd0 | ||
|
|
96947d7636 | ||
|
|
034a379ecd | ||
|
|
da856f2b58 | ||
|
|
845c87e3ee | ||
|
|
7d9c0894f8 | ||
|
|
ae30a20739 | ||
|
|
7e7d3c9846 | ||
|
|
daff70c34f | ||
|
|
94188db9ea | ||
|
|
b12497898a | ||
|
|
3e51208024 | ||
|
|
36a3851233 | ||
|
|
54190d7a83 | ||
|
|
2215ec3c49 | ||
|
|
d21dbeb214 | ||
|
|
ba0c32dcee | ||
|
|
f5efe9b041 | ||
|
|
a4a44e1154 | ||
|
|
cef08638af | ||
|
|
025e43f4c5 | ||
|
|
fa04ab8b5a | ||
|
|
f3e5a3bb35 | ||
|
|
0547fb1715 | ||
|
|
bb6b9bd84b | ||
|
|
4bfaeb728b | ||
|
|
c8cdd1d0b2 | ||
|
|
8fbfd35296 | ||
|
|
dfb745a5e4 | ||
|
|
537e2e4d06 | ||
|
|
9268c73776 | ||
|
|
6378cd33bd | ||
|
|
8c6d08d6bf | ||
|
|
29082b349d | ||
|
|
7d8656bfde | ||
|
|
45ce14e15a | ||
|
|
17650afe96 | ||
|
|
80fce34c1a | ||
|
|
6851c96a45 | ||
|
|
f22a6a9957 | ||
|
|
210cb5117f | ||
|
|
75e8a90ac7 |
No files matched your search
@@ -79,6 +79,7 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA:
|
||||
|
||||
- **Routing**: React Router v7; top-level routes in `src/pages/PageRoutes.tsx`, workspace sub-routes in `src/pages/WorkspaceRoutes.tsx`
|
||||
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
|
||||
- **AI 写作·对话版(对话驱动写作台)**: a **parallel new entry** beside the classic AI-writing page (classic page/routes untouched) — route `/page/canvas/ai-writing-chat`, sidebar 「问答管理 → 课题研究(对话版)」. Page `open-canvas/pages/AIWritingChatPage.tsx` reuses the engine (`AIWritingContext` + `useStream` + `AIWritingDraftPanel`); **idle keeps the classic setup layout** (`WritingSetupChat` + collapsible form) and switches to the chat workbench once writing starts; left panel `components/ai-writing-chat/WritingChatPanel.tsx` = **unified chronological feed** (`ChatFlowTimeline.tsx`, chat bubbles anchor-interleaved into the progress timeline so triggered events render below the user's message) + button-only intervention cards (`ChatInterventionCards.tsx`, inline textareas removed) + bottom unified smart composer. Intent resolution: frontend fast path + `POST /api/ai-writing/sessions/{id}/intent` → `deerflow/agents/ai_writing/intent_router.py` (per-pause action whitelist, high-cost confidence gates, payload cleaning); supports QA bypass, clarify follow-ups, control intents, and material-stage auto re-search + pending-intent resume. Tests `tests/test_ai_writing_intent.py`; plan doc `frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md`.
|
||||
- **轻应用中心 (Light App Center)**: a sibling of 任务管理 in the sidebar with two pages — 应用管理 (admin registers `window_open` or `iframe` mini-apps with a route-param builder: login params resolved from `localStorage.userInfo`, theme params literal) and 应用列表 (card grid of `window_open` apps, `window.open` launch). `iframe` apps are mounted under a chosen parent menu (XK/PG/TY/综合管理) and **dynamically injected into the sidebar** by `core/page-layout/use-sidebar-menu.ts` (`useSidebarMenuItems`), opening in the `LightAppIframeView` host. Client + React Query hooks in `strategy-components/api/light-apps.ts`; URL builder/constants in `strategy-components/lib/light-app.ts`. Backend: `/api/light-apps` (global/shared, admin-gated writes).
|
||||
- **菜单管理 (Menu Management, admin-only)**: an **overlay** over the static sidebar menu — `MenuManagementPage` (`pages/MenuManagementPage.tsx`, route `/page/strategy/admin/menu-management`, opened from the admin-only 「菜单管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`). Admins rename / 停用·启用 / reorder (↑↓ or @dnd-kit drag) / re-parent (horizontal drag **or** the edit dialog's 「移动到」parent selector) any node across 一级/二级/三级, **including injected iframe light-app nodes** (`light-app-<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.
|
||||
|
||||
@@ -80,6 +80,7 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA:
|
||||
- **Routing**: React Router v7; top-level routes in `src/pages/PageRoutes.tsx`, workspace sub-routes in `src/pages/WorkspaceRoutes.tsx`
|
||||
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
|
||||
- **定时任务「JSON → HTML 模板填充」(模板数据转换器)**: a third scheduled-task execution mode. In the create/edit dialog (`ScheduledTasksPage.tsx`), selecting the built-in agent **「模板数据转换器」** (`execution_agent_name === "template-json-builder"`, `TEMPLATE_BUILDER_AGENT_ID`) reveals a 「HTML模板」 select (`useHtmlTemplates` → `GET /api/scheduled-tasks/html-templates`) + a **.json 上传** button (reads the file's text into the prompt box) and **hides** the 必须生成 HTML/Markdown switches (this mode always outputs HTML). The chosen template persists as `execution_context.template_config.template_id` (`TemplateFillConfig` in `core/scheduled-tasks/types.ts`). At run time the backend converts the source JSON (the task prompt) into that template's `DATA` structure, validates (retry-on-fail), fills the template, and stores an HTML page previewable via the existing run-detail HTML preview. The source can be **pure JSON, plain text, or text-with-embedded-JSON** — the backend pre-extracts any embedded JSON and the agent's `SOUL.md` maps it (or the plain text's semantics) to the template's schema skeleton. **Chat-page debug entry (only this agent's `AgentChatPage`)**: when `agent_id === "template-json-builder"`, the chat header shows a 「页面模板」 select + a 「渲染预览」 button — after a normal Q&A run, the button takes the **latest AI reply**, POSTs it to `POST /api/scheduled-tasks/template-fill/render` (`renderTemplateFill`), and pops a dialog rendering the filled HTML in a `sandbox="allow-scripts"` iframe plus the structure-validation status/errors/gaps — for debugging the agent's conversion effect without creating a scheduled task. Gated strictly on the agent id, so other agents' chat pages are untouched. See the backend CLAUDE.md「Template-fill mode」for the engine (`deerflow/runtime/scheduler/template_fill.py`), agent seed, dispatch, and the render API.
|
||||
- **AI 写作·对话版(对话驱动写作台)**: a **parallel new entry** beside the classic AI-writing page (classic page/routes untouched) — route `/page/canvas/ai-writing-chat` (`OpenCanvasRoutes.tsx`), sidebar 「问答管理 → 课题研究(对话版)」. Page `open-canvas/pages/AIWritingChatPage.tsx` fully **reuses the engine** (`AIWritingContext` state machine + LangGraph `useStream`, `AIWritingHistoryProvider`, right-side `AIWritingDraftPanel`) but replaces the presentation: left = `components/ai-writing-chat/WritingChatPanel.tsx` (timeline + **button-only intervention cards** `ChatInterventionCards.tsx` — the five pause cards copied from `InterventionCard.tsx` with all inline textareas removed, confirm/action buttons kept — plus a bottom **unified smart composer**). Free text goes through two-level intent resolution (`open-canvas/api/ai-writing-intent.ts`): deterministic short-phrase fast path (确认/继续/重新搜索/重写大纲…; high-cost actions never fast-pathed) then `POST /api/ai-writing/sessions/{id}/intent` — the backend reads the graph checkpoint (authoritative pause point from the pending interrupt) and routes via `deerflow/agents/ai_writing/intent_router.py` (LLM + strict per-pause action whitelist aligned to the graph's real resume actions, confidence gates: finalize/force_finalize/覆盖式 re_search need ≥0.85 else clarify, payload key-whitelist cleaning). Results map to `submitIntervention`/control (暂停/继续/后台挂起)/QA bypass (`answer` rendered as a chat bubble, never touches graph state)/clarify (amber follow-up bubble with multi-turn context). **Two-state layout**: idle (未开始写作) renders the **classic setup experience unchanged** — `WritingSetupChat` + collapsible `AIWritingPanel` form under `WritingFormProvider` (same as `AIWritingPage`'s idle branch); once writing starts (or history view opens) it switches to the chat workbench. **Unified chronological feed** (`ChatFlowTimeline.tsx`): intent-layer chat bubbles are interleaved INTO the progress-event timeline by anchor (= `progressEvents.length` at message creation), so events triggered by a user message render **below** it (Google-AI-Studio-style single stream, not timeline-above/chat-below); composer-driven interventions suppress the duplicate 「我的要求」card (`suppressedRequirementIndices`). **素材不足自动续跑** only at `material_confirm` (the only pause the graph supports re-search from): needResearch caches the payload as a pending intent, submits `re_search + userQuery`, and auto-submits the pending intent when the new material-confirm pause arrives (cancellable pill). Stage chips + per-stage placeholder + 「当前交互对象」status badge. Backend tests `tests/test_ai_writing_intent.py`. Plan doc: `frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md`.
|
||||
- **轻应用中心 (Light App Center)**: a sibling of 任务管理 in the sidebar with two pages — 应用管理 (admin registers `window_open` or `iframe` mini-apps with a route-param builder: login params resolved from `localStorage.userInfo`, theme params literal) and 应用列表 (card grid of `window_open` apps, `window.open` launch). `iframe` apps are mounted under a chosen parent menu (XK/PG/TY/综合管理) and **dynamically injected into the sidebar** by `core/page-layout/use-sidebar-menu.ts` (`useSidebarMenuItems`), opening in the `LightAppIframeView` host. Client + React Query hooks in `strategy-components/api/light-apps.ts`; URL builder/constants in `strategy-components/lib/light-app.ts`. Backend: `/api/light-apps` (global/shared, admin-gated writes).
|
||||
- **菜单管理 (Menu Management, admin-only)**: an **overlay** over the static sidebar menu — `MenuManagementPage` (`pages/MenuManagementPage.tsx`, route `/page/strategy/admin/menu-management`, opened from the admin-only 「菜单管理」 item in the **bottom-left settings dropdown** of `components/page-sidebar.tsx`). Admins rename / 停用·启用 / reorder (↑↓ or @dnd-kit drag) / re-parent (horizontal drag **or** the edit dialog's 「移动到」parent selector) any node across 一级/二级/三级, **including injected iframe light-app nodes** (`light-app-<appId>`). The static tree (`core/page-layout/sidebar-menu.ts`) stays the source of icons/routes; only per-node deltas (`label`/`disabled`/`parentId`/`sortOrder`) persist to the backend. Merge logic in `core/page-layout/menu-overrides.ts` (`applyMenuOverrides`, applied in `use-sidebar-menu.ts` after light-app injection, before role filter; disabling a node hides its whole subtree) — strict **3-level cap** (`wouldExceedDepth`). Client `strategy-components/api/menu-overrides.ts`. Backend: `/api/menu-overrides` (global/shared; open read, admin atomic replace-all).
|
||||
- **白名单管理 (Login Whitelist, admin-only)**: gates **who may log in**, run as a **blocklist (黑名单模式)**. Two pieces: a global master switch (`system_settings.json → login_whitelist.enabled`, surfaced by **admin-only** `GET|PUT /api/system-settings/login-whitelist`) + a per-user **放行** flag (`users.approved` column, migration `20260625_02`). Users **self-register** as usual and **every new account defaults to `approved=True`** — so a user who has never logged into this system before is allowed straight through; the switch only blocks users an admin has explicitly **取消放行** (`approved=False`). (`create_user`/`User`/`UserRow` all default `approved=True`; admins are always approved; existing rows are backfilled `True`.) Login interception is the single helper `enforce_user_approved(user)` in `app/gateway/routers/auth.py`, called in all three login endpoints (`/login/{local,username,token}`) **after** the account is resolved/created and **before** the JWT is issued: switch off → everyone passes; `system_role=="admin"` → always passes (anti-lockout); else `approved=False` (admin-revoked) → 403 `{code:"PENDING_APPROVAL"}` (the frontend's `extractErrorMessage` surfaces the message and login throws before writing any auth state, so no half-login). Admin approves on `pages/LoginWhitelistPage.tsx` (route `/page/strategy/admin/login-whitelist`, entry「白名单管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both sidebar modes): a top master-switch + a list of all registered users (`GET /api/v1/auth/users`, now carrying `approved`) with a per-row 放行 Switch (`PUT /api/v1/auth/users/{id}/approval`, admin-only; revoking only blocks the **next** login — `token_version` is left untouched, existing sessions are not force-killed). Client/hooks: switch in `strategy-components/api/login-whitelist.ts`, user list + approval in `core/auth/{api,hooks}.ts` (`useSetUserApproval`). Backend tests: `tests/test_login_approval.py`. **账号级「登录口令」(per-account password — 临时开通)**: the same page also lets an admin assign one specific account an individual **plaintext** password (`users.login_password` column, migration `20260625_04`, nullable; auto-added on startup by `_ensure_orm_columns_sync`). Once set, **that account's** username login (`POST /api/v1/auth/login/username`) **requires** `?password=` to exactly match it and that personal password **takes precedence over** the global shared-password gate (`username_login.require_password`); accounts without one keep today's shared-gate / passwordless behavior. The user then logs in via the **existing** frontend URL `#/login/<用户名>?password=xxxx` (LoginPage already forwards `?password=`; `<用户名>` = the account's email `@`-prefix). **Plaintext is intentional** — the password rides in the URL query anyway, so storing it readably lets the admin re-copy the full login link from the page; it is exposed only on the **admin-only** `GET /api/v1/auth/users` (`UserListItem.login_password`) and the new admin-only `PUT /api/v1/auth/users/{id}/login-password` (set non-empty / clear with null·empty; doesn't touch `token_version`). The whitelist page renders a per-user 「登录口令」 column with a set/修改 editor + a live 「复制登录链接」 button (`useSetUserLoginPassword` in `core/auth/hooks.ts`, `setUserLoginPassword` in `core/auth/api.ts`). Backend gate helper `_lookup_user_by_username` (lookup-only, no auto-register) in `routers/auth.py`; tests `tests/test_login_personal_password.py`.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
VITE_USE_REAL_DATA=true
|
||||
|
||||
# 任务详情(登录深链 cop-task-detail)数据源:默认真实接口;改成 true 走本地假数据(consumer 外网不可达时调试用)。
|
||||
VITE_MOCK_COP_TASK_DETAIL=flase
|
||||
VITE_MOCK_COP_TASK_DETAIL=true
|
||||
|
||||
# 研判情报报告(大屏绘制智能体深链 selectSqReport)数据源:true 走本地样例假数据(真实接口未就绪时调试用);联调通过后置 false。
|
||||
VITE_MOCK_SQ_REPORT=true
|
||||
|
||||
@@ -50,4 +50,6 @@
|
||||
# 可选
|
||||
# VITE_CANVAS_LANGGRAPH_BASE_URL=
|
||||
# VITE_STATIC_WEBSITE_ONLY=
|
||||
# 部署级紧凑导航:true 时固定收起工作台左侧栏,并隐藏换肤与全量/简洁模式切换。
|
||||
# VITE_FORCE_COLLAPSED_SIDEBAR=false
|
||||
# VITE_GITHUB_OAUTH_TOKEN=
|
||||
@@ -14,8 +14,8 @@ VITE_MOCK_SQ_REPORT=false
|
||||
VITE_MOCK_COP_TASK_DETAIL=false
|
||||
|
||||
# Gateway / DeerFlow API
|
||||
VITE_BACKEND_BASE_URL=http://47.88.25.99:7001
|
||||
VITE_LANGGRAPH_BASE_URL=http://47.88.25.99:7001/api
|
||||
VITE_BACKEND_BASE_URL=http://10.19.200.5:2026
|
||||
VITE_LANGGRAPH_BASE_URL=http://10.19.200.5:2026/api
|
||||
|
||||
# 轻应用「新建笔记」系列接口
|
||||
VITE_NOTE_API_BASE_URL=http://47.88.25.99:8000
|
||||
@@ -42,7 +42,7 @@ VITE_AIPI_BACKENP_URL=http://47.88.25.99:8000
|
||||
# VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.uat.4.cn
|
||||
VITE_NOTEBOOK_API_BASE_URL=http://47.88.25.99:8000
|
||||
VITE_AIPI_FRONTEND_URL=http://47.88.25.99:3000
|
||||
VITE_AIPI_CONSUMER_URL=https://ch1.b.uat.4.cn/consumer
|
||||
VITE_AIPI_CONSUMER_URL=http://10.19.200.5:8002/consumer
|
||||
# A 系统跳转地址(人物/组织/事件等列表项打开链接)
|
||||
VITE_AIPI_PRESENT_URL=http://present.a.uat.4.cn/present/domain
|
||||
# B 系统知识库 iframe 根地址
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
# AI 写作「对话驱动写作台」实现方案(可落地版)
|
||||
|
||||
> 需求:**复制**现有 AI 写作代码,新增一个独立页面(**原页面/原路由零改动**)。在新页面里
|
||||
> **大改交互流程**——去掉「素材收集 / 大纲规划 / 作家写作 / 编辑审核」四个阶段干预卡里的**输入框**,
|
||||
> 只**保留原来的确认按钮**;在页面**底部新增一个统一的多行智能输入框**,具备**强意图理解**能力:
|
||||
> 重新搜索、新增检索词、添加检索素材、重新规划大纲、按要求改大纲、提修改意见、审核意见、
|
||||
> 素材不足继续搜集、对写作内容提问……**覆盖现有全部交互甚至更多**。
|
||||
>
|
||||
> 交互节奏不变:**一步一确认**——进行到某个专家阶段时,交互就针对该专家(阶段作用域);
|
||||
> 用户可以**点原来的确认按钮**,也可以**在底部输入框里发「继续下一步」的意图**推进。
|
||||
> 意图**拿不准时**主动向用户**发起协助/澄清**,绝不盲目触发高代价动作(定稿 / 重搜等)。
|
||||
|
||||
本文是**实现指引**,落地时按第 9 节路线图分阶段推进。文中所有文件路径、符号名均对齐当前代码。
|
||||
|
||||
---
|
||||
|
||||
## 1. 现状梳理(改造地基)
|
||||
|
||||
现有 AI 写作是一套**独立 LangGraph 子系统**(不是 lead_agent),前后端都已成型、可复用。
|
||||
|
||||
### 1.1 后端 `ai_writing` graph
|
||||
|
||||
- 图工厂:`offline-backend-20260512/backend/packages/harness/deerflow/agents/ai_writing/graph.py`
|
||||
(`make_ai_writing_graph`,registered as `assistant_id="ai_writing"`)
|
||||
- 状态:`.../ai_writing/state.py`(`AIWritingState`)
|
||||
- 四个「阶段大脑」节点:
|
||||
|
||||
| 阶段 | 节点 | 文件 |
|
||||
|------|------|------|
|
||||
| 素材收集 | `researcher` | `nodes/researcher.py` |
|
||||
| 大纲规划 | `writer_outline` | `nodes/writer_outline.py` |
|
||||
| 作家写作 | `writer_draft` | `nodes/writer_draft.py` |
|
||||
| 编辑审核 | `editor` | `nodes/editor.py` |
|
||||
|
||||
- **五个暂停点**(`interrupt()`,`Command(resume=payload)` 续跑)——这是对话改造的核心可复用资产:
|
||||
|
||||
| pause_point | 语义 | 现有 action |
|
||||
|-------------|------|-------------|
|
||||
| `material_confirm` | 素材确认 | `confirm` / `re_search` / `enable_skill_search` |
|
||||
| `outline_confirm` | 大纲确认 | `confirm` / `re_outline` |
|
||||
| `draft_confirm` | 草稿确认 | `to_editor` / `finalize` / `user_revise` |
|
||||
| `review_confirm` | 编辑打回确认 | `accept_review` / `force_finalize` |
|
||||
| `section_help` | 素材不足求助 | `section_help`(+`sectionDecisions`) |
|
||||
|
||||
- resume 载荷(`UserInterventionPayload`,`types/ai-writing.ts`)字段:`action`、`approvedMaterialIds`、
|
||||
`userQuery`(自然语言补充检索)、`editedOutline`、`outlineFeedback`、`userRevisionNotes`、
|
||||
`overrideVerdict`、`selectedIssueIndices`、`sectionDecisions`。
|
||||
**协议已同时支持「自然语言 + 结构化 action」**——这是对话层能复用的关键。
|
||||
|
||||
> 结论:**状态机 / 流式 / 暂停·续跑协议 / 持久化都可复用**,无需重写引擎。改造本质是
|
||||
> 「把分散在干预卡里的输入框,换成一个底部智能输入框 + 意图路由层」,再把意图翻译回**现有
|
||||
> `action + payload`**;仅少量新意图(对内容提问、素材不足自动回退重搜、追加审核意见)需新增能力。
|
||||
|
||||
### 1.2 前端 `open-canvas` 子系统
|
||||
|
||||
- 主页面:`frontend-web/src/open-canvas/pages/AIWritingPage.tsx`
|
||||
- 路由注册:`open-canvas/routes/OpenCanvasRoutes.tsx`(`/page/canvas/ai-writing/*`)、
|
||||
`pages/WorkspaceRoutes.tsx`(`/page/workspace/ai-writing/*`)、`pages/NotebookAIWritingPage.tsx`
|
||||
- 状态机 + 流式:`contexts/AIWritingContext.tsx`(`useReducer` + LangGraph `useStream`,`assistantId:'ai_writing'`)
|
||||
- 事件翻译 / reducer:`hooks/useAIWritingStream.ts`
|
||||
- 类型:`types/ai-writing.ts`
|
||||
- **左栏面板**:`components/ai-writing/AIWritingPanel.tsx`(时间线 + 干预卡 + 状态栏;idle 时挂启动表单)
|
||||
- **要改造的输入 UI**(本次重点):
|
||||
- 干预卡 `components/ai-writing/InterventionCard.tsx`:内含
|
||||
`MaterialConfirmCard`(素材:有 `MaterialsToolbar` 输入框)、
|
||||
`OutlineConfirmCard`(大纲:有 feedback textarea)、
|
||||
`DraftConfirmCard`(草稿:有「修改意见」textarea)、
|
||||
`ReviewConfirmCard`(审核:有「补充修改指令」textarea)、
|
||||
`SectionHelpCard`(素材不足:按钮组)。
|
||||
**每张卡里都既有输入框又有确认/动作按钮**——本次要**去掉输入框、保留按钮**。
|
||||
- 启动表单 `components/ai-writing/AIWritingForm.tsx`(idle 阶段的配置表单)——本次由底部输入框接管启动。
|
||||
- **已存在的对话原型**(可借鉴):`components/ai-writing/WritingSetupChat.tsx`
|
||||
(`useThreadStream` 起 lead_agent 线程 + `setup_writing` 审批卡回填表单;仅管启动前配置,不直接复用)。
|
||||
- 底部输入框可直接复用 UI 组件:`@/components/ai-elements/prompt-input`
|
||||
(`PromptInput` / `PromptInputTextarea` / `PromptInputSubmit` / `PromptInputFooter`,见 `WritingSetupChat`)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 目标与范围
|
||||
|
||||
### 2.1 必须满足
|
||||
|
||||
1. **复制式新增**:新目录 / 新路由 / 新侧边栏入口,**旧页面、旧路由、旧组件零改动**(「初始的不用动」)。
|
||||
2. 页面**底部单一多行智能输入框**接管全流程交互;四个阶段干预卡里的**输入框全部移除**。
|
||||
3. **保留确认按钮**:每个阶段到达暂停点时,消息流里仍渲染**产物卡 + 原来的确认/动作按钮**
|
||||
(素材「确认素材」、大纲「确认大纲」、草稿「让编辑审核 / 确认定稿」、审核「按编辑意见修改 / 强制定稿」、
|
||||
素材不足的三选一按钮)。用户**点按钮**或**在底部输入框发自然语言意图**二选一均可推进。
|
||||
4. **强意图理解**:把用户自由文本准确路由到正确动作,**覆盖现有全部交互 + 更多**(见 3.2)。
|
||||
5. **阶段作用域**:意图解析必须知道「当前停在哪个专家阶段」,把同一句话按当前阶段翻译成对应 action。
|
||||
6. **素材不足自动回退重搜**:修改意见需要的信息现有素材没有时,先重搜补素材、补完自动继续原意图。
|
||||
7. **拿不准就协助**:低置信意图**不猜着执行**,走澄清追问(clarify)或用户协助。
|
||||
8. 保留右侧草稿实时预览(可编辑)与时间线 / 进度展示。
|
||||
|
||||
### 2.2 明确不做(本期)
|
||||
|
||||
- 不改旧 `AIWritingPage` 及其 `AIWritingForm` / `InterventionCard`(这两个是要在**副本**里改的)。
|
||||
- 不替换 `ai_writing` graph 四个阶段大脑逻辑,不动五个暂停点 / checkpoint / 持久化。
|
||||
- 不引新状态管理库(继续 `useReducer` + `useStream`)。
|
||||
|
||||
### 2.3 复制策略(关键决策)
|
||||
|
||||
「复制一份」= **复制会被大改的表现层组件**(页面 + 干预卡 + 面板),**复用不改的引擎层**:
|
||||
|
||||
| 复制(新建副本,大改) | 复用(原样,不改;仅对 `types` 做**追加式**扩展) |
|
||||
|------------------------|--------------------------------------------------|
|
||||
| 新页面 `AIWritingChatPage.tsx` | `contexts/AIWritingContext.tsx`(状态机 + 流式) |
|
||||
| 新面板 `WritingChatPanel.tsx`(消息流 + 底部输入框) | `hooks/useAIWritingStream.ts`(事件 → state) |
|
||||
| 新消息卡 `chat-cards/*`(产物卡+确认按钮,**无输入框**) | `components/ai-writing/AIWritingDraftPanel.tsx`(右侧草稿预览) |
|
||||
| 新意图客户端 `api/ai-writing-intent.ts` | 各流式展示子组件(`MaterialsCard`/`OutlineCard`/`ReviewCard`/`SkillStepsCard`…) |
|
||||
| (可选)新 `contexts/WritingChatContext.tsx` 包一层「pending 意图 / 澄清态」 | `types/ai-writing.ts`(**只加字段不改旧字段**,保证旧页面不受影响) |
|
||||
|
||||
> **不复用、也不改** 的三个「输入框组件」:`AIWritingForm` / `InterventionCard` / `WritingFormContext`——
|
||||
> 旧页面继续用它们,新页面完全不引用它们。这样「初始的不用动」得到硬保证。
|
||||
>
|
||||
> 为什么复用 `AIWritingContext` 而不复制它?它**不含任何输入框 UI**,只是「状态机 + 与后端 graph 的
|
||||
> 流式桥」,复用它**不会改动旧页面的任何呈现**(旧页面照常在自己的 Provider 实例里跑)。复用能显著
|
||||
> 降低维护成本、避免两套引擎漂移。若要绝对物理隔离,也可整目录复制 `AIWritingContext` +
|
||||
> `useAIWritingStream` 到新目录——**推荐先复用**,仅当后续需要给对话态加大量图内新协议时再分叉。
|
||||
|
||||
---
|
||||
|
||||
## 3. 核心设计
|
||||
|
||||
### 3.1 三层结构
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ 对话 UI 层(新) WritingChatPanel │
|
||||
│ - 消息流:用户消息 + AI 阶段产物卡(含【保留的确认按钮】)+ 进度 │
|
||||
│ - 底部:统一多行智能输入框(唯一自由输入入口) │
|
||||
│ - 右侧:草稿实时预览(复用 AIWritingDraftPanel) │
|
||||
└───────────────┬──────────────────────────────────────────────┘
|
||||
│ 用户自然语言(+ 当前 status/pausePoint 上下文)
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ 意图解析层(新,核心) POST /api/ai-writing/sessions/{id}/intent │
|
||||
│ 输出:{ intent, pausePoint, action, payload, │
|
||||
│ needResearch, researchQuery, answer, confidence, clarify }│
|
||||
└───────────────┬──────────────────────────────────────────────┘
|
||||
│ 结构化 action + payload
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ 执行层(复用现有 AIWritingContext) │
|
||||
│ idle → startWriting(AIWritingRequest) │
|
||||
│ 暂停 → submitIntervention(UserInterventionPayload) │
|
||||
│ 问答 → 旁路回答(不改写作状态) │
|
||||
│ 素材不足 → 先重搜、缓存 pending、补完自动续跑 │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**设计原则**:意图解析层是「翻译官」——把自由文本翻译成**执行层已经懂的指令**。能复用
|
||||
`action + payload` 的绝不新造协议;确认按钮点击**直接走执行层**(不经意图层,零延迟、零误判)。
|
||||
|
||||
### 3.2 意图分类体系(覆盖全流程 + 更多)
|
||||
|
||||
按「意图 → 触发时机(当前 status/pausePoint)→ 映射执行」组织,即意图解析引擎的目标 schema。
|
||||
**「甚至更多」** = G(问答)、H(控制)、以及 B/C/D/E 里的「素材不足自动回退重搜」。
|
||||
|
||||
#### A. 启动类(status = `idle`)
|
||||
| 意图 | 用户说法示例 | 映射 |
|
||||
|------|-------------|------|
|
||||
| `start_writing` | 「写一篇关于新能源出口的深度分析,2000 字」 | 解析成 `AIWritingRequest` → `startWriting()` |
|
||||
| `start_with_outline` | 「按这个大纲写:…」 | `AIWritingRequest.userOutline` |
|
||||
| `start_imitate` | 「仿照这篇样文写…」 | `writingModeType='imitate'` + `sampleText` |
|
||||
|
||||
#### B. 素材类(pausePoint = `material_confirm`)
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `confirm_materials` | 「素材可以,继续 / 下一步」 | `{action:'confirm', approvedMaterialIds}` |
|
||||
| `research_again` | 「重新搜索素材」 | `{action:'re_search'}`(无 userQuery=覆盖式重检) |
|
||||
| `add_material`/`add_keyword` | 「再补点关于 X 的素材」「加个关键词 Y」 | `{action:'re_search', userQuery:'X/Y'}`(追加) |
|
||||
| `select_materials` | 「只用第 1、3 条」 | `{action:'confirm', approvedMaterialIds:[…]}` |
|
||||
| `drop_materials` | 「去掉第 2 条」 | 同上(反选后的子集) |
|
||||
|
||||
#### C. 大纲类(pausePoint = `outline_confirm`)
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `confirm_outline` | 「大纲 OK,开始写」 | `{action:'confirm'}` |
|
||||
| `reoutline` | 「重写大纲」 | `{action:'re_outline'}`(feedback 可空) |
|
||||
| `revise_outline` | 「第二章拆成两节」「调整顺序」 | `{action:'re_outline', outlineFeedback:自然语言}` |
|
||||
|
||||
#### D. 写作 / 草稿类(pausePoint = `draft_confirm`)
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `to_editor` | 「交给编辑审核」 | `{action:'to_editor'}` |
|
||||
| `finalize` | 「就这样定稿」 | `{action:'finalize'}` **(高代价:低置信必澄清)** |
|
||||
| `revise_draft` | 「第三段太啰嗦,精简」「补个 2024 案例」 | `{action:'user_revise', userRevisionNotes:意见}` |
|
||||
| `rewrite_section` | 「重写第二章」 | `user_revise` + 章节定位写进 notes |
|
||||
| `change_tone/style` | 「更口语一点 / 更正式」 | `user_revise` + notes |
|
||||
| `apply_review`(若已有审核结果) | 「按编辑意见改」「只接受第 1、2 条」 | `{action:'user_revise', selectedIssueIndices:[…]}` |
|
||||
|
||||
#### E. 编辑审核类(pausePoint = `review_confirm`)
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `accept_review` | 「按编辑意见改」 | `{action:'accept_review', selectedIssueIndices}` |
|
||||
| `partial_accept_review` | 「只接受第 1、2 条」 | `accept_review` + `selectedIssueIndices` 子集 |
|
||||
| `add_review_opinion` | 「再补一条:核查数据准确性」 | `accept_review` + `userRevisionNotes`(并入补充指令,现协议已支持) |
|
||||
| `force_finalize` | 「不改了,强制定稿」 | `{action:'force_finalize', overrideVerdict:true}` **(高代价:必澄清)** |
|
||||
|
||||
#### F. 素材不足求助类(pausePoint = `section_help`)
|
||||
| 意图 | 映射 |
|
||||
|------|------|
|
||||
| `section_supplement` | `{action:'section_help', sectionDecisions:[…'supplement']}` |
|
||||
| `section_loose` | `sectionDecisions:[…'loose']` |
|
||||
| `section_delete` | `sectionDecisions:[…'delete']` |
|
||||
|
||||
#### G. 问答类(**新**;任意 status;旁路,不改写作状态)
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `ask_about_content` | 「第二章讲了啥?」「为什么用这个论点?」 | 意图节点直接带回 `answer`,对话流渲染(见 5.4) |
|
||||
| `ask_meta` | 「现在到哪步了?」「用了哪些素材?」 | 读当前 state 直接回答,不走图 |
|
||||
|
||||
#### H. 控制类(**新 / 半新**)
|
||||
| 意图 | 映射 |
|
||||
|------|------|
|
||||
| `next_step`(通用「继续/下一步」) | 按**当前 pausePoint** 映射到该阶段的默认确认(material/outline→`confirm`,draft→`to_editor`…;等价点确认按钮) |
|
||||
| `restart_stage` | 重跑当前阶段(复用 `resumeWriting()` 空 command 续跑) |
|
||||
| `run_background` | 转后台自动跑:`suspendAIWritingToBackground()` |
|
||||
| `cancel` | `pauseWriting()`(`stream.stop()`) |
|
||||
| `unknown/clarify` | 无法判定 → 反问澄清 / 用户协助(**防误触发硬指标**) |
|
||||
|
||||
### 3.3 「素材不足自动重搜」判定与回退(用户强调点)
|
||||
|
||||
触发:用户在**大纲/草稿/审核**阶段提出修改意见,但意见需要的信息现有素材里没有。
|
||||
|
||||
判定来源(组合):
|
||||
1. **意图节点直接判**:把「素材摘要(keywords + 每条 title/source)」喂给意图 prompt,让它判断
|
||||
「这条意见能否用现有素材满足」;不能 → `needResearch=true` + `researchQuery`。
|
||||
2. **执行阶段兜底**:`writer_draft` 严格模式已有 `blocked_sections` → `section_help` 暂停点,
|
||||
对话层把它翻译成「素材不足,是否重搜?」的追问。
|
||||
|
||||
回退动作(**首期纯前端实现,不动后端协议**):`needResearch=true` 时,前端把用户的修改
|
||||
`payload` 缓存为 `pendingIntent`,先 `submitIntervention({action:'re_search', userQuery:researchQuery})`
|
||||
补素材;监听到新一轮 `material_confirm`(素材追加完成)后,**自动提交** `pendingIntent`。
|
||||
需处理「重搜期间用户又改主意」→ 允许覆盖 pending。
|
||||
|
||||
---
|
||||
|
||||
## 4. 意图解析引擎:方案与契约
|
||||
|
||||
**采用方案 A:后端 LLM 意图节点(独立 REST)**,叠加高频短句**规则快路径**优化。
|
||||
|
||||
理由:`needResearch` 判定需要**完整写作上下文**(素材/大纲/草稿),后端天然持有 checkpoint state;
|
||||
与 `setup_writing` 一脉相承,离线模型选择策略统一;输出 schema 稳定、前端只消费。
|
||||
|
||||
### 4.1 后端入口
|
||||
|
||||
`app/gateway/routers/ai_writing.py` 新增:
|
||||
|
||||
```
|
||||
POST /api/ai-writing/sessions/{session_id}/intent
|
||||
Body: { text: string, status: string, pausePoint?: string }
|
||||
Resp: IntentResult(见 4.3)
|
||||
```
|
||||
|
||||
实现:读该 session 的 checkpoint state(素材摘要 / 大纲纲要 / 草稿字数·章节 / 审核意见)→
|
||||
用 `ai_writing` 配置模型(复用 `intent_parser.py` 同套 `create_chat_model` + `parse_json` +
|
||||
模型容错 `_model_fallback`)解析 → 返回结构化契约。**不改图拓扑**。
|
||||
|
||||
新增 prompt:`agents/ai_writing/prompts/intent_router_prompts.py`
|
||||
- 输入:用户文本、`current_status`/`pause_point`、素材摘要、大纲纲要、草稿字数+章节标题、审核意见列表。
|
||||
- 输出:严格 JSON(4.3 契约)。硬要求:**只在证据充分时给高 confidence,否则给 `clarify`**;
|
||||
`finalize`/`force_finalize`/`re_search` 等高代价意图**必须**高置信才不澄清。
|
||||
|
||||
### 4.2 前端快路径(先跑规则,未命中再调后端)
|
||||
|
||||
`api/ai-writing-intent.ts` 里对**当前 pausePoint** 做少量确定性短语命中,直接产出 payload,省一次往返:
|
||||
- 「继续/下一步/确认/可以/ok/好的」→ 当前阶段默认 `confirm`(draft 阶段=`to_editor`)。
|
||||
- 「重新搜索/重搜」(material)→ `re_search`。「重写大纲」(outline)→ `re_outline`。
|
||||
- 「定稿/强制定稿」→ **不进快路径**(高代价,一律走后端 + 可能澄清)。
|
||||
- 命中即执行;未命中 → 调后端 `intent` 接口。
|
||||
|
||||
### 4.3 意图解析输出契约
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"intent": "revise_draft", // 见 3.2 分类
|
||||
"pausePoint": "draft_confirm", // 需要 resume 时;否则 null
|
||||
"action": "user_revise", // 映射到现有 action
|
||||
"payload": { // 直接可喂 submitIntervention 的字段(camelCase)
|
||||
"userRevisionNotes": "第三段精简,并补一个 2024 年的案例"
|
||||
},
|
||||
"needResearch": true, // 素材是否不足
|
||||
"researchQuery": "2024 行业案例", // needResearch 时的检索意图
|
||||
"answer": null, // 问答类意图的直接回答(旁路)
|
||||
"confidence": 0.86,
|
||||
"clarify": null // 低置信时的反问话术(非空则不执行、只追问)
|
||||
}
|
||||
```
|
||||
|
||||
前端消费顺序:
|
||||
1. `answer` 非空 → 对话流渲染回答(问答旁路,不动写作状态)。
|
||||
2. `clarify` 非空 **或** `confidence < 阈值(建议 0.6)` → 渲染反问气泡,等用户澄清(**防误触发**)。
|
||||
3. `needResearch=true` → 缓存 `pendingIntent=payload`,先重搜,收到新素材后自动提交。
|
||||
4. 否则 → `idle` 走 `startWriting(...)`;暂停态走 `submitIntervention({action, ...payload})`。
|
||||
|
||||
---
|
||||
|
||||
## 5. 前端改造方案
|
||||
|
||||
### 5.1 新页面与路由(复制式)
|
||||
|
||||
- 新页面:`open-canvas/pages/AIWritingChatPage.tsx`
|
||||
(骨架照抄 `AIWritingPage.tsx` 的 Provider 包裹与左右分栏;左栏换成 `WritingChatPanel`,右栏仍
|
||||
`AIWritingDraftPanel`;idle 不再挂 `AIWritingForm`,改由底部输入框启动)。
|
||||
- 路由注册(**新增,不动旧行**):
|
||||
- `open-canvas/routes/OpenCanvasRoutes.tsx` 加 `path="ai-writing-chat/*"`。
|
||||
- 侧边栏 `core/page-layout/sidebar-menu.ts`:在 `qa-research` 旁新增
|
||||
`{ id:"qa-research-chat", label:"AI写作(对话版)", icon:FileText, path:"/page/canvas/ai-writing-chat" }`。
|
||||
(或先不加、内部灰度直链验证。)
|
||||
|
||||
### 5.2 新面板 `WritingChatPanel.tsx`(左栏主体)
|
||||
|
||||
职责 = 消息流容器 + 底部输入框,替代 `AIWritingPanel` 里的「时间线 + InterventionCard + 状态栏」。
|
||||
复用 `useAIWriting()` 读 state / 调 `startWriting` / `submitIntervention` / `pauseWriting` /
|
||||
`suspendAIWritingToBackground`。
|
||||
|
||||
消息流渲染(把 `ProgressEvent` / 阶段产物适配成消息卡,复用现有展示子组件):
|
||||
- 运行中:`research_progress`/`outline_chunk`/`draft_chunk`/`review_chunk` → 进度 / 流式卡
|
||||
(复用 `SkillStepsCard`/`OutlineStreamingView`/`DraftGeneratingView`/`ReviewStreamingView` 的展示部分)。
|
||||
- 到达暂停点:渲染 **产物卡 + 保留的确认按钮**(见 5.3),不再有输入框。
|
||||
- 用户消息、AI 澄清追问、问答回答:普通气泡。
|
||||
|
||||
底部输入框:直接复用 `@/components/ai-elements/prompt-input`(`PromptInput`+`PromptInputTextarea`+
|
||||
`PromptInputSubmit`),Enter 发送、Shift+Enter 换行;发送时读当前 `state.status`/`currentPause?.pausePoint`
|
||||
交给意图路由(见 5.5)。运行中(非暂停点)可禁用发送或转「排队/提示当前在生成」。
|
||||
|
||||
### 5.3 新消息卡 `chat-cards/*`(**保留按钮、去掉输入框**)
|
||||
|
||||
把 `InterventionCard.tsx` 的五张卡各复制一份到 `open-canvas/components/ai-writing-chat/chat-cards/`,
|
||||
**删掉其中的 textarea / MaterialsToolbar 输入部分,保留产物展示 + 确认/动作按钮**:
|
||||
|
||||
| 新卡 | 展示(复用) | 保留的按钮 | 删除的输入 |
|
||||
|------|-------------|-----------|-----------|
|
||||
| `MaterialConfirmChatCard` | `MaterialsCard`(勾选保留)+ `SkillStepsCard` | 「确认素材,规划大纲」「重新搜索」 | `MaterialsToolbar` 的 userQuery 输入框 |
|
||||
| `OutlineConfirmChatCard` | `OutlineCard`(可点标题微调保留) | 「确认大纲,开始写作」 | feedback textarea + 发送 |
|
||||
| `DraftConfirmChatCard` | `ReviewCard`(若有审核,勾选保留) | 「按编辑审核意见修改」「让编辑继续审核」「确认定稿」 | 「修改意见」textarea |
|
||||
| `ReviewConfirmChatCard` | `ReviewCard`(勾选保留) | 「按编辑意见修改」「强制定稿」 | 「补充修改指令」textarea |
|
||||
| `SectionHelpChatCard` | 章节 + 三选一按钮组 | 三选一 + 「提交并继续」 | (本就无自由输入,原样保留) |
|
||||
|
||||
> 勾选态(素材/审核意见)**保留**——它是「点按钮」路径的一部分,不算自由输入框。用户想用自然语言
|
||||
> 「只用第 1、3 条」也能走底部输入框(意图层产出 `approvedMaterialIds`/`selectedIssueIndices`)。
|
||||
> 按钮点击 **直接调 `submitIntervention`**,与旧卡完全一致,零改动风险。
|
||||
|
||||
### 5.4 问答旁路(新能力)
|
||||
|
||||
「对写作内容提问」不改写作 state。首期**轻量实现**:意图节点检出 `ask_*` 时读 state 直接带回 `answer`,
|
||||
前端在消息流渲染为普通 AI 气泡即可(一次调用出答案)。完整版(后续)可另起只读 lead_agent 线程注入
|
||||
草稿/大纲作背景,类似 `WritingSetupChat` 的 `useThreadStream`。
|
||||
|
||||
### 5.5 交互流程(对话版)串起来
|
||||
|
||||
1. **空闲**:底部输入「写一篇关于 X 的深度分析,2000 字」→ 意图 `start_writing` → 组 `AIWritingRequest`
|
||||
→ `startWriting()`。(缺关键字段时先 `clarify` 追问字数/读者/类型。)
|
||||
2. **运行中**:进度/流式卡渲染。
|
||||
3. **到暂停点**:渲染产物卡 + 按钮 + 一句提示「你可以点上面的按钮,或直接说:确认继续 / 补充素材 / 改大纲…」。
|
||||
- **点按钮** → 直接 `submitIntervention`(旧逻辑)。
|
||||
- **发文字** → `resolveIntent(text, status, pausePoint)`(先快路径、后后端)→ 按 4.3 消费。
|
||||
4. **问答**:任意时刻提问 → 旁路 `answer`,不打断写作。
|
||||
5. **素材不足**:`needResearch` 或 `section_help` → 追问/执行「重搜 → 自动续跑 pending 意图」。
|
||||
6. **拿不准**:`clarify`/低置信 → 反问气泡,不执行。
|
||||
|
||||
### 5.6 pending 意图 & 澄清态(新增本地状态)
|
||||
|
||||
在 `WritingChatPanel`(或新 `WritingChatContext`)维护:
|
||||
- `pendingIntent: UserInterventionPayload | null` —— 素材不足重搜完成后自动提交。
|
||||
- `awaitingClarify: { originalText: string } | null` —— 澄清态,用户下一句与上一句拼接再解析。
|
||||
- pending 生命周期:设置 → 提交 `re_search` → 监听 reducer 里新一轮 `awaiting_material_confirm`
|
||||
(`state.status` 从 `researching` 回到 `awaiting_material_confirm`)→ 自动 `submitIntervention(pending)` → 清空。
|
||||
|
||||
---
|
||||
|
||||
## 6. 后端改造方案
|
||||
|
||||
### 6.1 意图解析入口(新增,唯一后端改动主体)
|
||||
|
||||
- `app/gateway/routers/ai_writing.py`:新增 `POST /sessions/{id}/intent`(见 4.1)。
|
||||
读 checkpoint state 用 `app.state.checkpointer` + `make_ai_writing_graph().aget_state(...)`
|
||||
(参照 `ai_writing_job_executor.py` 的读法)取素材/大纲/草稿/审核摘要。
|
||||
- `agents/ai_writing/prompts/intent_router_prompts.py`:新增意图 prompt(见 4.1)。
|
||||
- 复用 `nodes/intent_parser.py` 的模型创建 / `parse_json` / `_model_fallback` 容错。
|
||||
|
||||
### 6.2 不需要改的部分
|
||||
|
||||
- 四个阶段大脑节点、五个暂停点、checkpoint、StreamBridge、持久化、sessions/transcript REST——**全不动**。
|
||||
- 「素材不足自动续跑」「问答旁路」首期都在**前端 / 意图节点**实现,**不扩 resume 协议**。
|
||||
|
||||
### 6.3 可选增强(阶段 3,按需)
|
||||
|
||||
- `add_review_opinion` 完整版:`review_confirm` resume 增字段 `extra_review_notes`(首期已用现有
|
||||
`userRevisionNotes` 降级承载,够用)。
|
||||
- `resume_intent` 后端化(把「重搜完自动续跑」搬到后端,减少前端状态机复杂度)。
|
||||
- undo / 回退到上一暂停点(依赖 checkpoint 回滚)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 数据流时序(改稿 + 素材不足自动重搜)
|
||||
|
||||
```
|
||||
用户(draft_confirm 暂停): "第三段补个2024年的行业案例"
|
||||
│ 底部输入框 → resolveIntent(text, status='awaiting_draft_confirm', pausePoint='draft_confirm')
|
||||
▼ POST /api/ai-writing/sessions/{id}/intent { text, status, pausePoint }
|
||||
后端: 读 state(素材摘要) + LLM 解析
|
||||
│ 返回 { intent:revise_draft, action:user_revise,
|
||||
│ payload:{userRevisionNotes:"第三段…补2024案例"},
|
||||
│ needResearch:true, researchQuery:"2024 行业案例", confidence:0.9 }
|
||||
▼
|
||||
前端: needResearch=true → pendingIntent = payload
|
||||
│ submitIntervention({action:'re_search', userQuery:"2024 行业案例"})
|
||||
▼ LangGraph resume → researcher 追加素材 → status 回到 awaiting_material_confirm
|
||||
前端: 监听到新一轮素材确认 → 自动提交 pendingIntent
|
||||
│ submitIntervention({action:'user_revise', userRevisionNotes:"第三段…补2024案例"})
|
||||
▼ writer_draft 用新素材改稿 → draft_chunk… → draft_ready → draft_confirm
|
||||
前端: 消息流展示新草稿卡 + "已按你的意见改写并补充了 2024 案例"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 关键实现细节与坑
|
||||
|
||||
1. **阶段作用域**:`resolveIntent` 必须带 `state.currentPause?.pausePoint` + `state.status`——
|
||||
同一句「重新来」在 material 是重搜、在 outline 是重写大纲。`AIWritingContext` 已有这两个字段,直接读。
|
||||
2. **确认按钮零改动**:新卡的按钮 `onClick` 原样调 `submitIntervention(payload)`,与旧卡逐字一致,
|
||||
风险最低;**只删输入框**。
|
||||
3. **防误触发**:低置信(<0.6)或 `clarify` 非空一律追问;`finalize`/`force_finalize`/`re_search`
|
||||
即使命中也要求高置信,否则澄清。绝不盲目定稿/覆盖重搜。
|
||||
4. **pending 意图队列**:素材不足是「先插重搜、再回原意图」,用 5.6 的小状态机;重搜完成前允许覆盖 pending。
|
||||
5. **问答不污染 transcript**:问答/澄清消息在前端标记 `kind:'qa'|'clarify'`,与写作进度事件区分(
|
||||
`AIWritingContext` 的 transcript 只存 progressEvents/completedInterventions,问答气泡是纯前端消息,
|
||||
默认不入 transcript,避免历史回看错乱)。
|
||||
6. **流式产物→消息卡**:复用 `OutlineStreamingView`/`DraftGeneratingView`/`ReviewStreamingView`/
|
||||
`SkillStepsCard` 的**展示部分**,套进消息容器,不重写渲染。
|
||||
7. **右侧草稿预览**:`AIWritingDraftPanel` + `DraftSync` 原样复用(`DraftSync` 依据 status/markdown
|
||||
同步右侧画布)。
|
||||
8. **离线内网**:意图模型走 `config.yaml → ai_writing` 配置模型;检索仍走技能/内网 ES,不联网。
|
||||
9. **模型选择透传**:`submitIntervention` 的 resume 已把 `state.request?.modelName` 一并回传(见
|
||||
`AIWritingContext`),新页面沿用即可。
|
||||
10. **旧页面隔离验证**:改完后回归旧 `/page/canvas/ai-writing` 与 `/page/workspace/ai-writing`、
|
||||
笔记本嵌入页,确认零变化(新代码不 import 旧的 `AIWritingForm`/`InterventionCard`/`WritingFormContext`)。
|
||||
|
||||
---
|
||||
|
||||
## 9. 分阶段实施路线图
|
||||
|
||||
**阶段 0 — 骨架(不含意图)**
|
||||
- 复制 `AIWritingChatPage` + 注册新路由 + 侧边栏入口;复用 `AIWritingContext`/`useStream`/`DraftPanel`。
|
||||
- 复制五张 `chat-cards`(删输入框、留按钮);底部输入框先只做 idle 直发 `start_writing`
|
||||
(文本原样当 `userIntent`,其余字段取默认)+ 暂停点靠按钮推进。端到端跑通。
|
||||
|
||||
**阶段 1 — 意图解析(核心)**
|
||||
- 后端 `POST /sessions/{id}/intent` + `intent_router_prompts.py`,返回 4.3 契约。
|
||||
- 前端 `api/ai-writing-intent.ts`(快路径 + 后端)接入 `WritingChatPanel`,覆盖 A~F 类意图。
|
||||
- 低置信 `clarify` 澄清态(5.6)。
|
||||
|
||||
**阶段 2 — 问答旁路 + 素材不足自动重搜**
|
||||
- G 类问答(意图节点直接带 `answer`)。
|
||||
- `needResearch` + pending 意图机制(前端实现重搜后自动续跑,5.6)。
|
||||
|
||||
**阶段 3 — 增强(按需)**
|
||||
- `add_review_opinion` 扩协议、`resume_intent` 后端化、undo/回退、完整问答只读线程。
|
||||
|
||||
**阶段 4 — 打磨**
|
||||
- 消息卡视觉、历史回看(transcript)、后台挂起入口、灰度到侧边栏。
|
||||
|
||||
---
|
||||
|
||||
## 10. 关键文件清单(落地对照)
|
||||
|
||||
### 新增(前端)
|
||||
- `open-canvas/pages/AIWritingChatPage.tsx` — 新页面(复制 `AIWritingPage` 骨架改造)
|
||||
- `open-canvas/components/ai-writing-chat/WritingChatPanel.tsx` — 消息流 + 底部输入框
|
||||
- `open-canvas/components/ai-writing-chat/chat-cards/{MaterialConfirmChatCard,OutlineConfirmChatCard,DraftConfirmChatCard,ReviewConfirmChatCard,SectionHelpChatCard}.tsx` — 保留按钮、去掉输入框
|
||||
- `open-canvas/components/ai-writing-chat/progressToMessage.ts` — `ProgressEvent` → 消息卡适配
|
||||
- `open-canvas/api/ai-writing-intent.ts` — 意图解析客户端(快路径 + `POST …/intent`)
|
||||
- (可选)`open-canvas/contexts/WritingChatContext.tsx` — pending 意图 / 澄清态
|
||||
|
||||
### 修改(前端,仅追加,不动旧逻辑)
|
||||
- `open-canvas/routes/OpenCanvasRoutes.tsx` — 加一条 `ai-writing-chat/*` 路由
|
||||
- `core/page-layout/sidebar-menu.ts` — 加一个侧边栏入口(可选)
|
||||
- `open-canvas/types/ai-writing.ts` — **仅追加** `IntentResult` 等新类型,不改旧字段
|
||||
|
||||
### 新增(后端)
|
||||
- `app/gateway/routers/ai_writing.py` — 加 `POST /sessions/{id}/intent`
|
||||
- `agents/ai_writing/prompts/intent_router_prompts.py` — 意图 prompt
|
||||
- `tests/test_ai_writing_intent.py` — 意图接口单测(TDD 强制)
|
||||
|
||||
### 复用(不改)
|
||||
- `open-canvas/contexts/AIWritingContext.tsx`、`hooks/useAIWritingStream.ts`
|
||||
- `open-canvas/components/ai-writing/{AIWritingDraftPanel,DraftSync,MaterialsCard,OutlineCard,ReviewCard,SkillStepsCard,OutlineStreamingView,DraftGeneratingView,ReviewStreamingView}.tsx`
|
||||
- `agents/ai_writing/graph.py`、四个阶段节点、五个暂停点、`nodes/intent_parser.py`
|
||||
|
||||
### 绝不动(保证「初始的不用动」)
|
||||
- `open-canvas/pages/AIWritingPage.tsx` 及其引用的
|
||||
`components/ai-writing/{AIWritingForm,InterventionCard}.tsx`、`contexts/WritingFormContext.tsx`
|
||||
- 旧路由 `/page/canvas/ai-writing`、`/page/workspace/ai-writing`、笔记本嵌入页
|
||||
|
||||
---
|
||||
|
||||
## 11. 待确认(默认取值已给出,可直接推进)
|
||||
|
||||
1. 意图引擎:**后端 LLM 节点(方案 A)+ 前端短句快路径** —— 默认采用。
|
||||
2. `AIWritingContext` / `useAIWritingStream`:**复用**(不物理复制)——默认采用;需绝对隔离可改为复制。
|
||||
3. 新页面入口:**侧边栏新增「AI写作(对话版)」** —— 默认加;若要先灰度可只留直链。
|
||||
4. 「素材不足自动重搜」:**首期前端 pending 续跑**(不动后端 resume 协议)——默认采用。
|
||||
5. 问答旁路:**首期意图节点直接带 `answer`** —— 默认采用。
|
||||
|
||||
> 以上默认按「A + 复用引擎 + 侧边栏入口 + 前端 pending + 意图节点带答案」推进,如需调整请指出。
|
||||
@@ -0,0 +1,454 @@
|
||||
# AI 写作「对话驱动 + 意图解析」改造方案
|
||||
|
||||
> 目标:在**不动现有 AI 写作页面**的前提下,新建一个「对话驱动」的写作工作台。
|
||||
> 去掉素材收集 / 大纲规划 / 作家写作 / 编辑审核各阶段**分散的输入框/表单**,
|
||||
> 用**底部一个统一的智能输入框**接管全流程交互;该输入框具备**强意图解析**能力,
|
||||
> 能准确识别用户意图(重新搜索、加素材、加关键词、重写大纲、按要求改大纲、改写作、
|
||||
> 改编辑、提编辑意见、对写作内容提问……),并在**素材不足**时自动回退去重新检索素材。
|
||||
|
||||
本文只做**方案与实现指引**,不含代码改动。落地时按第 9 节的路线图分阶段推进。
|
||||
|
||||
---
|
||||
|
||||
## 1. 现状梳理(改造的地基)
|
||||
|
||||
现有 AI 写作是一套**独立的 LangGraph 子系统**(不是 lead_agent),前后端都已成型。
|
||||
|
||||
### 1.1 后端:`ai_writing` graph
|
||||
|
||||
- 图工厂:`offline-backend-20260512/backend/packages/harness/deerflow/agents/ai_writing/graph.py`
|
||||
- 状态:`.../agents/ai_writing/state.py`(`AIWritingState` + `UserInterventionPayload`)
|
||||
- 注册:`offline-backend-20260512/backend/langgraph.json` → `assistant_id = "ai_writing"`
|
||||
- 执行:与 lead agent **共用** RunManager + StreamBridge + checkpointer(`app/gateway/services.py` 里 `assistant_id=="ai_writing"` 分发到 `make_ai_writing_graph`)
|
||||
|
||||
节点拓扑(实际):
|
||||
|
||||
```
|
||||
sample_analyzer → intent_parser → researcher
|
||||
→ [cond] pause_material | writer_draft
|
||||
→ writer_outline → pause_outline
|
||||
→ writer_draft → [cond] pause_section_help | pause_draft | END
|
||||
→ editor → [cond] pause_draft | pause_review
|
||||
→ pause_review → END | writer_draft
|
||||
```
|
||||
|
||||
四个「阶段大脑」节点:
|
||||
|
||||
| 阶段 | 节点 | 文件 |
|
||||
|------|------|------|
|
||||
| 素材收集 | `researcher` | `nodes/researcher.py` |
|
||||
| 大纲规划 | `writer_outline` | `nodes/writer_outline.py` |
|
||||
| 作家写作 | `writer_draft` | `nodes/writer_draft.py` |
|
||||
| 编辑审核 | `editor` | `nodes/editor.py` |
|
||||
|
||||
五个**暂停点**(`interrupt()`,靠 `Command(resume=payload)` 续跑):
|
||||
|
||||
| pause_point | 语义 | 可用 action(现有) |
|
||||
|-------------|------|---------------------|
|
||||
| `material_confirm` | 素材确认 | `confirm` / `re_search` / `supplement_search` / `enable_skill_search` |
|
||||
| `outline_confirm` | 大纲确认 | `confirm` / `re_outline` |
|
||||
| `draft_confirm` | 草稿确认 | `to_editor` / `finalize` / `user_revise` / `custom_revise` |
|
||||
| `review_confirm` | 编辑打回确认 | `accept_review` / `force_finalize` |
|
||||
| `section_help` | 素材不足求助 | `supplement` / `loose` / `delete` |
|
||||
|
||||
> resume 载荷字段(`UserInterventionPayload`):`action`、`approved_material_ids`、
|
||||
> `extra_keywords`、`user_query`(自然语言补充检索)、`edited_outline`、`outline_feedback`、
|
||||
> `user_revision_notes`、`override_verdict`、`selected_issue_indices`、`section_decisions`。
|
||||
> **关键点**:现有协议已经支持「自然语言 + 结构化 action」,这是对话改造的核心可复用资产。
|
||||
|
||||
REST(业务元数据,非图执行):`app/gateway/routers/ai_writing.py`,前缀 `/api/ai-writing`
|
||||
(sessions CRUD、transcript 保存、article-types、后台挂起 `/background` + `/progress` 等)。
|
||||
|
||||
持久化:`ai_writing_sessions` 表(`transcript` 为 `PortableLongText`)
|
||||
+ `ai_writing_article_types`(`deerflow/persistence/...`)。
|
||||
|
||||
配置:`config.yaml → ai_writing`(`keyword_model`、`rank_model`、`max_materials`、
|
||||
`use_builtin_agents.{researcher,outliner,writer,editor}` 等)。
|
||||
|
||||
### 1.2 前端:`open-canvas` 子系统
|
||||
|
||||
- 主页面:`frontend-web/src/open-canvas/pages/AIWritingPage.tsx`
|
||||
- 路由:`/page/canvas/ai-writing`、`/page/workspace/ai-writing`
|
||||
- 状态机:`contexts/AIWritingContext.tsx`(`useReducer` + LangGraph `useStream`)
|
||||
- 事件翻译/reducer:`hooks/useAIWritingStream.ts`
|
||||
- 类型:`types/ai-writing.ts`(`WritingStatus`、`ProgressEvent`、`UserInterventionPayload`、`AIWritingRequest`…)
|
||||
- 流式:LangGraph `useStream`,`assistantId: 'ai_writing'`,`streamMode: ['values','updates','custom','messages-tuple']`
|
||||
- **要去掉的输入 UI**(改造重点):
|
||||
- 启动表单 `components/ai-writing/AIWritingForm.tsx` + `WritingFormContext`
|
||||
- 阶段暂停输入 `components/ai-writing/InterventionCard.tsx`(素材/大纲/草稿/审核四套内嵌表单)
|
||||
- **已存在的对话原型**:`components/ai-writing/WritingSetupChat.tsx`
|
||||
(用 `useThreadStream` 起一条 lead_agent 线程 + `setup_writing` 工具审批卡回填表单)——
|
||||
这是「对话 → 结构化配置」的现成范式,可借鉴但**不直接复用**(它只管启动前配置)。
|
||||
|
||||
### 1.3 结论
|
||||
|
||||
- **状态机、流式、暂停/续跑协议、持久化都可复用**,无需重写引擎。
|
||||
- 改造本质 = **把「分散表单」换成「一个对话输入框 + 意图路由层」**,
|
||||
再把意图映射回**现有的 `action + payload`**(大部分场景),
|
||||
少量新意图(如「对内容提问」「素材不足自动重搜」)需要**新增协议/节点**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 目标与范围
|
||||
|
||||
### 2.1 必须满足
|
||||
|
||||
1. 新页面/新路由,**旧页面零改动**(用户要求「初始的不用动」)。
|
||||
2. 底部**单一对话输入框**控制所有阶段交互,移除各阶段独立输入框。
|
||||
3. **强意图解析**:准确识别用户自然语言意图并路由到正确动作,覆盖全流程 + 更多。
|
||||
4. 用户给修改意见后,**若现有素材不足以满足要求 → 自动/建议重新检索素材**再继续。
|
||||
5. 保留右侧草稿实时预览(可编辑)与时间线/进度展示。
|
||||
|
||||
### 2.2 明确不做(本期)
|
||||
|
||||
- 不改旧 `AIWritingPage` 及其表单/干预卡组件。
|
||||
- 不替换底层 `ai_writing` graph 的四个阶段大脑逻辑(只加意图层与少量新协议)。
|
||||
- 不引入新的状态管理库(继续 `useReducer` + `useStream`)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 核心设计
|
||||
|
||||
### 3.1 总体思路:三层结构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ 对话 UI 层(新) │
|
||||
│ - 左:消息流(用户消息 + AI 阶段产物卡片 + 进度) │
|
||||
│ - 底:统一智能输入框(唯一交互入口) │
|
||||
│ - 右:草稿实时预览(复用 AIWritingDraftPanel) │
|
||||
└───────────────┬─────────────────────────────────────────┘
|
||||
│ 用户自然语言
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ 意图解析层(新,核心) │
|
||||
│ - 输入:用户文本 + 当前 WritingStatus + 上下文快照 │
|
||||
│ - 输出:{ intent, action, payload, needResearch, ... } │
|
||||
└───────────────┬─────────────────────────────────────────┘
|
||||
│ 结构化 action + payload
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ 执行层(复用现有) │
|
||||
│ - 空闲态:startWriting(AIWritingRequest) │
|
||||
│ - 暂停态:submitIntervention(UserInterventionPayload) │
|
||||
│ - 运行中:stream.stop() → 续跑 / 新命令 │
|
||||
│ - 提问态:旁路问答(不改写作状态) │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**设计原则**:意图解析层是「翻译官」——把自由文本翻译成**现有执行层已经懂的指令**。
|
||||
能复用 `action + payload` 的绝不新造协议;只有现有协议表达不了的才扩展。
|
||||
|
||||
### 3.2 意图分类体系(覆盖用户全流程 + 更多)
|
||||
|
||||
按「意图类别 → 触发时机(当前 status)→ 映射到的执行」组织。这是**意图解析引擎的目标 schema**。
|
||||
|
||||
#### A. 启动类(status = idle)
|
||||
|
||||
| 意图 | 说明 | 映射 |
|
||||
|------|------|------|
|
||||
| `start_writing` | 用户描述要写什么 | 解析成 `AIWritingRequest` → `startWriting()` |
|
||||
| `start_with_outline` | 用户自带大纲 | `AIWritingRequest.userOutline` |
|
||||
| `start_imitate` | 样文仿写 | `writingModeType=imitate` + 样文 |
|
||||
|
||||
#### B. 素材类(status ≈ awaiting_material_confirm / 运行中)
|
||||
|
||||
| 意图 | 用户说法示例 | 映射 |
|
||||
|------|-------------|------|
|
||||
| `confirm_materials` | 「素材可以,继续」 | `material_confirm` + `confirm`(可带勾选 ids) |
|
||||
| `research_again` | 「重新搜索素材」 | `material_confirm` + `re_search` |
|
||||
| `add_material` / `add_keyword` | 「补充关于 X 的素材」「加个关键词 Y」 | `material_confirm` + `supplement_search`,`user_query`=X/Y |
|
||||
| `use_skill_search` | 「用 XX 技能查」 | `material_confirm` + `enable_skill_search`,`user_query`=技能/来源 |
|
||||
| `select_materials` | 「只用第 1、3 条」 | `confirm` + `approved_material_ids` 子集 |
|
||||
| `drop_materials` | 「去掉第 2 条」 | 同上,反选后 `approved_material_ids` |
|
||||
|
||||
#### C. 大纲类(status ≈ awaiting_outline_confirm)
|
||||
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `confirm_outline` | 「大纲 OK」 | `outline_confirm` + `confirm` |
|
||||
| `reoutline` | 「重写大纲」 | `outline_confirm` + `re_outline`(`outline_feedback` 可空) |
|
||||
| `revise_outline` | 「第二章拆成两节」「调整顺序」 | `re_outline` + `outline_feedback`=自然语言 |
|
||||
| `edit_outline_manually` | 用户直接给出新大纲文本 | 解析成 `edited_outline` |
|
||||
|
||||
#### D. 写作/草稿类(status ≈ awaiting_draft_confirm / writing_draft)
|
||||
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `to_editor` | 「交给编辑审核」 | `draft_confirm` + `to_editor` |
|
||||
| `finalize` | 「就这样定稿」 | `draft_confirm` + `finalize` |
|
||||
| `revise_draft` | 「第三段太啰嗦,精简」「补个案例」 | `draft_confirm` + `user_revise`,`user_revision_notes`=意见 |
|
||||
| `rewrite_section` | 「重写第二章」 | `user_revise` + 定位信息(章节)写进 notes |
|
||||
| `change_tone/style` | 「更口语一点」 | `user_revise` + notes |
|
||||
|
||||
#### E. 编辑审核类(status ≈ awaiting_review_confirm)
|
||||
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `accept_review` | 「按编辑意见改」 | `review_confirm` + `accept_review`(可带 `selected_issue_indices`) |
|
||||
| `partial_accept_review` | 「只接受第 1、2 条意见」 | `accept_review` + `selected_issue_indices` |
|
||||
| `force_finalize` | 「不改了,强制定稿」 | `review_confirm` + `force_finalize` |
|
||||
| `add_review_opinion` | 「你再补一条:检查数据准确性」 | 追加自定义审核意见(见 5.3 扩展) |
|
||||
|
||||
#### F. 素材不足求助类(status = awaiting_section_help)
|
||||
|
||||
| 意图 | 映射 |
|
||||
|------|------|
|
||||
| `section_supplement` | `section_help` + `supplement`(去重搜) |
|
||||
| `section_loose` | `section_help` + `loose`(放宽续写) |
|
||||
| `section_delete` | `section_help` + `delete` |
|
||||
|
||||
#### G. 问答类(**新**,任意 status,旁路,不改写作状态)
|
||||
|
||||
| 意图 | 示例 | 映射 |
|
||||
|------|------|------|
|
||||
| `ask_about_content` | 「第二章讲了啥?」「为什么用这个论点?」 | 旁路问答(见 5.4) |
|
||||
| `ask_meta` | 「现在进行到哪一步?」「用了哪些素材?」 | 读当前 state 直接回答,不走图 |
|
||||
|
||||
#### H. 控制类(**新/半新**)
|
||||
|
||||
| 意图 | 映射 |
|
||||
|------|------|
|
||||
| `undo/back` | 回退到上一暂停点(依赖 checkpoint 回滚,见 8.4) |
|
||||
| `restart_stage` | 重跑当前阶段 |
|
||||
| `run_background` | 挂起后台自动跑 → `POST /sessions/{id}/background` |
|
||||
| `cancel` | `stream.stop()` |
|
||||
| `unknown/clarify` | 无法判定 → 反问澄清(对话追问,不误触发) |
|
||||
|
||||
> **覆盖「甚至更多」**:G(问答)、H(控制)、以及 D/E 里「素材不足自动回退重搜」都是超出原表单能力的新增。
|
||||
|
||||
### 3.3 「素材不足自动重搜」的判定与回退(用户强调的重点)
|
||||
|
||||
触发场景:用户在**大纲/草稿/审核**阶段提出修改意见,但意见需要的**信息现有素材里没有**。
|
||||
|
||||
判定放在**意图解析层**输出一个 `needResearch: boolean` + `researchQuery`,判定来源二选一(推荐组合):
|
||||
|
||||
1. **意图解析 LLM 直接判断**:把「当前素材摘要(keywords + 每条 title/来源)」喂给意图解析
|
||||
prompt,让它判断「用户这条意见能否用现有素材满足」。不能 → `needResearch=true` 并给出检索词。
|
||||
2. **执行阶段兜底**:`writer_draft` 严格模式本就有 `blocked_sections` → `pause_section_help`,
|
||||
这是**已有的**素材不足闸门;对话层把它翻译成「素材不足,是否重新检索?」的对话追问。
|
||||
|
||||
回退动作:`needResearch=true` 时,先走 `material_confirm + supplement_search`(或新的
|
||||
「带目标的重搜」协议,见 8.3)补素材,**补完自动继续**用户原本的修改意图(需要在对话层
|
||||
记住「pending 修改意图」,重搜结束后再提交)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 意图解析引擎:方案对比与推荐
|
||||
|
||||
| 方案 | 做法 | 优点 | 缺点 |
|
||||
|------|------|------|------|
|
||||
| **A. 后端 LLM 意图节点**(推荐) | 新增 `/api/ai-writing/intent/parse`(或图内新节点),后端用 LLM 把 `{text, status, contextSnapshot}` → 结构化意图 JSON | 能吃到完整 state(素材/大纲/草稿);可判 `needResearch`;prompt/模型集中可控;离线内网可用配置模型 | 多一次网络往返(可接受,交互本就等待) |
|
||||
| B. 前端调模型接口分类 | 前端直接调现有 `/api/models` 聊天做分类 | 少一层后端改动 | 前端难拿全后端 state 快照;prompt 分散;鉴权/模型选择复杂 |
|
||||
| C. 规则 + LLM 混合 | 常见短句走关键词规则快路径,兜底 LLM | 快、省 token | 规则易漏、维护成本高;中文表达多样命中率低 |
|
||||
|
||||
**推荐 A(后端 LLM 意图节点)**,并在其上**叠加 C 的快路径**做优化(如「确认/继续/定稿」等
|
||||
高频短句先走轻量规则,未命中再调 LLM)。理由:
|
||||
|
||||
- 意图判定需要**当前写作上下文**(尤其 `needResearch` 判定),后端天然持有 state/checkpoint。
|
||||
- 与现有「配置助手 `setup_writing`」一脉相承,模型选择/离线部署策略统一。
|
||||
- 输出 schema 稳定,前端只消费结构化结果,UI 简单。
|
||||
|
||||
### 4.1 意图解析输出契约(建议)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"intent": "revise_draft", // 见第 3.2 分类
|
||||
"pausePoint": "draft_confirm", // 若需 resume;否则 null
|
||||
"action": "user_revise", // 映射到现有 action;新意图可为新值
|
||||
"payload": { // 直接可喂 submitIntervention 的字段
|
||||
"userRevisionNotes": "第三段精简,并补一个 2024 年的案例"
|
||||
},
|
||||
"needResearch": true, // 素材是否不足
|
||||
"researchQuery": "2024 行业案例", // needResearch 时的检索意图
|
||||
"answer": null, // 问答类意图的直接回答(旁路)
|
||||
"confidence": 0.86,
|
||||
"clarify": null // 低置信时的反问话术
|
||||
}
|
||||
```
|
||||
|
||||
前端拿到后:
|
||||
- `answer` 非空 → 直接在对话流渲染回答(问答旁路,不动写作状态)。
|
||||
- `clarify` 非空或 `confidence` 低 → 渲染反问,等用户澄清(**防误触发**)。
|
||||
- `needResearch=true` → 先重搜,缓存 `payload` 为 pending,重搜完再提交。
|
||||
- 否则 → `submitIntervention({action, ...payload})` 或 `startWriting(...)`。
|
||||
|
||||
---
|
||||
|
||||
## 5. 前端改造方案
|
||||
|
||||
### 5.1 新页面与路由
|
||||
|
||||
- 新目录:`frontend-web/src/open-canvas/pages/AIWritingChatPage.tsx`(或 `conversational/` 子目录)。
|
||||
- 新路由:`/page/canvas/ai-writing-chat`(在 `OpenCanvasRoutes.tsx` 注册;旧路由保留)。
|
||||
- 侧边栏:`sidebar-menu.ts` 加一个入口(如「AI 写作(对话版)」),或先不加、内部灰度。
|
||||
|
||||
### 5.2 复用 vs 新建
|
||||
|
||||
| 复用(尽量不改) | 新建 |
|
||||
|------------------|------|
|
||||
| `AIWritingContext` / `useAIWritingStream`(状态机 + 流式) | 统一对话输入框组件 `WritingChatComposer` |
|
||||
| `AIWritingDraftPanel`(右侧草稿预览) | 消息流容器 `WritingChatThread`(渲染阶段产物为消息卡片) |
|
||||
| `types/ai-writing.ts`(按需扩展) | 意图解析客户端 `api/ai-writing-intent.ts` |
|
||||
| `ProgressEvent` 事件模型 | 阶段产物 → 消息卡片的适配器 `progressToMessage.ts` |
|
||||
| 会话持久化 REST | 「pending 意图」暂存逻辑(重搜后续跑) |
|
||||
|
||||
**不复用**:`AIWritingForm` / `WritingFormContext` / `InterventionCard`(这三个就是要去掉的表单)。
|
||||
|
||||
### 5.3 交互流程(对话版)
|
||||
|
||||
1. 空闲:用户在底部输入「写一篇关于 X 的深度分析,2000 字」→ 意图解析 `start_writing`
|
||||
→ 组装 `AIWritingRequest` → `startWriting()`。
|
||||
2. 运行中:`ProgressEvent`(`research_progress`/`outline_chunk`/`draft_chunk`…)
|
||||
→ 适配成消息流里的**进度卡片/流式卡片**(复用现有流式视图组件的展示部分)。
|
||||
3. 到达暂停点:不再弹 `InterventionCard`,而是在消息流里展示**阶段产物卡片**
|
||||
(素材列表 / 大纲 / 草稿 / 审核结果)+ 一句提示「你可以说:确认继续 / 补充素材 / 改大纲…」。
|
||||
用户下一句自然语言 → 意图解析 → `submitIntervention`。
|
||||
4. 问答:任意时刻用户提问 → 旁路回答,不打断写作状态。
|
||||
5. 素材不足:意图解析 `needResearch` 或后端 `section_help` → 对话追问「素材不足,帮你重搜?」
|
||||
→ 确认后重搜 → 自动续跑 pending 意图。
|
||||
|
||||
### 5.4 问答旁路(新能力)
|
||||
|
||||
「对写作内容提问」不应改写作 state。两种实现:
|
||||
|
||||
- **轻量(推荐先做)**:意图解析节点直接带回 `answer`(后端能读 state,一次调用出答案)。
|
||||
- **完整**:新起一条**只读**问答线程(lead_agent,context 注入当前草稿/大纲作为背景),
|
||||
类似 `WritingSetupChat` 的 `useThreadStream` 模式,但只读不回填。
|
||||
|
||||
---
|
||||
|
||||
## 6. 后端改造方案
|
||||
|
||||
### 6.1 意图解析入口(二选一)
|
||||
|
||||
- **方案 A1(推荐,独立 REST)**:`app/gateway/routers/ai_writing.py` 新增
|
||||
`POST /api/ai-writing/sessions/{id}/intent`,入参 `{text}`,后端读该 session 的
|
||||
checkpoint state(素材/大纲/草稿摘要)+ 用 `ai_writing` 配置模型解析,返回第 4.1 的契约。
|
||||
- 好处:不改图拓扑;前端拿到结果后再决定调 `startWriting`/`submitIntervention`。
|
||||
- 方案 A2(图内节点):在图里加 `conversation_router` 节点。改动大、状态耦合高,**不推荐**首期。
|
||||
|
||||
### 6.2 意图解析 prompt
|
||||
|
||||
新增 `agents/ai_writing/prompts/intent_router_prompts.py`(或复用/扩展 `intent_parser.py`):
|
||||
- 输入:用户文本、`current_status`、素材摘要(keywords + 每条 title/source)、大纲纲要、
|
||||
草稿字数/章节标题、审核意见列表。
|
||||
- 输出:严格 JSON(第 4.1 契约)。要求模型**只在证据充分时给高 confidence**,
|
||||
否则给 `clarify`(防误触发是硬指标)。
|
||||
|
||||
### 6.3 「带目标的重搜」协议扩展(可选增强)
|
||||
|
||||
现有 `supplement_search` 用 `user_query` 追加检索。为支持「改稿意见 → 缺素材 → 重搜 → 自动续跑」,
|
||||
建议在 `material_confirm` 的 resume 里新增可选字段 `resume_intent`(重搜完成后要自动执行的原始意图)。
|
||||
- 前端也可**纯前端**实现(重搜完成事件回来后再自动提交缓存的 pending payload),**首期优先前端实现**,避免动后端协议。
|
||||
|
||||
### 6.4 追加自定义审核意见(`add_review_opinion`)
|
||||
|
||||
`editor`/`pause_review` 目前只接受「接受/强制定稿」。要支持「你再补一条审核意见」,
|
||||
需在 `review_confirm` resume 里接受 `extra_review_notes`,`editor` 或 `writer_draft`
|
||||
修订时并入。首期可先降级为 `user_revise` + notes(把用户的审核诉求当作改稿意见),
|
||||
**完整版**再扩协议。
|
||||
|
||||
### 6.5 不需要改的部分
|
||||
|
||||
- 四个阶段大脑节点(researcher/writer_outline/writer_draft/editor)逻辑不动。
|
||||
- 五个暂停点、checkpoint、StreamBridge、持久化不动。
|
||||
|
||||
---
|
||||
|
||||
## 7. 数据流时序(改稿 + 素材不足自动重搜)
|
||||
|
||||
```
|
||||
用户: "第三段补个2024年的行业案例"
|
||||
│
|
||||
▼ POST /api/ai-writing/sessions/{id}/intent { text }
|
||||
后端: 读 state(素材摘要) + LLM 解析
|
||||
│ 返回 { intent:revise_draft, action:user_revise,
|
||||
│ payload:{userRevisionNotes:...},
|
||||
│ needResearch:true, researchQuery:"2024 行业案例" }
|
||||
▼
|
||||
前端: needResearch=true → 缓存 pending=payload
|
||||
│ 对话追问/直接执行: submitIntervention(material_confirm, supplement_search, user_query="2024 行业案例")
|
||||
▼ LangGraph resume → researcher 补素材 → materials_ready
|
||||
前端: 收到新素材 → 自动提交 pending
|
||||
│ submitIntervention(draft_confirm, user_revise, userRevisionNotes=...)
|
||||
▼ writer_draft 用新素材改稿 → draft_chunk... → draft_ready → pause_draft
|
||||
前端: 消息流展示新草稿 + "已按你的意见改写并补充了案例"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 关键实现细节与坑
|
||||
|
||||
1. **暂停态识别**:对话层必须知道「现在停在哪个 pause_point」才能正确映射 action。
|
||||
`AIWritingContext` 已有 `currentPause`/`status`,直接读。
|
||||
2. **防误触发**:低置信意图一律走 `clarify` 反问,绝不猜着执行(尤其 `finalize`/`re_search` 这种代价大的)。
|
||||
3. **pending 意图队列**:素材不足重搜是「先插一段、再回原意图」,需要一个小状态机记住 pending,
|
||||
并处理「重搜后用户又改主意」的情况(重搜完成前允许覆盖 pending)。
|
||||
4. **回退/undo(H 类)**:依赖 checkpoint 回滚,`runtime/runs/worker.py` 有 `rollback` 概念,
|
||||
首期可**不做**或只做「重跑当前阶段」。
|
||||
5. **问答旁路不污染 transcript**:问答消息可标记 `kind:'qa'`,与写作进度事件区分持久化。
|
||||
6. **流式产物→消息卡片**:复用现有 `OutlineStreamingView`/`DraftStreamingPreview` 等的**展示部分**,
|
||||
套进消息气泡即可,不必重写渲染。
|
||||
7. **离线内网**:意图解析模型走 `config.yaml → ai_writing` 里的配置模型;检索仍走技能/内网 ES,
|
||||
不联网(与现有并行席位「禁 web_search」的离线策略一致)。
|
||||
|
||||
---
|
||||
|
||||
## 9. 分阶段实施路线图
|
||||
|
||||
**阶段 0 — 骨架(不含意图)**
|
||||
- 新路由 + 新页面 `AIWritingChatPage`,复用 `AIWritingContext`/`useStream`/`DraftPanel`。
|
||||
- 底部对话框先只做「空闲 `start_writing` + 暂停点固定按钮」跑通端到端(相当于把干预卡换成消息)。
|
||||
|
||||
**阶段 1 — 意图解析(核心)**
|
||||
- 后端 `POST /sessions/{id}/intent` + intent prompt,返回第 4.1 契约。
|
||||
- 前端接入:自然语言 → 意图 → `startWriting`/`submitIntervention`,覆盖 A~F 类意图。
|
||||
- 加高频短句规则快路径 + 低置信 `clarify` 反问。
|
||||
|
||||
**阶段 2 — 问答旁路 + 素材不足自动重搜**
|
||||
- G 类问答(先用 intent 节点直接带 `answer`)。
|
||||
- `needResearch` + pending 意图机制(前端实现重搜后自动续跑)。
|
||||
|
||||
**阶段 3 — 增强协议(按需)**
|
||||
- `add_review_opinion` 扩 `review_confirm` 协议、`resume_intent` 后端化、undo/回退。
|
||||
|
||||
**阶段 4 — 打磨**
|
||||
- 消息卡片视觉、历史回看(复用 transcript)、后台挂起入口、灰度到侧边栏。
|
||||
|
||||
---
|
||||
|
||||
## 10. 关键文件清单(落地时对照)
|
||||
|
||||
### 新增(前端)
|
||||
- `open-canvas/pages/AIWritingChatPage.tsx` — 新页面
|
||||
- `open-canvas/components/ai-writing-chat/WritingChatComposer.tsx` — 统一输入框
|
||||
- `open-canvas/components/ai-writing-chat/WritingChatThread.tsx` — 消息流
|
||||
- `open-canvas/components/ai-writing-chat/progressToMessage.ts` — 事件→消息适配
|
||||
- `open-canvas/api/ai-writing-intent.ts` — 意图解析客户端
|
||||
- 路由注册:`open-canvas/OpenCanvasRoutes.tsx`(+ 可选 `sidebar-menu.ts`)
|
||||
|
||||
### 新增(后端)
|
||||
- `app/gateway/routers/ai_writing.py` — 加 `POST /sessions/{id}/intent`
|
||||
- `agents/ai_writing/prompts/intent_router_prompts.py` — 意图 prompt
|
||||
- (阶段 3)`state.py` / `nodes/*` — 扩 `review_confirm`、`resume_intent`
|
||||
|
||||
### 复用(尽量不改)
|
||||
- `open-canvas/contexts/AIWritingContext.tsx`、`hooks/useAIWritingStream.ts`
|
||||
- `open-canvas/components/ai-writing/AIWritingDraftPanel.tsx` 及各流式展示组件
|
||||
- `open-canvas/types/ai-writing.ts`(按需扩字段)
|
||||
- `agents/ai_writing/graph.py`、四个阶段节点、五个暂停点
|
||||
|
||||
### 不动
|
||||
- 旧 `open-canvas/pages/AIWritingPage.tsx` 及 `AIWritingForm`/`WritingFormContext`/`InterventionCard`
|
||||
|
||||
---
|
||||
|
||||
## 11. 待确认
|
||||
|
||||
1. 意图解析引擎是否采用**推荐的方案 A(后端 LLM 节点)**?
|
||||
2. 新页面是**独立入口**(侧边栏新增)还是先**内部灰度**(仅直链)?
|
||||
3. 「素材不足自动重搜」首期是否接受**前端实现 pending 续跑**(不动后端 resume 协议)?
|
||||
4. 问答旁路首期是否接受**意图节点直接带答案**(不新起只读线程)?
|
||||
|
||||
> 以上默认按「A / 内部灰度 / 前端 pending / 意图节点带答案」推进,如需调整请指出。
|
||||
@@ -16,6 +16,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<title>CM 助手</title>
|
||||
<script src="/runtime-config.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
"build:test": "node --max-old-space-size=8192 ./node_modules/vite/bin/vite.js build --mode test",
|
||||
"build:network": "node --max-old-space-size=8192 ./node_modules/vite/bin/vite.js build --mode network",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"check:chrome109-css": "node scripts/check-chrome109-css.mjs",
|
||||
"check:legacy-chrome-css": "node scripts/check-chrome109-css.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
@@ -110,6 +112,7 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.0.4",
|
||||
"lightningcss": "^1.30.2",
|
||||
"postcss": "^8.5.3",
|
||||
"tailwindcss": "^4.0.15",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import tailwindcss from "@tailwindcss/postcss";
|
||||
import legacyColorFallback from "./scripts/postcss-legacy-color-fallback.mjs";
|
||||
import lightningCssLegacyChrome from "./scripts/postcss-lightningcss-chrome109.mjs";
|
||||
|
||||
export default {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
plugins: [
|
||||
tailwindcss(),
|
||||
legacyColorFallback(),
|
||||
lightningCssLegacyChrome(),
|
||||
],
|
||||
};
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
@@ -0,0 +1,28 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" role="img" aria-labelledby="title">
|
||||
<title id="title">CM 助手</title>
|
||||
<defs>
|
||||
<linearGradient id="logoTopLeft" x1="7" y1="7" x2="25" y2="20" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#5DB5FF"/>
|
||||
<stop offset="1" stop-color="#328AF2"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="logoTopRight" x1="24" y1="3" x2="43" y2="19" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#62B2FF"/>
|
||||
<stop offset="1" stop-color="#4B98F4"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="logoLeft" x1="5" y1="14" x2="24" y2="45" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#2C7CF0"/>
|
||||
<stop offset="1" stop-color="#1F5EDA"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="logoBottom" x1="9" y1="31" x2="43" y2="40" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#276DE3"/>
|
||||
<stop offset="1" stop-color="#4E9DF5"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- The mark is drawn as four independent folded faces. Together they form
|
||||
the open C-shaped cube used in the product reference. -->
|
||||
<path d="M5 13.5 24 3v10L14 18.5 5 13.5Z" fill="url(#logoTopLeft)"/>
|
||||
<path d="M24 3 43 13.5 34 18.5 24 13V3Z" fill="url(#logoTopRight)"/>
|
||||
<path d="M5 13.5 14 18.5v11L24 35v10L5 34.5v-21Z" fill="url(#logoLeft)"/>
|
||||
<path d="M14 29.5 24 35l10-5.5 9 5L24 45 5 34.5l9-5Z" fill="url(#logoBottom)"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,100 @@
|
||||
// 前端运行时配置文件
|
||||
//
|
||||
// 说明:
|
||||
// 1. 本文件会在打包时原样复制到 dist/runtime-config.js。
|
||||
// 2. 应用启动时会优先读取 window.__CM_RUNTIME_CONFIG__ 里的配置。
|
||||
// 3. 部署后如果需要切换接口地址,直接修改 dist/runtime-config.js 即可,不需要重新 pnpm build。
|
||||
// 4. 这里的默认值来自 .env.network;如某个环境不用某项,可以留空字符串。
|
||||
// 5. 布尔开关也用字符串形式填写:"true" / "false"。
|
||||
window.__CM_RUNTIME_CONFIG__ = {
|
||||
// DeerFlow Gateway 地址:前端自有后端接口,例如 /api/agents、/api/auth、/api/threads 等。
|
||||
// VITE_BACKEND_BASE_URL: "http://10.19.200.5:2026",
|
||||
|
||||
// LangGraph 流式对话接口地址:普通问答、智能体对话等流式能力使用。
|
||||
// VITE_LANGGRAPH_BASE_URL: "http://10.19.200.5:2026/api",
|
||||
|
||||
// Canvas/AI 写作独立 LangGraph 地址:为空时前端会回退使用 VITE_LANGGRAPH_BASE_URL。
|
||||
VITE_CANVAS_LANGGRAPH_BASE_URL: "",
|
||||
|
||||
// 轻应用「新建笔记」系列接口地址。
|
||||
VITE_NOTE_API_BASE_URL: "http://47.88.25.99:8000",
|
||||
|
||||
// CMZS 后端接口:任务管理、任务分析、三情分析、行动分析等业务接口。
|
||||
VITE_API_BASE_URL: "https://ch1.b.uat.4.cn/zncm",
|
||||
|
||||
// 佳来模型对话接口。
|
||||
VITE_AIPI_CHAT_URL: "https://ch1.b.uat.4.cn/gpt",
|
||||
|
||||
// 多轮检索/生成接口。
|
||||
VITE_AIPI_GENERATE_CHAT_URL: "https://ch1.b.uat.4.cn/jialai_b1_chat",
|
||||
|
||||
// 任务问答接口。
|
||||
VITE_AIPI_TASK_CHAT_URL: "https://ch1.b.uat.4.cn/qq_b1_chat",
|
||||
|
||||
// B 系统知识库前端地址:用于打开知识详情、原文详情等。
|
||||
VITE_AIPI_KNOWLEDGE_URL: "https://chlib.b.uat.4.cn/knowlibrary",
|
||||
|
||||
// B1 COH 系统地址。
|
||||
VITE_AIPI_B1COH_URL: "https://ch1.b.uat.4.cn/web",
|
||||
|
||||
// B2 行为体/网络资源系统地址。
|
||||
VITE_AIPI_B2ACTOR_URL: "https://ty.b.uat.4.cn",
|
||||
|
||||
// B2 网络 XWT iframe 路径。
|
||||
VITE_AIPI_B2ACTOR_XWT_PATH: "/fromB/toXWT?isFrame=1",
|
||||
|
||||
// 知识库 iframe 地址换取接口。
|
||||
VITE_AIPI_KNOWLEDGE_IFRAME_API_URL: "https://ch1.b.uat.4.cn/knowes/api/iframeKnowledgeUrl",
|
||||
|
||||
// 知识库 iframe 皮肤参数。
|
||||
VITE_AIPI_KNOWLEDGE_IFRAME_SKIN: "red",
|
||||
|
||||
// MopeChat 接口地址。
|
||||
VITE_AIPI_MOPECHAT_URL: "https://ch1.b.uat.4.cn/likun_b1_mope",
|
||||
|
||||
// 工作室/空间后端接口:空间列表、空间详情、素材上传等使用。
|
||||
VITE_AIPI_BACKENP_URL: "http://47.88.25.99:8000",
|
||||
|
||||
// 工作室/空间后端别名:兼容旧配置命名,通常与 VITE_AIPI_BACKENP_URL 保持一致。
|
||||
VITE_NOTEBOOK_API_BASE_URL: "http://47.88.25.99:8000",
|
||||
|
||||
// 工作室/空间前端地址:用于 auth/callback、新建对话等跳转。
|
||||
VITE_AIPI_FRONTEND_URL: "http://47.88.25.99:3000",
|
||||
|
||||
// Consumer 接口:深链任务详情 cop-task-detail、研判情报报告 selectSqReport 等使用。
|
||||
VITE_AIPI_CONSUMER_URL: "http://10.19.200.5:8002/consumer",
|
||||
|
||||
// A 系统跳转地址:人物、组织、事件等列表项打开链接使用。
|
||||
VITE_AIPI_PRESENT_URL: "http://present.a.uat.4.cn/present/domain",
|
||||
|
||||
// B 系统 knowes 根地址。
|
||||
VITE_AIPI_KNOWES_URL: "http://ch1.b.uat.4.cn/knowes",
|
||||
|
||||
// MaxKey 鉴权地址:onlineTicket 换 token 使用。
|
||||
VITE_AUTH_BASE_URL: "https://auth.y.sit.4.cn",
|
||||
|
||||
// PG 中任务 iframe 地址。
|
||||
VITE_AIPI_PGLINKTO_URL: "https://pg.b.uat.4.cn",
|
||||
|
||||
// XK 中任务 iframe 地址。
|
||||
VITE_AIPI_XKLINKTO_URL: "https://kz.b.uat.4.cn",
|
||||
|
||||
// 是否使用真实任务看板数据:true=真实接口;false=本地 mock。
|
||||
VITE_USE_REAL_DATA: "true",
|
||||
|
||||
// 登录深链任务详情是否使用本地 mock:false=真实接口;true=本地 mock。
|
||||
VITE_MOCK_COP_TASK_DETAIL: "false",
|
||||
|
||||
// 大屏绘制 selectSqReport 是否使用本地 mock:不在运行时强制覆盖,
|
||||
// 由各环境的 .env 文件决定(开发环境为 true,生产环境为 false)。
|
||||
|
||||
// 静态站点模式开关;一般部署业务系统时保持 false。
|
||||
VITE_STATIC_WEBSITE_ONLY: "false",
|
||||
|
||||
// 紧凑导航开关:true 时固定使用简洁布局,工作台左侧栏收起为菜单图标,
|
||||
// 隐藏系统 Logo、换肤按钮以及“全量/简洁模式”切换。修改后刷新页面即可生效。
|
||||
VITE_FORCE_COLLAPSED_SIDEBAR: "false",
|
||||
|
||||
// GitHub OAuth Token;不使用 GitHub 相关能力时留空。
|
||||
VITE_GITHUB_OAUTH_TOKEN: "",
|
||||
};
|
||||
@@ -0,0 +1,109 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import postcss from "postcss";
|
||||
|
||||
const unsupportedColor = /(?:color-mix|oklch|oklab|lab|lch)\(/i;
|
||||
const assetsDir = path.resolve("dist/assets");
|
||||
|
||||
if (!fs.existsSync(assetsDir)) {
|
||||
throw new Error("dist/assets 不存在,请先运行 pnpm build");
|
||||
}
|
||||
|
||||
const cssFiles = fs
|
||||
.readdirSync(assetsDir)
|
||||
.filter((file) => file.endsWith(".css"));
|
||||
|
||||
if (cssFiles.length === 0) {
|
||||
throw new Error("dist/assets 中没有 CSS 构建产物");
|
||||
}
|
||||
|
||||
const failures = [];
|
||||
let modernDeclarations = 0;
|
||||
|
||||
const requiredLegacyFallbacks = [
|
||||
{
|
||||
file: "src/components/ui/textarea.tsx",
|
||||
pattern: /rows=\{rows\s*\?\?\s*3\}/,
|
||||
description: "Textarea needs a native rows fallback",
|
||||
},
|
||||
{
|
||||
file: "src/components/ai-elements/prompt-input.tsx",
|
||||
pattern: /<InputGroup className="h-auto min-h-16">/,
|
||||
description: "Prompt textarea must not rely on :has() for its parent height",
|
||||
},
|
||||
];
|
||||
|
||||
for (const file of cssFiles) {
|
||||
const root = postcss.parse(
|
||||
fs.readFileSync(path.join(assetsDir, file), "utf8"),
|
||||
{ from: file },
|
||||
);
|
||||
|
||||
root.walkDecls((declaration) => {
|
||||
if (!unsupportedColor.test(declaration.value)) return;
|
||||
modernDeclarations += 1;
|
||||
|
||||
let ancestor = declaration.parent;
|
||||
while (ancestor) {
|
||||
if (
|
||||
ancestor.type === "atrule" &&
|
||||
ancestor.name === "supports" &&
|
||||
unsupportedColor.test(ancestor.params)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
ancestor = ancestor.parent;
|
||||
}
|
||||
|
||||
let previous = declaration.prev();
|
||||
while (previous?.type === "comment") previous = previous.prev();
|
||||
const hasSafeFallback =
|
||||
!declaration.prop.startsWith("--") &&
|
||||
previous?.type === "decl" &&
|
||||
previous.prop === declaration.prop &&
|
||||
!unsupportedColor.test(previous.value);
|
||||
|
||||
if (!hasSafeFallback) {
|
||||
failures.push(
|
||||
`${file}:${declaration.source?.start?.line ?? "?"} ${declaration.prop}: ${declaration.value}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function walk(directory) {
|
||||
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
||||
const fullPath = path.join(directory, entry.name);
|
||||
return entry.isDirectory() ? walk(fullPath) : [fullPath];
|
||||
});
|
||||
}
|
||||
|
||||
for (const file of walk(path.resolve("src"))) {
|
||||
if (!/\.[jt]sx?$/.test(file)) continue;
|
||||
const source = fs.readFileSync(file, "utf8");
|
||||
if (unsupportedColor.test(source)) {
|
||||
failures.push(
|
||||
`${path.relative(process.cwd(), file)} contains a runtime-only modern color function`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (const fallback of requiredLegacyFallbacks) {
|
||||
const source = fs.readFileSync(path.resolve(fallback.file), "utf8");
|
||||
if (!fallback.pattern.test(source)) {
|
||||
failures.push(`${fallback.file}: ${fallback.description}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length > 0) {
|
||||
console.error("Legacy Chrome CSS compatibility check failed:\n");
|
||||
console.error(failures.slice(0, 50).join("\n"));
|
||||
if (failures.length > 50) {
|
||||
console.error(`... and ${failures.length - 50} more`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Legacy Chrome (100+) CSS compatibility check passed (${modernDeclarations} guarded modern declarations).`,
|
||||
);
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Tailwind 4 gracefully falls back from color-mix() to the base semantic
|
||||
* color, but that turns utilities such as bg-primary/5 into an opaque fill on
|
||||
* Chrome 109. Replace that fallback with an sRGB-channel based alpha color.
|
||||
* The modern color-mix() declaration remains in its @supports block.
|
||||
*/
|
||||
|
||||
const LEGACY_RGB_TOKENS = new Set([
|
||||
"accent",
|
||||
"background",
|
||||
"border",
|
||||
"brand-200",
|
||||
"card",
|
||||
"destructive",
|
||||
"foreground",
|
||||
"input",
|
||||
"muted",
|
||||
"muted-foreground",
|
||||
"primary",
|
||||
"primary-foreground",
|
||||
"ring",
|
||||
"secondary",
|
||||
"sidebar-accent",
|
||||
"sidebar-border",
|
||||
"sidebar-foreground",
|
||||
"workspace-brand",
|
||||
]);
|
||||
|
||||
const TRANSPARENT_MIX_RE =
|
||||
/color-mix\(\s*in\s+[\w-]+\s*,\s*var\(--([\w-]+)\)\s+([\d.]+)%\s*,\s*transparent\s*\)/i;
|
||||
|
||||
function legacyAlphaColor(value) {
|
||||
const match = value.match(TRANSPARENT_MIX_RE);
|
||||
if (!match || !LEGACY_RGB_TOKENS.has(match[1])) return null;
|
||||
|
||||
const [, token, percentage] = match;
|
||||
return `rgb(var(--legacy-${token}-rgb) / ${percentage}%)`;
|
||||
}
|
||||
|
||||
export default function legacyColorFallback() {
|
||||
return {
|
||||
postcssPlugin: "postcss-legacy-color-fallback",
|
||||
OnceExit(root) {
|
||||
root.walkAtRules("supports", (atRule) => {
|
||||
if (!atRule.params.includes("color-mix")) return;
|
||||
|
||||
atRule.walkDecls((modernDeclaration) => {
|
||||
const fallbackValue = legacyAlphaColor(modernDeclaration.value);
|
||||
if (!fallbackValue) return;
|
||||
|
||||
// Tailwind emits the old-browser declaration immediately before
|
||||
// the nested @supports block, in the same utility/variant rule.
|
||||
let fallbackDeclaration = atRule.prev();
|
||||
while (fallbackDeclaration?.type === "comment") {
|
||||
fallbackDeclaration = fallbackDeclaration.prev();
|
||||
}
|
||||
|
||||
if (
|
||||
fallbackDeclaration?.type === "decl" &&
|
||||
fallbackDeclaration.prop === modernDeclaration.prop
|
||||
) {
|
||||
fallbackDeclaration.value = fallbackValue;
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
legacyColorFallback.postcss = true;
|
||||
@@ -0,0 +1,33 @@
|
||||
import postcss from "postcss";
|
||||
import { transform } from "lightningcss";
|
||||
|
||||
const LEGACY_CHROME = 100 << 16;
|
||||
|
||||
/**
|
||||
* Keep Vite's PostCSS pipeline (required by Tailwind 4), then compile the
|
||||
* resulting CSS to Chrome 100-compatible syntax for both dev and production.
|
||||
*/
|
||||
export default function lightningCssLegacyChrome() {
|
||||
return {
|
||||
postcssPlugin: "postcss-lightningcss-legacy-chrome",
|
||||
OnceExit(root, { result }) {
|
||||
const filename = root.source?.input.file ?? result.opts.from ?? "style.css";
|
||||
const output = transform({
|
||||
filename,
|
||||
code: Buffer.from(root.toString()),
|
||||
targets: { chrome: LEGACY_CHROME },
|
||||
minify: false,
|
||||
});
|
||||
const compiled = postcss.parse(output.code.toString(), { from: filename });
|
||||
|
||||
root.removeAll();
|
||||
root.append(compiled.nodes);
|
||||
|
||||
for (const warning of output.warnings) {
|
||||
result.warn(warning.message, { plugin: "lightningcss" });
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
lightningCssLegacyChrome.postcss = true;
|
||||
@@ -86,7 +86,7 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
||||
attribute="class"
|
||||
storageKey="strategy-theme"
|
||||
defaultTheme="light"
|
||||
themes={["light", "dark", "lightblue"]}
|
||||
themes={["light", "dark", "lightblue", "lightgreen"]}
|
||||
enableSystem={false}
|
||||
disableTransitionOnChange
|
||||
forcedTheme={forcedTheme}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { copyTextToClipboard } from "@/core/clipboard";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
@@ -147,13 +148,8 @@ export const CodeBlockCopyButton = ({
|
||||
const { code } = useContext(CodeBlockContext);
|
||||
|
||||
const copyToClipboard = async () => {
|
||||
if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {
|
||||
onError?.(new Error("Clipboard API not available"));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(code);
|
||||
await copyTextToClipboard(code);
|
||||
setIsCopied(true);
|
||||
onCopy?.();
|
||||
setTimeout(() => setIsCopied(false), timeout);
|
||||
|
||||
@@ -846,7 +846,10 @@ export const PromptInput = ({
|
||||
ref={formRef}
|
||||
{...props}
|
||||
>
|
||||
<InputGroup>{children}</InputGroup>
|
||||
{/* Do not rely on InputGroup's :has(textarea) selector here: Chrome
|
||||
versions before 105 ignore :has(), retain h-9, and clip the whole
|
||||
multi-line composer to a single row. */}
|
||||
<InputGroup className="h-auto min-h-16">{children}</InputGroup>
|
||||
</form>
|
||||
</PromptInputValidationContext.Provider>
|
||||
);
|
||||
@@ -875,6 +878,7 @@ export type PromptInputTextareaProps = ComponentProps<
|
||||
|
||||
export const PromptInputTextarea = ({
|
||||
onChange,
|
||||
onInput,
|
||||
className,
|
||||
placeholder = "What would you like to know?",
|
||||
...props
|
||||
@@ -883,6 +887,37 @@ export const PromptInputTextarea = ({
|
||||
const attachments = usePromptInputAttachments();
|
||||
const sanitizeIncomingFiles = usePromptInputValidation();
|
||||
const [isComposing, setIsComposing] = useState(false);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
|
||||
const resizeForLegacyChrome = useCallback((textarea: HTMLTextAreaElement) => {
|
||||
if (
|
||||
typeof CSS !== "undefined" &&
|
||||
typeof CSS.supports === "function" &&
|
||||
CSS.supports("field-sizing", "content")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Chrome 109 ignores field-sizing: content. Preserve the same 4rem–12rem
|
||||
// autosize range used by min-h-16/max-h-48 instead of leaving the prompt
|
||||
// stuck at its minimum height.
|
||||
textarea.style.height = "auto";
|
||||
const height = Math.max(64, Math.min(textarea.scrollHeight, 192));
|
||||
textarea.style.height = `${height}px`;
|
||||
textarea.style.overflowY = textarea.scrollHeight > 192 ? "auto" : "hidden";
|
||||
}, []);
|
||||
|
||||
// onInput does not run for a controlled value filled by a suggested question
|
||||
// or restored draft. Resize once after every render in legacy Chrome too.
|
||||
useEffect(() => {
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
resizeForLegacyChrome(textarea);
|
||||
});
|
||||
return () => window.cancelAnimationFrame(frame);
|
||||
}, [controller?.textInput.value, resizeForLegacyChrome]);
|
||||
|
||||
const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
@@ -965,9 +1000,15 @@ export const PromptInputTextarea = ({
|
||||
<InputGroupTextarea
|
||||
className={cn("field-sizing-content max-h-48 min-h-16", className)}
|
||||
name="message"
|
||||
ref={textareaRef}
|
||||
rows={3}
|
||||
onCompositionEnd={() => setIsComposing(false)}
|
||||
onCompositionStart={() => setIsComposing(true)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onInput={(event) => {
|
||||
resizeForLegacyChrome(event.currentTarget);
|
||||
onInput?.(event);
|
||||
}}
|
||||
onPaste={handlePaste}
|
||||
placeholder={placeholder}
|
||||
{...props}
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "sonner";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
import { queryClient } from "@/components/query-client-provider";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import Empty from "./empty";
|
||||
@@ -303,11 +304,11 @@ const DocumentUploadPopupContent: FC<{
|
||||
const searchSpaceId = String(searchSpace?.id);
|
||||
|
||||
// 从环境变量获取配置
|
||||
const backendUrl = import.meta.env.VITE_AIPI_BACKENP_URL || "http://localhost:8001";
|
||||
const consumerUrl = import.meta.env.VITE_AIPI_CONSUMER_URL || "http://ch1.b.uat.4.cn/consumer";
|
||||
const presentUrl = import.meta.env.VITE_AIPI_PRESENT_URL || "http://present.a.uat.4.cn/present/domain";
|
||||
const knowesUrl = import.meta.env.VITE_AIPI_KNOWES_URL || "http://ch1.b.uat.4.cn/knowes";
|
||||
const knowledgeUrl = import.meta.env.VITE_AIPI_KNOWLEDGE_URL || "http://chlib.b.uat.4.cn/knowlibrary";
|
||||
const backendUrl = readRuntimeEnv("VITE_AIPI_BACKENP_URL") || "http://localhost:8001";
|
||||
const consumerUrl = readRuntimeEnv("VITE_AIPI_CONSUMER_URL") || "http://ch1.b.uat.4.cn/consumer";
|
||||
const presentUrl = readRuntimeEnv("VITE_AIPI_PRESENT_URL") || "http://present.a.uat.4.cn/present/domain";
|
||||
const knowesUrl = readRuntimeEnv("VITE_AIPI_KNOWES_URL") || "http://ch1.b.uat.4.cn/knowes";
|
||||
const knowledgeUrl = readRuntimeEnv("VITE_AIPI_KNOWLEDGE_URL") || "http://chlib.b.uat.4.cn/knowlibrary";
|
||||
|
||||
const [searchText, setSearchText] = useState("");
|
||||
const [searchValue, setSearchValue] = useState("");
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { toast } from "sonner";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { authenticatedFetch } from "@/components/assistant-ui/document-upload-popup";
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
|
||||
|
||||
interface NetworkActorProps {
|
||||
@@ -186,9 +187,9 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
const [actorCount, setActorCount] = useState<number>(0);
|
||||
const [directionType, setDirectionType] = useState<string>('TW');
|
||||
const directionValue = useRef<string>('TW');
|
||||
const consumerUrl = import.meta.env.VITE_AIPI_CONSUMER_URL || 'https://ch1.b.uat.4.cn/consumer';
|
||||
const consumerUrl = readRuntimeEnv("VITE_AIPI_CONSUMER_URL") || 'https://ch1.b.uat.4.cn/consumer';
|
||||
const backendUrl = typeof window !== 'undefined'
|
||||
? (import.meta.env.VITE_BACKEND_BASE_URL || 'http://localhost:8001')
|
||||
? (readRuntimeEnv("VITE_BACKEND_BASE_URL") || 'http://localhost:8001')
|
||||
: 'http://localhost:8001';
|
||||
const [selectedSearchSources, setSelectedSearchSources] = useState<UserDataItem[]>([]);
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
|
||||
@@ -508,8 +508,9 @@ export default function ProgressiveSkillsAnimation() {
|
||||
"deploying",
|
||||
"done",
|
||||
].includes(phase) && (
|
||||
<div className="text-base text-zinc-300">
|
||||
<span className="text-purple-400">✨</span> Found 3 skills
|
||||
<div className="flex items-center gap-2 text-base text-zinc-300">
|
||||
<Sparkles size={16} className="text-purple-400" />
|
||||
<span>Found 3 skills</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -526,8 +527,9 @@ export default function ProgressiveSkillsAnimation() {
|
||||
].includes(phase) && (
|
||||
<div className="mt-4">
|
||||
<hr className="mb-3 border-zinc-700" />
|
||||
<div className="mb-3 text-zinc-300">
|
||||
🔬 Researching...
|
||||
<div className="mb-3 inline-flex items-center gap-2 text-zinc-300">
|
||||
<Search size={16} className="text-blue-400" />
|
||||
<span>Researching...</span>
|
||||
</div>
|
||||
<div className="mb-3 space-y-2">
|
||||
{/* Loading SKILL.md */}
|
||||
@@ -623,7 +625,10 @@ export default function ProgressiveSkillsAnimation() {
|
||||
className="mt-4"
|
||||
>
|
||||
<hr className="mb-3 border-zinc-700" />
|
||||
<div className="mb-3 text-zinc-300">🔨 Building...</div>
|
||||
<div className="mb-3 inline-flex items-center gap-2 text-zinc-300">
|
||||
<FileText size={16} className="text-zinc-400" />
|
||||
<span>Building...</span>
|
||||
</div>
|
||||
<div className="mb-3 flex items-center gap-2 pl-4 text-zinc-400">
|
||||
<FileText size={16} />
|
||||
<span>Loading frontend-design/SKILL.md...</span>
|
||||
@@ -653,7 +658,10 @@ export default function ProgressiveSkillsAnimation() {
|
||||
className="mt-4"
|
||||
>
|
||||
<hr className="mb-3 border-zinc-700" />
|
||||
<div className="mb-3 text-zinc-300">🚀 Deploying...</div>
|
||||
<div className="mb-3 inline-flex items-center gap-2 text-zinc-300">
|
||||
<Terminal size={16} className="text-zinc-400" />
|
||||
<span>Deploying...</span>
|
||||
</div>
|
||||
<div className="mb-3 space-y-2">
|
||||
<div className="flex items-center gap-2 pl-4 text-zinc-400">
|
||||
<FileText size={16} />
|
||||
@@ -676,8 +684,9 @@ export default function ProgressiveSkillsAnimation() {
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="mt-4 rounded-xl border border-green-500/30 bg-green-500/10 p-4"
|
||||
>
|
||||
<div className="text-lg font-medium text-green-500">
|
||||
✅ Live at biotech-startup.vercel.app
|
||||
<div className="inline-flex items-center gap-2 text-lg font-medium text-green-500">
|
||||
<Check size={18} />
|
||||
<span>Live at biotech-startup.vercel.app</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
@@ -35,27 +35,27 @@ export function SandboxSection({ className }: { className?: string }) {
|
||||
$ pip install -r requirements.txt
|
||||
</TypingAnimation>
|
||||
<AnimatedSpan delay={2000} className="text-green-500">
|
||||
✔ Installed pygame
|
||||
[ok] Installed pygame
|
||||
</AnimatedSpan>
|
||||
|
||||
<TypingAnimation delay={2400}>
|
||||
$ write game.py --lines 156
|
||||
</TypingAnimation>
|
||||
<AnimatedSpan delay={3200} className="text-blue-500">
|
||||
✔ Written 156 lines
|
||||
[ok] Written 156 lines
|
||||
</AnimatedSpan>
|
||||
|
||||
<TypingAnimation delay={3600}>
|
||||
$ python game.py --test
|
||||
</TypingAnimation>
|
||||
<AnimatedSpan delay={4200} className="text-green-500">
|
||||
✔ All sprites loaded
|
||||
[ok] All sprites loaded
|
||||
</AnimatedSpan>
|
||||
<AnimatedSpan delay={4500} className="text-green-500">
|
||||
✔ Physics engine OK
|
||||
[ok] Physics engine OK
|
||||
</AnimatedSpan>
|
||||
<AnimatedSpan delay={4800} className="text-green-500">
|
||||
✔ 60 FPS stable
|
||||
[ok] 60 FPS stable
|
||||
</AnimatedSpan>
|
||||
|
||||
{/* Scene 2: Data Analysis */}
|
||||
|
||||
@@ -144,13 +144,14 @@ function InputGroupInput({
|
||||
);
|
||||
}
|
||||
|
||||
function InputGroupTextarea({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"textarea">) {
|
||||
const InputGroupTextarea = React.forwardRef<
|
||||
HTMLTextAreaElement,
|
||||
React.ComponentProps<"textarea">
|
||||
>(function InputGroupTextarea({ className, ...props }, ref) {
|
||||
return (
|
||||
<Textarea
|
||||
data-slot="input-group-control"
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||
className,
|
||||
@@ -158,7 +159,9 @@ function InputGroupTextarea({
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
InputGroupTextarea.displayName = "InputGroupTextarea";
|
||||
|
||||
export {
|
||||
InputGroup,
|
||||
|
||||
@@ -27,7 +27,9 @@ import {
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||
const SIDEBAR_WIDTH = "16rem";
|
||||
// Keep the workbench navigation compact across every theme. The visual theme
|
||||
// only changes tokens; the information density should remain consistent.
|
||||
const SIDEBAR_WIDTH = "14rem";
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem";
|
||||
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||
|
||||
@@ -2,12 +2,19 @@ import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
const Textarea = React.forwardRef<
|
||||
HTMLTextAreaElement,
|
||||
React.ComponentProps<"textarea">
|
||||
>(function Textarea({ className, rows, ...props }, ref) {
|
||||
// `field-sizing` is not available in older Chrome. Keep a native rows
|
||||
// fallback so a multi-line editor never collapses into a single line.
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
ref={ref}
|
||||
rows={rows ?? 3}
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground/60 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"border-input placeholder:text-muted-foreground/60 flex min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"dark:border-[#1B477E] dark:bg-[#022248] dark:text-[#AACEFF] ",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className,
|
||||
@@ -15,6 +22,8 @@ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Textarea.displayName = "Textarea";
|
||||
|
||||
export { Textarea };
|
||||
@@ -3,7 +3,7 @@ export function EmptyDocumentState() {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center bg-white px-6 text-center dark:bg-slate-900">
|
||||
<div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-10 py-12 sm:px-12 dark:border-slate-700 dark:bg-slate-800/50">
|
||||
<div className="mb-4 text-[40px] leading-none">📚</div>
|
||||
<div className="mb-4 text-[28px] font-semibold leading-none text-slate-500 dark:text-slate-300">文档</div>
|
||||
<div className="mb-2 text-lg font-bold text-slate-700 dark:text-slate-200">
|
||||
选择一篇文档开始阅读
|
||||
</div>
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { BookOpen, ListTree } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { reasoningPlugins } from "@/core/streamdown";
|
||||
import { createMarkdownAnchorResolver } from "@/core/utils/markdown";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import "./wiki.css";
|
||||
|
||||
function stripMarkdownToText(markdown: string): string {
|
||||
return markdown
|
||||
.replace(/```[\s\S]*?```/g, " ")
|
||||
.replace(/~~~[\s\S]*?~~~/g, " ")
|
||||
.replace(/!\[[^\]]*\]\([^)]+\)/g, " ")
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
|
||||
.replace(/^#{1,6}\s+/gm, "")
|
||||
.replace(/^[>\-*+\d.)\s]+/gm, "")
|
||||
.replace(/[`*_~|]/g, "")
|
||||
.replace(/<[^>]+>/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function getMarkdownExcerpt(markdown: string): string {
|
||||
const text = stripMarkdownToText(markdown);
|
||||
if (!text) return "";
|
||||
return text.length > 150 ? `${text.slice(0, 150)}...` : text;
|
||||
}
|
||||
|
||||
function countReadableWords(markdown: string): number {
|
||||
const text = stripMarkdownToText(markdown);
|
||||
if (!text) return 0;
|
||||
const cjk = text.match(/[\u4e00-\u9fff]/g)?.length ?? 0;
|
||||
const words = text.replace(/[\u4e00-\u9fff]/g, " ").match(/[A-Za-z0-9]+/g)?.length ?? 0;
|
||||
return cjk + words;
|
||||
}
|
||||
|
||||
function selectorForId(id: string): string {
|
||||
const css = window.CSS;
|
||||
if (css?.escape) return `#${css.escape(id)}`;
|
||||
return `[id="${id.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"]`;
|
||||
}
|
||||
|
||||
export function ReportMarkdownView({
|
||||
content,
|
||||
title,
|
||||
subtitle,
|
||||
badgeLabel = "报告阅读",
|
||||
className,
|
||||
compactHeader = false,
|
||||
}: {
|
||||
content: string;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
badgeLabel?: string;
|
||||
className?: string;
|
||||
compactHeader?: boolean;
|
||||
}) {
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const anchorResolver = useMemo(() => createMarkdownAnchorResolver(content), [content]);
|
||||
const headings = useMemo(
|
||||
() => anchorResolver.headings.filter((item) => item.level >= 1 && item.level <= 3),
|
||||
[anchorResolver],
|
||||
);
|
||||
const [activeHeadingId, setActiveHeadingId] = useState<string | null>(null);
|
||||
const excerpt = useMemo(() => getMarkdownExcerpt(content), [content]);
|
||||
const sectionCount = headings.length;
|
||||
const wordCount = useMemo(() => countReadableWords(content), [content]);
|
||||
|
||||
useEffect(() => {
|
||||
setActiveHeadingId(headings[0]?.id ?? null);
|
||||
}, [headings]);
|
||||
|
||||
useEffect(() => {
|
||||
const root = rootRef.current;
|
||||
if (!root || headings.length === 0) return;
|
||||
|
||||
const targets = headings
|
||||
.map((item) => root.querySelector<HTMLElement>(selectorForId(item.id)))
|
||||
.filter((item): item is HTMLElement => !!item);
|
||||
if (targets.length === 0) return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
const visible = entries
|
||||
.filter((entry) => entry.isIntersecting)
|
||||
.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
|
||||
if (visible?.target.id) setActiveHeadingId(visible.target.id);
|
||||
},
|
||||
{
|
||||
root: root.closest("[data-radix-scroll-area-viewport]") ?? null,
|
||||
rootMargin: "-96px 0px -65% 0px",
|
||||
threshold: [0, 1],
|
||||
},
|
||||
);
|
||||
|
||||
targets.forEach((target) => observer.observe(target));
|
||||
return () => observer.disconnect();
|
||||
}, [headings, content]);
|
||||
|
||||
const scrollToHeading = useCallback((id: string) => {
|
||||
const root = rootRef.current;
|
||||
const target =
|
||||
root?.querySelector<HTMLElement>(selectorForId(id)) ?? document.getElementById(id);
|
||||
setActiveHeadingId(id);
|
||||
target?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={cn("report-markdown-shell grid min-h-0 gap-5 lg:grid-cols-[minmax(0,1fr)_300px]", className)}
|
||||
>
|
||||
<article className="report-markdown-paper min-w-0 overflow-hidden">
|
||||
<header className={cn("report-markdown-header", compactHeader && "report-markdown-header-compact")}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary" className="report-markdown-badge">
|
||||
<BookOpen className="size-3.5" />
|
||||
{badgeLabel}
|
||||
</Badge>
|
||||
{subtitle && (
|
||||
<span className="max-w-full truncate text-xs text-slate-500 dark:text-slate-400">
|
||||
{subtitle}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{title && <h1 className="report-markdown-title">{title}</h1>}
|
||||
{!compactHeader && excerpt && <p className="report-markdown-excerpt">{excerpt}</p>}
|
||||
<div className="report-markdown-metrics">
|
||||
<span>{sectionCount || 1} 个章节</span>
|
||||
<span>约 {wordCount} 字</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="wiki-markdown report-markdown-body">
|
||||
<MarkdownContent
|
||||
className="max-w-none"
|
||||
content={content}
|
||||
isLoading={false}
|
||||
remarkPlugins={reasoningPlugins.remarkPlugins}
|
||||
rehypePlugins={reasoningPlugins.rehypePlugins}
|
||||
/>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<aside className="hidden min-w-0 lg:block">
|
||||
<div className="report-markdown-toc">
|
||||
<div className="mb-3 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-slate-900 dark:text-slate-100">
|
||||
<ListTree className="size-4" />
|
||||
内容目录
|
||||
</div>
|
||||
<span className="rounded-md bg-slate-100 px-1.5 py-0.5 text-xs text-slate-500 dark:bg-slate-800 dark:text-slate-400">
|
||||
{sectionCount || 0}
|
||||
</span>
|
||||
</div>
|
||||
{headings.length > 0 ? (
|
||||
<nav className="report-markdown-toc-list">
|
||||
{headings.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
"report-markdown-toc-item",
|
||||
activeHeadingId === item.id && "report-markdown-toc-item-active",
|
||||
item.level === 2 && "report-markdown-toc-level-2",
|
||||
item.level === 3 && "report-markdown-toc-level-3",
|
||||
)}
|
||||
title={item.text}
|
||||
onClick={() => scrollToHeading(item.id)}
|
||||
>
|
||||
{item.text}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
) : (
|
||||
<div className="rounded-md border border-dashed p-3 text-xs text-slate-500 dark:border-slate-800 dark:text-slate-400">
|
||||
暂无标题目录
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -111,340 +111,6 @@
|
||||
border-color: #eef1f5;
|
||||
}
|
||||
|
||||
.public-report-markdown {
|
||||
color: #334155;
|
||||
font-feature-settings: "kern";
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
.public-report-markdown h1 {
|
||||
font-size: 30px;
|
||||
letter-spacing: 0;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.public-report-markdown h2 {
|
||||
font-size: 22px;
|
||||
margin-top: 42px;
|
||||
margin-bottom: 16px;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
.public-report-markdown h3 {
|
||||
font-size: 18px;
|
||||
margin-top: 30px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.public-report-markdown p,
|
||||
.public-report-markdown li {
|
||||
font-size: 16px;
|
||||
line-height: 1.9;
|
||||
}
|
||||
|
||||
.public-report-markdown p {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.public-report-markdown ul,
|
||||
.public-report-markdown ol {
|
||||
margin: 14px 0 18px;
|
||||
padding-left: 26px;
|
||||
}
|
||||
|
||||
.public-report-markdown ul {
|
||||
list-style-type: disc;
|
||||
}
|
||||
|
||||
.public-report-markdown ol {
|
||||
list-style-type: decimal;
|
||||
}
|
||||
|
||||
.public-report-markdown li {
|
||||
padding-left: 2px;
|
||||
}
|
||||
|
||||
.public-report-markdown code {
|
||||
border-radius: 6px;
|
||||
background: #f1f5f9;
|
||||
padding: 2px 6px;
|
||||
color: #be123c;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
|
||||
.public-report-markdown pre {
|
||||
margin: 20px 0;
|
||||
border-radius: 8px;
|
||||
background: #0f172a;
|
||||
padding: 16px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.public-report-markdown pre code {
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.public-report-markdown table {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #e8ecf1;
|
||||
}
|
||||
|
||||
.public-report-markdown th,
|
||||
.public-report-markdown td {
|
||||
min-width: 120px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.public-report-markdown blockquote {
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.dark .public-report-markdown {
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
.dark .public-report-markdown code {
|
||||
background: #1e293b;
|
||||
color: #f9a8d4;
|
||||
}
|
||||
|
||||
.dark .public-report-markdown pre {
|
||||
background: #020617;
|
||||
}
|
||||
|
||||
.dark .public-report-markdown table {
|
||||
border-color: #334155;
|
||||
}
|
||||
|
||||
.report-markdown-shell {
|
||||
align-items: start;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.report-markdown-paper {
|
||||
border: 1px solid rgba(203, 213, 225, 0.85);
|
||||
border-radius: 8px;
|
||||
background:
|
||||
linear-gradient(180deg, rgba(248, 250, 252, 0.92), rgba(255, 255, 255, 0) 220px),
|
||||
#ffffff;
|
||||
box-shadow:
|
||||
0 1px 2px rgba(15, 23, 42, 0.04),
|
||||
0 18px 44px rgba(15, 23, 42, 0.07);
|
||||
}
|
||||
|
||||
.report-markdown-header {
|
||||
border-bottom: 1px solid #e8edf4;
|
||||
padding: 26px 34px 22px;
|
||||
}
|
||||
|
||||
.report-markdown-header-compact {
|
||||
padding-bottom: 18px;
|
||||
}
|
||||
|
||||
.report-markdown-badge {
|
||||
gap: 6px;
|
||||
border: 1px solid #dbe3ef;
|
||||
background: #ffffff;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.report-markdown-title {
|
||||
margin: 14px 0 0;
|
||||
color: #0f172a;
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.report-markdown-excerpt {
|
||||
margin: 14px 0 0;
|
||||
max-width: 840px;
|
||||
color: #64748b;
|
||||
font-size: 14px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.report-markdown-metrics {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
color: #64748b;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.report-markdown-metrics span {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.78);
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
.report-markdown-body {
|
||||
max-width: 920px;
|
||||
margin: 0 auto;
|
||||
padding: 32px 42px 44px;
|
||||
}
|
||||
|
||||
.report-markdown-body h1 {
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.report-markdown-body h2 {
|
||||
position: relative;
|
||||
margin-top: 44px;
|
||||
border-bottom-color: #e5edf7;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.report-markdown-body h2::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: -16px;
|
||||
top: 0.34em;
|
||||
width: 4px;
|
||||
height: 1.05em;
|
||||
border-radius: 999px;
|
||||
background: #2563eb;
|
||||
}
|
||||
|
||||
.report-markdown-body h3 {
|
||||
color: #1e293b;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.report-markdown-body p,
|
||||
.report-markdown-body li {
|
||||
font-size: 16px;
|
||||
line-height: 1.92;
|
||||
}
|
||||
|
||||
.report-markdown-body blockquote {
|
||||
border-left-color: #2563eb;
|
||||
background: #f8fbff;
|
||||
}
|
||||
|
||||
.report-markdown-body table {
|
||||
box-shadow: 0 1px 0 rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.report-markdown-toc {
|
||||
position: sticky;
|
||||
top: 16px;
|
||||
max-height: calc(100vh - 32px);
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(203, 213, 225, 0.82);
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.92);
|
||||
padding: 14px;
|
||||
box-shadow: 0 12px 34px rgba(15, 23, 42, 0.06);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.report-markdown-toc-list {
|
||||
max-height: calc(100vh - 128px);
|
||||
overflow: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.report-markdown-toc-item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
border-left: 2px solid transparent;
|
||||
border-radius: 6px;
|
||||
padding: 7px 8px;
|
||||
color: #64748b;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
text-align: left;
|
||||
transition: background 160ms ease, border-color 160ms ease, color 160ms ease;
|
||||
}
|
||||
|
||||
.report-markdown-toc-item:hover {
|
||||
background: #f1f5f9;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.report-markdown-toc-item-active {
|
||||
border-left-color: #2563eb;
|
||||
background: #eff6ff;
|
||||
color: #1d4ed8;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.report-markdown-toc-level-2 {
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
.report-markdown-toc-level-3 {
|
||||
padding-left: 30px;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.dark .report-markdown-paper {
|
||||
border-color: #1f2937;
|
||||
background:
|
||||
linear-gradient(180deg, rgba(15, 23, 42, 0.9), rgba(2, 6, 23, 0) 220px),
|
||||
#020617;
|
||||
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.24);
|
||||
}
|
||||
|
||||
.dark .report-markdown-header {
|
||||
border-bottom-color: #1e293b;
|
||||
}
|
||||
|
||||
.dark .report-markdown-badge,
|
||||
.dark .report-markdown-metrics span {
|
||||
border-color: #334155;
|
||||
background: #0f172a;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
.dark .report-markdown-title {
|
||||
color: #f8fafc;
|
||||
}
|
||||
|
||||
.dark .report-markdown-excerpt,
|
||||
.dark .report-markdown-metrics {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.dark .report-markdown-body h3 {
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
.dark .report-markdown-body h2::before {
|
||||
background: #60a5fa;
|
||||
}
|
||||
|
||||
.dark .report-markdown-body blockquote {
|
||||
background: #0f172a;
|
||||
border-left-color: #60a5fa;
|
||||
}
|
||||
|
||||
.dark .report-markdown-toc {
|
||||
border-color: #1f2937;
|
||||
background: rgba(2, 6, 23, 0.88);
|
||||
}
|
||||
|
||||
.dark .report-markdown-toc-item:hover {
|
||||
background: #0f172a;
|
||||
color: #f8fafc;
|
||||
}
|
||||
|
||||
.dark .report-markdown-toc-item-active {
|
||||
background: rgba(37, 99, 235, 0.16);
|
||||
color: #93c5fd;
|
||||
}
|
||||
|
||||
/* Anchor target offset so headings clear the floating "目录" pill. */
|
||||
.wiki-markdown h1,
|
||||
.wiki-markdown h2,
|
||||
|
||||
@@ -213,7 +213,7 @@ const errorToastDarkOptions = {
|
||||
</div>
|
||||
<div className="flex flex-1 flex-wrap items-center gap-1.5">
|
||||
{summary && Object.keys(summary.by_category).length === 0 && (
|
||||
<span className="text-muted-foreground text-sm">暂无失败记录 🎉</span>
|
||||
<span className="text-muted-foreground text-sm">暂无失败记录</span>
|
||||
)}
|
||||
{summary &&
|
||||
Object.entries(summary.by_category)
|
||||
|
||||
@@ -35,7 +35,7 @@ export function AgentWelcome({
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="bg-primary/10 ring-primary/15 mb-2 flex h-[72px] w-[72px] items-center justify-center rounded-3xl ring-1">
|
||||
<div className="agent-avatar bg-primary/10 ring-primary/15 mb-2 flex h-[72px] w-[72px] items-center justify-center rounded-3xl ring-1">
|
||||
<BotIcon className="text-primary h-9 w-9" />
|
||||
</div>
|
||||
<div className="text-3xl font-bold tracking-tight">
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type AgentBrandIconProps = {
|
||||
className?: string;
|
||||
size?: "nav" | "sm" | "md" | "lg";
|
||||
};
|
||||
|
||||
const SIZE_STYLES = {
|
||||
nav: {
|
||||
frame: "size-[22px] rounded-md",
|
||||
},
|
||||
sm: {
|
||||
frame: "size-10 rounded-full",
|
||||
},
|
||||
md: {
|
||||
frame: "size-12 rounded-full",
|
||||
},
|
||||
lg: {
|
||||
frame: "size-16 rounded-full",
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function AgentBrandIcon({
|
||||
className,
|
||||
size = "md",
|
||||
}: AgentBrandIconProps) {
|
||||
const styles = SIZE_STYLES[size];
|
||||
const { theme } = useTheme();
|
||||
const avatarSrc =
|
||||
theme === "light" ? "/agent-avatar-red.png" : "/agent-avatar.png";
|
||||
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
data-agent-brand-icon={size}
|
||||
className={cn(
|
||||
"relative inline-flex shrink-0 overflow-hidden rounded-full",
|
||||
styles.frame,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src={avatarSrc}
|
||||
alt=""
|
||||
className="size-full object-contain"
|
||||
draggable={false}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
BotIcon,
|
||||
ClockIcon,
|
||||
CopyIcon,
|
||||
EyeOffIcon,
|
||||
GlobeIcon,
|
||||
LockIcon,
|
||||
MessageSquareIcon,
|
||||
MoreHorizontalIcon,
|
||||
PinIcon,
|
||||
ShieldIcon,
|
||||
SparklesIcon,
|
||||
@@ -46,6 +46,13 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
@@ -60,6 +67,7 @@ import { usePublishSquares } from "@/core/system-settings/hooks";
|
||||
import { PublishSquarePickerDialog } from "@/components/workspace/publish-square-picker-dialog";
|
||||
import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-dialog";
|
||||
import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor";
|
||||
import { AgentBrandIcon } from "@/components/workspace/agents/agent-brand-icon";
|
||||
import { SkillTransferSelector } from "@/components/workspace/agents/skill-transfer-selector";
|
||||
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
||||
import { TagPickerDialog } from "@/components/workspace/tags/tag-picker-dialog";
|
||||
@@ -551,7 +559,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
{isOwned && (
|
||||
<Badge
|
||||
variant="default"
|
||||
className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-300 text-xs"
|
||||
className="border border-emerald-200 bg-emerald-50 text-xs text-emerald-700 hover:bg-emerald-50 dark:border-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-300"
|
||||
>
|
||||
我的
|
||||
</Badge>
|
||||
@@ -559,7 +567,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
{isFromOthers && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-blue-500/30 text-blue-700 dark:text-blue-300 text-xs"
|
||||
className="border-primary/20 bg-primary/5 text-primary text-xs dark:border-primary/40 dark:bg-primary/10 dark:text-primary"
|
||||
title={agent.user_id ? `来自用户 ${agent.user_id}` : "已发布"}
|
||||
>
|
||||
来自他人
|
||||
@@ -568,7 +576,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
{(isOwned || isAdmin) && !isBuiltin && agent.published && !agent.is_private && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
||||
className="border-primary/20 bg-primary/5 text-primary text-xs dark:border-primary/40 dark:bg-primary/10 dark:text-primary"
|
||||
title="该智能体已对所有用户可见"
|
||||
>
|
||||
<GlobeIcon className="size-3" />
|
||||
@@ -664,7 +672,11 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
...(agent.tool_groups ?? []).map((group) => ({
|
||||
key: `tg:${group}`,
|
||||
node: (
|
||||
<Badge key={`tg:${group}`} variant="outline" className="text-xs">
|
||||
<Badge
|
||||
key={`tg:${group}`}
|
||||
variant="outline"
|
||||
className="border-0 bg-primary/5 text-primary hover:bg-primary/10 px-2.5 py-1 text-xs font-normal"
|
||||
>
|
||||
{desensitize(group)}
|
||||
</Badge>
|
||||
),
|
||||
@@ -675,7 +687,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
<Badge
|
||||
key={`sk:${skill}`}
|
||||
variant="secondary"
|
||||
className="hover:bg-secondary/70 cursor-pointer text-xs"
|
||||
className="bg-primary/5 text-primary hover:bg-primary/10 cursor-pointer border-0 px-2.5 py-1 text-xs font-normal"
|
||||
title={t.settings.skills.viewDetailAction}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
@@ -825,78 +837,179 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
|
||||
const chatButton = (
|
||||
<Button
|
||||
variant={isList ? "default" : "outline"}
|
||||
size="sm"
|
||||
className={cn(isList ? "shrink-0" : "w-full")}
|
||||
className={cn(
|
||||
isList
|
||||
? "bg-primary hover:bg-primary/90 shrink-0 rounded-xl px-4 font-medium text-primary-foreground"
|
||||
: "border-primary/35 text-primary hover:border-primary/55 hover:bg-primary/5 h-11 w-full rounded-lg bg-white font-medium shadow-none dark:bg-slate-900 dark:text-primary",
|
||||
)}
|
||||
onClick={handleChat}
|
||||
>
|
||||
<MessageSquareIcon className="mr-1.5 h-3.5 w-3.5" />
|
||||
{t.agents.chat}
|
||||
开始对话
|
||||
</Button>
|
||||
);
|
||||
|
||||
const cardStatusBadge = agent.is_private ? (
|
||||
<Badge className="border-0 bg-purple-50 px-2.5 py-1 text-xs font-normal text-purple-600 hover:bg-purple-50 dark:bg-purple-500/15 dark:text-purple-300">
|
||||
<span className="mr-1.5 size-1.5 rounded-full bg-purple-500" />
|
||||
私密
|
||||
</Badge>
|
||||
) : agent.published || isBuiltin ? (
|
||||
<Badge className="border-0 bg-primary/5 text-primary hover:bg-primary/5 px-2.5 py-1 text-xs font-normal dark:bg-primary/15 dark:text-primary">
|
||||
<span className="bg-primary mr-1.5 size-1.5 rounded-full" />
|
||||
已发布
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge className="border-0 bg-emerald-50 px-2.5 py-1 text-xs font-normal text-emerald-600 hover:bg-emerald-50 dark:bg-emerald-500/15 dark:text-emerald-300">
|
||||
<span className="mr-1.5 size-1.5 rounded-full bg-emerald-500" />
|
||||
运行中
|
||||
</Badge>
|
||||
);
|
||||
|
||||
const updatedAtText = formatDateTime(agent.updated_at ?? agent.created_at);
|
||||
const cardActionsMenu = (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="size-8 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-900 dark:hover:bg-slate-800 dark:hover:text-white"
|
||||
title="更多操作"
|
||||
>
|
||||
<MoreHorizontalIcon className="size-5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-44">
|
||||
{canFavorite && (
|
||||
<DropdownMenuItem onSelect={() => void handleToggleFavorite()}>
|
||||
<StarIcon className={cn("size-4", isFavorite && "fill-current text-amber-500")} />
|
||||
{isFavorite ? "取消收藏" : "收藏到我的"}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onSelect={() => void handleTogglePin()}>
|
||||
<PinIcon className={cn("size-4", isPinned && "fill-current text-emerald-600")} />
|
||||
{isPinned ? "取消置顶" : "置顶"}
|
||||
</DropdownMenuItem>
|
||||
{isAdmin && (
|
||||
<DropdownMenuItem onSelect={() => void handleToggleFeatured()}>
|
||||
<SparklesIcon className="size-4" />
|
||||
{agent.featured_order != null ? "取消推荐" : "设为推荐"}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onSelect={() => setTagPickerOpen(true)}>
|
||||
<TagsIcon className="size-4" />
|
||||
{t.adminTags.manageTags}
|
||||
</DropdownMenuItem>
|
||||
{isOwned && (
|
||||
<DropdownMenuItem onSelect={() => void handleTogglePublished()}>
|
||||
{agent.published ? <LockIcon className="size-4" /> : <GlobeIcon className="size-4" />}
|
||||
{agent.published ? "取消发布" : "发布"}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{(isOwned || isAdmin) && (
|
||||
<DropdownMenuItem onSelect={() => void handleTogglePrivate()}>
|
||||
<ShieldIcon className="size-4" />
|
||||
{agent.is_private ? "移出私密广场" : "放入私密广场"}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={() => void handleDuplicate()}>
|
||||
<CopyIcon className="size-4" />
|
||||
复制智能体
|
||||
</DropdownMenuItem>
|
||||
{canEdit && (
|
||||
<DropdownMenuItem onSelect={() => setEditOpen(true)}>
|
||||
<SquarePenIcon className="size-4" />
|
||||
编辑智能体
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canDelete && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onSelect={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2Icon className="size-4" />
|
||||
{t.agents.delete}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
|
||||
const cardLayout = (
|
||||
<Card className="group flex min-w-0 flex-col transition-shadow hover:shadow-md">
|
||||
<CardHeader className="min-w-0 pb-2">
|
||||
<div className="flex min-w-0 items-start justify-between gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
|
||||
<div className="bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
||||
<BotIcon className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<CardTitle
|
||||
className="block w-full min-w-0 overflow-hidden text-base text-ellipsis whitespace-nowrap"
|
||||
title={desensitize(agent.name)}
|
||||
>
|
||||
{desensitize(agent.name)}
|
||||
</CardTitle>
|
||||
{agent.model && (
|
||||
<Badge variant="secondary" className="mt-0.5 text-xs">
|
||||
{desensitize(agent.model)}
|
||||
</Badge>
|
||||
)}
|
||||
<Card
|
||||
className={cn(
|
||||
"group flex min-h-[334px] min-w-0 flex-col gap-0 overflow-hidden rounded-2xl border-slate-200/90 bg-white py-0 shadow-[0_5px_18px_rgba(15,23,42,0.035)] transition-[background-color,border-color,box-shadow] duration-200 hover:!border-primary/30 hover:!bg-primary/5 hover:!ring-1 hover:!ring-primary/10 hover:shadow-[0_8px_24px_rgba(15,23,42,0.08)] dark:border-slate-800 dark:bg-slate-900",
|
||||
agent.featured_order != null && "border-primary/40 ring-1 ring-primary/15 dark:border-primary/45 dark:ring-primary/20",
|
||||
)}
|
||||
>
|
||||
<CardHeader className="min-w-0 gap-0 px-5 pt-5 pb-2">
|
||||
{agent.featured_order != null ? (
|
||||
<>
|
||||
<div className="mb-1 flex h-7 items-center justify-between">
|
||||
<Badge className="border border-primary/20 bg-primary/5 text-primary hover:bg-primary/5 px-2.5 py-1 text-xs font-medium dark:border-primary/40 dark:bg-primary/15 dark:text-primary">
|
||||
<SparklesIcon className="mr-1 size-3.5 fill-current" />
|
||||
推荐
|
||||
</Badge>
|
||||
{cardActionsMenu}
|
||||
</div>
|
||||
<AgentBrandIcon size="lg" />
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-start justify-between">
|
||||
<AgentBrandIcon size="lg" />
|
||||
{cardActionsMenu}
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap items-center justify-end gap-1">
|
||||
{statusBadges}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<CardTitle
|
||||
className="mt-3 block w-full min-w-0 overflow-hidden text-[18px] leading-6 font-semibold tracking-[-0.015em] text-ellipsis whitespace-nowrap text-slate-950 dark:text-white"
|
||||
title={desensitize(agent.name)}
|
||||
>
|
||||
{desensitize(agent.name)}
|
||||
</CardTitle>
|
||||
{agent.description && (
|
||||
<CardDescription className="mt-2 line-clamp-2 text-sm">
|
||||
<CardDescription className="mt-1.5 min-h-11 line-clamp-2 text-[14px] leading-[22px] text-slate-600 dark:text-slate-400">
|
||||
{desensitize(agent.description)}
|
||||
</CardDescription>
|
||||
)}
|
||||
{publisherNode && <div className="mt-2">{publisherNode}</div>}
|
||||
{createdAtNode && <div className="mt-1">{createdAtNode}</div>}
|
||||
</CardHeader>
|
||||
|
||||
{(agent.tags?.length ?? 0) > 0 && (
|
||||
<CardContent className="pt-0 pb-2">
|
||||
<CardContent className="px-5 pt-0 pb-1.5">
|
||||
<TagChipList tags={agent.tags!} />
|
||||
</CardContent>
|
||||
)}
|
||||
|
||||
{hasSkillsOrTools && (
|
||||
<CardContent className="pt-0 pb-2">
|
||||
<CardContent className="px-5 pt-0 pb-2">
|
||||
<ClampedBadgeRow items={skillBadgeItems} />
|
||||
</CardContent>
|
||||
)}
|
||||
|
||||
<CardFooter className="mt-auto flex flex-col items-stretch gap-2 pt-2">
|
||||
{showActionRow && (
|
||||
<div className="flex flex-wrap items-center justify-end gap-1">
|
||||
{actionButtons}
|
||||
</div>
|
||||
)}
|
||||
<CardFooter className="mt-auto flex flex-col items-stretch gap-4 px-5 pt-2 pb-4">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
{cardStatusBadge}
|
||||
<span
|
||||
className="min-w-0 truncate text-xs text-slate-400"
|
||||
title={updatedAtText ? `更新于 ${updatedAtText}` : undefined}
|
||||
>
|
||||
{updatedAtText ? `更新于 ${updatedAtText}` : "最近更新"}
|
||||
{publisherLabel ? ` · 由 ${publisherLabel} 更新` : isBuiltin ? " · 由系统更新" : ""}
|
||||
</span>
|
||||
</div>
|
||||
{chatButton}
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
|
||||
const listLayout = (
|
||||
<div className="group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||
<div className="bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
||||
<BotIcon className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="group flex min-w-0 items-center gap-4 rounded-2xl border border-slate-200/90 bg-white p-4 shadow-[0_8px_24px_rgba(15,23,42,0.04)] transition-all hover:border-primary/25 hover:shadow-[0_12px_32px_rgba(15,23,42,0.09)] dark:border-slate-800 dark:bg-slate-900">
|
||||
<AgentBrandIcon className="agent-avatar" size="md" />
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
@@ -980,7 +1093,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
? "正在加载 SOUL.md..."
|
||||
: "输入 SOUL.md 内容"
|
||||
}
|
||||
className="max-h-[45vh] min-h-48 resize-y font-mono text-xs"
|
||||
className="max-h-[45vh] min-h-48 resize-y text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
|
||||
@@ -260,37 +260,68 @@ export function AgentChatSidebar({ activeAgentId }: { activeAgentId?: string })
|
||||
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",
|
||||
"group relative flex w-full items-start gap-3 rounded-xl border px-3 py-2.5 transition-all duration-150",
|
||||
isActive
|
||||
? "border-primary/40 bg-primary/5"
|
||||
: "border-transparent hover:border-border hover:bg-accent/50",
|
||||
? isDark
|
||||
? "border-[#2b8ffe] bg-[#0b4fae]/65 shadow-[0_0_0_1px_rgba(43,143,254,0.5),0_12px_28px_rgba(37,128,255,0.25)]"
|
||||
: "agent-sidebar-card--active border-primary/50 bg-primary/10 shadow-sm"
|
||||
: isDark
|
||||
? "border-[#2b8ffe]/20 bg-[#042b59]/35 hover:border-[#2b8ffe]/60 hover:bg-[#063b77]/60"
|
||||
: "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"
|
||||
className={cn(
|
||||
"mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-lg text-white shadow-sm",
|
||||
isDark &&
|
||||
isActive &&
|
||||
"ring-2 ring-[#83c1ff]/35 shadow-[0_0_18px_rgba(43,143,254,0.45)]",
|
||||
)}
|
||||
style={{
|
||||
backgroundImage: `linear-gradient(135deg, ${from}, ${to})`,
|
||||
}}
|
||||
>
|
||||
<Bot className="size-[18px]" />
|
||||
<Bot className="size-[19px]" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span
|
||||
className={cn(
|
||||
"block truncate text-[13px] font-semibold",
|
||||
isActive ? "text-primary" : "text-foreground",
|
||||
"block truncate text-[16px] leading-5 font-bold",
|
||||
isActive
|
||||
? isDark
|
||||
? "text-white"
|
||||
: "text-primary"
|
||||
: isDark
|
||||
? "text-white/95"
|
||||
: "text-foreground",
|
||||
)}
|
||||
>
|
||||
{desensitize(agent.name)}
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-[11px] leading-snug text-muted-foreground">
|
||||
<span
|
||||
className={cn(
|
||||
"mt-1 block truncate text-[13px] leading-[1.35]",
|
||||
isDark
|
||||
? isActive
|
||||
? "text-[#d6eaff]"
|
||||
: "text-[#9ebfe2]"
|
||||
: "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" />
|
||||
<span
|
||||
className={cn(
|
||||
"absolute top-1/2 right-1.5 h-8 w-1.5 -translate-y-1/2 rounded-full",
|
||||
isDark
|
||||
? "bg-[#2b8ffe] shadow-[0_0_14px_rgba(43,143,254,0.85)]"
|
||||
: "bg-primary",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
BotIcon,
|
||||
CheckIcon,
|
||||
GlobeIcon,
|
||||
InfoIcon,
|
||||
@@ -43,6 +42,7 @@ import {
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor";
|
||||
import { AgentBrandIcon } from "@/components/workspace/agents/agent-brand-icon";
|
||||
import { AgentRecentChats } from "@/components/workspace/agents/agent-recent-chats";
|
||||
import { useArtifactsOptional } from "@/components/workspace/artifacts";
|
||||
import { EnabledSkillList } from "@/components/workspace/agents/enabled-skill-list";
|
||||
@@ -138,6 +138,7 @@ export function AgentDetailPanel({
|
||||
disabled,
|
||||
defaultCollapsed,
|
||||
showRecentChats,
|
||||
compactAppearanceActions,
|
||||
}: {
|
||||
agent: Agent | null | undefined;
|
||||
agentName: string;
|
||||
@@ -147,6 +148,8 @@ export function AgentDetailPanel({
|
||||
defaultCollapsed?: boolean;
|
||||
/** 在面板底部展示「有关此智能体的最近对话」(仅智能体问答页开启,任务工作区不展示)。 */
|
||||
showRecentChats?: boolean;
|
||||
/** 简洁模式下挂在右上角收起/展开按钮左侧的外观控件。 */
|
||||
compactAppearanceActions?: ReactNode;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [collapsed, setCollapsed] = useState(defaultCollapsed ?? false);
|
||||
@@ -517,9 +520,7 @@ export function AgentDetailPanel({
|
||||
{/* ── Identity / 基础信息 ─────────────────────────────────────────── */}
|
||||
<section className="bg-card/60 rounded-xl border p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="bg-primary/10 ring-primary/15 flex size-12 shrink-0 items-center justify-center rounded-2xl ring-1">
|
||||
<BotIcon className="text-primary size-6" />
|
||||
</div>
|
||||
<AgentBrandIcon className="agent-avatar" size="lg" />
|
||||
<div className="min-w-0 flex-1 space-y-1.5">
|
||||
{editing && draft ? (
|
||||
<Input
|
||||
@@ -827,9 +828,10 @@ export function AgentDetailPanel({
|
||||
const panelChrome = (collapseButton: ReactNode) => (
|
||||
<>
|
||||
<div className="flex h-12 shrink-0 items-center justify-between border-b px-4">
|
||||
<span className="text-sm font-semibold">智能体信息</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="shrink-0 whitespace-nowrap text-sm font-semibold">智能体信息</span>
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
{headerActions}
|
||||
{compactAppearanceActions}
|
||||
{collapseButton}
|
||||
</div>
|
||||
</div>
|
||||
@@ -841,17 +843,20 @@ export function AgentDetailPanel({
|
||||
<>
|
||||
{/* ── Desktop (lg+): inline aside, collapsible to a rail ───────────── */}
|
||||
{collapsed ? (
|
||||
<div className="hidden shrink-0 flex-col items-center border-l pt-3 lg:flex">
|
||||
<Tooltip content="智能体信息">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setCollapsed(false)}
|
||||
aria-label="展开智能体信息"
|
||||
>
|
||||
<PanelRightOpenIcon className="size-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<div className="hidden shrink-0 items-start border-l px-2 pt-3 lg:flex">
|
||||
<div className="flex items-center gap-1">
|
||||
{compactAppearanceActions}
|
||||
<Tooltip content="智能体信息">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setCollapsed(false)}
|
||||
aria-label="展开智能体信息"
|
||||
>
|
||||
<PanelRightOpenIcon className="size-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<aside className="bg-card/40 hidden h-full w-[360px] shrink-0 flex-col border-l lg:flex">
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowDownUpIcon, BotIcon, Loader2, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";
|
||||
import {
|
||||
ArrowDownUpIcon,
|
||||
BotIcon,
|
||||
Loader2,
|
||||
LockIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
ShieldIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
@@ -10,17 +19,17 @@ import { Input } from "@/components/ui/input";
|
||||
import { Pagination } from "@/components/ui/pagination";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
|
||||
import { ViewModeToggle } from "@/components/workspace/view-mode-toggle";
|
||||
import { AgentBrandIcon } from "@/components/workspace/agents/agent-brand-icon";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useAgentsPaginated, usePrivateAgentsPaginated } from "@/core/agents";
|
||||
import type { Agent, AgentSort } from "@/core/agents";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { usePrivateSquareStatus, usePublishSquares, useViewMode } from "@/core/system-settings/hooks";
|
||||
import { usePrivateSquareStatus, usePublishSquares } from "@/core/system-settings/hooks";
|
||||
|
||||
import { AgentCard } from "./agent-card";
|
||||
|
||||
const PAGE_SIZE = 12;
|
||||
type AgentStatusFilter = "all" | "published" | "draft" | "private" | "builtin";
|
||||
|
||||
// Within a single tab the verified password is kept in sessionStorage so a
|
||||
// refresh / route navigation does not re-prompt. Cleared on tab close, so the
|
||||
@@ -32,11 +41,10 @@ export function AgentGallery() {
|
||||
const router = useRouter();
|
||||
// 「内置智能体」筛选仅管理员可见(后端 scope=builtin 也做了 admin 闸门兜底)。
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const [viewMode, setViewMode] = useViewMode("agent");
|
||||
const [activeTab, setActiveTab] = useState<string>("mine");
|
||||
const [search, setSearch] = useState("");
|
||||
const [tagIds, setTagIds] = useState<string[]>([]);
|
||||
const [sort, setSort] = useState<AgentSort>("time_desc");
|
||||
const [statusFilter, setStatusFilter] = useState<AgentStatusFilter>("all");
|
||||
const { data: publishSquares } = usePublishSquares();
|
||||
// Each configured publish square (发布广场) becomes its own browse tab; the
|
||||
// backend always returns at least one (the built-in default).
|
||||
@@ -53,10 +61,9 @@ export function AgentGallery() {
|
||||
// frontend's desensitize map, so typing the displayed abbreviation (e.g.
|
||||
// "TS") still matches the stored raw name (e.g. "态势分析"). Whenever the
|
||||
// filters change, every tab returns to its first page.
|
||||
const tagKey = tagIds.join(",");
|
||||
useEffect(() => {
|
||||
setPages({});
|
||||
}, [search, tagKey, sort, publisher?.id]);
|
||||
}, [search, sort, publisher?.id, statusFilter]);
|
||||
|
||||
// If the active square tab disappears (admin removed that square), fall back
|
||||
// to "我的" so the gallery never points at a dead tab.
|
||||
@@ -108,7 +115,6 @@ export function AgentGallery() {
|
||||
} = useAgentsPaginated({
|
||||
scope: mainScope,
|
||||
search,
|
||||
tagIds,
|
||||
sort,
|
||||
page: mainPage,
|
||||
pageSize: PAGE_SIZE,
|
||||
@@ -126,7 +132,6 @@ export function AgentGallery() {
|
||||
error: privateError,
|
||||
} = usePrivateAgentsPaginated(privatePassword, {
|
||||
search,
|
||||
tagIds,
|
||||
sort,
|
||||
page: pages.private ?? 1,
|
||||
pageSize: PAGE_SIZE,
|
||||
@@ -177,21 +182,22 @@ export function AgentGallery() {
|
||||
const handlePublisherClick = (p: { id: string; label: string }) =>
|
||||
setPublisher(p);
|
||||
|
||||
const renderGrid = (list: Agent[]) =>
|
||||
viewMode === "list" ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{list.map((agent) => (
|
||||
<AgentCard
|
||||
key={agent.id}
|
||||
agent={agent}
|
||||
layout="list"
|
||||
onPublisherClick={handlePublisherClick}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{list.map((agent) => (
|
||||
const filterByStatus = (agent: Agent) => {
|
||||
if (statusFilter === "published") return agent.published && !agent.is_private;
|
||||
if (statusFilter === "draft") return !agent.published && !agent.is_private && !agent.builtin;
|
||||
if (statusFilter === "private") return agent.is_private;
|
||||
if (statusFilter === "builtin") return agent.builtin;
|
||||
return true;
|
||||
};
|
||||
|
||||
const renderGrid = (list: Agent[]) => {
|
||||
const visibleAgents = list.filter(filterByStatus);
|
||||
if (visibleAgents.length === 0 && list.length > 0) {
|
||||
return renderEmpty("当前状态筛选下没有智能体。");
|
||||
}
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
{visibleAgents.map((agent) => (
|
||||
<AgentCard
|
||||
key={agent.id}
|
||||
agent={agent}
|
||||
@@ -200,6 +206,7 @@ export function AgentGallery() {
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
/** Loading / empty / (grid + pagination) for one paginated tab. */
|
||||
const renderListBody = (opts: {
|
||||
@@ -264,20 +271,17 @@ export function AgentGallery() {
|
||||
};
|
||||
|
||||
const renderEmpty = (description: string, showNewButton = false) => (
|
||||
<div className="flex h-64 flex-col items-center justify-center gap-3 text-center">
|
||||
<div className="bg-muted flex h-14 w-14 items-center justify-center rounded-full dark:bg-[#022248]">
|
||||
<BotIcon className="text-muted-foreground h-7 w-7 dark:text-[#AACEFF]" />
|
||||
</div>
|
||||
<div className="flex h-72 flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-primary/25 bg-white/70 text-center shadow-[0_12px_36px_rgba(15,23,42,0.05)] dark:border-primary/40 dark:bg-slate-900/70">
|
||||
<AgentBrandIcon size="lg" />
|
||||
<div>
|
||||
<p className="font-medium dark:text-[#AACEFF]">{t.agents.emptyTitle}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm dark:text-[#55A6FE]">
|
||||
<p className="font-medium">{t.agents.emptyTitle}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
{showNewButton && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="mt-2 dark:border-[#2580FF] dark:bg-[#2580FF] dark:text-white dark:hover:border-[#2580FF] dark:hover:bg-[#2580FF]/90 dark:hover:text-white"
|
||||
className="bg-primary hover:bg-primary/90 mt-2 rounded-xl px-5 text-primary-foreground shadow-[0_8px_20px_rgba(15,23,42,0.16)]"
|
||||
onClick={handleNewAgent}
|
||||
>
|
||||
<PlusIcon className="mr-1.5 h-4 w-4" />
|
||||
@@ -364,17 +368,22 @@ export function AgentGallery() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex size-full min-h-0 flex-col">
|
||||
<div className="flex size-full min-h-0 flex-col overflow-hidden bg-white dark:bg-slate-950">
|
||||
{/* Page header */}
|
||||
<div className="flex items-center justify-between border-b px-6 py-4">
|
||||
<div className="flex shrink-0 items-start justify-between px-5 pt-7 pb-6 sm:px-8">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold">{t.agents.title}</h1>
|
||||
<p className="text-muted-foreground mt-0.5 text-sm">
|
||||
{t.agents.description}
|
||||
<h1 className="text-[26px] leading-none font-semibold tracking-[-0.03em] text-slate-950 dark:text-white">
|
||||
{t.agents.title}
|
||||
</h1>
|
||||
<p className="mt-2.5 text-[15px] text-slate-500 dark:text-slate-400">
|
||||
创建并管理专属的 AI 智能体,助力更高效的工作与决策。
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={handleNewAgent}>
|
||||
<PlusIcon className="mr-1.5 h-4 w-4" />
|
||||
<Button
|
||||
onClick={handleNewAgent}
|
||||
className="bg-primary hover:bg-primary/90 h-11 w-[148px] rounded-xl px-0 text-[15px] font-medium text-primary-foreground shadow-[0_9px_22px_rgba(15,23,42,0.16)]"
|
||||
>
|
||||
<PlusIcon className="mr-2 h-[18px] w-[18px]" />
|
||||
{t.agents.newAgent}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -384,43 +393,99 @@ export function AgentGallery() {
|
||||
value={activeTab}
|
||||
onValueChange={(v) => {
|
||||
setActiveTab(v);
|
||||
// Each tab starts from a clean slate: switching tabs clears the
|
||||
// keyword / tag / sort / publisher filters instead of carrying them
|
||||
// over. The TagSearchBar's own input box is reset via its key below.
|
||||
// Each tab starts from a clean slate instead of carrying filters over.
|
||||
setSearch("");
|
||||
setTagIds([]);
|
||||
setSort("time_desc");
|
||||
setStatusFilter("all");
|
||||
setPublisher(null);
|
||||
}}
|
||||
className="flex min-h-0 flex-1 flex-col overflow-hidden"
|
||||
>
|
||||
<div className="mx-6 mt-4 flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<TabsList className="w-auto max-w-full flex-wrap justify-start self-start">
|
||||
<TabsTrigger value="mine">我的</TabsTrigger>
|
||||
<div className="shrink-0 px-5 sm:px-8">
|
||||
<div className="flex min-h-12 flex-col gap-3 border-b border-slate-200/90 lg:flex-row lg:items-end lg:justify-between dark:border-slate-800">
|
||||
<TabsList variant="line" className="h-auto w-auto max-w-full flex-wrap justify-start self-start rounded-none border-0 bg-transparent p-0">
|
||||
<TabsTrigger
|
||||
value="mine"
|
||||
className="h-12 rounded-none border-x-0 border-t-0 border-b-2 border-transparent bg-transparent px-3 text-[15px] shadow-none after:hidden data-[state=active]:border-x-0 data-[state=active]:border-t-0 data-[state=active]:!border-b-primary data-[state=active]:bg-transparent data-[state=active]:text-primary data-[state=active]:!shadow-none"
|
||||
>
|
||||
我的
|
||||
</TabsTrigger>
|
||||
{squareTabs.map((sq) => (
|
||||
<TabsTrigger key={sq.id} value={sq.id} title={sq.description || sq.name}>
|
||||
<TabsTrigger
|
||||
key={sq.id}
|
||||
value={sq.id}
|
||||
title={sq.description || sq.name}
|
||||
className="h-12 rounded-none border-x-0 border-t-0 border-b-2 border-transparent bg-transparent px-5 text-[15px] shadow-none after:hidden data-[state=active]:border-x-0 data-[state=active]:border-t-0 data-[state=active]:!border-b-primary data-[state=active]:bg-transparent data-[state=active]:text-primary data-[state=active]:!shadow-none"
|
||||
>
|
||||
{sq.name}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
{privateFeatureAvailable && (
|
||||
<TabsTrigger value="private">
|
||||
<TabsTrigger
|
||||
value="private"
|
||||
className="h-12 rounded-none border-x-0 border-t-0 border-b-2 border-transparent bg-transparent px-5 text-[15px] shadow-none after:hidden data-[state=active]:border-x-0 data-[state=active]:border-t-0 data-[state=active]:!border-b-primary data-[state=active]:bg-transparent data-[state=active]:text-primary data-[state=active]:!shadow-none"
|
||||
>
|
||||
<LockIcon className="mr-1 h-3.5 w-3.5" />
|
||||
私密广场
|
||||
</TabsTrigger>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<TabsTrigger value="builtin" title="内置/功能型智能体(仅管理员可见)">
|
||||
<TabsTrigger
|
||||
value="builtin"
|
||||
title="内置/功能型智能体(仅管理员可见)"
|
||||
className="h-12 rounded-none border-x-0 border-t-0 border-b-2 border-transparent bg-transparent px-5 text-[15px] shadow-none after:hidden data-[state=active]:border-x-0 data-[state=active]:border-t-0 data-[state=active]:!border-b-primary data-[state=active]:bg-transparent data-[state=active]:text-primary data-[state=active]:!shadow-none"
|
||||
>
|
||||
<BotIcon className="mr-1 h-3.5 w-3.5" />
|
||||
内置智能体
|
||||
</TabsTrigger>
|
||||
)}
|
||||
</TabsList>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-muted-foreground text-sm whitespace-nowrap">
|
||||
共 {activeTotal} 个
|
||||
</span>
|
||||
<ViewModeToggle value={viewMode} onChange={setViewMode} />
|
||||
{showSearchBar && (
|
||||
<div className="flex flex-wrap items-center justify-end gap-3 pb-2">
|
||||
<div className="relative w-[320px] max-w-full">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3.5 size-[18px] -translate-y-1/2 text-slate-500" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="搜索智能体名称或描述"
|
||||
className="h-11 rounded-xl border-slate-200 bg-white pl-11 text-sm shadow-none placeholder:text-slate-400 focus-visible:border-primary/50 focus-visible:ring-primary/15 dark:border-slate-700 dark:bg-slate-900"
|
||||
/>
|
||||
{(activeTab === "private" ? isPrivateFetching : mainFetching) && (
|
||||
<Loader2 className="text-primary absolute top-1/2 right-3.5 size-4 -translate-y-1/2 animate-spin" />
|
||||
)}
|
||||
</div>
|
||||
<Select
|
||||
value={statusFilter}
|
||||
onValueChange={(value) => setStatusFilter(value as AgentStatusFilter)}
|
||||
>
|
||||
<SelectTrigger className="h-11 w-[150px] rounded-xl border-slate-200 px-4 text-sm shadow-none dark:border-slate-700">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper" side="bottom" sideOffset={4}>
|
||||
<SelectItem value="all">全部状态</SelectItem>
|
||||
<SelectItem value="published">已发布</SelectItem>
|
||||
<SelectItem value="draft">未发布</SelectItem>
|
||||
<SelectItem value="private">私密</SelectItem>
|
||||
<SelectItem value="builtin">内置</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={sort} onValueChange={(v) => setSort(v as AgentSort)}>
|
||||
<SelectTrigger
|
||||
className="h-11 w-[150px] rounded-xl border-slate-200 px-4 text-sm shadow-none dark:border-slate-700"
|
||||
title="排序"
|
||||
>
|
||||
<ArrowDownUpIcon className="mr-1 size-4 text-slate-500" />
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper" side="bottom" sideOffset={4}>
|
||||
<SelectItem value="time_desc">更新时间</SelectItem>
|
||||
<SelectItem value="time_asc">最早创建</SelectItem>
|
||||
<SelectItem value="updated_desc">最近更新</SelectItem>
|
||||
<SelectItem value="updated_asc">最早更新</SelectItem>
|
||||
<SelectItem value="name_asc">名称 A-Z</SelectItem>
|
||||
<SelectItem value="name_desc">名称 Z-A</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{activeTab === "private" && privatePassword && (
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -432,48 +497,16 @@ export function AgentGallery() {
|
||||
锁定
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{showSearchBar && (
|
||||
<TagSearchBar
|
||||
// Remount per tab so the internal keyword input / 展开 state also
|
||||
// resets when the parent-owned filters are cleared on tab switch.
|
||||
key={activeTab}
|
||||
targetType="agent"
|
||||
searching={
|
||||
activeTab === "private" ? isPrivateFetching : mainFetching
|
||||
}
|
||||
onSearchChange={setSearch}
|
||||
tagIds={tagIds}
|
||||
onTagIdsChange={setTagIds}
|
||||
actions={
|
||||
<Select value={sort} onValueChange={(v) => setSort(v as AgentSort)}>
|
||||
<SelectTrigger
|
||||
className="h-9 w-full gap-2 px-3 text-xs sm:w-[148px]"
|
||||
title="排序"
|
||||
>
|
||||
<ArrowDownUpIcon className="text-muted-foreground size-3.5" />
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper" side="bottom" sideOffset={4}>
|
||||
<SelectItem value="time_desc">最新创建</SelectItem>
|
||||
<SelectItem value="time_asc">最早创建</SelectItem>
|
||||
<SelectItem value="updated_desc">最近更新</SelectItem>
|
||||
<SelectItem value="updated_asc">最早更新</SelectItem>
|
||||
<SelectItem value="name_asc">名称 A-Z</SelectItem>
|
||||
<SelectItem value="name_desc">名称 Z-A</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{publisher && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<span className="text-muted-foreground text-xs">筛选发布者:</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPublisher(null)}
|
||||
className="bg-primary/10 text-primary hover:bg-primary/20 inline-flex items-center gap-1 rounded-full px-3 py-1 text-xs font-medium transition-colors"
|
||||
className="bg-primary/5 text-primary hover:bg-primary/10 inline-flex items-center gap-1 rounded-full px-3 py-1 text-xs font-medium transition-colors dark:bg-primary/15 dark:text-primary"
|
||||
title="点击清除发布者筛选"
|
||||
>
|
||||
{publisher.label}
|
||||
@@ -481,13 +514,16 @@ export function AgentGallery() {
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="py-4 text-[15px] text-slate-600 dark:text-slate-300">
|
||||
共 {activeTotal} 个智能体
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{squareTabs.map((sq) => (
|
||||
<TabsContent
|
||||
key={sq.id}
|
||||
value={sq.id}
|
||||
className="flex-1 overflow-y-auto p-6 mt-0"
|
||||
className="mt-0 flex-1 overflow-y-auto px-5 pb-6 sm:px-8"
|
||||
>
|
||||
{renderListBody({
|
||||
list: mainAgents,
|
||||
@@ -500,7 +536,7 @@ export function AgentGallery() {
|
||||
</TabsContent>
|
||||
))}
|
||||
|
||||
<TabsContent value="mine" className="flex-1 overflow-y-auto p-6 mt-0">
|
||||
<TabsContent value="mine" className="mt-0 flex-1 overflow-y-auto px-5 pb-6 sm:px-8">
|
||||
{renderListBody({
|
||||
list: mainAgents,
|
||||
total: mainTotal,
|
||||
@@ -513,7 +549,7 @@ export function AgentGallery() {
|
||||
</TabsContent>
|
||||
|
||||
{isAdmin && (
|
||||
<TabsContent value="builtin" className="flex-1 overflow-y-auto p-6 mt-0">
|
||||
<TabsContent value="builtin" className="mt-0 flex-1 overflow-y-auto px-5 pb-6 sm:px-8">
|
||||
{renderListBody({
|
||||
list: mainAgents,
|
||||
total: mainTotal,
|
||||
@@ -528,7 +564,7 @@ export function AgentGallery() {
|
||||
{privateFeatureAvailable && (
|
||||
<TabsContent
|
||||
value="private"
|
||||
className="flex-1 overflow-y-auto p-6 mt-0"
|
||||
className="mt-0 flex-1 overflow-y-auto px-5 pb-6 sm:px-8"
|
||||
>
|
||||
{renderPrivateTab()}
|
||||
</TabsContent>
|
||||
|
||||
@@ -138,7 +138,7 @@ export function AgentModuleSettingsDialog({
|
||||
key={agent.id}
|
||||
className="flex items-start gap-3 rounded-xl border border-border/60 bg-card p-3"
|
||||
>
|
||||
<div className="bg-primary/10 text-primary mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg">
|
||||
<div className="agent-avatar bg-primary/10 text-primary mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg">
|
||||
<Bot className="size-4" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
|
||||
@@ -211,34 +211,72 @@ export function AgentModuleSidebar({
|
||||
<Link
|
||||
key={`${keyPrefix}:${agent.id}`}
|
||||
href={href}
|
||||
onClick={() => {
|
||||
try {
|
||||
sessionStorage.setItem(`agent-module:${moduleKey}:last-agent`, agent.id);
|
||||
} catch {
|
||||
// Ignore storage failures; route navigation is the source of truth.
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
"group relative flex w-full items-start gap-2.5 rounded-xl border px-2.5 py-2 transition-colors",
|
||||
"group relative flex w-full items-start gap-3 rounded-xl border px-3 py-2.5 transition-all duration-150",
|
||||
isActive
|
||||
? "border-primary/40 bg-primary/5"
|
||||
: "border-transparent hover:border-border hover:bg-accent/50",
|
||||
? isDark
|
||||
? "border-[#2b8ffe] bg-[#0b4fae]/65 shadow-[0_0_0_1px_rgba(43,143,254,0.5),0_12px_28px_rgba(37,128,255,0.25)]"
|
||||
: "agent-sidebar-card--active border-primary/50 bg-primary/10 shadow-sm"
|
||||
: isDark
|
||||
? "border-[#2b8ffe]/20 bg-[#042b59]/35 hover:border-[#2b8ffe]/60 hover:bg-[#063b77]/60"
|
||||
: "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"
|
||||
className={cn(
|
||||
"mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-lg text-white shadow-sm",
|
||||
isDark &&
|
||||
isActive &&
|
||||
"ring-2 ring-[#83c1ff]/35 shadow-[0_0_18px_rgba(43,143,254,0.45)]",
|
||||
)}
|
||||
style={{ backgroundImage: `linear-gradient(135deg, ${from}, ${to})` }}
|
||||
>
|
||||
<Bot className="size-[18px]" />
|
||||
<Bot className="size-[19px]" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span
|
||||
className={cn(
|
||||
"block truncate text-[13px] font-semibold",
|
||||
isActive ? "text-primary" : "text-foreground",
|
||||
"block truncate text-[16px] leading-5 font-bold",
|
||||
isActive
|
||||
? isDark
|
||||
? "text-white"
|
||||
: "text-primary"
|
||||
: isDark
|
||||
? "text-white/95"
|
||||
: "text-foreground",
|
||||
)}
|
||||
>
|
||||
{desensitize(agent.name)}
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-[11px] leading-snug text-muted-foreground">
|
||||
<span
|
||||
className={cn(
|
||||
"mt-1 block truncate text-[13px] leading-[1.35]",
|
||||
isDark
|
||||
? isActive
|
||||
? "text-[#d6eaff]"
|
||||
: "text-[#9ebfe2]"
|
||||
: "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" />
|
||||
<span
|
||||
className={cn(
|
||||
"absolute top-1/2 right-1.5 h-8 w-1.5 -translate-y-1/2 rounded-full",
|
||||
isDark
|
||||
? "bg-[#2b8ffe] shadow-[0_0_14px_rgba(43,143,254,0.85)]"
|
||||
: "bg-primary",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
|
||||
@@ -93,47 +93,43 @@ export function AgentSelector({
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
{iconMode ? (
|
||||
<Tooltip content={iconTooltipLabel}>
|
||||
<div>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={disabled}
|
||||
aria-label={selectedAgent ? `已选择智能体:${triggerLabel}` : "选择智能体"}
|
||||
className={cn(
|
||||
"relative size-9 rounded-full text-muted-foreground shadow-none hover:bg-muted/60 hover:text-foreground",
|
||||
selectedAgent && "text-amber-600 hover:text-amber-700",
|
||||
selectedAgent && iconActiveClassName,
|
||||
iconButtonClassName,
|
||||
)}
|
||||
>
|
||||
<BotIcon className="size-4" />
|
||||
{selectedAgent && (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="清除已选 agent"
|
||||
className="absolute -right-1 -top-1 inline-flex size-4 items-center justify-center rounded-full border bg-background text-foreground shadow-sm hover:bg-muted"
|
||||
onClick={handleClear}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
onAgentChange(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XIcon className="size-2.5" />
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<DialogTrigger asChild>
|
||||
<DialogTrigger asChild>
|
||||
{iconMode ? (
|
||||
<Tooltip content={iconTooltipLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={disabled}
|
||||
aria-label={selectedAgent ? `已选择智能体:${triggerLabel}` : "选择智能体"}
|
||||
className={cn(
|
||||
"relative size-9 rounded-full text-muted-foreground shadow-none hover:bg-muted/60 hover:text-foreground",
|
||||
selectedAgent && "text-amber-600 hover:text-amber-700",
|
||||
selectedAgent && iconActiveClassName,
|
||||
iconButtonClassName,
|
||||
)}
|
||||
>
|
||||
<BotIcon className="size-4" />
|
||||
{selectedAgent && (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="清除已选 agent"
|
||||
className="absolute -right-1 -top-1 inline-flex size-4 items-center justify-center rounded-full border bg-background text-foreground shadow-sm hover:bg-muted"
|
||||
onClick={handleClear}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
onAgentChange(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<XIcon className="size-2.5" />
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<PromptInputButton
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
@@ -171,8 +167,8 @@ export function AgentSelector({
|
||||
</span>
|
||||
)}
|
||||
</PromptInputButton>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="overflow-hidden p-0 sm:max-w-md">
|
||||
<DialogTitle className="sr-only">选择 Agent</DialogTitle>
|
||||
<Command className="**:data-[slot=command-input-wrapper]:h-auto">
|
||||
|
||||
@@ -45,32 +45,11 @@ function skillLabel(skill: Skill) {
|
||||
|
||||
function matchesQuery(skill: Skill, q: string) {
|
||||
if (!q) return true;
|
||||
const haystack = [
|
||||
skill.name,
|
||||
skill.name_zh,
|
||||
skill.description,
|
||||
skill.detail,
|
||||
skill.category,
|
||||
skill.license,
|
||||
skill.source,
|
||||
skill.state,
|
||||
skill.owner_username,
|
||||
skill.created_at,
|
||||
skill.last_activity_at,
|
||||
skill.use_count != null ? `使用 ${skill.use_count}` : null,
|
||||
skill.view_count != null ? `查看 ${skill.view_count}` : null,
|
||||
skill.patch_count != null ? `变迁 ${skill.patch_count}` : null,
|
||||
...(skill.tags ?? []).flatMap((tag) => [
|
||||
tag.name,
|
||||
tag.description,
|
||||
tag.color,
|
||||
tag.usage_count != null ? `标签使用 ${tag.usage_count}` : null,
|
||||
]),
|
||||
]
|
||||
.filter((value): value is string => typeof value === "string" && value.length > 0)
|
||||
.join(" ")
|
||||
.toLowerCase();
|
||||
return haystack.includes(q);
|
||||
return (
|
||||
skill.name.toLowerCase().includes(q) ||
|
||||
(skill.name_zh ?? "").toLowerCase().includes(q) ||
|
||||
(skill.description ?? "").toLowerCase().includes(q)
|
||||
);
|
||||
}
|
||||
|
||||
export function SkillTransferSelector({
|
||||
@@ -180,7 +159,7 @@ export function SkillTransferSelector({
|
||||
<div className="relative flex-1">
|
||||
<SearchIcon className="text-muted-foreground absolute left-2 top-1/2 size-3.5 -translate-y-1/2" />
|
||||
<Input
|
||||
placeholder="搜索技能名称、描述、分类、标签、变迁..."
|
||||
placeholder="搜索全部技能(中英文名称、描述)…"
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.currentTarget.value);
|
||||
@@ -260,7 +239,7 @@ export function SkillTransferSelector({
|
||||
{/* Two-column transfer panes */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<SkillPane
|
||||
title="未勾选技能"
|
||||
title="可用技能"
|
||||
count={availableSkills.length}
|
||||
items={availableView}
|
||||
variant="available"
|
||||
@@ -269,10 +248,10 @@ export function SkillTransferSelector({
|
||||
onPageChange={setAvailablePage}
|
||||
onPick={add}
|
||||
onViewDetail={onViewDetail}
|
||||
emptyHint={query || category !== ALL_CATEGORIES ? "没有匹配的技能" : "已全部勾选"}
|
||||
emptyHint={query || category !== ALL_CATEGORIES ? "没有匹配的技能" : "已全部启用"}
|
||||
/>
|
||||
<SkillPane
|
||||
title="已勾选技能"
|
||||
title="已启用技能"
|
||||
count={selectedSkills.length}
|
||||
items={selectedView}
|
||||
variant="selected"
|
||||
@@ -281,7 +260,7 @@ export function SkillTransferSelector({
|
||||
onPageChange={setSelectedPage}
|
||||
onPick={remove}
|
||||
onViewDetail={onViewDetail}
|
||||
emptyHint={query ? "没有匹配的已选技能" : "尚未勾选任何技能"}
|
||||
emptyHint={query ? "没有匹配的已选技能" : "尚未启用任何技能"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Check, LayoutIcon, PanelLeftIcon, Shirt } from "lucide-react";
|
||||
import { Check, ExternalLink, LayoutIcon, PanelLeftIcon, Shirt } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
@@ -14,8 +14,10 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { useTheme, type ThemeType } from "@/contexts/ThemeContext";
|
||||
import { useLayoutMode } from "@/core/system-settings/hooks";
|
||||
import { env } from "@/env";
|
||||
import { useAppearanceSettings, useLayoutMode } from "@/core/system-settings/hooks";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { buildLightAppUrl } from "@/strategy-components/lib/light-app";
|
||||
|
||||
/**
|
||||
* 换肤 / 界面模式 顶栏控件。深色顶栏(Header)与简洁模式页面级顶栏(ChatPage 等)共用,
|
||||
@@ -25,9 +27,10 @@ import { cn } from "@/lib/utils";
|
||||
*/
|
||||
export type AppearanceControlTone = "banner-dark" | "banner-light" | "content";
|
||||
|
||||
// 换肤色板:红色=红白主题(light),蓝色=浅蓝主题(lightblue),深蓝色=深色主题(dark)
|
||||
// 换肤色板:红色=红白主题(light),绿色=WeKnora 绿色主题(lightgreen),蓝色=浅蓝主题(lightblue),深蓝色=深色主题(dark)
|
||||
export const THEME_SWATCHES: { id: ThemeType; label: string; color: string }[] = [
|
||||
{ id: "light", label: "红色", color: "#cf1322" },
|
||||
{ id: "lightgreen", label: "绿色", color: "#07c05f" },
|
||||
{ id: "lightblue", label: "蓝色", color: "#0062d9" },
|
||||
{ id: "dark", label: "深蓝色", color: "#002466" },
|
||||
];
|
||||
@@ -39,7 +42,46 @@ const triggerToneClass = (tone: AppearanceControlTone) =>
|
||||
? "text-white hover:bg-[var(--brand-950)] hover:text-white active:bg-[#8a0618]"
|
||||
: "text-muted-foreground hover:bg-muted hover:text-foreground";
|
||||
|
||||
export function CompactShortcutButtons({ tone }: { tone: AppearanceControlTone }) {
|
||||
const { data: appearance } = useAppearanceSettings();
|
||||
const buttons = (appearance?.compact_shortcut_buttons ?? [])
|
||||
.filter((button) => button.enabled && button.label.trim() && button.url.trim())
|
||||
.sort((a, b) => a.sort_order - b.sort_order);
|
||||
|
||||
if (buttons.length === 0) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{buttons.map((button) => (
|
||||
<Button
|
||||
key={button.id}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(
|
||||
"h-8 max-w-[168px] shrink-0 gap-1.5 rounded-sm px-2 text-xs font-medium",
|
||||
triggerToneClass(tone),
|
||||
)}
|
||||
title={button.label}
|
||||
onClick={() => {
|
||||
const url = buildLightAppUrl({
|
||||
url: button.url,
|
||||
routeParams: button.route_params.map((param) => ({ ...param })),
|
||||
});
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
}}
|
||||
>
|
||||
<ExternalLink className="size-4 shrink-0" />
|
||||
<span className="truncate">{button.label}</span>
|
||||
</Button>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThemeSwitcher({ tone }: { tone: AppearanceControlTone }) {
|
||||
if (env.FORCE_COLLAPSED_SIDEBAR) return null;
|
||||
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [open, setOpen] = useState(false);
|
||||
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
@@ -136,10 +178,14 @@ const LAYOUT_OPTIONS = [
|
||||
export function LayoutModeSwitcher({
|
||||
tone,
|
||||
fallback = "compact",
|
||||
navigateTo = "/page/workspace/chats/new",
|
||||
}: {
|
||||
tone: AppearanceControlTone;
|
||||
fallback?: "full" | "compact";
|
||||
navigateTo?: string | null;
|
||||
}) {
|
||||
if (env.FORCE_COLLAPSED_SIDEBAR) return null;
|
||||
|
||||
const [mode, setLayoutMode] = useLayoutMode();
|
||||
const navigate = useNavigate();
|
||||
const current = mode ?? fallback;
|
||||
@@ -170,7 +216,9 @@ export function LayoutModeSwitcher({
|
||||
key={option.id}
|
||||
onClick={() => {
|
||||
setLayoutMode(option.id);
|
||||
navigate("/page/workspace/chats/new");
|
||||
if (navigateTo) {
|
||||
navigate(navigateTo);
|
||||
}
|
||||
}}
|
||||
className="gap-2"
|
||||
>
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
LoaderIcon,
|
||||
PackageIcon,
|
||||
SaveIcon,
|
||||
SparklesIcon,
|
||||
UploadCloudIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
@@ -37,9 +38,11 @@ import {
|
||||
} from "@/components/ui/select";
|
||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
||||
import { CodeEditor } from "@/components/workspace/code-editor";
|
||||
import { MarkdownAiEditor } from "@/open-canvas/components/artifact/MarkdownAiEditor";
|
||||
import { publishArtifactToKnowledge } from "@/core/agents/api";
|
||||
import { useAgent } from "@/core/agents/hooks";
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { copyTextToClipboard } from "@/core/clipboard";
|
||||
import {
|
||||
downloadArtifactFile,
|
||||
} from "@/core/artifacts/download";
|
||||
@@ -213,6 +216,10 @@ export function ArtifactFileDetail({
|
||||
!useWriteFileStreaming &&
|
||||
!isSkillFile &&
|
||||
!isMock;
|
||||
// 「AI 写作」md 展示开关:只要是可编辑的 markdown 就提供「AI 写作」视图(在 源码/预览 旁多一个
|
||||
// 切换项),用户可随时切过去体验划词「AI 改写」。默认仍是「预览」,避免编辑器在内容加载期间
|
||||
// 挂载导致白屏 + 避免复杂 md(表格/公式/HTML)误入有损编辑。
|
||||
const canUseAiEditor = canEditArtifact;
|
||||
const [draftContent, setDraftContent] = useState("");
|
||||
const [hasLocalEdits, setHasLocalEdits] = useState(false);
|
||||
const updateArtifact = useUpdateArtifactContent();
|
||||
@@ -230,7 +237,7 @@ export function ArtifactFileDetail({
|
||||
return "FILE";
|
||||
}, [filepath, isSkillFile, isSpreadsheetFile, language]);
|
||||
|
||||
const [viewMode, setViewMode] = useState<"code" | "preview">("code");
|
||||
const [viewMode, setViewMode] = useState<"code" | "preview" | "edit">("code");
|
||||
const [allowAutoViewSwitch, setAllowAutoViewSwitch] = useState(true);
|
||||
const [installDialogOpen, setInstallDialogOpen] = useState(false);
|
||||
const [showPreviewSwitchPulse, setShowPreviewSwitchPulse] = useState(false);
|
||||
@@ -267,6 +274,7 @@ export function ArtifactFileDetail({
|
||||
return;
|
||||
}
|
||||
|
||||
// md/mermaid 默认预览(AI 写作视图作为可选切换项,由用户手动进入)。
|
||||
if (isSupportPreview) {
|
||||
setViewMode("preview");
|
||||
return;
|
||||
@@ -576,7 +584,9 @@ export function ArtifactFileDetail({
|
||||
{fileTypeLabel}
|
||||
</span>
|
||||
<ArtifactTitle className="min-w-0">
|
||||
{useWriteFileStreaming ? (
|
||||
{/* markdown:隐藏文件名(仅留 MD 徽标),把横向空间让给工具栏,避免窄面板下
|
||||
工具栏换行错位;多文件仍保留切换下拉(靠它切文件)。文件名仍可在下载/另存为时取到。 */}
|
||||
{language === "markdown" && !hasMultipleArtifacts ? null : useWriteFileStreaming ? (
|
||||
<div className="truncate px-3">{getFileName(filepath)}</div>
|
||||
) : hasMultipleArtifacts ? (
|
||||
<Select value={filepath} onValueChange={select}>
|
||||
@@ -616,10 +626,19 @@ export function ArtifactFileDetail({
|
||||
onValueChange={(value) => {
|
||||
if (value) {
|
||||
setAllowAutoViewSwitch(false);
|
||||
setViewMode(value as "code" | "preview");
|
||||
setViewMode(value as "code" | "preview" | "edit");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{canUseAiEditor && (
|
||||
<ToggleGroupItem
|
||||
className="text-muted-foreground h-8 min-w-10 rounded-full border-0 bg-transparent px-3 shadow-none data-[state=on]:bg-background data-[state=on]:text-foreground data-[state=on]:shadow-[0_6px_14px_-10px_rgba(15,23,42,0.35)]"
|
||||
value="edit"
|
||||
aria-label="AI 写作编辑"
|
||||
>
|
||||
<SparklesIcon />
|
||||
</ToggleGroupItem>
|
||||
)}
|
||||
<ToggleGroupItem
|
||||
className="text-muted-foreground h-8 min-w-10 rounded-full border-0 bg-transparent px-3 shadow-none data-[state=on]:bg-background data-[state=on]:text-foreground data-[state=on]:shadow-[0_6px_14px_-10px_rgba(15,23,42,0.35)]"
|
||||
value="code"
|
||||
@@ -682,7 +701,7 @@ export function ArtifactFileDetail({
|
||||
disabled={!content}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(displayContent ?? "");
|
||||
await copyTextToClipboard(displayContent ?? "");
|
||||
toast.success(t.clipboard.copiedToClipboard);
|
||||
} catch (error) {
|
||||
toast.error("Failed to copy to clipboard");
|
||||
@@ -692,7 +711,7 @@ export function ArtifactFileDetail({
|
||||
tooltip={t.clipboard.copyToClipboard}
|
||||
/>
|
||||
)}
|
||||
{!useWriteFileStreaming && language === "markdown" && (
|
||||
{language === "markdown" && (
|
||||
<ArtifactAction
|
||||
icon={isExportingWord ? LoaderIcon : FileType2Icon}
|
||||
label="另存为 Word"
|
||||
@@ -780,6 +799,17 @@ export function ArtifactFileDetail({
|
||||
滑动到底部并继续自动下滑
|
||||
</button>
|
||||
)}
|
||||
{viewMode === "edit" && canUseAiEditor && (
|
||||
<MarkdownAiEditor
|
||||
// 编辑用原始内容(与源码模式一致,不脱敏);保存仍走头部「保存 Markdown」按钮。
|
||||
markdown={displayContent ?? ""}
|
||||
onChange={(value) => {
|
||||
setDraftContent(value);
|
||||
setHasLocalEdits(true);
|
||||
}}
|
||||
threadId={threadId}
|
||||
/>
|
||||
)}
|
||||
{isSupportPreview &&
|
||||
viewMode === "preview" &&
|
||||
(language === "markdown" ||
|
||||
|
||||
@@ -423,6 +423,7 @@ const ChatBox: React.FC<{
|
||||
className="size-full"
|
||||
filepath={selectedArtifact}
|
||||
threadId={threadId}
|
||||
allowVirtualMarkdownEdit
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="references" className="min-h-0 flex-1 overflow-y-auto p-0">
|
||||
@@ -437,6 +438,7 @@ const ChatBox: React.FC<{
|
||||
className="size-full"
|
||||
filepath={selectedArtifact}
|
||||
threadId={threadId}
|
||||
allowVirtualMarkdownEdit
|
||||
/>
|
||||
) : hasCitationReferences ? (
|
||||
<div className="relative size-full overflow-hidden">
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
BookOpenCheck,
|
||||
Brain,
|
||||
CalendarClock,
|
||||
MessageSquare,
|
||||
MessageSquarePlus,
|
||||
PanelLeftClose,
|
||||
PenLine,
|
||||
Settings,
|
||||
Sparkles,
|
||||
UsersRound,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import type { MouseEvent } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
|
||||
import { AgentBrandIcon } from "./agents/agent-brand-icon";
|
||||
import { RecentChatList } from "./recent-chat-list";
|
||||
import { WorkspaceNavMenu } from "./workspace-nav-menu";
|
||||
|
||||
const NEW_CHAT_PATH = "/page/workspace/chats/new";
|
||||
|
||||
type NavItem = {
|
||||
label: string;
|
||||
href: string;
|
||||
icon: typeof MessageSquare;
|
||||
match: string;
|
||||
};
|
||||
|
||||
const NAV_ITEMS: NavItem[] = [
|
||||
{ label: "新建对话", href: NEW_CHAT_PATH, icon: MessageSquarePlus, match: NEW_CHAT_PATH },
|
||||
{ label: "对话", href: "/page/workspace/chats", icon: MessageSquare, match: "/page/workspace/chats" },
|
||||
{ label: "智能体", href: "/page/workspace/agents", icon: Sparkles, match: "/page/workspace/agents" },
|
||||
{ label: "技能", href: "/page/workspace/skills", icon: Sparkles, match: "/page/workspace/skills" },
|
||||
{ label: "记忆", href: "/page/workspace/memory", icon: Brain, match: "/page/workspace/memory" },
|
||||
{ label: "AI 写作", href: "/page/workspace/ai-writing", icon: PenLine, match: "/page/workspace/ai-writing" },
|
||||
{
|
||||
label: "多智能体规划",
|
||||
href: "/page/workspace/roundtable/planning",
|
||||
icon: UsersRound,
|
||||
match: "/page/workspace/roundtable",
|
||||
},
|
||||
{
|
||||
label: "定时任务",
|
||||
href: "/page/workspace/scheduled/tasks",
|
||||
icon: CalendarClock,
|
||||
match: "/page/workspace/scheduled",
|
||||
},
|
||||
{ label: "问答梳理", href: "/page/workspace/knowledge", icon: BookOpenCheck, match: "/page/workspace/knowledge" },
|
||||
] as const;
|
||||
|
||||
export function CmChatSidebar({
|
||||
onCollapse,
|
||||
collapsed = false,
|
||||
forceCollapsed = false,
|
||||
}: {
|
||||
onCollapse?: () => void;
|
||||
collapsed?: boolean;
|
||||
/** Deployment-level compact navigation: retain only accessible menu icons. */
|
||||
forceCollapsed?: boolean;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
const navigate = useNavigate();
|
||||
const { theme } = useTheme();
|
||||
const brandLogoSrc = theme === "light" ? "/cm-assistant-logo-red.png" : "/cm-assistant-logo.png";
|
||||
|
||||
const handleNewChat = (event: MouseEvent<HTMLAnchorElement>) => {
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.button === 1) return;
|
||||
event.preventDefault();
|
||||
navigate(NEW_CHAT_PATH, { replace: true, state: { resetAt: Date.now() } });
|
||||
};
|
||||
|
||||
if (collapsed) {
|
||||
return (
|
||||
<aside className="flex h-full min-h-0 w-14 flex-col border-r border-slate-200/80 bg-white text-slate-700 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-200">
|
||||
{!forceCollapsed && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCollapse}
|
||||
aria-label="展开侧边栏"
|
||||
title="展开侧边栏"
|
||||
className="mx-auto mt-2 flex size-11 shrink-0 items-center justify-center rounded-xl transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 dark:hover:bg-slate-900"
|
||||
>
|
||||
<img
|
||||
src={brandLogoSrc}
|
||||
alt="CM 助手"
|
||||
className="size-10 object-contain"
|
||||
/>
|
||||
</button>
|
||||
<div className="mx-2 mt-2 h-px shrink-0 bg-slate-200/80 dark:bg-slate-800" />
|
||||
</>
|
||||
)}
|
||||
|
||||
<nav
|
||||
className={cn(
|
||||
"flex shrink-0 flex-col items-center gap-1 px-2 py-3",
|
||||
forceCollapsed && "pt-4",
|
||||
)}
|
||||
aria-label="工作台导航"
|
||||
>
|
||||
{NAV_ITEMS.map((item) => {
|
||||
const active = item.href === NEW_CHAT_PATH
|
||||
? pathname === NEW_CHAT_PATH
|
||||
: item.href === "/page/workspace/chats"
|
||||
? pathname.startsWith(item.match) && pathname !== NEW_CHAT_PATH
|
||||
: pathname.startsWith(item.match);
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
onClick={item.href === NEW_CHAT_PATH ? handleNewChat : undefined}
|
||||
aria-current={active ? "page" : undefined}
|
||||
aria-label={item.label}
|
||||
title={item.label}
|
||||
className={cn(
|
||||
"flex size-10 items-center justify-center rounded-xl transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40",
|
||||
active
|
||||
? "bg-primary/10 text-primary dark:bg-primary/15 dark:text-primary"
|
||||
: "text-slate-600 hover:bg-slate-100 hover:text-slate-950 dark:text-slate-300 dark:hover:bg-slate-900 dark:hover:text-white",
|
||||
)}
|
||||
>
|
||||
{item.href === "/page/workspace/agents" ? (
|
||||
<AgentBrandIcon size="nav" />
|
||||
) : (
|
||||
<Icon className="size-[19px]" strokeWidth={1.8} />
|
||||
)}
|
||||
<span className="sr-only">{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className="mt-auto flex shrink-0 justify-center border-t border-slate-200/80 py-3 dark:border-slate-800">
|
||||
<Link
|
||||
href="/page/workspace/settings"
|
||||
aria-label="设置和更多"
|
||||
title="设置和更多"
|
||||
className="flex size-10 items-center justify-center rounded-xl text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-950 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 dark:text-slate-300 dark:hover:bg-slate-900 dark:hover:text-white"
|
||||
>
|
||||
<Settings className="size-[19px]" strokeWidth={1.8} />
|
||||
</Link>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col overflow-hidden border-r border-slate-200/80 bg-white text-slate-900 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100">
|
||||
<div className="flex shrink-0 items-center gap-1.5 px-4 pt-3.5 pb-2.5">
|
||||
<Link href={NEW_CHAT_PATH} className="flex min-w-0 flex-1 items-center gap-2.5 outline-none focus-visible:ring-2 focus-visible:ring-primary/40">
|
||||
<img
|
||||
src={brandLogoSrc}
|
||||
alt="CM 助手"
|
||||
className="size-9 shrink-0 object-contain"
|
||||
/>
|
||||
<span className="truncate text-[19px] font-semibold tracking-[-0.025em]">CM 助手</span>
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCollapse}
|
||||
aria-label="收起侧边栏"
|
||||
title="收起侧边栏"
|
||||
className="flex size-8 shrink-0 items-center justify-center rounded-md text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 dark:hover:bg-slate-900 dark:hover:text-white"
|
||||
>
|
||||
<PanelLeftClose className="size-[18px]" strokeWidth={1.8} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav className="shrink-0 px-3 pt-1" aria-label="工作台导航">
|
||||
<div className="space-y-1">
|
||||
{NAV_ITEMS.map((item) => {
|
||||
const active = item.href === NEW_CHAT_PATH
|
||||
? pathname === NEW_CHAT_PATH
|
||||
: item.href === "/page/workspace/chats"
|
||||
? pathname.startsWith(item.match) && pathname !== NEW_CHAT_PATH
|
||||
: pathname.startsWith(item.match);
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
onClick={item.href === NEW_CHAT_PATH ? handleNewChat : undefined}
|
||||
aria-current={active ? "page" : undefined}
|
||||
className={cn(
|
||||
"flex h-10 items-center gap-3 rounded-xl px-3 text-[14px] font-medium transition-colors",
|
||||
active
|
||||
? "bg-primary/10 text-primary dark:bg-primary/15 dark:text-primary"
|
||||
: "text-slate-600 hover:bg-slate-100 hover:text-slate-950 dark:text-slate-300 dark:hover:bg-slate-900 dark:hover:text-white",
|
||||
)}
|
||||
>
|
||||
{item.href === "/page/workspace/agents" ? (
|
||||
<AgentBrandIcon size="nav" />
|
||||
) : (
|
||||
<Icon className="size-[18px] shrink-0" strokeWidth={1.8} />
|
||||
)}
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-1">
|
||||
<RecentChatList compact limit={5} moreHref="/page/workspace/chats" />
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 border-t border-slate-200/80 px-3 py-3 dark:border-slate-800">
|
||||
<WorkspaceNavMenu />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,38 +11,15 @@ export function CompactWelcome({ className }: { className?: string }) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"mx-auto flex w-full flex-col items-center justify-center text-center select-none",
|
||||
"mx-auto flex w-full flex-col items-center justify-center text-center",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* CM logo:浅底圆环 + 主色渐变圆角方块 */}
|
||||
<div
|
||||
className="mb-3.5 inline-flex items-center justify-center rounded-full p-3"
|
||||
style={{
|
||||
backgroundColor:
|
||||
"color-mix(in srgb, var(--workspace-brand) 5%, transparent)",
|
||||
border:
|
||||
"1px solid color-mix(in srgb, var(--workspace-brand) 12%, transparent)",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex size-14 items-center justify-center rounded-2xl shadow-md"
|
||||
style={{
|
||||
backgroundImage:
|
||||
"linear-gradient(to top right, var(--workspace-brand), color-mix(in srgb, var(--workspace-brand) 55%, white))",
|
||||
}}
|
||||
>
|
||||
<span className="text-2xl font-black tracking-wide text-white italic">
|
||||
CM
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h1 className="flex items-center justify-center gap-2 text-2xl font-bold tracking-tight text-foreground/90">
|
||||
<span className="text-2xl">👋</span> 欢迎使用CM助手
|
||||
<h1 className="flex items-center justify-center text-[34px] font-semibold tracking-[-0.035em] text-slate-950 dark:text-slate-50">
|
||||
你好,欢迎使用 CM 助手
|
||||
</h1>
|
||||
<p className="text-muted-foreground mx-auto mt-2 max-w-sm text-xs leading-relaxed">
|
||||
基于先进深度推理模型,为您提供高效的市场分析、专业报告撰写、调研设计与协同脑暴支持。
|
||||
<p className="mx-auto mt-2.5 max-w-xl text-[15px] leading-6 text-slate-500 dark:text-slate-400">
|
||||
我可以帮你写作、问答、分析和规划各类内容,让工作更高效
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import { useCallback, useState, type ComponentProps } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { copyTextToClipboard } from "@/core/clipboard";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
|
||||
import { Tooltip } from "./tooltip";
|
||||
@@ -14,11 +16,15 @@ export function CopyButton({
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const handleCopy = useCallback(() => {
|
||||
void navigator.clipboard.writeText(clipboardData);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}, [clipboardData]);
|
||||
const handleCopy = useCallback(async () => {
|
||||
try {
|
||||
await copyTextToClipboard(clipboardData);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
toast.error(t.clipboard.failedToCopyToClipboard);
|
||||
}
|
||||
}, [clipboardData, t.clipboard.failedToCopyToClipboard]);
|
||||
return (
|
||||
<Tooltip content={t.clipboard.copyToClipboard}>
|
||||
<Button
|
||||
|
||||
@@ -46,10 +46,12 @@ export function CustomPromptBar({
|
||||
onInsert,
|
||||
className,
|
||||
currentAgentId,
|
||||
compact = false,
|
||||
}: {
|
||||
onInsert: (content: string) => void;
|
||||
className?: string;
|
||||
currentAgentId?: string | null;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const allPrompts = useCustomPrompts();
|
||||
const prompts = allPrompts.filter(
|
||||
@@ -81,7 +83,13 @@ export function CustomPromptBar({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={cn("flex min-w-0 items-center gap-1", className)}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 items-center gap-1",
|
||||
compact && "min-h-9 justify-end",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{prompts.length > 0 && (
|
||||
<>
|
||||
{overflowing && (
|
||||
@@ -111,6 +119,7 @@ export function CustomPromptBar({
|
||||
title={prompt.content}
|
||||
className={cn(
|
||||
"border-border/60 bg-muted/40 text-foreground/80 hover:bg-muted hover:text-foreground hover:border-border max-w-[200px] shrink-0 truncate rounded-full border px-3 py-1 text-xs font-medium shadow-sm transition-colors",
|
||||
compact && "border-slate-200 bg-white px-3.5 py-1.5 text-[12px] text-slate-600 shadow-none hover:border-primary/25 hover:bg-primary/5 hover:text-primary",
|
||||
"dark:border-slate-600/70 dark:bg-slate-700/40 dark:text-slate-200 dark:hover:bg-slate-700",
|
||||
)}
|
||||
>
|
||||
@@ -139,7 +148,11 @@ export function CustomPromptBar({
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-muted/70 h-7 w-7 shrink-0 rounded-full"
|
||||
className={cn(
|
||||
"text-muted-foreground hover:text-foreground hover:bg-muted/70 h-7 w-7 shrink-0 rounded-full",
|
||||
compact &&
|
||||
"h-9 w-9 rounded-xl border border-slate-200 bg-white text-slate-600 shadow-[0_6px_18px_-14px_rgba(15,23,42,0.4)] hover:border-primary/25 hover:bg-primary/5 hover:text-primary dark:border-slate-700 dark:bg-slate-900",
|
||||
)}
|
||||
title="管理常用提示词"
|
||||
aria-label="管理常用提示词"
|
||||
onClick={() => setManageOpen(true)}
|
||||
|
||||
@@ -320,7 +320,7 @@ export function GeneralQaSidebar() {
|
||||
className={cn(
|
||||
"flex h-10 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-[5px] text-[14px] font-semibold transition-colors",
|
||||
"border border-solid",
|
||||
"bg-[color-mix(in_srgb,var(--primary)_14%,transparent)] hover:bg-[color-mix(in_srgb,var(--primary)_24%,transparent)]",
|
||||
"bg-[rgb(var(--legacy-primary-rgb)/14%)] hover:bg-[rgb(var(--legacy-primary-rgb)/24%)]",
|
||||
)}
|
||||
>
|
||||
<Plus className="size-4 stroke-[2.5]" />
|
||||
@@ -349,33 +349,64 @@ export function GeneralQaSidebar() {
|
||||
type="button"
|
||||
onClick={() => handleSelectAgent(agent.id)}
|
||||
className={cn(
|
||||
"group relative flex w-full items-start gap-2.5 rounded-xl border px-2.5 py-2 text-left transition-colors",
|
||||
"group relative flex w-full items-start gap-3 rounded-xl border px-3 py-2.5 text-left transition-all duration-150",
|
||||
isActive
|
||||
? "border-primary/40 bg-primary/5"
|
||||
: "border-transparent hover:border-border hover:bg-accent/50",
|
||||
? isDark
|
||||
? "border-[#2b8ffe] bg-[#0b4fae]/65 shadow-[0_0_0_1px_rgba(43,143,254,0.5),0_12px_28px_rgba(37,128,255,0.25)]"
|
||||
: "agent-sidebar-card--active border-primary/50 bg-primary/10 shadow-sm"
|
||||
: isDark
|
||||
? "border-[#2b8ffe]/20 bg-[#042b59]/35 hover:border-[#2b8ffe]/60 hover:bg-[#063b77]/60"
|
||||
: "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"
|
||||
className={cn(
|
||||
"mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-lg text-white shadow-sm",
|
||||
isDark &&
|
||||
isActive &&
|
||||
"ring-2 ring-[#83c1ff]/35 shadow-[0_0_18px_rgba(43,143,254,0.45)]",
|
||||
)}
|
||||
style={{ backgroundImage: `linear-gradient(135deg, ${from}, ${to})` }}
|
||||
>
|
||||
<Bot className="size-[18px]" />
|
||||
<Bot className="size-[19px]" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span
|
||||
className={cn(
|
||||
"block truncate text-[13px] font-semibold",
|
||||
isActive ? "text-primary" : "text-foreground",
|
||||
"block truncate text-[16px] leading-5 font-bold",
|
||||
isActive
|
||||
? isDark
|
||||
? "text-white"
|
||||
: "text-primary"
|
||||
: isDark
|
||||
? "text-white/95"
|
||||
: "text-foreground",
|
||||
)}
|
||||
>
|
||||
{desensitize(agent.name)}
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-[11px] leading-snug text-muted-foreground">
|
||||
<span
|
||||
className={cn(
|
||||
"mt-1 block truncate text-[13px] leading-[1.35]",
|
||||
isDark
|
||||
? isActive
|
||||
? "text-[#d6eaff]"
|
||||
: "text-[#9ebfe2]"
|
||||
: "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" />
|
||||
<span
|
||||
className={cn(
|
||||
"absolute top-1/2 right-1.5 h-8 w-1.5 -translate-y-1/2 rounded-full",
|
||||
isDark
|
||||
? "bg-[#2b8ffe] shadow-[0_0_14px_rgba(43,143,254,0.85)]"
|
||||
: "bg-primary",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -2,14 +2,18 @@
|
||||
|
||||
import type { ChatStatus } from "ai";
|
||||
import {
|
||||
BarChart3Icon,
|
||||
BrainCircuitIcon,
|
||||
BookMarkedIcon,
|
||||
CheckIcon,
|
||||
ClipboardCheckIcon,
|
||||
FileTextIcon,
|
||||
GraduationCapIcon,
|
||||
LightbulbIcon,
|
||||
MessageCircleQuestionIcon,
|
||||
PaperclipIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
ShrinkIcon,
|
||||
SparklesIcon,
|
||||
RocketIcon,
|
||||
@@ -104,6 +108,57 @@ import { Tooltip } from "./tooltip";
|
||||
|
||||
type InputMode = "flash" | "thinking" | "pro" | "ultra";
|
||||
|
||||
const COMPACT_QUICK_STARTS = [
|
||||
{
|
||||
id: "report",
|
||||
title: "撰写报告",
|
||||
content: "请帮我撰写一份结构清晰的专业报告,先向我确认主题、受众和篇幅要求。",
|
||||
icon: FileTextIcon,
|
||||
},
|
||||
{
|
||||
id: "knowledge",
|
||||
title: "知识问答",
|
||||
content: "请基于已有资料回答我的问题,并明确区分已知事实、推断和需要补充的信息。",
|
||||
icon: MessageCircleQuestionIcon,
|
||||
},
|
||||
{
|
||||
id: "planning",
|
||||
title: "任务规划",
|
||||
content: "请把我的目标拆解为可执行的任务计划,列出优先级、里程碑和风险。",
|
||||
icon: ClipboardCheckIcon,
|
||||
},
|
||||
{
|
||||
id: "analysis",
|
||||
title: "数据分析",
|
||||
content: "请帮我分析数据中的关键趋势、异常和可能原因,并给出下一步验证建议。",
|
||||
icon: BarChart3Icon,
|
||||
},
|
||||
{
|
||||
id: "solution",
|
||||
title: "方案策划",
|
||||
content: "请围绕我的目标设计一套完整方案,包含背景、目标、实施步骤、资源需求和风险预案。",
|
||||
icon: LightbulbIcon,
|
||||
},
|
||||
{
|
||||
id: "summary",
|
||||
title: "内容总结",
|
||||
content: "请提炼我提供内容的核心观点、关键结论和待办事项,并按重要程度整理。",
|
||||
icon: BookMarkedIcon,
|
||||
},
|
||||
{
|
||||
id: "research",
|
||||
title: "调研提纲",
|
||||
content: "请根据我的调研主题生成一份结构完整的调研提纲,覆盖对象、问题、方法和输出形式。",
|
||||
icon: GraduationCapIcon,
|
||||
},
|
||||
{
|
||||
id: "polish",
|
||||
title: "文案润色",
|
||||
content: "请在不改变原意的前提下润色我提供的内容,使表达更清晰、专业、简洁。",
|
||||
icon: SparklesIcon,
|
||||
},
|
||||
] as const;
|
||||
|
||||
|
||||
function getResolvedMode(
|
||||
mode: InputMode | undefined,
|
||||
@@ -211,6 +266,7 @@ export function InputBox({
|
||||
const wasStreamingRef = useRef(false);
|
||||
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [compactPromptOrder, setCompactPromptOrder] = useState(0);
|
||||
const [pendingSuggestion, setPendingSuggestion] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
@@ -221,6 +277,29 @@ export function InputBox({
|
||||
!hideAdminRecommendedQuestions &&
|
||||
!userPreferences.hide_admin_prompt_prefix &&
|
||||
recommendedQuestions.length > 0;
|
||||
const compactQuickStarts = useMemo(() => {
|
||||
if (!hideAdminRecommendedQuestions && recommendedQuestions.length > 0) {
|
||||
return recommendedQuestions.map((configured, index) => {
|
||||
const fallback =
|
||||
COMPACT_QUICK_STARTS[index % COMPACT_QUICK_STARTS.length]!;
|
||||
return {
|
||||
...fallback,
|
||||
id: configured.id,
|
||||
title: desensitize(configured.title) || `提示词 ${index + 1}`,
|
||||
content: configured.content || fallback.content,
|
||||
};
|
||||
});
|
||||
}
|
||||
return [...COMPACT_QUICK_STARTS];
|
||||
}, [hideAdminRecommendedQuestions, recommendedQuestions]);
|
||||
const orderedCompactQuickStarts = useMemo(() => {
|
||||
if (compactQuickStarts.length < 2) return compactQuickStarts;
|
||||
const offset = compactPromptOrder % compactQuickStarts.length;
|
||||
return [
|
||||
...compactQuickStarts.slice(offset),
|
||||
...compactQuickStarts.slice(0, offset),
|
||||
];
|
||||
}, [compactPromptOrder, compactQuickStarts]);
|
||||
|
||||
useEffect(() => {
|
||||
if (models.length === 0) {
|
||||
@@ -256,6 +335,7 @@ export function InputBox({
|
||||
() => selectedModel?.supports_thinking ?? false,
|
||||
[selectedModel],
|
||||
);
|
||||
const effectiveMode = getResolvedMode(context.mode, supportThinking);
|
||||
|
||||
const supportReasoningEffort = useMemo(
|
||||
() => selectedModel?.supports_reasoning_effort ?? false,
|
||||
@@ -529,14 +609,68 @@ export function InputBox({
|
||||
}, [context.model_name, disabled, isMock, status, thread.messages, threadId]);
|
||||
|
||||
return (
|
||||
<div ref={promptRootRef} className="relative flex flex-col gap-6">
|
||||
<div
|
||||
ref={promptRootRef}
|
||||
className={cn(
|
||||
"relative flex flex-col",
|
||||
compact ? "gap-[clamp(32px,6vh,58px)]" : "gap-6",
|
||||
)}
|
||||
>
|
||||
{extraHeader && (
|
||||
<div className="flex items-center justify-center">
|
||||
{extraHeader}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isNewThread && searchParams.get("mode") !== "skill" && showAdminRecommendedQuestions && (
|
||||
{isNewThread && searchParams.get("mode") !== "skill" && compact && (
|
||||
<section className="px-2" aria-labelledby="recommended-prompts-title">
|
||||
<div className="mb-3 flex items-center justify-center gap-1.5">
|
||||
<h2
|
||||
id="recommended-prompts-title"
|
||||
className="text-[14px] font-normal text-slate-400 dark:text-slate-500"
|
||||
>
|
||||
你可以这样问我
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
data-prompt-order-refresh="true"
|
||||
title="调整提示词顺序"
|
||||
aria-label="调整提示词顺序"
|
||||
onClick={() => setCompactPromptOrder((current) => current + 1)}
|
||||
className="flex size-7 items-center justify-center rounded-full text-slate-400 transition-colors hover:bg-slate-100 hover:text-primary focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/15 dark:hover:bg-slate-800 dark:hover:text-primary"
|
||||
>
|
||||
<RefreshCwIcon className="size-3.5" strokeWidth={1.8} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mx-auto flex max-w-[900px] flex-wrap justify-center gap-x-3 gap-y-3">
|
||||
{orderedCompactQuickStarts.map((item) => {
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
data-quick-prompt={item.id}
|
||||
title={item.content}
|
||||
className="inline-flex min-h-11 max-w-full items-center justify-center rounded-xl border border-[#e5e7eb] bg-white px-4 py-2 text-center text-[14px] font-normal leading-5 text-slate-700 shadow-[0_2px_6px_rgba(15,23,42,0.025)] transition-[background-color,border-color,box-shadow] hover:border-primary/25 hover:bg-primary/5 hover:text-slate-900 hover:shadow-[0_4px_10px_rgba(15,23,42,0.04)] focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/15 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:border-primary/35 dark:hover:bg-primary/10"
|
||||
onClick={() => {
|
||||
textInput.setInput(item.content);
|
||||
requestAnimationFrame(() =>
|
||||
document
|
||||
.querySelector<HTMLTextAreaElement>(
|
||||
"textarea[name='message']",
|
||||
)
|
||||
?.focus(),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<span className="max-w-full whitespace-normal">{item.title}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{isNewThread && searchParams.get("mode") !== "skill" && !compact && showAdminRecommendedQuestions && (
|
||||
<div className="flex flex-wrap justify-center gap-2.5 px-4 mb-[10px]">
|
||||
{recommendedQuestions.map((q) => (
|
||||
<button
|
||||
@@ -589,7 +723,8 @@ export function InputBox({
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{isNewThread && (
|
||||
<CustomPromptBar
|
||||
className="px-1"
|
||||
compact={compact}
|
||||
className={cn(compact ? "px-2" : "px-1")}
|
||||
currentAgentId={agentSelector?.selectedAgentId ?? assistantId ?? null}
|
||||
onInsert={(content) => {
|
||||
const current = textInput.value?.trim() ?? "";
|
||||
@@ -613,7 +748,7 @@ export function InputBox({
|
||||
: "*:data-[slot='input-group']:rounded-3xl",
|
||||
// 紧凑落地态(CM 参考图):白卡 + 细边 + 轻阴影 + 主色聚焦环(无旋转彩边)
|
||||
compact && isNewThread
|
||||
? "rounded-2xl border border-gray-200/70 bg-white overflow-hidden shadow-[0_4.5px_22px_rgba(0,0,0,0.025)] transition-all duration-300 focus-within:border-[color-mix(in_srgb,var(--primary)_35%,transparent)] focus-within:ring-4 focus-within:ring-[color-mix(in_srgb,var(--primary)_5%,transparent)] focus-within:shadow-[0_10px_35px_color-mix(in_srgb,var(--primary)_4%,transparent)] dark:border-slate-700 dark:bg-slate-800"
|
||||
? "overflow-hidden rounded-[24px] border border-slate-200/90 bg-white shadow-[0_18px_50px_-32px_rgba(15,23,42,0.22),0_8px_24px_-20px_rgba(15,23,42,0.35)] transition-all duration-300 focus-within:border-primary/35 focus-within:ring-4 focus-within:ring-primary/10 dark:border-slate-700 dark:bg-slate-800"
|
||||
: // landing 态:透明,让外层 gemini-gradient-border 提供白卡 + 旋转描边
|
||||
// 对话态:常规白卡 + 中性边框 + 轻阴影
|
||||
isNewThread
|
||||
@@ -637,7 +772,8 @@ export function InputBox({
|
||||
className={cn(
|
||||
"size-full px-2 py-1 text-[15px] leading-7 placeholder:text-muted-foreground/60",
|
||||
isNewThread && "min-h-[110px]!",
|
||||
compact && "min-h-[84px]! px-3 pt-3 pb-1 text-[14px]",
|
||||
compact &&
|
||||
"min-h-[clamp(150px,18vh,176px)]! px-7 pt-7 pb-2 text-[15px]",
|
||||
)}
|
||||
disabled={disabled}
|
||||
placeholder={t.inputBox.placeholder}
|
||||
@@ -648,7 +784,7 @@ export function InputBox({
|
||||
<PromptInputFooter
|
||||
className={cn(
|
||||
"flex items-center border-t-0 px-2 pt-1 pb-1.5",
|
||||
compact && "gap-2 px-3 pt-1.5 pb-3",
|
||||
compact && "gap-2 px-6 pt-2 pb-5",
|
||||
)}
|
||||
>
|
||||
<PromptInputTools
|
||||
@@ -682,13 +818,16 @@ export function InputBox({
|
||||
"gap-1.5! rounded-full px-3! shadow-none",
|
||||
compact && "rounded-lg px-2.5! py-1! text-[11px] font-medium",
|
||||
context.writing_mode
|
||||
? "border border-amber-300 bg-amber-50 text-amber-700 hover:bg-amber-100 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
|
||||
? "border border-amber-300 bg-amber-50 text-amber-700 ring-1 ring-amber-300/35 hover:bg-amber-100 dark:border-amber-300/70 dark:bg-amber-400/20 dark:text-amber-100 dark:ring-amber-300/35 dark:shadow-[0_0_0_1px_rgba(251,191,36,0.18),0_0_18px_rgba(251,191,36,0.18)] dark:hover:bg-amber-400/25"
|
||||
: compact
|
||||
? "border border-transparent bg-muted/40 text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
: "border-0 bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
|
||||
)}
|
||||
onClick={handleWritingModeToggle}
|
||||
>
|
||||
{context.writing_mode && (
|
||||
<CheckIcon className="size-3 text-amber-700 dark:text-amber-100" />
|
||||
)}
|
||||
<FileTextIcon className="size-3" />
|
||||
<span className="text-xs font-normal">写作</span>
|
||||
</PromptInputButton>
|
||||
@@ -705,13 +844,16 @@ export function InputBox({
|
||||
"gap-1.5! rounded-full px-3! shadow-none",
|
||||
compact && "rounded-lg px-2.5! py-1! text-[11px] font-medium",
|
||||
memoryInjectionEnabled
|
||||
? "border border-blue-300 bg-blue-50 text-blue-700 hover:bg-blue-100 dark:border-blue-700 dark:bg-blue-950/40 dark:text-blue-200"
|
||||
? "border border-primary/35 bg-primary/5 text-primary ring-1 ring-primary/20 hover:bg-primary/10 dark:border-primary/45 dark:bg-primary/15 dark:text-primary dark:ring-primary/25 dark:hover:bg-primary/20"
|
||||
: compact
|
||||
? "border border-transparent bg-muted/40 text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
: "border-0 bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
|
||||
)}
|
||||
onClick={handleMemoryInjectionToggle}
|
||||
>
|
||||
{memoryInjectionEnabled && (
|
||||
<CheckIcon className="text-primary size-3" />
|
||||
)}
|
||||
<BrainCircuitIcon className="size-3" />
|
||||
<span className="text-xs font-normal">记忆</span>
|
||||
</PromptInputButton>
|
||||
@@ -778,12 +920,7 @@ export function InputBox({
|
||||
<PromptInputActionMenu>
|
||||
<ModeHoverGuide
|
||||
mode={
|
||||
context.mode === "flash" ||
|
||||
context.mode === "thinking" ||
|
||||
context.mode === "pro" ||
|
||||
context.mode === "ultra"
|
||||
? context.mode
|
||||
: "flash"
|
||||
effectiveMode
|
||||
}
|
||||
>
|
||||
<PromptInputActionMenuTrigger
|
||||
@@ -791,38 +928,38 @@ export function InputBox({
|
||||
"gap-1.5! rounded-full border-0 bg-transparent px-3! text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
|
||||
compact && "rounded-lg border px-2.5! py-1! text-[11px] font-medium",
|
||||
compact &&
|
||||
(context.mode === "thinking"
|
||||
(effectiveMode === "thinking"
|
||||
? "border-indigo-200 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100 dark:border-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-200"
|
||||
: context.mode === "pro"
|
||||
: effectiveMode === "pro"
|
||||
? "border-violet-200 bg-violet-50/60 text-violet-700 hover:bg-violet-100 dark:border-violet-700 dark:bg-violet-950/40 dark:text-violet-200"
|
||||
: context.mode === "ultra"
|
||||
: effectiveMode === "ultra"
|
||||
? "border-amber-200 bg-amber-50/60 text-amber-700 hover:bg-amber-100 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
|
||||
: "border-transparent bg-muted/40 hover:bg-muted hover:text-foreground"),
|
||||
)}
|
||||
>
|
||||
<div>
|
||||
{context.mode === "flash" && <ZapIcon className="size-3" />}
|
||||
{context.mode === "thinking" && (
|
||||
{effectiveMode === "flash" && <ZapIcon className="size-3" />}
|
||||
{effectiveMode === "thinking" && (
|
||||
<LightbulbIcon className="size-3" />
|
||||
)}
|
||||
{context.mode === "pro" && (
|
||||
{effectiveMode === "pro" && (
|
||||
<GraduationCapIcon className="size-3" />
|
||||
)}
|
||||
{context.mode === "ultra" && (
|
||||
{effectiveMode === "ultra" && (
|
||||
<RocketIcon className="size-3 text-[#dabb5e]" />
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"text-xs font-normal",
|
||||
context.mode === "ultra" ? "golden-text" : "",
|
||||
effectiveMode === "ultra" ? "golden-text" : "",
|
||||
)}
|
||||
>
|
||||
{(context.mode === "flash" && t.inputBox.flashMode) ||
|
||||
(context.mode === "thinking" &&
|
||||
{(effectiveMode === "flash" && t.inputBox.flashMode) ||
|
||||
(effectiveMode === "thinking" &&
|
||||
t.inputBox.reasoningMode) ||
|
||||
(context.mode === "pro" && t.inputBox.proMode) ||
|
||||
(context.mode === "ultra" && t.inputBox.ultraMode)}
|
||||
(effectiveMode === "pro" && t.inputBox.proMode) ||
|
||||
(effectiveMode === "ultra" && t.inputBox.ultraMode)}
|
||||
</div>
|
||||
</PromptInputActionMenuTrigger>
|
||||
</ModeHoverGuide>
|
||||
@@ -1119,6 +1256,8 @@ export function InputBox({
|
||||
>
|
||||
<ModelSelectorTrigger asChild>
|
||||
<PromptInputButton
|
||||
disabled={models.length === 0}
|
||||
aria-label="模型选择"
|
||||
className={cn(
|
||||
"rounded-full border-0 bg-transparent px-3 shadow-none text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
|
||||
compact &&
|
||||
@@ -1132,7 +1271,7 @@ export function InputBox({
|
||||
compact && "text-[11px]",
|
||||
)}
|
||||
>
|
||||
{selectedModel?.display_name}
|
||||
{selectedModel?.display_name || "默认模型"}
|
||||
</ModelSelectorName>
|
||||
</div>
|
||||
</PromptInputButton>
|
||||
@@ -1164,9 +1303,9 @@ export function InputBox({
|
||||
</ModelSelector>
|
||||
<PromptInputSubmit
|
||||
className={cn(
|
||||
"rounded-full border-border bg-background shadow-sm hover:bg-muted dark:bg-blue-500 dark:border-blue-500 dark:text-white dark:hover:bg-blue-400 dark:shadow-none",
|
||||
"rounded-full border-border bg-background shadow-sm hover:bg-muted dark:bg-primary dark:border-primary dark:text-primary-foreground dark:hover:bg-primary/90 dark:shadow-none",
|
||||
compact &&
|
||||
"size-7 rounded-lg border-0 bg-[var(--primary)] text-[var(--primary-foreground)] hover:bg-[color-mix(in_srgb,var(--primary)_88%,black)] disabled:bg-muted disabled:text-muted-foreground/40 dark:bg-[var(--primary)] dark:border-0 dark:text-[var(--primary-foreground)] dark:hover:bg-[color-mix(in_srgb,var(--primary)_88%,black)] dark:disabled:bg-muted",
|
||||
"bg-primary hover:bg-primary/90 size-10 rounded-full border-0 text-primary-foreground shadow-[0_8px_18px_-10px_rgba(15,23,42,0.34)] disabled:bg-muted disabled:text-muted-foreground/40 dark:border-0 dark:bg-primary dark:text-primary-foreground dark:hover:bg-primary/90 dark:disabled:bg-muted",
|
||||
)}
|
||||
disabled={disabled}
|
||||
variant="outline"
|
||||
|
||||
@@ -65,7 +65,10 @@ import { cn } from "@/lib/utils";
|
||||
import { useArtifactsOptional } from "../artifacts";
|
||||
import { FlipDisplay } from "../flip-display";
|
||||
import { Tooltip } from "../tooltip";
|
||||
import { SourceCard } from "../skill-display-sources";
|
||||
import {
|
||||
isWeKnoraSourcePreviewUrl,
|
||||
SourceCard,
|
||||
} from "../skill-display-sources";
|
||||
|
||||
import { MarkdownContent } from "./markdown-content";
|
||||
|
||||
@@ -651,6 +654,30 @@ function SearchResultCard({ item }: { item: SearchResultItem }) {
|
||||
sourceLabel = sourceLabel ?? item.url;
|
||||
}
|
||||
}
|
||||
|
||||
// MCP retrieval tools without a configured display adapter fall back to this
|
||||
// generic result card. Preserve the normal web-search UI, but route our
|
||||
// credential-free WeKnora pointer through SourceCard so its dialog exposes a
|
||||
// deliberate “查看原文” action rather than rendering the internal route text.
|
||||
if (isWeKnoraSourcePreviewUrl(item.url)) {
|
||||
const weknoraSource: RuntimeDisplaySource = {
|
||||
id: item.id ?? item.uuid ?? item.docId,
|
||||
title: item.title ?? "检索结果",
|
||||
type: item.source ?? "document",
|
||||
snippet: item.snippet ?? item.content ?? "",
|
||||
content,
|
||||
source: item.source,
|
||||
author: item.author,
|
||||
time: date,
|
||||
url: item.url,
|
||||
index: 0,
|
||||
skillName: "weknora-knowledge-search",
|
||||
mode: "list",
|
||||
raw: { ...item },
|
||||
};
|
||||
return <SourceCard source={weknoraSource} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
|
||||
@@ -112,7 +112,7 @@ export function RecentRoundtableList() {
|
||||
}
|
||||
try {
|
||||
await rename(id, title);
|
||||
toast.success("✏️ 已重命名");
|
||||
toast.success("已重命名");
|
||||
} catch {
|
||||
toast.error("重命名失败,请重试");
|
||||
} finally {
|
||||
@@ -126,7 +126,7 @@ export function RecentRoundtableList() {
|
||||
if (!window.confirm("确定删除这条会商记录吗?此操作不可恢复。")) return;
|
||||
try {
|
||||
await remove(draft.id);
|
||||
toast.success("🗑 已删除会商记录");
|
||||
toast.success("已删除会商记录");
|
||||
} catch {
|
||||
toast.error("删除失败,请重试");
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ CM Assistant is an internal super-agent platform that orchestrates sub-agents, m
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Core Features
|
||||
## Core Features
|
||||
|
||||
* **Skills & Tools**: With built-in and extensible skills and tools, CM Assistant can do almost anything.
|
||||
* **Sub-Agents**: Sub-Agents help the main agent to do the tasks that are too complex to be done by the main agent.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { CopyIcon, LogOutIcon, UserIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { clearStoredAuth, getAccountDisplayName, getStoredAuth } from "@/core/auth";
|
||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
import { clearYLogToken } from "@/core/log/y-log-token";
|
||||
|
||||
@@ -27,7 +27,10 @@ function copy(text: string, hint = "已复制") {
|
||||
}
|
||||
|
||||
export function AccountSettingsPage() {
|
||||
const auth = useMemo(() => getStoredAuth(), []);
|
||||
// Subscribe to same-tab and cross-tab auth changes. The dialog may stay open
|
||||
// while the active account is switched elsewhere.
|
||||
useLiveAccount();
|
||||
const auth = getStoredAuth();
|
||||
|
||||
if (!auth) {
|
||||
return (
|
||||
|
||||
@@ -1,7 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { DropletIcon, LayoutGridIcon, LayoutIcon, ListIcon, MoonIcon, PanelLeftIcon, SunIcon } from "lucide-react";
|
||||
import { useMemo, useState, type ComponentType, type SVGProps } from "react";
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
DropletIcon,
|
||||
ExternalLink,
|
||||
LayoutGridIcon,
|
||||
LayoutIcon,
|
||||
LeafIcon,
|
||||
ListIcon,
|
||||
MoonIcon,
|
||||
PanelLeftIcon,
|
||||
Plus,
|
||||
SunIcon,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState, type ComponentType, type SVGProps } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -9,6 +23,7 @@ import { useTheme } from "@/contexts/ThemeContext";
|
||||
|
||||
import { FONT_SCALE_OPTIONS } from "@/components/font-scale";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -32,7 +47,17 @@ import {
|
||||
useUpdateAppearanceSettings,
|
||||
useUpdateCitationDisplaySettings,
|
||||
} from "@/core/system-settings/hooks";
|
||||
import type {
|
||||
CompactShortcutButton,
|
||||
CompactShortcutRouteParam,
|
||||
} from "@/core/system-settings/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
APP_THEME_COLORS,
|
||||
LOGIN_SOURCE_OPTIONS,
|
||||
parseThemeMap,
|
||||
stringifyThemeMap,
|
||||
} from "@/strategy-components/lib/light-app";
|
||||
|
||||
import PrivateSquareSettingsPage from "@/pages/PrivateSquareSettingsPage";
|
||||
import PublishSquaresSettingsPage from "@/pages/PublishSquaresSettingsPage";
|
||||
@@ -46,6 +71,97 @@ const languageOptions: { value: Locale; label: string }[] = [
|
||||
{ value: "zh-CN", label: zhCN.locale.localName },
|
||||
];
|
||||
|
||||
const DEFAULT_SHORTCUT_THEME_MAP = "red=red;green=green;blue=blue;dark-blue=dark-blue";
|
||||
|
||||
function makeShortcutId() {
|
||||
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
return `shortcut-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
function newShortcutParam(): CompactShortcutRouteParam {
|
||||
return {
|
||||
key: "access_token",
|
||||
paramType: "login",
|
||||
source: "access_token",
|
||||
customValue: "",
|
||||
themeValue: DEFAULT_SHORTCUT_THEME_MAP,
|
||||
};
|
||||
}
|
||||
|
||||
function newShortcutButton(): CompactShortcutButton {
|
||||
return {
|
||||
id: makeShortcutId(),
|
||||
label: "快捷入口",
|
||||
url: "",
|
||||
route_params: [newShortcutParam()],
|
||||
enabled: true,
|
||||
sort_order: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeShortcutDraft(
|
||||
buttons: CompactShortcutButton[] | undefined,
|
||||
): CompactShortcutButton[] {
|
||||
const source = buttons?.length ? buttons : [newShortcutButton()];
|
||||
return [...source]
|
||||
.sort((a, b) => a.sort_order - b.sort_order)
|
||||
.map((button, index) => ({
|
||||
...button,
|
||||
id: button.id || makeShortcutId(),
|
||||
label: button.label || "快捷入口",
|
||||
url: button.url || "",
|
||||
route_params: (button.route_params?.length
|
||||
? button.route_params
|
||||
: [newShortcutParam()]
|
||||
).map((param) => ({
|
||||
key: param.key || "",
|
||||
paramType: param.paramType || "login",
|
||||
source: param.source || "access_token",
|
||||
customValue: param.customValue ?? "",
|
||||
themeValue: param.themeValue || DEFAULT_SHORTCUT_THEME_MAP,
|
||||
})),
|
||||
enabled: button.enabled ?? true,
|
||||
sort_order: index,
|
||||
}));
|
||||
}
|
||||
|
||||
function cleanShortcutParams(
|
||||
params: CompactShortcutRouteParam[],
|
||||
): CompactShortcutRouteParam[] {
|
||||
return params
|
||||
.filter((param) => param.key.trim())
|
||||
.map((param) => {
|
||||
const base: CompactShortcutRouteParam = {
|
||||
key: param.key.trim(),
|
||||
paramType: param.paramType,
|
||||
};
|
||||
if (param.paramType === "theme") {
|
||||
base.themeValue = stringifyThemeMap(parseThemeMap(param.themeValue));
|
||||
return base;
|
||||
}
|
||||
base.source = param.source || "access_token";
|
||||
if (base.source === "other") {
|
||||
base.customValue = (param.customValue ?? "").trim();
|
||||
}
|
||||
return base;
|
||||
});
|
||||
}
|
||||
|
||||
function cleanShortcutButtons(
|
||||
buttons: CompactShortcutButton[],
|
||||
): CompactShortcutButton[] {
|
||||
return buttons.map((button, index) => ({
|
||||
id: button.id || makeShortcutId(),
|
||||
label: button.label.trim() || "快捷入口",
|
||||
url: button.url.trim(),
|
||||
route_params: cleanShortcutParams(button.route_params),
|
||||
enabled: button.enabled,
|
||||
sort_order: index,
|
||||
}));
|
||||
}
|
||||
|
||||
export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
const { t, locale, changeLocale } = useI18n();
|
||||
const { theme, setTheme } = useTheme();
|
||||
@@ -55,6 +171,7 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const { data: appearance } = useAppearanceSettings();
|
||||
const updateAppearance = useUpdateAppearanceSettings();
|
||||
const [shortcutDraft, setShortcutDraft] = useState<CompactShortcutButton[]>([]);
|
||||
const { data: citationDisplay } = useCitationDisplaySettings();
|
||||
const updateCitationDisplay = useUpdateCitationDisplaySettings();
|
||||
const globalDefault = appearance?.default_theme ?? "light";
|
||||
@@ -66,6 +183,12 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
const cleanupWords =
|
||||
citationDisplay?.cleanup_words ?? settings.display.citationCleanupWords ?? [];
|
||||
|
||||
useEffect(() => {
|
||||
setShortcutDraft(
|
||||
normalizeShortcutDraft(appearance?.compact_shortcut_buttons),
|
||||
);
|
||||
}, [appearance?.compact_shortcut_buttons]);
|
||||
|
||||
// 独立登录会话(本标签页):开关切换鉴权存储 localStorage ↔ sessionStorage(见 scoped-storage)。
|
||||
const [isolatedSession, setIsolatedSessionState] = useState(() => isIsolatedSession());
|
||||
const handleToggleIsolatedSession = (checked: boolean) => {
|
||||
@@ -90,13 +213,19 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
};
|
||||
|
||||
const handleSetGlobalDefault = async (
|
||||
value: "light" | "dark" | "lightblue",
|
||||
value: "light" | "dark" | "lightblue" | "lightgreen",
|
||||
) => {
|
||||
if (value === globalDefault) return;
|
||||
try {
|
||||
await updateAppearance.mutateAsync({ default_theme: value });
|
||||
const label =
|
||||
value === "light" ? "浅色" : value === "dark" ? "深色" : "浅蓝";
|
||||
value === "light"
|
||||
? "浅色"
|
||||
: value === "dark"
|
||||
? "深色"
|
||||
: value === "lightgreen"
|
||||
? "绿色"
|
||||
: "浅蓝";
|
||||
toast.success(`已将系统默认主题设置为${label}`);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "保存失败");
|
||||
@@ -136,6 +265,102 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
}
|
||||
};
|
||||
|
||||
const patchShortcut = (
|
||||
id: string,
|
||||
patch: Partial<CompactShortcutButton>,
|
||||
) => {
|
||||
setShortcutDraft((items) =>
|
||||
items.map((item) => (item.id === id ? { ...item, ...patch } : item)),
|
||||
);
|
||||
};
|
||||
|
||||
const patchShortcutParam = (
|
||||
id: string,
|
||||
index: number,
|
||||
patch: Partial<CompactShortcutRouteParam>,
|
||||
) => {
|
||||
setShortcutDraft((items) =>
|
||||
items.map((item) =>
|
||||
item.id === id
|
||||
? {
|
||||
...item,
|
||||
route_params: item.route_params.map((param, paramIndex) =>
|
||||
paramIndex === index ? { ...param, ...patch } : param,
|
||||
),
|
||||
}
|
||||
: item,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const moveShortcut = (id: string, direction: -1 | 1) => {
|
||||
setShortcutDraft((items) => {
|
||||
const index = items.findIndex((item) => item.id === id);
|
||||
const target = index + direction;
|
||||
if (index < 0 || target < 0 || target >= items.length) return items;
|
||||
const next = [...items];
|
||||
[next[index], next[target]] = [next[target]!, next[index]!];
|
||||
return next.map((item, order) => ({ ...item, sort_order: order }));
|
||||
});
|
||||
};
|
||||
|
||||
const addShortcutParam = (id: string) => {
|
||||
setShortcutDraft((items) =>
|
||||
items.map((item) =>
|
||||
item.id === id
|
||||
? {
|
||||
...item,
|
||||
route_params: [...item.route_params, newShortcutParam()],
|
||||
}
|
||||
: item,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const removeShortcutParam = (id: string, index: number) => {
|
||||
setShortcutDraft((items) =>
|
||||
items.map((item) =>
|
||||
item.id === id
|
||||
? {
|
||||
...item,
|
||||
route_params: item.route_params.filter((_, paramIndex) => paramIndex !== index),
|
||||
}
|
||||
: item,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const handleSaveShortcuts = async () => {
|
||||
for (const item of shortcutDraft) {
|
||||
if (item.enabled && !item.url.trim()) {
|
||||
toast.error(`请填写「${item.label.trim() || "快捷入口"}」的跳转链接,或先关闭该按钮`);
|
||||
return;
|
||||
}
|
||||
for (const param of item.route_params) {
|
||||
if (!param.key.trim()) {
|
||||
toast.error("路由参数键名不可为空");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
param.paramType === "login" &&
|
||||
param.source === "other" &&
|
||||
!param.customValue?.trim()
|
||||
) {
|
||||
toast.error("登录参数自定义值不可为空");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
await updateAppearance.mutateAsync({
|
||||
compact_shortcut_buttons: cleanShortcutButtons(shortcutDraft),
|
||||
});
|
||||
toast.success("顶部快捷按钮已保存");
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "保存失败");
|
||||
}
|
||||
};
|
||||
|
||||
const themeOptions = useMemo(
|
||||
() => [
|
||||
{
|
||||
@@ -156,6 +381,12 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
description: t.settings.appearance.lightblueDescription,
|
||||
icon: DropletIcon,
|
||||
},
|
||||
{
|
||||
id: "lightgreen",
|
||||
label: t.settings.appearance.lightgreen,
|
||||
description: t.settings.appearance.lightgreenDescription,
|
||||
icon: LeafIcon,
|
||||
},
|
||||
],
|
||||
[
|
||||
t.settings.appearance.dark,
|
||||
@@ -164,6 +395,8 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
t.settings.appearance.lightDescription,
|
||||
t.settings.appearance.lightblue,
|
||||
t.settings.appearance.lightblueDescription,
|
||||
t.settings.appearance.lightgreen,
|
||||
t.settings.appearance.lightgreenDescription,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -181,7 +414,7 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
active={currentTheme === option.id}
|
||||
mode={option.id as "light" | "dark" | "lightblue"}
|
||||
mode={option.id as "light" | "dark" | "lightblue" | "lightgreen"}
|
||||
onSelect={(value) => setTheme(value)}
|
||||
/>
|
||||
))}
|
||||
@@ -261,6 +494,40 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{isAdmin && (
|
||||
<>
|
||||
<Separator />
|
||||
<SettingsSection
|
||||
title="顶部快捷按钮(管理员)"
|
||||
description="配置全量/简洁模式右上角、换肤按钮左侧显示的跳转按钮。支持多个按钮、启停和与应用管理一致的登录/主题参数。"
|
||||
>
|
||||
<CompactShortcutSettings
|
||||
buttons={shortcutDraft}
|
||||
saving={updateAppearance.isPending}
|
||||
onAdd={() =>
|
||||
setShortcutDraft((items) => [
|
||||
...items,
|
||||
{ ...newShortcutButton(), sort_order: items.length },
|
||||
])
|
||||
}
|
||||
onPatch={patchShortcut}
|
||||
onMove={moveShortcut}
|
||||
onRemove={(id) =>
|
||||
setShortcutDraft((items) =>
|
||||
items
|
||||
.filter((item) => item.id !== id)
|
||||
.map((item, index) => ({ ...item, sort_order: index })),
|
||||
)
|
||||
}
|
||||
onAddParam={addShortcutParam}
|
||||
onPatchParam={patchShortcutParam}
|
||||
onRemoveParam={removeShortcutParam}
|
||||
onSave={handleSaveShortcuts}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isAdmin && (
|
||||
<>
|
||||
<Separator />
|
||||
@@ -299,13 +566,25 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
<DropletIcon className="mr-1.5 size-4" />
|
||||
浅蓝
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={globalDefault === "lightgreen" ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => void handleSetGlobalDefault("lightgreen")}
|
||||
disabled={updateAppearance.isPending}
|
||||
>
|
||||
<LeafIcon className="mr-1.5 size-4" />
|
||||
绿色
|
||||
</Button>
|
||||
<p className="text-muted-foreground ml-2 text-xs">
|
||||
当前系统默认:
|
||||
{globalDefault === "light"
|
||||
? "浅色"
|
||||
: globalDefault === "dark"
|
||||
? "深色"
|
||||
: "浅蓝"}
|
||||
: globalDefault === "lightgreen"
|
||||
? "绿色"
|
||||
: "浅蓝"}
|
||||
</p>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
@@ -518,6 +797,298 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
function CompactShortcutSettings({
|
||||
buttons,
|
||||
saving,
|
||||
onAdd,
|
||||
onPatch,
|
||||
onMove,
|
||||
onRemove,
|
||||
onAddParam,
|
||||
onPatchParam,
|
||||
onRemoveParam,
|
||||
onSave,
|
||||
}: {
|
||||
buttons: CompactShortcutButton[];
|
||||
saving: boolean;
|
||||
onAdd: () => void;
|
||||
onPatch: (id: string, patch: Partial<CompactShortcutButton>) => void;
|
||||
onMove: (id: string, direction: -1 | 1) => void;
|
||||
onRemove: (id: string) => void;
|
||||
onAddParam: (id: string) => void;
|
||||
onPatchParam: (
|
||||
id: string,
|
||||
index: number,
|
||||
patch: Partial<CompactShortcutRouteParam>,
|
||||
) => void;
|
||||
onRemoveParam: (id: string, index: number) => void;
|
||||
onSave: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<p className="text-muted-foreground text-xs">
|
||||
已配置 {buttons.length} 个按钮;只有启用且填写了跳转链接的按钮会显示。
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={onAdd}>
|
||||
<Plus className="mr-1.5 size-4" />
|
||||
添加按钮
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={onSave}
|
||||
disabled={saving}
|
||||
>
|
||||
保存按钮配置
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{buttons.length === 0 ? (
|
||||
<div className="text-muted-foreground rounded-lg border border-dashed p-6 text-center text-sm">
|
||||
暂无按钮,点击“添加按钮”创建一个。
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{buttons.map((button, index) => (
|
||||
<div key={button.id} className="space-y-4 rounded-lg border p-4">
|
||||
<div className="flex flex-col gap-3 xl:flex-row xl:items-start">
|
||||
<div className="flex items-center gap-2 pt-6">
|
||||
<Switch
|
||||
checked={button.enabled}
|
||||
onCheckedChange={(checked) =>
|
||||
onPatch(button.id, { enabled: checked })
|
||||
}
|
||||
aria-label="启用快捷按钮"
|
||||
/>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{button.enabled ? "启用" : "停用"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid min-w-0 flex-1 gap-3 md:grid-cols-[220px_minmax(0,1fr)]">
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-xs font-medium">按钮名称</div>
|
||||
<Input
|
||||
value={button.label}
|
||||
onChange={(event) =>
|
||||
onPatch(button.id, { label: event.target.value })
|
||||
}
|
||||
placeholder="如:业务系统"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-xs font-medium">跳转链接</div>
|
||||
<Input
|
||||
value={button.url}
|
||||
onChange={(event) =>
|
||||
onPatch(button.id, { url: event.target.value })
|
||||
}
|
||||
placeholder="https://example.com/page"
|
||||
className="font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 pt-6">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => onMove(button.id, -1)}
|
||||
disabled={index === 0}
|
||||
title="上移"
|
||||
>
|
||||
<ArrowUp className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => onMove(button.id, 1)}
|
||||
disabled={index === buttons.length - 1}
|
||||
title="下移"
|
||||
>
|
||||
<ArrowDown className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => onRemove(button.id)}
|
||||
title="删除"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border bg-muted/20 p-3">
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 text-sm font-medium">
|
||||
<ExternalLink className="size-4" />
|
||||
路由参数
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onAddParam(button.id)}
|
||||
>
|
||||
<Plus className="mr-1.5 size-4" />
|
||||
添加参数
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{button.route_params.length === 0 ? (
|
||||
<div className="text-muted-foreground rounded-md border border-dashed bg-background/70 p-4 text-center text-xs">
|
||||
不追加额外参数。
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{button.route_params.map((param, paramIndex) => {
|
||||
const themeMap =
|
||||
param.paramType === "theme"
|
||||
? parseThemeMap(param.themeValue)
|
||||
: {};
|
||||
return (
|
||||
<div
|
||||
key={`${button.id}-${paramIndex}`}
|
||||
className="space-y-2 rounded-md border bg-background p-2"
|
||||
>
|
||||
<div className="grid gap-2 md:grid-cols-[minmax(120px,1fr)_130px_minmax(180px,1.4fr)_32px]">
|
||||
<Input
|
||||
value={param.key}
|
||||
onChange={(event) =>
|
||||
onPatchParam(button.id, paramIndex, {
|
||||
key: event.target.value,
|
||||
})
|
||||
}
|
||||
placeholder="参数名 key"
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
<Select
|
||||
value={param.paramType}
|
||||
onValueChange={(value) =>
|
||||
onPatchParam(button.id, paramIndex, {
|
||||
paramType: value as "login" | "theme",
|
||||
source:
|
||||
value === "login"
|
||||
? param.source || "access_token"
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="login">登录参数</SelectItem>
|
||||
<SelectItem value="theme">主题参数</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{param.paramType === "login" ? (
|
||||
<div className="flex min-w-0 gap-2">
|
||||
<Select
|
||||
value={param.source || "access_token"}
|
||||
onValueChange={(value) =>
|
||||
onPatchParam(button.id, paramIndex, {
|
||||
source: value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="min-w-0 flex-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LOGIN_SOURCE_OPTIONS.map((option) => (
|
||||
<SelectItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{param.source === "other" && (
|
||||
<Input
|
||||
value={param.customValue ?? ""}
|
||||
onChange={(event) =>
|
||||
onPatchParam(button.id, paramIndex, {
|
||||
customValue: event.target.value,
|
||||
})
|
||||
}
|
||||
placeholder="自定义值"
|
||||
className="w-32 text-xs"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground flex items-center text-xs">
|
||||
按当前主题取值
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() =>
|
||||
onRemoveParam(button.id, paramIndex)
|
||||
}
|
||||
title="删除参数"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{param.paramType === "theme" && (
|
||||
<div className="grid gap-2 rounded-md bg-muted/40 p-2 md:grid-cols-3">
|
||||
{APP_THEME_COLORS.map((color) => (
|
||||
<label
|
||||
key={color.key}
|
||||
className="flex min-w-0 items-center gap-2"
|
||||
>
|
||||
<span
|
||||
className="size-2.5 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: color.dot }}
|
||||
/>
|
||||
<span className="text-muted-foreground shrink-0 text-xs">
|
||||
{color.label}
|
||||
</span>
|
||||
<Input
|
||||
value={themeMap[color.key] ?? color.key}
|
||||
onChange={(event) =>
|
||||
onPatchParam(button.id, paramIndex, {
|
||||
themeValue: stringifyThemeMap({
|
||||
...themeMap,
|
||||
[color.key]: event.target.value,
|
||||
}),
|
||||
})
|
||||
}
|
||||
placeholder={color.key}
|
||||
className="h-8 min-w-0 font-mono text-xs"
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ThemePreviewCard({
|
||||
icon: Icon,
|
||||
label,
|
||||
@@ -530,8 +1101,8 @@ function ThemePreviewCard({
|
||||
label: string;
|
||||
description: string;
|
||||
active: boolean;
|
||||
mode: "light" | "dark" | "lightblue";
|
||||
onSelect: (mode: "light" | "dark" | "lightblue") => void;
|
||||
mode: "light" | "dark" | "lightblue" | "lightgreen";
|
||||
onSelect: (mode: "light" | "dark" | "lightblue" | "lightgreen") => void;
|
||||
}) {
|
||||
const previewMode = mode;
|
||||
return (
|
||||
@@ -563,6 +1134,8 @@ function ThemePreviewCard({
|
||||
? "border-neutral-800 bg-neutral-900 text-neutral-200"
|
||||
: previewMode === "lightblue"
|
||||
? "border-blue-200 bg-white text-slate-900"
|
||||
: previewMode === "lightgreen"
|
||||
? "border-emerald-200 bg-white text-emerald-950"
|
||||
: "border-slate-200 bg-white text-slate-900",
|
||||
)}
|
||||
>
|
||||
@@ -574,7 +1147,9 @@ function ThemePreviewCard({
|
||||
? "bg-emerald-400"
|
||||
: previewMode === "lightblue"
|
||||
? "bg-blue-500"
|
||||
: "bg-emerald-500",
|
||||
: previewMode === "lightgreen"
|
||||
? "bg-[#07c05f]"
|
||||
: "bg-[#cf1322]",
|
||||
)}
|
||||
/>
|
||||
<div className="h-2 w-10 rounded-full bg-current/20" />
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
TrendingUpIcon,
|
||||
Upload,
|
||||
UserIcon,
|
||||
WorkflowIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
@@ -50,13 +51,6 @@ import {
|
||||
EmptyTitle,
|
||||
} from "@/components/ui/empty";
|
||||
|
||||
import {
|
||||
Item,
|
||||
ItemActions,
|
||||
ItemTitle,
|
||||
ItemContent,
|
||||
ItemDescription,
|
||||
} from "@/components/ui/item";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
@@ -500,11 +494,6 @@ function SkillSettingsList({ onClose }: { onClose?: () => void }) {
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
{!isLoading && !error && (
|
||||
<div className="text-muted-foreground flex justify-end text-sm tabular-nums">
|
||||
共 {orderedSkills.length} 个技能
|
||||
</div>
|
||||
)}
|
||||
{publisher && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground text-xs">筛选发布者:</span>
|
||||
@@ -749,7 +738,7 @@ export function SkillRow({
|
||||
|
||||
const badgeGroup = (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className={cn(isCard && "truncate font-medium")}>
|
||||
<span className="min-w-0 truncate text-[15px] font-semibold tracking-[-0.01em] text-slate-900 dark:text-slate-100">
|
||||
{skill.name_zh?.trim() ? skill.name_zh : desensitize(skill.name)}
|
||||
</span>
|
||||
{skill.name_zh?.trim() && (
|
||||
@@ -773,7 +762,7 @@ export function SkillRow({
|
||||
{isFromOthers && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-blue-500/30 text-blue-700 dark:text-blue-300 text-xs"
|
||||
className="border-primary/30 text-primary text-xs dark:text-primary"
|
||||
title={
|
||||
skill.owner_user_id
|
||||
? t.settings.skills.badgeFromOthersTitle.replace(
|
||||
@@ -912,7 +901,7 @@ export function SkillRow({
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 shrink-0"
|
||||
className="h-8 w-8 shrink-0 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-950 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-white"
|
||||
onClick={() => setTagPickerOpen(true)}
|
||||
title={t.adminTags.manageTags}
|
||||
>
|
||||
@@ -923,7 +912,7 @@ export function SkillRow({
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"h-8 w-8 shrink-0",
|
||||
"h-8 w-8 shrink-0 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-950 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-white",
|
||||
skill.featured && "text-amber-600 hover:text-amber-700",
|
||||
)}
|
||||
disabled={setFeatured.isPending}
|
||||
@@ -944,7 +933,7 @@ export function SkillRow({
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"h-8 w-8 shrink-0",
|
||||
"h-8 w-8 shrink-0 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-950 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-white",
|
||||
skill.pinned && "text-emerald-600 hover:text-emerald-700",
|
||||
)}
|
||||
disabled={setPinned.isPending}
|
||||
@@ -965,7 +954,7 @@ export function SkillRow({
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"h-8 w-8 shrink-0",
|
||||
"h-8 w-8 shrink-0 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-950 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-white",
|
||||
skill.always_on && "text-amber-600 hover:text-amber-700",
|
||||
)}
|
||||
disabled={setAlwaysOn.isPending}
|
||||
@@ -1004,7 +993,7 @@ export function SkillRow({
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 shrink-0"
|
||||
className="h-8 w-8 shrink-0 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-950 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-white"
|
||||
disabled={duplicateSkillMutation.isPending}
|
||||
onClick={handleOpenDuplicate}
|
||||
title="复制为新技能"
|
||||
@@ -1013,9 +1002,9 @@ export function SkillRow({
|
||||
</Button>
|
||||
{canManage && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="text-destructive hover:text-destructive h-8 w-8 shrink-0 rounded-lg hover:bg-red-50 dark:hover:bg-red-950/30"
|
||||
onClick={() => setConfirmDeleteOpen(true)}
|
||||
title={t.settings.skills.deleteAction}
|
||||
>
|
||||
@@ -1025,38 +1014,121 @@ export function SkillRow({
|
||||
</>
|
||||
);
|
||||
|
||||
const iconStyle = skill.name.includes("web") || skill.name.includes("search")
|
||||
? {
|
||||
Icon: GlobeIcon,
|
||||
className: "bg-emerald-600 text-white shadow-[0_6px_16px_rgba(22,163,74,0.22)]",
|
||||
}
|
||||
: skill.name.includes("doc") || skill.name.includes("file")
|
||||
? {
|
||||
Icon: FileArchive,
|
||||
className: "bg-violet-600 text-white shadow-[0_6px_16px_rgba(124,58,237,0.22)]",
|
||||
}
|
||||
: skill.source === "agent"
|
||||
? {
|
||||
Icon: WorkflowIcon,
|
||||
className: "bg-primary text-primary-foreground shadow-[0_6px_16px_rgba(15,23,42,0.18)]",
|
||||
}
|
||||
: {
|
||||
Icon: Upload,
|
||||
className: "bg-amber-500 text-white shadow-[0_6px_16px_rgba(245,158,11,0.22)]",
|
||||
};
|
||||
const SkillIcon = iconStyle.Icon;
|
||||
const activityAt = formatDateTime(skill.last_activity_at ?? skill.created_at);
|
||||
const actionArea = (
|
||||
<div className="flex flex-wrap items-center justify-end gap-1" onClick={(event) => event.stopPropagation()}>
|
||||
{actionButtons}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isCard ? (
|
||||
<div className="flex h-full min-w-0 flex-col rounded-lg border p-3 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C] dark:text-white">
|
||||
<div className="flex h-full min-w-0 flex-col rounded-2xl border border-slate-200 bg-white p-5 shadow-[0_5px_18px_rgba(15,23,42,0.035)] transition-[background-color,border-color,box-shadow] hover:border-primary/25 hover:bg-primary/[0.025] hover:shadow-[0_10px_28px_rgba(15,23,42,0.07)] dark:border-slate-800 dark:bg-slate-900 dark:text-white">
|
||||
<div
|
||||
className="min-w-0 flex-1 cursor-pointer"
|
||||
onClick={() => setDetailOpen(true)}
|
||||
>
|
||||
{badgeGroup}
|
||||
<p className="text-muted-foreground mt-1 line-clamp-3 text-sm">
|
||||
{desensitize(skill.description ?? "")}
|
||||
</p>
|
||||
{metaNodes}
|
||||
<div className="flex items-start gap-3.5">
|
||||
<div className={cn("flex size-12 shrink-0 items-center justify-center rounded-full", iconStyle.className)}>
|
||||
<SkillIcon className="size-6" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
{badgeGroup}
|
||||
<p className="mt-1.5 line-clamp-3 text-sm leading-6 text-slate-600 dark:text-slate-400">
|
||||
{desensitize(skill.description ?? "")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
<Badge className={cn("border-0 px-2.5 py-1 text-xs font-normal", skill.enabled ? "bg-emerald-50 text-emerald-600 hover:bg-emerald-50 dark:bg-emerald-500/15 dark:text-emerald-300" : "bg-slate-100 text-slate-500 hover:bg-slate-100 dark:bg-slate-800 dark:text-slate-400")}>
|
||||
<span className={cn("mr-1.5 size-1.5 rounded-full", skill.enabled ? "bg-emerald-500" : "bg-slate-400")} />
|
||||
{skill.enabled ? "已启用" : "未启用"}
|
||||
</Badge>
|
||||
<span className="text-xs text-slate-400">{skill.use_count ? `调用 ${skill.use_count} 次` : "暂无调用"}</span>
|
||||
{activityAt && <span className="text-xs text-slate-400">更新于 {activityAt}</span>}
|
||||
</div>
|
||||
{(skill.tags?.length ?? 0) > 0 && <TagChipList tags={skill.tags!} className="mt-3" />}
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap items-center justify-end gap-1 border-t pt-2 dark:border-[#213D5E]">
|
||||
{actionButtons}
|
||||
<div className="mt-4 border-t border-slate-100 pt-3 dark:border-slate-800">
|
||||
{actionArea}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Item className="w-full dark:border-[#213D5E] dark:bg-[#02244C] dark:text-white" variant="outline">
|
||||
<ItemContent
|
||||
className="cursor-pointer"
|
||||
onClick={() => setDetailOpen(true)}
|
||||
>
|
||||
<ItemTitle>{badgeGroup}</ItemTitle>
|
||||
<ItemDescription className="line-clamp-4">
|
||||
{desensitize(skill.description ?? "")}
|
||||
</ItemDescription>
|
||||
{metaNodes}
|
||||
</ItemContent>
|
||||
<ItemActions>{actionButtons}</ItemActions>
|
||||
</Item>
|
||||
<div className="group/skill-card w-full rounded-2xl border border-slate-200 bg-white px-5 py-3.5 shadow-[0_5px_18px_rgba(15,23,42,0.03)] transition-[background-color,border-color,box-shadow] hover:border-primary/25 hover:bg-primary/[0.025] hover:shadow-[0_10px_28px_rgba(15,23,42,0.07)] dark:border-slate-800 dark:bg-slate-900 dark:text-white">
|
||||
<div className="grid min-w-0 grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1.55fr)_minmax(160px,0.78fr)_minmax(110px,0.42fr)_minmax(142px,0.56fr)_auto] xl:items-center xl:gap-x-5">
|
||||
<div className="flex min-w-0 cursor-pointer items-start gap-3.5" onClick={() => setDetailOpen(true)}>
|
||||
<div className={cn("flex size-14 shrink-0 items-center justify-center rounded-2xl", iconStyle.className)}>
|
||||
<SkillIcon className="size-7" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 pt-0.5">
|
||||
{badgeGroup}
|
||||
<p className="mt-1.5 line-clamp-2 text-sm leading-5 text-slate-600 dark:text-slate-400">
|
||||
{desensitize(skill.description ?? "")}
|
||||
</p>
|
||||
{!isBuiltin && skill.owner_username && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={!skill.owner_user_id || !onPublisherClick}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (!skill.owner_user_id || !onPublisherClick) return;
|
||||
onPublisherClick({ id: skill.owner_user_id, label: desensitize(skill.owner_username!) });
|
||||
}}
|
||||
className={cn(
|
||||
"mt-2 flex max-w-full items-center gap-1 text-xs text-slate-400",
|
||||
skill.owner_user_id && onPublisherClick && "cursor-pointer hover:text-primary hover:underline",
|
||||
)}
|
||||
>
|
||||
<UserIcon className="size-3.5 shrink-0" />
|
||||
<span className="truncate">发布者:{desensitize(skill.owner_username)}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0 xl:border-l xl:border-slate-100 xl:pl-5 xl:dark:border-slate-800">
|
||||
{(skill.tags?.length ?? 0) > 0 ? (
|
||||
<TagChipList tags={skill.tags!} />
|
||||
) : (
|
||||
<span className="text-xs text-slate-400">未设置标签</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 text-sm text-slate-600 dark:text-slate-300">
|
||||
<span className="block text-xs text-slate-400 xl:hidden">使用次数</span>
|
||||
{skill.use_count ? `${skill.use_count} 次` : "暂无调用"}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<Badge className={cn("border-0 px-2.5 py-1 text-xs font-normal", skill.enabled ? "bg-emerald-50 text-emerald-600 hover:bg-emerald-50 dark:bg-emerald-500/15 dark:text-emerald-300" : "bg-slate-100 text-slate-500 hover:bg-slate-100 dark:bg-slate-800 dark:text-slate-400")}>
|
||||
<span className={cn("mr-1.5 size-1.5 rounded-full", skill.enabled ? "bg-emerald-500" : "bg-slate-400")} />
|
||||
{skill.enabled ? "已启用" : "未启用"}
|
||||
</Badge>
|
||||
{activityAt && <p className="mt-2 truncate text-xs text-slate-400" title={activityAt}>更新于 {activityAt}</p>}
|
||||
</div>
|
||||
<div className="min-w-0 border-t border-slate-100 pt-3 xl:border-t-0 xl:pt-0 dark:border-slate-800">
|
||||
{actionArea}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Dialog open={duplicateOpen} onOpenChange={setDuplicateOpen}>
|
||||
<DialogContent>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ExternalLinkIcon } from "lucide-react";
|
||||
import { ExternalLinkIcon, FileTextIcon, LoaderCircle } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -9,10 +9,12 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import type { RuntimeDisplaySource } from "@/core/skill-display/runtime";
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { useLocalSettings } from "@/core/settings";
|
||||
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export function SkillDisplaySources({
|
||||
highlightedReferenceId,
|
||||
@@ -51,6 +53,10 @@ export function SourceCard({
|
||||
referenceTarget?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [showOriginal, setShowOriginal] = useState(false);
|
||||
const [context, setContext] = useState<WeKnoraSourceContext | null>(null);
|
||||
const [contextLoading, setContextLoading] = useState(false);
|
||||
const [contextError, setContextError] = useState<string | null>(null);
|
||||
const [settings] = useLocalSettings();
|
||||
const { data: citationDisplay } = useCitationDisplaySettings();
|
||||
const cleanupWords =
|
||||
@@ -73,6 +79,44 @@ export function SourceCard({
|
||||
].filter(Boolean);
|
||||
const isCitation = source.mode === "citation";
|
||||
const showReferenceNumber = isCitation;
|
||||
const previewTarget = parseWeKnoraPreviewUrl(source.url);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !showOriginal || !previewTarget) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setContext(null);
|
||||
setContextError(null);
|
||||
setContextLoading(true);
|
||||
const params = new URLSearchParams({
|
||||
knowledge_base_id: previewTarget.knowledgeBaseId,
|
||||
chunk_id: previewTarget.chunkId,
|
||||
});
|
||||
void apiFetch(`${getBackendBaseURL()}/api/weknora/source-context?${params}`)
|
||||
.then(async (response) => {
|
||||
const payload = (await response.json().catch(() => null)) as unknown;
|
||||
if (!response.ok || !isWeKnoraSourceContextResponse(payload)) {
|
||||
throw new Error(readPreviewError(payload, response.status));
|
||||
}
|
||||
if (!cancelled) {
|
||||
setContext(payload.data);
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!cancelled) {
|
||||
setContextError(error instanceof Error ? error.message : "无法加载原文上下文");
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) {
|
||||
setContextLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, showOriginal, previewTarget?.chunkId, previewTarget?.knowledgeBaseId]);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -85,7 +129,10 @@ export function SourceCard({
|
||||
highlighted &&
|
||||
"border-amber-300 bg-amber-50/80 shadow-[0_0_0_2px_rgba(251,191,36,0.14)]",
|
||||
)}
|
||||
onClick={() => setOpen(true)}
|
||||
onClick={() => {
|
||||
setShowOriginal(false);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{showReferenceNumber && (
|
||||
@@ -114,11 +161,26 @@ export function SourceCard({
|
||||
)}
|
||||
</div>
|
||||
{source.url && (
|
||||
<ExternalLinkIcon className="text-muted-foreground/60 group-hover:text-primary mt-1 size-3.5 shrink-0 transition-colors" />
|
||||
previewTarget ? (
|
||||
<span className="text-primary bg-primary/10 mt-0.5 inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-[11px] font-medium">
|
||||
<FileTextIcon className="size-3.5" />
|
||||
查看原文
|
||||
</span>
|
||||
) : (
|
||||
<ExternalLinkIcon className="text-muted-foreground/60 group-hover:text-primary mt-1 size-3.5 shrink-0 transition-colors" />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
setOpen(nextOpen);
|
||||
if (!nextOpen) {
|
||||
setShowOriginal(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<div className="flex items-start justify-between gap-3 pr-8">
|
||||
@@ -141,7 +203,7 @@ export function SourceCard({
|
||||
</DialogDescription>
|
||||
)}
|
||||
</div>
|
||||
{source.url && (
|
||||
{source.url && !previewTarget && (
|
||||
<Button size="icon-sm" variant="outline" asChild>
|
||||
<a
|
||||
href={source.url}
|
||||
@@ -155,7 +217,33 @@ export function SourceCard({
|
||||
)}
|
||||
</div>
|
||||
</DialogHeader>
|
||||
{paragraphs.length > 0 && (
|
||||
{previewTarget && (
|
||||
<div className="border-b pb-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{showOriginal
|
||||
? "正在查看命中文段及其前后上下文"
|
||||
: "当前为检索命中的片段,可继续查看原文上下文"}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={showOriginal ? "outline" : "default"}
|
||||
onClick={() => setShowOriginal((current) => !current)}
|
||||
>
|
||||
<FileTextIcon className="size-3.5" />
|
||||
{showOriginal ? "返回检索片段" : "查看原文"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{previewTarget && showOriginal ? (
|
||||
<WeKnoraSourceContextPanel
|
||||
context={context}
|
||||
loading={contextLoading}
|
||||
error={contextError}
|
||||
/>
|
||||
) : paragraphs.length > 0 ? (
|
||||
<div className="text-foreground max-h-[55vh] space-y-3 overflow-y-auto text-sm leading-relaxed">
|
||||
{paragraphs.map((paragraph, index) => (
|
||||
<p key={index} className="whitespace-pre-wrap">
|
||||
@@ -163,8 +251,8 @@ export function SourceCard({
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{source.url && (
|
||||
) : null}
|
||||
{source.url && !previewTarget && (
|
||||
<div className="text-muted-foreground border-t pt-3 text-xs break-all">
|
||||
{source.url}
|
||||
</div>
|
||||
@@ -175,6 +263,133 @@ export function SourceCard({
|
||||
);
|
||||
}
|
||||
|
||||
type WeKnoraPreviewTarget = {
|
||||
knowledgeBaseId: string;
|
||||
chunkId: string;
|
||||
};
|
||||
|
||||
type WeKnoraSourceContext = {
|
||||
knowledge_base_name?: string;
|
||||
document_title?: string;
|
||||
document_file_name?: string;
|
||||
focus_chunk_id: string;
|
||||
chunks: Array<{
|
||||
id: string;
|
||||
chunk_index?: number;
|
||||
content: string;
|
||||
is_focus: boolean;
|
||||
}>;
|
||||
};
|
||||
|
||||
export function isWeKnoraSourcePreviewUrl(url?: string): boolean {
|
||||
return parseWeKnoraPreviewUrl(url) !== null;
|
||||
}
|
||||
|
||||
function parseWeKnoraPreviewUrl(url?: string): WeKnoraPreviewTarget | null {
|
||||
const normalizedUrl = url
|
||||
?.trim()
|
||||
.replace(/^[\u200B-\u200D\uFEFF]+/, "");
|
||||
const marker = "/weknora-source-preview?";
|
||||
const start = normalizedUrl?.indexOf(marker) ?? -1;
|
||||
if (start < 0) {
|
||||
return null;
|
||||
}
|
||||
// Some MCP tool results wrap the relative pointer in formatting characters
|
||||
// or append a newline. Keep accepting that safe internal path, but never
|
||||
// treat a normal external URL as an original-document preview.
|
||||
const previewUrl = normalizedUrl!
|
||||
.slice(start)
|
||||
.split(/[\r\n\s]/, 1)[0];
|
||||
const queryIndex = previewUrl.indexOf("?");
|
||||
const params = new URLSearchParams(previewUrl.slice(queryIndex + 1));
|
||||
const knowledgeBaseId = params.get("knowledge_base_id")?.trim();
|
||||
const chunkId = params.get("chunk_id")?.trim();
|
||||
return knowledgeBaseId && chunkId ? { knowledgeBaseId, chunkId } : null;
|
||||
}
|
||||
|
||||
function isWeKnoraSourceContextResponse(
|
||||
value: unknown,
|
||||
): value is { success: true; data: WeKnoraSourceContext } {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
const data = (value as { data?: unknown }).data;
|
||||
return (
|
||||
(value as { success?: unknown }).success === true &&
|
||||
!!data &&
|
||||
typeof data === "object" &&
|
||||
Array.isArray((data as WeKnoraSourceContext).chunks)
|
||||
);
|
||||
}
|
||||
|
||||
function readPreviewError(payload: unknown, status: number): string {
|
||||
if (payload && typeof payload === "object") {
|
||||
const detail = (payload as { detail?: unknown }).detail;
|
||||
if (typeof detail === "string" && detail) {
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
return status === 404 ? "原文已不可用" : "无法加载原文上下文";
|
||||
}
|
||||
|
||||
function WeKnoraSourceContextPanel({
|
||||
context,
|
||||
loading,
|
||||
error,
|
||||
}: {
|
||||
context: WeKnoraSourceContext | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}) {
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="text-muted-foreground flex min-h-36 items-center justify-center gap-2 text-sm">
|
||||
<LoaderCircle className="size-4 animate-spin" />
|
||||
正在加载原文上下文…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (error) {
|
||||
return (
|
||||
<div className="border-destructive/30 bg-destructive/5 text-destructive rounded-lg border p-3 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="max-h-[55vh] space-y-3 overflow-y-auto pr-1">
|
||||
<div className="bg-muted/60 text-muted-foreground rounded-lg px-3 py-2 text-xs">
|
||||
<span>{context.knowledge_base_name || "WeKnora 知识库"}</span>
|
||||
{context.document_title && <span> · {context.document_title}</span>}
|
||||
</div>
|
||||
{context.chunks.map((chunk) => (
|
||||
<section
|
||||
key={chunk.id}
|
||||
className={cn(
|
||||
"rounded-lg border p-3 text-sm leading-relaxed",
|
||||
chunk.is_focus
|
||||
? "border-primary/50 bg-primary/5 shadow-sm"
|
||||
: "bg-muted/20",
|
||||
)}
|
||||
>
|
||||
<div className="text-muted-foreground mb-2 flex items-center gap-2 text-xs">
|
||||
<span>分段 {typeof chunk.chunk_index === "number" ? chunk.chunk_index + 1 : "-"}</span>
|
||||
{chunk.is_focus && (
|
||||
<span className="bg-primary text-primary-foreground rounded px-1.5 py-0.5 font-medium">
|
||||
检索命中
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="whitespace-pre-wrap">{chunk.content}</p>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function cleanReferenceText(
|
||||
raw: string | undefined,
|
||||
cleanupWords: string[],
|
||||
|
||||
@@ -1,45 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { User } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { UserRound } from "lucide-react";
|
||||
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||
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`),
|
||||
* (实时 auth 展示名;岗位取 `useMyPosition`),
|
||||
* 供页面级顶栏(如 ChatPage)右侧复用,保证两套布局一致。
|
||||
*
|
||||
* 配色按当前内容区前景色(foreground / muted-foreground),适配聊天页浅底顶栏,
|
||||
* 而非 Header 的白字贴 banner 方案。
|
||||
*/
|
||||
export function UserIdentityBadge({ className }: { className?: string }) {
|
||||
const auth = getStoredAuth();
|
||||
export function UserIdentityBadge({
|
||||
className,
|
||||
variant = "plain",
|
||||
}: {
|
||||
className?: string;
|
||||
variant?: "plain" | "topbar";
|
||||
}) {
|
||||
// userInfo belongs to external-app route parameters and can legitimately
|
||||
// outlive a login switch. The visible account name must instead match the
|
||||
// settings page's current auth identity.
|
||||
const liveAccount = useLiveAccount();
|
||||
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]);
|
||||
const displayName = liveAccount.displayName;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("flex shrink-0 items-center gap-2", className)}
|
||||
data-workspace-user={variant}
|
||||
className={cn(
|
||||
"flex shrink-0 items-center gap-2",
|
||||
variant === "topbar" &&
|
||||
"h-10 max-w-[240px] rounded-lg px-1.5 py-1 text-slate-700 dark:text-slate-200",
|
||||
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
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground relative flex size-7 shrink-0 items-center justify-center rounded-full",
|
||||
variant === "topbar" &&
|
||||
"bg-primary text-primary-foreground size-8 shadow-[0_4px_12px_-6px_rgba(15,23,42,0.26)] ring-1 ring-primary/15",
|
||||
)}
|
||||
>
|
||||
<UserRound className={cn("size-3.5", variant === "topbar" && "size-4")} />
|
||||
{variant === "topbar" && (
|
||||
<span className="absolute right-0 bottom-0 size-2.5 rounded-full border-2 border-white bg-emerald-500 dark:border-slate-950" />
|
||||
)}
|
||||
</div>
|
||||
<div className="hidden min-w-0 text-left sm:block">
|
||||
<div
|
||||
className={cn(
|
||||
"hidden min-w-0 text-left sm:block",
|
||||
variant === "topbar" && "max-w-[165px]",
|
||||
)}
|
||||
>
|
||||
<p className="text-foreground truncate text-sm font-medium leading-tight">
|
||||
{displayName}
|
||||
</p>
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { AuroraText } from "../ui/aurora-text";
|
||||
|
||||
let waved = false;
|
||||
|
||||
export function Welcome({
|
||||
className,
|
||||
mode,
|
||||
@@ -26,9 +24,6 @@ export function Welcome({
|
||||
}
|
||||
return ["var(--color-foreground)"];
|
||||
}, [isUltra]);
|
||||
useEffect(() => {
|
||||
waved = true;
|
||||
}, []);
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -38,12 +33,9 @@ export function Welcome({
|
||||
>
|
||||
<div className="text-[26px] font-medium tracking-tight text-foreground/85">
|
||||
{searchParams.get("mode") === "skill" ? (
|
||||
`✨ ${t.welcome.createYourOwnSkill} ✨`
|
||||
t.welcome.createYourOwnSkill
|
||||
) : (
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className={cn("inline-block text-2xl", !waved ? "animate-wave" : "")}>
|
||||
{isUltra ? "🚀" : "👋"}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<AuroraText colors={colors}>{t.welcome.greeting}</AuroraText>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useMemo } from "react";
|
||||
import { type ReactNode, useMemo } from "react";
|
||||
|
||||
import {
|
||||
Breadcrumb,
|
||||
@@ -13,7 +13,10 @@ import {
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { env } from "@/env";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ThemeSwitcher } from "@/components/workspace/appearance-controls";
|
||||
import { UserIdentityBadge } from "@/components/workspace/user-identity-badge";
|
||||
|
||||
export function WorkspaceContainer({
|
||||
className,
|
||||
@@ -33,8 +36,11 @@ export function WorkspaceContainer({
|
||||
export function WorkspaceHeader({
|
||||
className,
|
||||
children,
|
||||
rightActions,
|
||||
...props
|
||||
}: React.ComponentProps<"header">) {
|
||||
}: React.ComponentProps<"header"> & {
|
||||
rightActions?: ReactNode;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const pathname = usePathname();
|
||||
const segments = useMemo(() => {
|
||||
@@ -90,6 +96,19 @@ export function WorkspaceHeader({
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 px-4">
|
||||
{rightActions}
|
||||
{!env.FORCE_COLLAPSED_SIDEBAR && (
|
||||
<>
|
||||
<ThemeSwitcher tone="content" />
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="mx-1 h-6 w-px bg-slate-200 dark:bg-slate-700"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<UserIdentityBadge variant="topbar" />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -119,5 +138,6 @@ function nameOfSegment(
|
||||
if (!segment) return t.common.home;
|
||||
if (segment === "workspace") return t.breadcrumb.workspace;
|
||||
if (segment === "chats") return t.breadcrumb.chats;
|
||||
if (segment === "agents") return t.agents.title;
|
||||
return segment[0]?.toUpperCase() + segment.slice(1);
|
||||
}
|
||||
@@ -36,8 +36,8 @@ const NEW_CHAT_CLASS =
|
||||
// 紧凑模式(CM 参考图):白卡描边、居中、主色 + 图标
|
||||
const NEW_CHAT_COMPACT_CLASS =
|
||||
"h-9 justify-center gap-2 rounded-xl bg-card text-[13px] font-semibold text-foreground transition-colors " +
|
||||
"border border-[color-mix(in_srgb,var(--primary)_18%,transparent)] " +
|
||||
"hover:bg-[color-mix(in_srgb,var(--primary)_4%,transparent)] hover:text-[var(--primary)] hover:border-[color-mix(in_srgb,var(--primary)_32%,transparent)] " +
|
||||
"border border-[rgb(var(--legacy-primary-rgb)/18%)] " +
|
||||
"hover:bg-[rgb(var(--legacy-primary-rgb)/4%)] hover:text-[var(--primary)] hover:border-[rgb(var(--legacy-primary-rgb)/32%)] " +
|
||||
"data-[active=true]:bg-card data-[active=true]:text-[var(--primary)] data-[active=true]:shadow-none";
|
||||
|
||||
export function WorkspaceNavChatList({
|
||||
|
||||
@@ -2,117 +2,51 @@
|
||||
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarHeader,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarRail,
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
import { GeneralQaSidebar } from "./general-qa-sidebar";
|
||||
import { RecentChatList } from "./recent-chat-list";
|
||||
import { RecentRoundtableList } from "./recent-roundtable-list";
|
||||
import { RecentWritingList } from "./recent-writing-list";
|
||||
import { WorkspaceHeader } from "./workspace-header";
|
||||
import { WorkspaceNavChatList } from "./workspace-nav-chat-list";
|
||||
import { WorkspaceNavMenu } from "./workspace-nav-menu";
|
||||
import { CmChatSidebar } from "./cm-chat-sidebar";
|
||||
|
||||
export function WorkspaceSidebar({
|
||||
compactChrome = false,
|
||||
className,
|
||||
compactChrome: _compactChrome,
|
||||
forceCollapsed = false,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Sidebar> & { compactChrome?: boolean }) {
|
||||
const { open: isSidebarOpen } = useSidebar();
|
||||
const { theme } = useTheme();
|
||||
const pathname = usePathname();
|
||||
const useWhiteSidebar = compactChrome && theme === "light";
|
||||
// 通用问答(全量模式)左栏:新建回答 → 常用智能体 → 聊天记录(需求 0616 #1)。
|
||||
// 仅在通用问答(/page/workspace/chats*)下启用三块式布局;点击常用智能体后是
|
||||
// 「原地嵌入」(停留在 /chats/new?agent=...,仅右侧问答区换成智能体对话),左侧栏不变。
|
||||
const isGeneralQa = pathname.startsWith("/page/workspace/chats");
|
||||
}: React.ComponentProps<typeof Sidebar> & {
|
||||
compactChrome?: boolean;
|
||||
forceCollapsed?: boolean;
|
||||
}) {
|
||||
const { open: isSidebarOpen, toggleSidebar } = useSidebar();
|
||||
|
||||
// 紧凑模式:用「外层定宽容器 + transition-[width]」做展开/收起过渡动画。
|
||||
// collapsible="none" 的 Sidebar 是普通 in-flow 定宽块(非 absolute,故不受本布局对
|
||||
// sidebar-container 的 absolute/left-0 覆盖影响),外层 overflow-hidden 把它从
|
||||
// --sidebar-width 裁到 0、聊天区随宽度平滑回流;收起后整列不接收指针。
|
||||
if (compactChrome) {
|
||||
return (
|
||||
<div
|
||||
aria-hidden={!isSidebarOpen}
|
||||
return (
|
||||
<div
|
||||
aria-hidden={false}
|
||||
className={cn(
|
||||
"h-full shrink-0 overflow-hidden transition-[width] duration-200 ease-out",
|
||||
isSidebarOpen ? "w-(--sidebar-width)" : "w-0 pointer-events-none",
|
||||
isSidebarOpen ? "w-(--sidebar-width)" : "w-14",
|
||||
)}
|
||||
>
|
||||
<Sidebar
|
||||
variant="sidebar"
|
||||
collapsible="none"
|
||||
className={cn(
|
||||
"h-full w-(--sidebar-width) border-r border-border",
|
||||
useWhiteSidebar &&
|
||||
"[&_[data-slot=sidebar-inner]]:bg-white [&_[data-slot=sidebar-container]]:bg-white",
|
||||
"h-full border-r border-border",
|
||||
isSidebarOpen ? "w-(--sidebar-width)" : "w-14",
|
||||
"[&_[data-slot=sidebar-container]]:bg-white [&_[data-slot=sidebar-inner]]:bg-white",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SidebarContent>
|
||||
{isGeneralQa ? (
|
||||
// 全量版通用问答(/page/workspace/chats*):新建对话侧栏独立成
|
||||
// GeneralQaSidebar(按 0616 样式参考图重画),与其余 workspace 页解耦。
|
||||
<GeneralQaSidebar />
|
||||
) : (
|
||||
<>
|
||||
<WorkspaceNavChatList showCollapseTrigger compact />
|
||||
<RecentChatList compact />
|
||||
</>
|
||||
)}
|
||||
<CmChatSidebar
|
||||
onCollapse={forceCollapsed ? undefined : toggleSidebar}
|
||||
collapsed={!isSidebarOpen}
|
||||
forceCollapsed={forceCollapsed}
|
||||
/>
|
||||
</SidebarContent>
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Sidebar
|
||||
variant="sidebar"
|
||||
// 紧凑模式:展开时为固定宽度整列(none,无内置折叠),收起由上面的条件渲染处理;
|
||||
// 非紧凑沿用 icon。
|
||||
collapsible={compactChrome ? "none" : "icon"}
|
||||
className={cn(
|
||||
useWhiteSidebar &&
|
||||
"[&_[data-slot=sidebar-inner]]:bg-white [&_[data-slot=sidebar-container]]:bg-white",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{!compactChrome && (
|
||||
<SidebarHeader className="py-0">
|
||||
<WorkspaceHeader />
|
||||
</SidebarHeader>
|
||||
)}
|
||||
<SidebarContent>
|
||||
<WorkspaceNavChatList
|
||||
showCollapseTrigger={compactChrome}
|
||||
compact={compactChrome}
|
||||
/>
|
||||
{isSidebarOpen && <RecentChatList compact={compactChrome} />}
|
||||
{/* 「多智能体会商」「最近写作」与「智能体/技能」等菜单项保持一致的显隐:
|
||||
仅在非紧凑模式(!compactChrome)下展示,紧凑模式(有外层页面侧栏时)一并隐藏。 */}
|
||||
{isSidebarOpen && !compactChrome && <RecentRoundtableList />}
|
||||
{isSidebarOpen && !compactChrome && <RecentWritingList />}
|
||||
</SidebarContent>
|
||||
{!compactChrome && (
|
||||
<SidebarFooter>
|
||||
<WorkspaceNavMenu />
|
||||
</SidebarFooter>
|
||||
)}
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { useTheme as useNextTheme } from 'next-themes';
|
||||
import { useAppearanceSettings } from '@/core/system-settings/hooks';
|
||||
|
||||
// 主题类型
|
||||
export type ThemeType = 'dark' | 'light' | 'lightblue';
|
||||
export type ThemeType = 'dark' | 'light' | 'lightblue' | 'lightgreen';
|
||||
|
||||
// 主题配置
|
||||
export interface ThemeConfig {
|
||||
@@ -104,6 +104,28 @@ const themes: Record<ThemeType, ThemeConfig> = {
|
||||
overlay: 'black/30',
|
||||
},
|
||||
},
|
||||
lightgreen: {
|
||||
type: 'lightgreen',
|
||||
name: '绿色主题',
|
||||
colors: {
|
||||
background: 'white',
|
||||
backgroundSecondary: 'emerald-50',
|
||||
text: 'emerald-950',
|
||||
textSecondary: 'emerald-800',
|
||||
primary: 'emerald-600',
|
||||
primaryHover: 'emerald-500',
|
||||
border: 'emerald-200',
|
||||
accent: 'emerald-700',
|
||||
success: 'emerald-600',
|
||||
warning: 'amber-500',
|
||||
error: 'red-600',
|
||||
card: 'white',
|
||||
cardHover: 'emerald-50',
|
||||
input: 'white',
|
||||
inputBorder: 'emerald-200',
|
||||
overlay: 'black/30',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'strategy-theme';
|
||||
@@ -121,6 +143,7 @@ function readPersistedTheme(): ThemeType {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
if (saved === 'dark') return 'dark';
|
||||
if (saved === 'lightblue') return 'lightblue';
|
||||
if (saved === 'lightgreen') return 'lightgreen';
|
||||
return 'light';
|
||||
}
|
||||
|
||||
@@ -179,7 +202,8 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
||||
current &&
|
||||
current !== 'light' &&
|
||||
current !== 'dark' &&
|
||||
current !== 'lightblue'
|
||||
current !== 'lightblue' &&
|
||||
current !== 'lightgreen'
|
||||
) {
|
||||
// Garbage value — wipe it so the boot-sync below can take over.
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
@@ -216,6 +240,8 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
||||
? 'dark'
|
||||
: effectiveTheme === 'lightblue'
|
||||
? 'lightblue'
|
||||
: effectiveTheme === 'lightgreen'
|
||||
? 'lightgreen'
|
||||
: 'light'
|
||||
: readPersistedTheme();
|
||||
|
||||
@@ -234,8 +260,8 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
||||
root.removeAttribute('theme-mode');
|
||||
root.classList.remove('dark');
|
||||
|
||||
if (theme === 'lightblue') {
|
||||
root.setAttribute('data-theme', 'lightblue');
|
||||
if (theme === 'lightblue' || theme === 'lightgreen') {
|
||||
root.setAttribute('data-theme', theme);
|
||||
} else {
|
||||
root.removeAttribute('data-theme');
|
||||
}
|
||||
|
||||
@@ -1,100 +1,19 @@
|
||||
/**
|
||||
* 大屏绘制智能体「独立页面」的**输入 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`。
|
||||
* 报告详情由 Gateway 的 `/api/task-reports/by-task/{taskId}` 提供,返回格式
|
||||
* 与原 `selectSqReport` 一致:`{state, msg, data}`。每条 `contentJson` 是
|
||||
* JSON 字符串,本模块将其按 `categoryType` 解析为智能体和大屏页面可直接使用的
|
||||
* 结构化输入。
|
||||
*/
|
||||
|
||||
import { requestCrudService } from "@/service/request-axios-service";
|
||||
import { readCopTaskDetail } from "@/core/auth/task-deeplink";
|
||||
import { fetchTaskDeeplinkConfig } from "@/core/auth/task-deeplink-config";
|
||||
import { getTaskReport } from "@/strategy-components/api/task-reports";
|
||||
import { readRuntimeFlag } from "@/env";
|
||||
import { SQ_REPORT_MOCK_RESPONSE } from "@/strategy-components/components/task-components/sq-report-mock-data";
|
||||
|
||||
/** 本页输入 JSON 暂存的 sessionStorage key(拉取一次后复用,避免重复请求)。 */
|
||||
/** 保留给既有调用方的 sessionStorage key;报告本身不再使用 mock 缓存。 */
|
||||
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();
|
||||
@@ -102,11 +21,11 @@ function parseContentJson(raw: unknown): unknown {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return text; // 解析失败就把原始字符串透传给智能体,让它自行理解
|
||||
// 非 JSON 字符串仍透传给智能体,避免因单条异常让整份报告不可用。
|
||||
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();
|
||||
@@ -114,151 +33,76 @@ function categoryKey(categoryType: unknown, index: number): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 selectSqReport 的整包响应**提取**成喂给智能体的干净结构化输入:
|
||||
* `{ taskId, source, categories: { [类目]: 反序列化后的内容 } }`
|
||||
* 返回 null 表示无可用内容(调用方据此回退/不开跑)。
|
||||
* 将接口 envelope 提取为 `{ 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})`; // 同名类目去重保留
|
||||
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 };
|
||||
return { taskId, source: "api/task-reports", 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;
|
||||
}
|
||||
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 */
|
||||
}
|
||||
/** 兼容旧调用方:报告数据只由后端接口维护。 */
|
||||
export function persistDashboardInputJson(_data: unknown): void {
|
||||
// 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 演示数据,保证开发能跑通。
|
||||
*/
|
||||
/** 查询并提取当前任务的报告详情;失败或空数据均返回 null。 */
|
||||
export async function fetchDashboardInputJson(
|
||||
taskId: string,
|
||||
opts?: { forceRefresh?: boolean },
|
||||
_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 */
|
||||
}
|
||||
if (!taskId) return null;
|
||||
// 开发演示模式使用与 Gateway 接口同形的本地样例;这样不依赖报告库是否已为
|
||||
// 当前深链 taskId 写入数据,同时真实/生产环境仍始终从 Gateway 读取。
|
||||
if (readRuntimeFlag("VITE_MOCK_SQ_REPORT")) {
|
||||
return extractSqReport(
|
||||
{
|
||||
...SQ_REPORT_MOCK_RESPONSE,
|
||||
data: SQ_REPORT_MOCK_RESPONSE.data.map((item) => ({ ...item, taskId })),
|
||||
},
|
||||
taskId,
|
||||
);
|
||||
}
|
||||
|
||||
// 真实接口模式:**不兜底假数据**。失败/空 → 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;
|
||||
const body = await getTaskReport(taskId);
|
||||
return extractSqReport(body, taskId);
|
||||
}
|
||||
|
||||
/* ---------------------- rwfx 进入预检:3q 是否完成 ---------------------- */
|
||||
|
||||
/**
|
||||
* 「3q(研判情报报告)是否完成」状态:
|
||||
* - ``complete`` = selectSqReport 数组里有有效内容;
|
||||
* - ``incomplete`` = 数组为空 / 每条 contentJson 都是 null/空(3q 未完成);
|
||||
* - ``unknown`` = 缺 consumer 地址 / 请求异常(无法判定,调用方应静默放行)。
|
||||
*/
|
||||
export type SqReportStatus = "complete" | "incomplete" | "unknown";
|
||||
|
||||
/**
|
||||
* rwfx(任务分析)进入时的「3q 是否完成」预检:调 selectSqReport,复用 ``extractSqReport``
|
||||
* 判定该任务是否已有有效研判情报。判定口径与大屏绘制取数完全一致(空/全 null → 无内容)。
|
||||
* - 有可用内容 → ``complete``(正常);
|
||||
* - 空 / 全 null → ``incomplete``(rwfx 据此弹框引导去 3qfx);
|
||||
* - 缺地址 / 请求失败 → ``unknown``(不打扰用户)。
|
||||
*
|
||||
* **数据源由后端配置 ``task_deeplink.test`` 决定**(线上 selectSqReport 外部不可用时):
|
||||
* - ``test=true`` → 直接用 ``config.yaml`` 的 ``mock.sq_report`` 假数据判定,**不发请求**
|
||||
* (与目的树查询/行动解析的 mock 同一套机制,见 [[task-deeplink-config]]);
|
||||
* - ``test=false`` → 调真实接口 ``GET {VITE_AIPI_CONSUMER_URL}/cop/selectSqReport?taskId=``。
|
||||
*/
|
||||
export async function fetchSqReportStatus(taskId: string): Promise<SqReportStatus> {
|
||||
if (!taskId) return "unknown";
|
||||
const cfg = await fetchTaskDeeplinkConfig();
|
||||
// test=true:外部接口不可用,直接用后端 config 的假数据判定(不打真实接口)。
|
||||
if (cfg.test) {
|
||||
return extractSqReport(cfg.mock.sqReport, taskId) ? "complete" : "incomplete";
|
||||
}
|
||||
// 真实模式:打真实接口。service 拦截器统一注入鉴权并返回整包 body;空/全 null → null。
|
||||
const url = sqReportUrl();
|
||||
if (!url) return "unknown";
|
||||
export interface SqReportCheckResult {
|
||||
status: SqReportStatus;
|
||||
report?: unknown;
|
||||
}
|
||||
|
||||
/** rwfx 进入前检查:任务已有可解析报告则 complete,否则 incomplete。 */
|
||||
export async function fetchSqReportCheck(taskId: string): Promise<SqReportCheckResult> {
|
||||
if (!taskId) return { status: "unknown" };
|
||||
try {
|
||||
const body = await requestCrudService.get(url, { taskId });
|
||||
return extractSqReport(body, taskId) ? "complete" : "incomplete";
|
||||
const report = await fetchDashboardInputJson(taskId);
|
||||
return report ? { status: "complete", report } : { status: "incomplete" };
|
||||
} catch {
|
||||
return "unknown";
|
||||
return { status: "unknown" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchSqReportStatus(taskId: string): Promise<SqReportStatus> {
|
||||
return (await fetchSqReportCheck(taskId)).status;
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
import { authStorageGet, authStorageSet } from "@/core/auth/scoped-storage";
|
||||
|
||||
export const EXTERNAL_ACCESS_TOKEN_STORAGE_KEY = "access_token";
|
||||
|
||||
export function normalizeExternalAccessToken(value: unknown): string {
|
||||
if (value == null) return "";
|
||||
const token = String(value).trim();
|
||||
@@ -5,3 +9,53 @@ export function normalizeExternalAccessToken(value: unknown): string {
|
||||
const lowered = token.toLowerCase();
|
||||
return lowered === "null" || lowered === "undefined" ? "" : token;
|
||||
}
|
||||
|
||||
function readTokenFromStoredValue(raw: string | null): string {
|
||||
const token = normalizeExternalAccessToken(raw);
|
||||
if (!token) return "";
|
||||
if (!token.startsWith("{")) return token;
|
||||
try {
|
||||
const parsed = JSON.parse(token);
|
||||
if (!parsed || typeof parsed !== "object") return token;
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
return (
|
||||
normalizeExternalAccessToken(obj.access_token) ||
|
||||
normalizeExternalAccessToken(obj.accessToken) ||
|
||||
normalizeExternalAccessToken(obj.token)
|
||||
);
|
||||
} catch {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
|
||||
export function readStoredExternalAccessTokenValue(): string {
|
||||
return readTokenFromStoredValue(authStorageGet(EXTERNAL_ACCESS_TOKEN_STORAGE_KEY));
|
||||
}
|
||||
|
||||
export function readExternalAccessTokenValue(userInfo: Record<string, unknown>): string {
|
||||
return normalizeExternalAccessToken(userInfo.access_token) || normalizeExternalAccessToken(userInfo.accessToken);
|
||||
}
|
||||
|
||||
export function readCurrentExternalAccessTokenValue(userInfo: Record<string, unknown>): string {
|
||||
return readStoredExternalAccessTokenValue() || readExternalAccessTokenValue(userInfo);
|
||||
}
|
||||
|
||||
export function writeExternalAccessTokenFields(
|
||||
userInfo: Record<string, unknown>,
|
||||
token: string,
|
||||
): void {
|
||||
userInfo.access_token = token;
|
||||
userInfo.accessToken = token;
|
||||
}
|
||||
|
||||
export function writeStoredExternalAccessToken(token: string): void {
|
||||
const normalized = normalizeExternalAccessToken(token);
|
||||
if (normalized) {
|
||||
authStorageSet(EXTERNAL_ACCESS_TOKEN_STORAGE_KEY, normalized);
|
||||
}
|
||||
}
|
||||
|
||||
export function deleteExternalAccessTokenFields(userInfo: Record<string, unknown>): void {
|
||||
delete userInfo.access_token;
|
||||
delete userInfo.accessToken;
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
|
||||
import { authStorageGet, authStorageSet } from "@/core/auth/scoped-storage";
|
||||
import type { ThemeType } from "@/contexts/ThemeContext";
|
||||
|
||||
export const EXTERNAL_LOGIN_STORAGE_KEYS = {
|
||||
ticket: "login.ticket",
|
||||
@@ -58,6 +59,21 @@ export function readExternalLoginParams(): Required<ExternalLoginParams> {
|
||||
* - ``blue`` → 暂无该主题,先用浅色代替(命中 else 分支)
|
||||
* 其余/缺省同样回退浅色。将来若新增 blue 主题,在此扩展映射即可。
|
||||
*/
|
||||
export function resolveThemeFromQuery(themeParam: string | null | undefined): "dark" | "light" {
|
||||
return themeParam === "dark-blue" ? "dark" : "light";
|
||||
export function resolveThemeFromQuery(themeParam: string | null | undefined): ThemeType {
|
||||
switch (themeParam?.trim().toLowerCase()) {
|
||||
case "dark":
|
||||
case "dark-blue":
|
||||
case "darkblue":
|
||||
return "dark";
|
||||
case "blue":
|
||||
case "lightblue":
|
||||
case "light-blue":
|
||||
return "lightblue";
|
||||
case "green":
|
||||
case "lightgreen":
|
||||
case "light-green":
|
||||
return "lightgreen";
|
||||
default:
|
||||
return "light";
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
} from "@/core/auth/scoped-storage";
|
||||
|
||||
const AUTH_STORAGE_KEY = "deerflow.auth";
|
||||
/** Fired in the current tab because the browser `storage` event only reaches other tabs. */
|
||||
export const AUTH_STATE_CHANGED_EVENT = "deerflow:auth-state-changed";
|
||||
|
||||
function isBrowser(): boolean {
|
||||
return typeof window !== "undefined";
|
||||
@@ -48,6 +50,7 @@ export function setStoredAuth(auth: LoginByUsernameResponse) {
|
||||
return;
|
||||
}
|
||||
authStorageSet(AUTH_STORAGE_KEY, JSON.stringify(auth));
|
||||
window.dispatchEvent(new Event(AUTH_STATE_CHANGED_EVENT));
|
||||
}
|
||||
|
||||
export function clearStoredAuth() {
|
||||
@@ -55,6 +58,7 @@ export function clearStoredAuth() {
|
||||
return;
|
||||
}
|
||||
authStorageRemove(AUTH_STORAGE_KEY);
|
||||
window.dispatchEvent(new Event(AUTH_STATE_CHANGED_EVENT));
|
||||
}
|
||||
|
||||
/** 与设置 → 个人信息页「用户名」一致:邮箱 @ 前缀,否则 user_id。 */
|
||||
|
||||
@@ -62,7 +62,7 @@ export function authStorageRemove(key: string): void {
|
||||
* ticket/userId/env/maxkeyOnlineToken/userDetailToken)。用于「开启独立会话」时把当前登录态从
|
||||
* localStorage 快照搬进 sessionStorage,避免切换存储后被登出。
|
||||
*/
|
||||
const PROTECTED_AUTH_EXACT_KEYS = ["deerflow.auth", "userInfo", "userId", "tools_token"];
|
||||
const PROTECTED_AUTH_EXACT_KEYS = ["deerflow.auth", "userInfo", "userId", "tools_token", "access_token"];
|
||||
const PROTECTED_AUTH_PREFIX = "login.";
|
||||
|
||||
function isProtectedAuthKey(key: string): boolean {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
import { requestCrudService } from "@/service/request-axios-service";
|
||||
import { clearTaskContext, persistTaskContext } from "@/core/auth/task-purpose";
|
||||
import { fetchTaskDeeplinkConfig } from "@/core/auth/task-deeplink-config";
|
||||
import { readRuntimeEnv, readRuntimeFlag } from "@/env";
|
||||
import { listBusinessMappings } from "@/strategy-components/api/business-mapping";
|
||||
|
||||
/** xdfx 业务码:深链传入的是「行动id」,需先调 action 接口解析出真正的「任务id」。 */
|
||||
@@ -73,13 +74,13 @@ export function parseGoPath(goPath: string): ParsedGoPath | null {
|
||||
}
|
||||
|
||||
function consumerBaseUrl(): string {
|
||||
const value = import.meta.env.VITE_AIPI_CONSUMER_URL;
|
||||
const value = readRuntimeEnv("VITE_AIPI_CONSUMER_URL");
|
||||
return typeof value === "string" ? value.replace(/\/+$/, "") : "";
|
||||
}
|
||||
|
||||
/** cop-task-detail 是否走本地假数据:开关 `VITE_MOCK_COP_TASK_DETAIL=true`(真实接口未就绪时调试用)。 */
|
||||
function copTaskDetailMockEnabled(): boolean {
|
||||
return (import.meta.env as Record<string, unknown>).VITE_MOCK_COP_TASK_DETAIL === "true";
|
||||
return readRuntimeFlag("VITE_MOCK_COP_TASK_DETAIL");
|
||||
}
|
||||
|
||||
/** cop-task-detail 本地假数据(与真实 data 字段同构;mock 开关开启时返回)。 */
|
||||
@@ -234,7 +235,7 @@ export interface TaskDeeplinkTarget {
|
||||
}
|
||||
|
||||
/** xdfx(行动分析)开场信息里要追加的行动信息:行动标题 + 行动内容 + 行动id。 */
|
||||
interface ActionOpeningInfo {
|
||||
export interface ActionOpeningInfo {
|
||||
/** 行动id(action_id)。 */
|
||||
actionId?: string;
|
||||
/** 行动标题(行动名称 actionName)。 */
|
||||
@@ -264,8 +265,12 @@ function buildOpeningText(detail: CopTaskDetail, taskId: string, action?: Action
|
||||
* 3qfx/rwfx 这类“按任务id 直接问答”的任务工作区,在 ``TaskContext`` 丢失但
|
||||
* ``login.copTaskDetail`` 仍存在时,可用它重新拼出开场词做前端自恢复。
|
||||
*/
|
||||
export function buildTaskOpeningText(detail: CopTaskDetail, taskId: string): string {
|
||||
return buildOpeningText(detail, taskId);
|
||||
export function buildTaskOpeningText(
|
||||
detail: CopTaskDetail,
|
||||
taskId: string,
|
||||
action?: ActionOpeningInfo,
|
||||
): string {
|
||||
return buildOpeningText(detail, taskId, action);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { getAccountDisplayName, getStoredAuth } from "@/core/auth";
|
||||
import {
|
||||
AUTH_STATE_CHANGED_EVENT,
|
||||
getAccountDisplayName,
|
||||
getStoredAuth,
|
||||
} from "@/core/auth";
|
||||
import { isEmbedActive } from "@/core/embed/embed-session";
|
||||
|
||||
const AUTH_STORAGE_KEY = "deerflow.auth";
|
||||
@@ -61,11 +65,13 @@ export function useLiveAccount(): LiveAccount {
|
||||
if (!isEmbedActive()) {
|
||||
window.addEventListener("storage", onStorage);
|
||||
}
|
||||
window.addEventListener(AUTH_STATE_CHANGED_EVENT, refresh);
|
||||
window.addEventListener("focus", refresh);
|
||||
document.addEventListener("visibilitychange", refresh);
|
||||
refresh();
|
||||
return () => {
|
||||
window.removeEventListener("storage", onStorage);
|
||||
window.removeEventListener(AUTH_STATE_CHANGED_EVENT, refresh);
|
||||
window.removeEventListener("focus", refresh);
|
||||
document.removeEventListener("visibilitychange", refresh);
|
||||
};
|
||||
|
||||
@@ -5,12 +5,13 @@ import {
|
||||
persistExternalLoginParams,
|
||||
} from "./external-login";
|
||||
import { authStorageSet } from "@/core/auth/scoped-storage";
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
|
||||
const AUTH_BASE_URL = (import.meta.env.VITE_AUTH_BASE_URL || "").replace(
|
||||
const AUTH_BASE_URL = (readRuntimeEnv("VITE_AUTH_BASE_URL") || "").replace(
|
||||
/\/$/,
|
||||
"",
|
||||
);
|
||||
const CONSUMER_URL = (import.meta.env.VITE_AIPI_CONSUMER_URL || "").replace(
|
||||
const CONSUMER_URL = (readRuntimeEnv("VITE_AIPI_CONSUMER_URL") || "").replace(
|
||||
/\/$/,
|
||||
"",
|
||||
);
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { requestCrudService } from "@/service/request-axios-service";
|
||||
import { authStorageGet, authStorageSet } from "@/core/auth/scoped-storage";
|
||||
import { normalizeExternalAccessToken } from "@/core/auth/external-access-token";
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
import {
|
||||
deleteExternalAccessTokenFields,
|
||||
normalizeExternalAccessToken,
|
||||
readStoredExternalAccessTokenValue,
|
||||
readExternalAccessTokenValue,
|
||||
writeExternalAccessTokenFields,
|
||||
writeStoredExternalAccessToken,
|
||||
} from "@/core/auth/external-access-token";
|
||||
|
||||
const CONSUMER_URL = import.meta.env.VITE_AIPI_CONSUMER_URL || "";
|
||||
const CONSUMER_URL = readRuntimeEnv("VITE_AIPI_CONSUMER_URL") || "";
|
||||
|
||||
export const TOOLS_TOKEN_STORAGE_KEY = "tools_token";
|
||||
export const EXTERNAL_USER_ID_STORAGE_KEY = "userId";
|
||||
@@ -36,6 +44,38 @@ function readStoredYUserId(info: Record<string, unknown>): string {
|
||||
return value == null ? "" : String(value).trim();
|
||||
}
|
||||
|
||||
function normalizeExternalUserId(value: unknown): string {
|
||||
if (value == null) return "";
|
||||
const text = String(value).trim();
|
||||
if (!text) return "";
|
||||
const lowered = text.toLowerCase();
|
||||
return lowered === "null" || lowered === "undefined" ? "" : text;
|
||||
}
|
||||
|
||||
function maskToken(token: string): string {
|
||||
if (!token) return "";
|
||||
if (token.length <= 10) return `${token.slice(0, 2)}***(${token.length})`;
|
||||
return `${token.slice(0, 6)}...${token.slice(-4)}(${token.length})`;
|
||||
}
|
||||
|
||||
function summarizeUserInfo(info: Record<string, unknown>): Record<string, unknown> {
|
||||
return {
|
||||
keys: Object.keys(info),
|
||||
yUserId: info.yUserId,
|
||||
userId: info.userId,
|
||||
userName: info.userName,
|
||||
gateDepartName: info.gateDepartName,
|
||||
typeName: info.typeName,
|
||||
access_token: maskToken(normalizeExternalAccessToken(info.access_token)),
|
||||
accessToken: maskToken(normalizeExternalAccessToken(info.accessToken)),
|
||||
};
|
||||
}
|
||||
|
||||
function logYUserLogin(step: string, payload: Record<string, unknown>): void {
|
||||
if (typeof console === "undefined") return;
|
||||
console.info(`[yUserId-login] ${step}`, payload);
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -84,6 +124,7 @@ function writeCachedYUserInfo(yUserId: string, info: Record<string, unknown>): v
|
||||
function buildExternalUserInfo(
|
||||
yUserId: string,
|
||||
result: Record<string, unknown>,
|
||||
access_token: string | null | undefined,
|
||||
previous: Record<string, unknown>,
|
||||
cached: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
@@ -94,22 +135,34 @@ function buildExternalUserInfo(
|
||||
}
|
||||
}
|
||||
next.yUserId = yUserId;
|
||||
const externalUserId =
|
||||
normalizeExternalUserId(result.id) ||
|
||||
normalizeExternalUserId(result.userId) ||
|
||||
normalizeExternalUserId(result.user_id) ||
|
||||
yUserId;
|
||||
next.userId = externalUserId;
|
||||
|
||||
const incomingAccessToken = normalizeExternalAccessToken(result.accessToken);
|
||||
const incomingAccessToken = readExternalAccessTokenValue(result);
|
||||
if (incomingAccessToken) {
|
||||
next.accessToken = incomingAccessToken;
|
||||
writeExternalAccessTokenFields(next, incomingAccessToken);
|
||||
return next;
|
||||
}
|
||||
|
||||
const queryAccessToken = normalizeExternalAccessToken(access_token);
|
||||
if (queryAccessToken) {
|
||||
writeExternalAccessTokenFields(next, queryAccessToken);
|
||||
return next;
|
||||
}
|
||||
|
||||
const previousYUserId = readStoredYUserId(previous);
|
||||
const previousAccessToken =
|
||||
previousYUserId === yUserId ? normalizeExternalAccessToken(previous.accessToken) : "";
|
||||
const cachedAccessToken = normalizeExternalAccessToken(cached.accessToken);
|
||||
previousYUserId === yUserId ? readExternalAccessTokenValue(previous) : "";
|
||||
const cachedAccessToken = readExternalAccessTokenValue(cached);
|
||||
const fallbackAccessToken = previousAccessToken || cachedAccessToken;
|
||||
if (fallbackAccessToken) {
|
||||
next.accessToken = fallbackAccessToken;
|
||||
writeExternalAccessTokenFields(next, fallbackAccessToken);
|
||||
} else {
|
||||
delete next.accessToken;
|
||||
deleteExternalAccessTokenFields(next);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -121,27 +174,61 @@ function buildExternalUserInfo(
|
||||
export async function loginByYUserId(
|
||||
yUserId: string,
|
||||
token?: string | null,
|
||||
access_token?: string | null,
|
||||
): Promise<void> {
|
||||
if (token) {
|
||||
authStorageSet(TOOLS_TOKEN_STORAGE_KEY, token);
|
||||
}
|
||||
|
||||
const requestUrl = `${CONSUMER_URL}/cop/userDetailByYuserId`;
|
||||
logYUserLogin("request", {
|
||||
requestUrl,
|
||||
yUserId,
|
||||
hasToolsToken: Boolean(token),
|
||||
queryAccessToken: maskToken(normalizeExternalAccessToken(access_token)),
|
||||
});
|
||||
|
||||
const res = (await requestCrudService.get(
|
||||
`${CONSUMER_URL}/cop/userDetailByYuserId`,
|
||||
requestUrl,
|
||||
{ yuserId: yUserId },
|
||||
)) as UserDetailResponse;
|
||||
|
||||
// consumer 返回 { accessToken, gateDepartName, typeName, userName }。
|
||||
// 一并存入路由参数 yUserId,使「应用管理」里 source=yUserId 的路由参数能取到(与
|
||||
// source=userName/gateDepartName/typeName 直接取接口值统一走 userInfo[source])。
|
||||
// 注意:接口也会返回 accessToken,但 XK/PG 及 source=accessToken 要用路由透传的
|
||||
// access_token,故登录流程随后会用 persistAccessToken 覆盖 userInfo.accessToken。
|
||||
// 注意:接口返回的 accessToken 优先;登录 URL 的 access_token 只在接口值为空时兜底。
|
||||
// The consumer API may return accessToken. URL access_token is only used as
|
||||
// a fallback when that API token is empty.
|
||||
const result = res.data ?? {};
|
||||
logYUserLogin("response", {
|
||||
keys: Object.keys(result),
|
||||
id: result.id,
|
||||
userId: result.userId,
|
||||
user_id: result.user_id,
|
||||
userName: result.userName,
|
||||
gateDepartName: result.gateDepartName,
|
||||
typeName: result.typeName,
|
||||
access_token: maskToken(normalizeExternalAccessToken(result.access_token)),
|
||||
accessToken: maskToken(normalizeExternalAccessToken(result.accessToken)),
|
||||
});
|
||||
const previous = readExternalUserInfo();
|
||||
const cached = readCachedYUserInfo(yUserId);
|
||||
const next = buildExternalUserInfo(yUserId, result, previous, cached);
|
||||
const next = buildExternalUserInfo(yUserId, result, access_token, previous, cached);
|
||||
const externalUserId = normalizeExternalUserId(next.userId);
|
||||
if (externalUserId) {
|
||||
authStorageSet(EXTERNAL_USER_ID_STORAGE_KEY, externalUserId);
|
||||
}
|
||||
const externalAccessToken = readExternalAccessTokenValue(next);
|
||||
if (externalAccessToken) {
|
||||
writeStoredExternalAccessToken(externalAccessToken);
|
||||
}
|
||||
authStorageSet(EXTERNAL_USER_INFO_STORAGE_KEY, JSON.stringify(next));
|
||||
writeCachedYUserInfo(yUserId, next);
|
||||
logYUserLogin("stored", {
|
||||
userId: externalUserId,
|
||||
topLevelAccessToken: maskToken(readStoredExternalAccessTokenValue()),
|
||||
userInfo: summarizeUserInfo(next),
|
||||
});
|
||||
}
|
||||
|
||||
export function persistToolsToken(token: string): void {
|
||||
@@ -149,17 +236,18 @@ export function persistToolsToken(token: string): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* 把内网登录路由参数 access_token 合并写入 userInfo.accessToken(覆盖接口返回的同名值)。
|
||||
* 把内网登录路由参数 access_token 合并写入 userInfo.access_token / userInfo.accessToken。
|
||||
* 据此拼参的有:XK/PG 中任务 iframe(XK 用 accessToken、PG 用 access_token,二者均读
|
||||
* external-links.getAccessToken() = userInfo.accessToken);以及「应用管理」里
|
||||
* source=accessToken 的轻应用路由参数(resolveRouteParamValue 取 userInfo.accessToken)。
|
||||
* external-links.getAccessToken());以及「应用管理」里 source=access_token / accessToken
|
||||
* 的轻应用路由参数(resolveRouteParamValue 统一读两种字段)。
|
||||
* 用合并而非覆盖整对象,避免抹掉 loginByYUserId 从 consumer 拿到的用户信息。
|
||||
*/
|
||||
export function persistAccessToken(token: string): void {
|
||||
const trimmed = normalizeExternalAccessToken(token);
|
||||
if (!trimmed) return;
|
||||
const info = readExternalUserInfo();
|
||||
info.accessToken = trimmed;
|
||||
writeExternalAccessTokenFields(info, trimmed);
|
||||
writeStoredExternalAccessToken(trimmed);
|
||||
authStorageSet(EXTERNAL_USER_INFO_STORAGE_KEY, JSON.stringify(info));
|
||||
const yUserId = readStoredYUserId(info);
|
||||
if (yUserId) {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
export async function copyTextToClipboard(text: string): Promise<void> {
|
||||
let clipboardError: unknown;
|
||||
|
||||
if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return;
|
||||
} catch (error) {
|
||||
clipboardError = error;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof document === "undefined" || !document.body) {
|
||||
throw clipboardError instanceof Error
|
||||
? clipboardError
|
||||
: new Error("Clipboard is not available");
|
||||
}
|
||||
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.value = text;
|
||||
textarea.setAttribute("readonly", "");
|
||||
textarea.style.position = "fixed";
|
||||
textarea.style.top = "0";
|
||||
textarea.style.left = "0";
|
||||
textarea.style.width = "1px";
|
||||
textarea.style.height = "1px";
|
||||
textarea.style.opacity = "0";
|
||||
|
||||
document.body.appendChild(textarea);
|
||||
textarea.focus();
|
||||
textarea.select();
|
||||
textarea.setSelectionRange(0, textarea.value.length);
|
||||
|
||||
try {
|
||||
const copied = document.execCommand("copy");
|
||||
if (!copied) {
|
||||
throw clipboardError instanceof Error
|
||||
? clipboardError
|
||||
: new Error("Copy command failed");
|
||||
}
|
||||
} finally {
|
||||
textarea.remove();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import type { ThemeType } from "@/contexts/ThemeContext";
|
||||
|
||||
/**
|
||||
* 公开页(被第三方 iframe 嵌套)的可配置外观:背景色 + 整体明暗主题。
|
||||
@@ -63,19 +64,25 @@ function readFromSearch(search: string): PublicBackground {
|
||||
*/
|
||||
export function normalizePublicTheme(
|
||||
raw: string | null | undefined,
|
||||
): "dark" | "light" | undefined {
|
||||
): ThemeType | undefined {
|
||||
const value = raw?.trim().toLowerCase();
|
||||
if (!value) return undefined;
|
||||
if (value === "dark" || value === "dark-blue" || value === "深蓝" || value === "深色") {
|
||||
return "dark";
|
||||
}
|
||||
if (value === "blue" || value === "lightblue" || value === "light-blue" || value === "浅蓝") {
|
||||
return "lightblue";
|
||||
}
|
||||
if (value === "green" || value === "lightgreen" || value === "light-green" || value === "绿色") {
|
||||
return "lightgreen";
|
||||
}
|
||||
if (value === "light" || value === "red" || value === "红白" || value === "浅色") {
|
||||
return "light";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readThemeFromSearch(search: string): "dark" | "light" | undefined {
|
||||
function readThemeFromSearch(search: string): ThemeType | undefined {
|
||||
const params = new URLSearchParams(search.startsWith("?") ? search : `?${search}`);
|
||||
return normalizePublicTheme(params.get("theme"));
|
||||
}
|
||||
@@ -86,7 +93,7 @@ function readThemeFromSearch(search: string): "dark" | "light" | undefined {
|
||||
* 与 `usePublicBackground` 同样合并两处查询串(hash 路由内优先),
|
||||
* postMessage 的动态值优先级最高。返回 undefined 表示外部未指定。
|
||||
*/
|
||||
export function usePublicEmbedTheme(): "dark" | "light" | undefined {
|
||||
export function usePublicEmbedTheme(): ThemeType | undefined {
|
||||
const location = useLocation();
|
||||
|
||||
const fromUrl = useMemo(() => {
|
||||
@@ -97,7 +104,7 @@ export function usePublicEmbedTheme(): "dark" | "light" | undefined {
|
||||
return inner ?? outer;
|
||||
}, [location.search]);
|
||||
|
||||
const [override, setOverride] = useState<"dark" | "light" | undefined>(undefined);
|
||||
const [override, setOverride] = useState<ThemeType | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
function onMessage(event: MessageEvent) {
|
||||
|
||||
@@ -27,9 +27,11 @@
|
||||
* 正常页标签页里既无这些参数也无这份会话 → 所有 `isXxx()` 恒为 false,完全不受影响。
|
||||
*/
|
||||
|
||||
import type { ThemeType } from "@/contexts/ThemeContext";
|
||||
|
||||
const EMBED_SESSION_KEY = "embed.session";
|
||||
|
||||
export type EmbedTheme = "light" | "dark";
|
||||
export type EmbedTheme = ThemeType;
|
||||
|
||||
/** 本标签页的嵌入会话(按需置位的若干独立开关)。 */
|
||||
export interface EmbedSession {
|
||||
@@ -92,6 +94,8 @@ export function readIsolateParam(search: string): FlagParam {
|
||||
export function resolveEmbedThemeMode(raw: string | null | undefined): EmbedTheme {
|
||||
const v = (raw ?? "").trim().toLowerCase();
|
||||
if (v === "dark" || v === "dark-blue" || v === "深色" || v === "深蓝") return "dark";
|
||||
if (v === "blue" || v === "lightblue" || v === "light-blue" || v === "浅蓝") return "lightblue";
|
||||
if (v === "green" || v === "lightgreen" || v === "light-green" || v === "绿色") return "lightgreen";
|
||||
return "light";
|
||||
}
|
||||
|
||||
@@ -108,7 +112,10 @@ export function readEmbedSession(): EmbedSession | null {
|
||||
const p = JSON.parse(raw) as Partial<EmbedSession>;
|
||||
return {
|
||||
embed: p.embed === true,
|
||||
theme: p.theme === "dark" ? "dark" : "light",
|
||||
theme:
|
||||
p.theme === "dark" || p.theme === "lightblue" || p.theme === "lightgreen"
|
||||
? p.theme
|
||||
: "light",
|
||||
hideJump: p.hideJump === true,
|
||||
hideChrome: p.hideChrome === true,
|
||||
isolate: p.isolate === true,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { resolveThemeFromQuery } from "@/core/auth/external-login";
|
||||
import type { ThemeType } from "@/contexts/ThemeContext";
|
||||
|
||||
const DEFAULT_USERNAME = "guest";
|
||||
|
||||
@@ -41,7 +42,7 @@ export function resolveEmbedChatParams(search: string): EmbedChatParams {
|
||||
return { sessionId, message, username, theme };
|
||||
}
|
||||
|
||||
export function resolveEmbedTheme(themeParam: string): "dark" | "light" {
|
||||
export function resolveEmbedTheme(themeParam: string): ThemeType {
|
||||
return resolveThemeFromQuery(themeParam || null);
|
||||
}
|
||||
|
||||
@@ -50,8 +51,10 @@ export function resolveEmbedTheme(themeParam: string): "dark" | "light" {
|
||||
* 只有明确传 light/红白 才走浅色,其余(dark / dark-blue / 深蓝 / 空)一律深蓝。
|
||||
* 不复用 `resolveEmbedTheme`(它只认严格的 "dark-blue",传 "dark" 会被判成浅色)。
|
||||
*/
|
||||
export function resolveEmbedRoundtableTheme(raw: string): "dark" | "light" {
|
||||
export function resolveEmbedRoundtableTheme(raw: string): ThemeType {
|
||||
const v = raw.trim().toLowerCase();
|
||||
if (v === "light" || v === "red" || v === "红白") return "light";
|
||||
if (v === "blue" || v === "lightblue" || v === "light-blue" || v === "浅蓝") return "lightblue";
|
||||
if (v === "green" || v === "lightgreen" || v === "light-green" || v === "绿色") return "lightgreen";
|
||||
return "dark";
|
||||
}
|
||||
@@ -448,11 +448,13 @@ export const enUS: Translations = {
|
||||
system: "System",
|
||||
light: "Light",
|
||||
dark: "Dark",
|
||||
lightblue: "Light Blue",
|
||||
lightblue: "Light Blue",
|
||||
lightgreen: "Green",
|
||||
systemDescription: "Match the operating system preference automatically.",
|
||||
lightDescription: "Bright palette with higher contrast for daytime.",
|
||||
darkDescription: "Dim palette that reduces glare for focus.",
|
||||
lightblueDescription: "A crisp light palette built around blue.",
|
||||
lightblueDescription: "A crisp light palette built around blue.",
|
||||
lightgreenDescription: "A crisp light palette built around WeKnora green.",
|
||||
languageTitle: "Language",
|
||||
languageDescription: "Switch between languages.",
|
||||
},
|
||||
|
||||
@@ -383,11 +383,13 @@ export interface Translations {
|
||||
system: string;
|
||||
light: string;
|
||||
dark: string;
|
||||
lightblue: string;
|
||||
lightblue: string;
|
||||
lightgreen: string;
|
||||
systemDescription: string;
|
||||
lightDescription: string;
|
||||
darkDescription: string;
|
||||
lightblueDescription: string;
|
||||
lightblueDescription: string;
|
||||
lightgreenDescription: string;
|
||||
languageTitle: string;
|
||||
languageDescription: string;
|
||||
};
|
||||
|
||||
@@ -429,11 +429,13 @@ export const zhCN: Translations = {
|
||||
system: "系统",
|
||||
light: "浅色",
|
||||
dark: "深色",
|
||||
lightblue: "浅蓝",
|
||||
lightblue: "浅蓝",
|
||||
lightgreen: "绿色",
|
||||
systemDescription: "自动跟随系统主题。",
|
||||
lightDescription: "更明亮的配色,适合日间使用。",
|
||||
darkDescription: "更暗的配色,减少眩光方便专注。",
|
||||
lightblueDescription: "以蓝色为主色的清爽浅色配色。",
|
||||
lightblueDescription: "以蓝色为主色的清爽浅色配色。",
|
||||
lightgreenDescription: "采用 WeKnora 绿色的清爽浅色配色。",
|
||||
languageTitle: "语言",
|
||||
languageDescription: "在不同语言之间切换。",
|
||||
},
|
||||
|
||||
@@ -80,6 +80,12 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
{ id: "qa-zzxd", label: "XD应用", icon: Layout, path: "/page/strategy/qa/zzxd" },
|
||||
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
|
||||
{
|
||||
id: "qa-research-chat",
|
||||
label: "课题研究(对话版)",
|
||||
icon: FileText,
|
||||
path: "/page/canvas/ai-writing-chat",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
/** Strategy 模块外部 iframe / 嵌入页链接(来自 Vite 环境变量) */
|
||||
|
||||
import { authStorageGet } from "@/core/auth/scoped-storage";
|
||||
import { normalizeExternalAccessToken } from "@/core/auth/external-access-token";
|
||||
import { readCurrentExternalAccessTokenValue } from "@/core/auth/external-access-token";
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
|
||||
function trimTrailingSlash(url: string): string {
|
||||
return url.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function readEnv(key: string): string {
|
||||
const value = import.meta.env[key];
|
||||
const value = readRuntimeEnv(key);
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
@@ -44,7 +45,7 @@ function readUserInfo(): Record<string, unknown> {
|
||||
|
||||
/** 当前登录态 accessToken(无则空串)。 */
|
||||
export function getAccessToken(): string {
|
||||
return normalizeExternalAccessToken(readUserInfo().accessToken);
|
||||
return readCurrentExternalAccessTokenValue(readUserInfo());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -276,15 +276,34 @@ export async function updatePublishSquares(
|
||||
return data;
|
||||
}
|
||||
|
||||
export type ThemeMode = "light" | "dark" | "lightblue";
|
||||
export type ThemeMode = "light" | "dark" | "lightblue" | "lightgreen";
|
||||
export type ViewMode = "card" | "list";
|
||||
export type LayoutMode = "full" | "compact";
|
||||
export type CompactShortcutParamType = "login" | "theme";
|
||||
|
||||
export interface CompactShortcutRouteParam {
|
||||
key: string;
|
||||
paramType: CompactShortcutParamType;
|
||||
source?: string | null;
|
||||
customValue?: string | null;
|
||||
themeValue?: string | null;
|
||||
}
|
||||
|
||||
export interface CompactShortcutButton {
|
||||
id: string;
|
||||
label: string;
|
||||
url: string;
|
||||
route_params: CompactShortcutRouteParam[];
|
||||
enabled: boolean;
|
||||
sort_order: number;
|
||||
}
|
||||
|
||||
export interface AppearanceSettings {
|
||||
default_theme: ThemeMode;
|
||||
default_skill_view: ViewMode;
|
||||
default_agent_view: ViewMode;
|
||||
default_layout_mode: LayoutMode;
|
||||
compact_shortcut_buttons: CompactShortcutButton[];
|
||||
}
|
||||
|
||||
export interface AppearanceUpdate {
|
||||
@@ -292,6 +311,7 @@ export interface AppearanceUpdate {
|
||||
default_skill_view?: ViewMode;
|
||||
default_agent_view?: ViewMode;
|
||||
default_layout_mode?: LayoutMode;
|
||||
compact_shortcut_buttons?: CompactShortcutButton[];
|
||||
}
|
||||
|
||||
export async function loadAppearanceSettings(): Promise<AppearanceSettings> {
|
||||
@@ -449,16 +469,12 @@ export interface ModelConcurrencySettings {
|
||||
enabled: boolean;
|
||||
default_limit: number;
|
||||
model_limits: Record<string, number>;
|
||||
user_default_limit: number;
|
||||
user_model_limits: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface ModelConcurrencyUpdate {
|
||||
enabled?: boolean;
|
||||
default_limit?: number;
|
||||
model_limits?: Record<string, number>;
|
||||
user_default_limit?: number;
|
||||
user_model_limits?: Record<string, number>;
|
||||
}
|
||||
|
||||
export async function loadSkillCompressionSettings(): Promise<SkillCompressionSettings> {
|
||||
|
||||
@@ -263,24 +263,11 @@ function isModelConcurrencyLimitError(message: string): boolean {
|
||||
return (
|
||||
/\b429\b/.test(message) ||
|
||||
/并发已达到上限/.test(message) ||
|
||||
/并发调用已达到上限/.test(message) ||
|
||||
/使用人数较多/.test(message) ||
|
||||
/too many requests/i.test(message)
|
||||
);
|
||||
}
|
||||
|
||||
function friendlySendLimitMessage(message: string): string | null {
|
||||
if (isActiveRunConflictError(message)) {
|
||||
return "当前对话还在生成回答,请等待本轮回复结束,或先点“停止”再发送新的问题。";
|
||||
}
|
||||
if (isModelConcurrencyLimitError(message)) {
|
||||
return /当前账号对该模型/.test(message)
|
||||
? "当前账号对该模型的并发调用已达到上限,请等待已有回答结束后再试。"
|
||||
: "当前使用人数较多,请稍等一下再试。";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildCurrentUserLabel(): string {
|
||||
const auth = getStoredAuth();
|
||||
if (!auth) {
|
||||
@@ -360,8 +347,17 @@ function lastHumanFromChatModelInput(input: unknown): string {
|
||||
for (let i = flat.length - 1; i >= 0; i--) {
|
||||
const m = flat[i];
|
||||
if (!m || typeof m !== "object") continue;
|
||||
const type = (m as Record<string, unknown>).type ?? (m as Record<string, unknown>).role;
|
||||
const obj = m as Record<string, unknown>;
|
||||
const type = obj.type ?? obj.role;
|
||||
if (type === "human" || type === "user") {
|
||||
const kwargs = obj.additional_kwargs;
|
||||
if (
|
||||
kwargs &&
|
||||
typeof kwargs === "object" &&
|
||||
(kwargs as Record<string, unknown>).hide_from_ui === true
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const text = textFromChatModelOutput(m);
|
||||
if (text) return text;
|
||||
}
|
||||
@@ -617,11 +613,14 @@ export function useThreadStream({
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 上一轮还没结束又发了新问题(409)或并发达到上限(429):
|
||||
// 给一句明确的中文提示,而不是把原始 HTTP 错误抛给用户。
|
||||
const friendly = friendlySendLimitMessage(message);
|
||||
if (friendly) {
|
||||
toast.info(friendly);
|
||||
// 上一轮还没结束又发了新问题(后端 409):给一句明确的中文提示,而不是
|
||||
// 把原始的英文/HTTP 错误抛给用户。
|
||||
if (isActiveRunConflictError(message)) {
|
||||
toast.info("当前对话还在生成回答,请等待本轮回复结束,或先点「停止」再发送新的问题。");
|
||||
return;
|
||||
}
|
||||
if (isModelConcurrencyLimitError(message)) {
|
||||
toast.info("当前使用人数较多,请稍等一下再试。");
|
||||
return;
|
||||
}
|
||||
toast.error(message);
|
||||
@@ -1019,26 +1018,6 @@ export function useThreadStream({
|
||||
);
|
||||
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
const friendly = friendlySendLimitMessage(message);
|
||||
if (friendly) {
|
||||
setOptimisticMessages((messages) => {
|
||||
const human = messages.find((item) => item.type === "human");
|
||||
const kept = human ? [human] : [];
|
||||
return [
|
||||
...kept,
|
||||
{
|
||||
type: "ai",
|
||||
id: `opt-ai-limit-${Date.now()}`,
|
||||
content: friendly,
|
||||
additional_kwargs: { element: "task" },
|
||||
} as Message,
|
||||
];
|
||||
});
|
||||
setIsUploading(false);
|
||||
return;
|
||||
}
|
||||
setOptimisticMessages([]);
|
||||
setIsUploading(false);
|
||||
throw error;
|
||||
|
||||
+29
-18
@@ -1,28 +1,39 @@
|
||||
type EnvValue = string | undefined;
|
||||
|
||||
function readEnv(
|
||||
key:
|
||||
| "VITE_BACKEND_BASE_URL"
|
||||
| "VITE_LANGGRAPH_BASE_URL"
|
||||
| "VITE_CANVAS_LANGGRAPH_BASE_URL"
|
||||
| "VITE_NOTE_API_BASE_URL"
|
||||
| "VITE_AIPI_BACKENP_URL"
|
||||
| "VITE_AIPI_FRONTEND_URL"
|
||||
| "VITE_STATIC_WEBSITE_ONLY"
|
||||
| "VITE_GITHUB_OAUTH_TOKEN",
|
||||
): EnvValue {
|
||||
declare global {
|
||||
interface Window {
|
||||
__CM_RUNTIME_CONFIG__?: Record<string, string | undefined>;
|
||||
}
|
||||
}
|
||||
|
||||
export function readRuntimeEnv(key: string): EnvValue {
|
||||
const runtimeValue =
|
||||
typeof window !== "undefined" ? window.__CM_RUNTIME_CONFIG__?.[key] : undefined;
|
||||
if (typeof runtimeValue === "string" && runtimeValue.trim()) {
|
||||
return runtimeValue.trim();
|
||||
}
|
||||
const value = import.meta.env[key];
|
||||
return typeof value === "string" && value.trim() ? value : undefined;
|
||||
}
|
||||
|
||||
export function readRuntimeFlag(key: string): boolean {
|
||||
return readRuntimeEnv(key) === "true";
|
||||
}
|
||||
|
||||
export const env = {
|
||||
NEXT_PUBLIC_BACKEND_BASE_URL: readEnv("VITE_BACKEND_BASE_URL"),
|
||||
NEXT_PUBLIC_LANGGRAPH_BASE_URL: readEnv("VITE_LANGGRAPH_BASE_URL"),
|
||||
NEXT_PUBLIC_BACKEND_BASE_URL: readRuntimeEnv("VITE_BACKEND_BASE_URL"),
|
||||
NEXT_PUBLIC_LANGGRAPH_BASE_URL: readRuntimeEnv("VITE_LANGGRAPH_BASE_URL"),
|
||||
// Canvas page uses its own LangGraph base URL so it can be independently
|
||||
// routed (e.g. a separate canvas-agent server). Falls back to the main URL.
|
||||
NEXT_PUBLIC_CANVAS_LANGGRAPH_BASE_URL: readEnv("VITE_CANVAS_LANGGRAPH_BASE_URL"),
|
||||
NEXT_PUBLIC_NOTE_API_BASE_URL: readEnv("VITE_NOTE_API_BASE_URL"),
|
||||
NEXT_PUBLIC_NOTEBOOK_API_BASE_URL: readEnv("VITE_AIPI_BACKENP_URL"),
|
||||
NEXT_PUBLIC_STATIC_WEBSITE_ONLY: readEnv("VITE_STATIC_WEBSITE_ONLY"),
|
||||
GITHUB_OAUTH_TOKEN: readEnv("VITE_GITHUB_OAUTH_TOKEN"),
|
||||
NEXT_PUBLIC_CANVAS_LANGGRAPH_BASE_URL: readRuntimeEnv("VITE_CANVAS_LANGGRAPH_BASE_URL"),
|
||||
NEXT_PUBLIC_NOTE_API_BASE_URL: readRuntimeEnv("VITE_NOTE_API_BASE_URL"),
|
||||
NEXT_PUBLIC_NOTEBOOK_API_BASE_URL: readRuntimeEnv("VITE_AIPI_BACKENP_URL"),
|
||||
NEXT_PUBLIC_STATIC_WEBSITE_ONLY: readRuntimeEnv("VITE_STATIC_WEBSITE_ONLY"),
|
||||
/**
|
||||
* Deployment-level compact navigation mode. This is intentionally a runtime
|
||||
* flag so an operations deployment can switch the shell without rebuilding
|
||||
* the frontend bundle.
|
||||
*/
|
||||
FORCE_COLLAPSED_SIDEBAR: readRuntimeFlag("VITE_FORCE_COLLAPSED_SIDEBAR"),
|
||||
GITHUB_OAUTH_TOKEN: readRuntimeEnv("VITE_GITHUB_OAUTH_TOKEN"),
|
||||
};
|
||||
@@ -0,0 +1,445 @@
|
||||
/**
|
||||
* 对话驱动写作台的「意图解析」客户端。
|
||||
*
|
||||
* 两级解析:
|
||||
* 1. `fastPathIntent`:高频确定性短句的前端规则快路径(确认/继续/重新搜索/重写大纲…),
|
||||
* 零延迟、零误判;**高代价动作(定稿/强制定稿/覆盖式重搜的模糊说法)绝不走快路径**。
|
||||
* 2. `streamWritingIntent`:POST /api/ai-writing/sessions/{id}/intent/stream —— 后端读该会话的
|
||||
* graph checkpoint(素材/大纲/草稿/审核摘要)+ LLM 流式解析,实时返回 thinking/text,
|
||||
* 最后一帧返回结构化意图契约。`parseWritingIntent` 保留为一次性兼容接口。
|
||||
*
|
||||
* 返回的 payload 字段与 `UserInterventionPayload` 对齐,可直接喂 `submitIntervention`。
|
||||
*/
|
||||
import { getBackendBaseURL } from '@/core/config';
|
||||
import { apiFetch } from '@/core/api';
|
||||
|
||||
import type { BlockedSection, UserInterventionPayload } from '../types/ai-writing';
|
||||
|
||||
export type WritingIntentSource = 'rule' | 'llm';
|
||||
|
||||
export interface WritingIntentResult {
|
||||
/** 意图标识:confirm_materials / research_again / revise_draft / ask_content / clarify / run_background… */
|
||||
intent: string;
|
||||
/** 需 resume 的暂停点(后端以 checkpoint 里真实 interrupt 为准回传);无动作时为 null */
|
||||
pausePoint: string | null;
|
||||
/** 映射到现有协议的 action;null = 不执行图动作(问答/澄清/控制类) */
|
||||
action: string | null;
|
||||
/** action 非空时可直接喂 submitIntervention 的载荷 */
|
||||
payload: UserInterventionPayload | null;
|
||||
/** 用户的要求需要现有素材之外的信息(素材确认阶段可自动重搜续跑,其余阶段仅提示) */
|
||||
needResearch: boolean;
|
||||
researchQuery: string;
|
||||
/** 问答类意图(ask_content / ask_meta)的直接回答 */
|
||||
answer: string;
|
||||
confidence: number;
|
||||
/** 非空 = 需要向用户澄清,不执行任何动作 */
|
||||
clarify: string;
|
||||
source: WritingIntentSource;
|
||||
}
|
||||
|
||||
/** 前端判定「执行动作」的置信度下限(后端 normalize 已兜底一层,这里再保守一档)。 */
|
||||
export const INTENT_CONFIDENCE_THRESHOLD = 0.55;
|
||||
|
||||
// ── 规则快路径 ────────────────────────────────────────────────────────────────
|
||||
|
||||
const CONFIRM_RE = /^(继续|下一步|确认|好的|好|可以|行|嗯|没问题|OK|ok|Ok|开始吧|通过)$/;
|
||||
const RESEARCH_AGAIN_RE = /^(重新搜索|重新检索|重搜|再搜一次|重新搜)$/;
|
||||
const REOUTLINE_RE = /^(重新规划大纲|重写大纲|大纲重来|重新规划)$/;
|
||||
const TO_EDITOR_RE = /^((交给|让)?编辑(继续)?审核|送审|提交(编辑)?审核)$/;
|
||||
const ACCEPT_REVIEW_RE = /^(按编辑(的)?意见(修改|改)|采纳编辑意见)$/;
|
||||
const SECTION_ALL_SUPPLEMENT_RE = /^(都|全部|全都)(补充|补)检索(素材)?$/;
|
||||
const SECTION_ALL_LOOSE_RE = /^(都|全部|全都)(按通用知识|用通用知识)?(续写|写|继续写)$/;
|
||||
const WRITING_ACTION_VERB_RE = /(新增|增加|添加|加入|加上|补充|补上|补个|补一个|生成|撰写|写一|写个|写成|扩写|缩写|精简|改写|润色|调整|修改|重写|删除|删掉|拆成|合并|挪到|移动|规划|重新规划|设计|安排)/;
|
||||
const WRITING_ACTION_TARGET_RE = /(第[一二三四五六七八九十\d]+[章节段]|章节|章|小节|段落|段|结尾|开头|标题|大纲|内容|案例|表格|总结章|总结章节|结论|摘要|观点|部分)/;
|
||||
const INFO_QUESTION_RE = /(哪些|什么|为什么|是什么|有哪些|多少|是否)/;
|
||||
|
||||
function stripPunct(text: string): string {
|
||||
return text.trim().replace(/[。..!!~~\s]+$/g, '');
|
||||
}
|
||||
|
||||
function looksLikeWritingChangeRequest(text: string): boolean {
|
||||
if (INFO_QUESTION_RE.test(text)) return false;
|
||||
return WRITING_ACTION_VERB_RE.test(text) && WRITING_ACTION_TARGET_RE.test(text);
|
||||
}
|
||||
|
||||
function ruleResult(
|
||||
intent: string,
|
||||
pausePoint: string | null,
|
||||
action: string | null,
|
||||
payload: UserInterventionPayload | null,
|
||||
): WritingIntentResult {
|
||||
return {
|
||||
intent,
|
||||
pausePoint,
|
||||
action,
|
||||
payload,
|
||||
needResearch: false,
|
||||
researchQuery: '',
|
||||
answer: '',
|
||||
confidence: 1,
|
||||
clarify: '',
|
||||
source: 'rule',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 高频短句规则快路径。命中返回结果,未命中返回 null(走后端 LLM)。
|
||||
*
|
||||
* 只做「当前暂停点语义完全无歧义」的映射;一切带自由文本的要求(补充检索内容、
|
||||
* 修改意见等)与高代价动作(定稿/强制定稿)一律交给后端 LLM + 澄清机制。
|
||||
*/
|
||||
export function fastPathIntent(
|
||||
rawText: string,
|
||||
ctx: {
|
||||
pausePoint: string | null;
|
||||
isPaused: boolean;
|
||||
blockedSections?: BlockedSection[];
|
||||
},
|
||||
): WritingIntentResult | null {
|
||||
const text = stripPunct(rawText);
|
||||
if (!text) return null;
|
||||
|
||||
// 「暂停中 + 继续」= 恢复运行(控制类,优先于阶段确认语义)
|
||||
if (ctx.isPaused && CONFIRM_RE.test(text)) {
|
||||
return ruleResult('resume_writing', null, null, null);
|
||||
}
|
||||
|
||||
const pp = ctx.pausePoint;
|
||||
if (!pp) return null;
|
||||
|
||||
if (pp === 'outline_confirm' && looksLikeWritingChangeRequest(text)) {
|
||||
return ruleResult('revise_outline', pp, 're_outline', {
|
||||
action: 're_outline',
|
||||
outlineFeedback: rawText.trim(),
|
||||
});
|
||||
}
|
||||
|
||||
if (pp === 'draft_confirm' && looksLikeWritingChangeRequest(text)) {
|
||||
return ruleResult('revise_draft', pp, 'user_revise', {
|
||||
action: 'user_revise',
|
||||
userRevisionNotes: rawText.trim(),
|
||||
});
|
||||
}
|
||||
|
||||
if (pp === 'review_confirm' && looksLikeWritingChangeRequest(text)) {
|
||||
return ruleResult('accept_review_with_user_notes', pp, 'accept_review', {
|
||||
action: 'accept_review',
|
||||
userRevisionNotes: rawText.trim(),
|
||||
});
|
||||
}
|
||||
|
||||
if (text.length > 12) return null;
|
||||
|
||||
if (pp === 'material_confirm') {
|
||||
if (CONFIRM_RE.test(text)) {
|
||||
// 不带 approvedMaterialIds → 后端默认采用全部素材
|
||||
return ruleResult('confirm_materials', pp, 'confirm', { action: 'confirm' });
|
||||
}
|
||||
if (RESEARCH_AGAIN_RE.test(text)) {
|
||||
return ruleResult('research_again', pp, 're_search', { action: 're_search', approvedMaterialIds: [] });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (pp === 'outline_confirm') {
|
||||
if (CONFIRM_RE.test(text)) {
|
||||
return ruleResult('confirm_outline', pp, 'confirm', { action: 'confirm' });
|
||||
}
|
||||
if (REOUTLINE_RE.test(text)) {
|
||||
return ruleResult('reoutline', pp, 're_outline', { action: 're_outline' });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (pp === 'draft_confirm') {
|
||||
// 「继续/下一步」在草稿阶段的安全缺省是送审(绝不缺省成定稿)
|
||||
if (CONFIRM_RE.test(text) || TO_EDITOR_RE.test(text)) {
|
||||
return ruleResult('to_editor', pp, 'to_editor', { action: 'to_editor' });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (pp === 'review_confirm') {
|
||||
if (CONFIRM_RE.test(text) || ACCEPT_REVIEW_RE.test(text)) {
|
||||
// 不带 selectedIssueIndices → 后端按全部意见修改(与后台挂起的默认放行一致)
|
||||
return ruleResult('accept_review', pp, 'accept_review', { action: 'accept_review' });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (pp === 'section_help') {
|
||||
const blocked = ctx.blockedSections ?? [];
|
||||
if (blocked.length === 0) return null;
|
||||
const buildDecisions = (decision: 'supplement' | 'loose') => ({
|
||||
action: 'section_help',
|
||||
sectionDecisions: blocked.map((b) => ({ sectionTitle: b.sectionTitle, decision })),
|
||||
});
|
||||
if (SECTION_ALL_SUPPLEMENT_RE.test(text)) {
|
||||
return ruleResult('section_supplement_all', pp, 'section_help', buildDecisions('supplement'));
|
||||
}
|
||||
if (SECTION_ALL_LOOSE_RE.test(text)) {
|
||||
return ruleResult('section_loose_all', pp, 'section_help', buildDecisions('loose'));
|
||||
}
|
||||
// 「继续/确认」在求助点语义含糊(补检索 or 续写?),交给 LLM 澄清
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── 后端 LLM 解析 ─────────────────────────────────────────────────────────────
|
||||
|
||||
interface RawIntentResponse {
|
||||
intent?: string;
|
||||
pause_point?: string | null;
|
||||
action?: string | null;
|
||||
payload?: Record<string, unknown> | null;
|
||||
need_research?: boolean;
|
||||
research_query?: string | null;
|
||||
answer?: string | null;
|
||||
confidence?: number;
|
||||
clarify?: string | null;
|
||||
}
|
||||
|
||||
export type WritingIntentStreamEvent =
|
||||
| { type: 'thinking'; chunk: string }
|
||||
| { type: 'text'; chunk: string }
|
||||
| { type: 'result'; result: WritingIntentResult }
|
||||
| { type: 'done' }
|
||||
| { type: 'error'; message: string };
|
||||
|
||||
export type WritingAnswerStreamEvent =
|
||||
| { type: 'start' }
|
||||
| { type: 'thinking'; chunk: string }
|
||||
| { type: 'text'; chunk: string }
|
||||
| { type: 'done' }
|
||||
| { type: 'error'; message: string };
|
||||
|
||||
export interface WritingSuggestionMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
}
|
||||
|
||||
function normalizePayload(raw: Record<string, unknown> | null | undefined, action: string | null): UserInterventionPayload | null {
|
||||
if (!action) return null;
|
||||
const p = raw ?? {};
|
||||
const payload: UserInterventionPayload = { action };
|
||||
if (Array.isArray(p.approvedMaterialIds)) payload.approvedMaterialIds = p.approvedMaterialIds.map(String);
|
||||
if (typeof p.userQuery === 'string' && p.userQuery.trim()) payload.userQuery = p.userQuery.trim();
|
||||
if (typeof p.outlineFeedback === 'string' && p.outlineFeedback.trim()) payload.outlineFeedback = p.outlineFeedback.trim();
|
||||
if (typeof p.userRevisionNotes === 'string' && p.userRevisionNotes.trim()) payload.userRevisionNotes = p.userRevisionNotes.trim();
|
||||
if (typeof p.overrideVerdict === 'boolean') payload.overrideVerdict = p.overrideVerdict;
|
||||
if (Array.isArray(p.selectedIssueIndices)) {
|
||||
payload.selectedIssueIndices = p.selectedIssueIndices
|
||||
.map((n) => Number(n))
|
||||
.filter((n) => Number.isInteger(n) && n >= 0);
|
||||
}
|
||||
if (Array.isArray(p.sectionDecisions)) {
|
||||
payload.sectionDecisions = (p.sectionDecisions as Array<Record<string, unknown>>)
|
||||
.map((d) => ({
|
||||
sectionTitle: String(d.sectionTitle ?? d.section_title ?? ''),
|
||||
decision: (['supplement', 'loose', 'delete'].includes(String(d.decision))
|
||||
? String(d.decision)
|
||||
: 'loose') as 'supplement' | 'loose' | 'delete',
|
||||
}))
|
||||
.filter((d) => d.sectionTitle);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
function normalizeIntentResponse(raw: RawIntentResponse): WritingIntentResult {
|
||||
const action = raw.action || null;
|
||||
return {
|
||||
intent: raw.intent || 'unknown',
|
||||
pausePoint: raw.pause_point || null,
|
||||
action,
|
||||
payload: normalizePayload(raw.payload, action),
|
||||
needResearch: Boolean(raw.need_research),
|
||||
researchQuery: (raw.research_query || '').trim(),
|
||||
answer: (raw.answer || '').trim(),
|
||||
confidence: typeof raw.confidence === 'number' ? Math.max(0, Math.min(1, raw.confidence)) : 0,
|
||||
clarify: (raw.clarify || '').trim(),
|
||||
source: 'llm',
|
||||
};
|
||||
}
|
||||
|
||||
async function* parseSse(body: ReadableStream<Uint8Array>): AsyncGenerator<{ event: string; data: string }> {
|
||||
const reader = body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
let currentEvent = '';
|
||||
|
||||
try {
|
||||
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 line of lines) {
|
||||
const trimmed = line.trimEnd();
|
||||
if (trimmed.startsWith('event: ')) {
|
||||
currentEvent = trimmed.slice(7);
|
||||
} else if (trimmed.startsWith('data: ')) {
|
||||
yield { event: currentEvent, data: trimmed.slice(6) };
|
||||
currentEvent = '';
|
||||
} else if (trimmed === '') {
|
||||
currentEvent = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
/** 后端 LLM 意图解析。会话必须已存在(sessionId = graph thread_id)。 */
|
||||
export async function parseWritingIntent(
|
||||
sessionId: string,
|
||||
body: { text: string; status?: string; pausePoint?: string | null },
|
||||
): Promise<WritingIntentResult> {
|
||||
const resp = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/ai-writing/sessions/${encodeURIComponent(sessionId)}/intent`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
text: body.text,
|
||||
status: body.status ?? null,
|
||||
pause_point: body.pausePoint ?? null,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!resp.ok) {
|
||||
const detail = await resp.text().catch(() => '');
|
||||
throw new Error(`意图解析失败 ${resp.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`);
|
||||
}
|
||||
const raw = (await resp.json()) as RawIntentResponse;
|
||||
return normalizeIntentResponse(raw);
|
||||
}
|
||||
|
||||
/** 后端 LLM 意图解析的 SSE 流式版本,包含 `<think>`/reasoning 思考增量。 */
|
||||
export async function* streamWritingIntent(
|
||||
sessionId: string,
|
||||
body: { text: string; status?: string; pausePoint?: string | null },
|
||||
signal?: AbortSignal,
|
||||
): AsyncGenerator<WritingIntentStreamEvent> {
|
||||
const resp = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/ai-writing/sessions/${encodeURIComponent(sessionId)}/intent/stream`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
text: body.text,
|
||||
status: body.status ?? null,
|
||||
pause_point: body.pausePoint ?? null,
|
||||
}),
|
||||
signal,
|
||||
},
|
||||
);
|
||||
if (!resp.ok) {
|
||||
const detail = await resp.text().catch(() => '');
|
||||
throw new Error(`意图解析失败 ${resp.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`);
|
||||
}
|
||||
if (!resp.body) {
|
||||
throw new Error('意图解析失败:响应体为空');
|
||||
}
|
||||
|
||||
for await (const { event, data } of parseSse(resp.body)) {
|
||||
if (signal?.aborted) return;
|
||||
try {
|
||||
const parsed = JSON.parse(data) as Record<string, unknown>;
|
||||
if (event === 'thinking') {
|
||||
yield { type: 'thinking', chunk: String(parsed.chunk ?? '') };
|
||||
} else if (event === 'text') {
|
||||
yield { type: 'text', chunk: String(parsed.chunk ?? '') };
|
||||
} else if (event === 'result') {
|
||||
yield { type: 'result', result: normalizeIntentResponse(parsed as RawIntentResponse) };
|
||||
} else if (event === 'done') {
|
||||
yield { type: 'done' };
|
||||
return;
|
||||
} else if (event === 'error') {
|
||||
yield { type: 'error', message: String(parsed.message ?? '意图解析流式接口异常') };
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 忽略畸形帧,等待下一帧或 done。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchWritingAnswerSuggestions(
|
||||
sessionId: string,
|
||||
body: { messages: WritingSuggestionMessage[]; n?: number; modelName?: string | null },
|
||||
): Promise<string[]> {
|
||||
const resp = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/ai-writing/sessions/${encodeURIComponent(sessionId)}/suggestions`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
messages: body.messages,
|
||||
n: body.n ?? 3,
|
||||
model_name: body.modelName || null,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!resp.ok) return [];
|
||||
const raw = (await resp.json().catch(() => ({}))) as { suggestions?: unknown[] };
|
||||
return (raw.suggestions ?? [])
|
||||
.map((item) => (typeof item === 'string' ? item.trim() : ''))
|
||||
.filter(Boolean)
|
||||
.slice(0, body.n ?? 3);
|
||||
}
|
||||
|
||||
export async function* streamWritingAnswer(
|
||||
sessionId: string,
|
||||
body: { text: string; status?: string; pausePoint?: string | null; modelName?: string | null },
|
||||
signal?: AbortSignal,
|
||||
): AsyncGenerator<WritingAnswerStreamEvent> {
|
||||
const resp = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/ai-writing/sessions/${encodeURIComponent(sessionId)}/answer/stream`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
text: body.text,
|
||||
status: body.status ?? null,
|
||||
pause_point: body.pausePoint ?? null,
|
||||
model_name: body.modelName || null,
|
||||
}),
|
||||
signal,
|
||||
},
|
||||
);
|
||||
if (!resp.ok) {
|
||||
const detail = await resp.text().catch(() => '');
|
||||
throw new Error(`回答生成失败 ${resp.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`);
|
||||
}
|
||||
if (!resp.body) {
|
||||
throw new Error('回答生成失败:响应体为空');
|
||||
}
|
||||
|
||||
for await (const { event, data } of parseSse(resp.body)) {
|
||||
if (signal?.aborted) return;
|
||||
try {
|
||||
const parsed = JSON.parse(data) as Record<string, unknown>;
|
||||
if (event === 'start') {
|
||||
yield { type: 'start' };
|
||||
} else if (event === 'thinking') {
|
||||
yield { type: 'thinking', chunk: String(parsed.chunk ?? '') };
|
||||
} else if (event === 'text') {
|
||||
yield { type: 'text', chunk: String(parsed.chunk ?? '') };
|
||||
} else if (event === 'done') {
|
||||
yield { type: 'done' };
|
||||
return;
|
||||
} else if (event === 'error') {
|
||||
yield { type: 'error', message: String(parsed.message ?? '回答生成失败') };
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 忽略畸形帧,等待下一帧或 done。
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { getBackendBaseURL } from '@/core/config';
|
||||
import { apiFetch } from '@/core/api';
|
||||
|
||||
export interface AIWritingSampleExtractResult {
|
||||
filename: string;
|
||||
text: string;
|
||||
char_count: number;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
export async function extractAIWritingSample(file: File): Promise<AIWritingSampleExtractResult> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const resp = await apiFetch(`${getBackendBaseURL()}/api/ai-writing/sample/extract`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text().catch(() => '');
|
||||
let detail = '';
|
||||
try {
|
||||
const parsed = text ? JSON.parse(text) as { detail?: unknown } : null;
|
||||
detail = parsed?.detail ? String(parsed.detail) : '';
|
||||
} catch {}
|
||||
if (detail) throw new Error(detail);
|
||||
throw new Error(text || `样文解析失败:${resp.status}`);
|
||||
}
|
||||
return resp.json();
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,920 @@
|
||||
/**
|
||||
* 对话版干预卡(AI 写作·对话驱动写作台专用)。
|
||||
*
|
||||
* 与旧版 `../ai-writing/InterventionCard.tsx` 的关系:**复制后减法**——
|
||||
* - 保留:阶段产物展示(素材列表勾选 / 大纲可点选编辑 / 审核意见勾选)+ 全部确认/动作按钮;
|
||||
* - 移除:每张卡内嵌的自由文本输入框(补充检索输入 / 大纲修改意见 textarea /
|
||||
* 草稿修改意见 textarea / 审核补充指令 textarea)——这些自由输入统一改由页面
|
||||
* 底部的智能输入框(WritingChatComposer)承接,经意图解析层翻译成 action。
|
||||
*
|
||||
* 按钮点击路径与旧卡完全一致:直接调 `onSubmit(UserInterventionPayload)`,
|
||||
* 不经意图解析层,零延迟零误判。旧页面的 InterventionCard 不受本文件影响。
|
||||
*/
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import {
|
||||
ArrowRight, BookOpen, CheckCircle2, ClipboardEdit, FileCheck2, FileText,
|
||||
ListTree, MessageSquareText, RotateCcw, Search, ShieldAlert, ShieldCheck, Trash2,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type {
|
||||
AIMaterial, AIOutline, BlockedSection, ProgressEvent, ReviewIssue,
|
||||
ReviewResult, SectionDecisionKind, SkillSearchStep, UserInterventionPayload,
|
||||
} from '../../types/ai-writing';
|
||||
import { normalizeKeyPoint } from '../../types/ai-writing';
|
||||
import { MaterialsCard } from '../ai-writing/MaterialsCard';
|
||||
import { OutlineCard } from '../ai-writing/OutlineCard';
|
||||
import { SkillStepsCard } from '../ai-writing/SkillStepsCard';
|
||||
|
||||
interface ChatInterventionCardProps {
|
||||
pauseEvent: ProgressEvent;
|
||||
materials: AIMaterial[];
|
||||
outline: AIOutline | null;
|
||||
reviewResult: ReviewResult | null;
|
||||
draftTitle: string;
|
||||
draftWordCount?: number;
|
||||
wordCountTarget?: number;
|
||||
revisionCount: number;
|
||||
skillSearchSteps?: SkillSearchStep[];
|
||||
skillSearchInProgress?: boolean;
|
||||
onSubmit: (payload: UserInterventionPayload) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function ChatInterventionCard({
|
||||
pauseEvent, materials, outline, reviewResult,
|
||||
draftTitle, draftWordCount, wordCountTarget, revisionCount,
|
||||
skillSearchSteps, skillSearchInProgress, onSubmit, disabled,
|
||||
}: ChatInterventionCardProps) {
|
||||
const pausePoint = pauseEvent.pausePoint;
|
||||
|
||||
if (pausePoint === 'material_confirm') {
|
||||
return (
|
||||
<MaterialConfirmChatCard
|
||||
materials={materials}
|
||||
skillSearchSteps={skillSearchSteps ?? []}
|
||||
skillSearchInProgress={skillSearchInProgress}
|
||||
onSubmit={onSubmit}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (pausePoint === 'outline_confirm') {
|
||||
return (
|
||||
<OutlineConfirmChatCard
|
||||
outline={outline ?? pauseEvent.outline ?? null}
|
||||
onSubmit={onSubmit}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (pausePoint === 'draft_confirm') {
|
||||
return (
|
||||
<DraftConfirmChatCard
|
||||
draftTitle={draftTitle}
|
||||
draftWordCount={draftWordCount}
|
||||
wordCountTarget={wordCountTarget}
|
||||
revisionCount={revisionCount}
|
||||
reviewResult={reviewResult}
|
||||
onSubmit={onSubmit}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (pausePoint === 'section_help') {
|
||||
return (
|
||||
<SectionHelpChatCard
|
||||
blockedSections={pauseEvent.blockedSections ?? []}
|
||||
onSubmit={onSubmit}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (pausePoint === 'review_confirm') {
|
||||
return (
|
||||
<ReviewConfirmChatCard
|
||||
reviewResult={reviewResult ?? (pauseEvent.pauseContext?.reviewResult as ReviewResult | null) ?? null}
|
||||
revisionCount={revisionCount}
|
||||
onSubmit={onSubmit}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-md border border-yellow-200 bg-yellow-50/50 dark:border-yellow-900/40 dark:bg-yellow-950/20 px-3 py-2.5 text-xs text-muted-foreground flex items-center gap-2">
|
||||
<ShieldAlert className="size-3.5 text-yellow-500 shrink-0" />
|
||||
等待用户确认({pausePoint})…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── 工具 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeDefaultSelection(issues: ReviewIssue[]): Set<number> {
|
||||
return new Set(issues.map((_, i) => i));
|
||||
}
|
||||
|
||||
function formatSelectedIssues(issues: ReviewIssue[], selectedIndices: Set<number>): string {
|
||||
const selected = issues.filter((_, i) => selectedIndices.has(i));
|
||||
if (selected.length === 0) return '';
|
||||
return selected
|
||||
.map((iss, n) => {
|
||||
const location = iss.location ? `【位置】${iss.location};` : '';
|
||||
const suggestion = iss.suggestion ? `;【建议】${iss.suggestion}` : '';
|
||||
return `${n + 1}. [${iss.category}] ${location}${iss.issue}${suggestion}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
type DecisionTone = 'blue' | 'amber' | 'emerald';
|
||||
|
||||
interface DecisionMetric {
|
||||
label: string;
|
||||
value: string;
|
||||
tone?: DecisionTone | 'muted';
|
||||
}
|
||||
|
||||
const PANEL_TONE: Record<DecisionTone, {
|
||||
shell: string;
|
||||
icon: string;
|
||||
badge: string;
|
||||
}> = {
|
||||
blue: {
|
||||
shell: 'border-blue-200/80 bg-blue-50/35 dark:border-blue-900/40 dark:bg-blue-950/15',
|
||||
icon: 'border-blue-200 bg-background text-blue-600 dark:border-blue-900/50 dark:text-blue-300',
|
||||
badge: 'bg-blue-100 text-blue-700 dark:bg-blue-950/50 dark:text-blue-300',
|
||||
},
|
||||
amber: {
|
||||
shell: 'border-amber-200/90 bg-amber-50/45 dark:border-amber-900/40 dark:bg-amber-950/20',
|
||||
icon: 'border-amber-200 bg-background text-amber-600 dark:border-amber-900/50 dark:text-amber-300',
|
||||
badge: 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-300',
|
||||
},
|
||||
emerald: {
|
||||
shell: 'border-emerald-200/80 bg-emerald-50/35 dark:border-emerald-900/40 dark:bg-emerald-950/15',
|
||||
icon: 'border-emerald-200 bg-background text-emerald-600 dark:border-emerald-900/50 dark:text-emerald-300',
|
||||
badge: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300',
|
||||
},
|
||||
};
|
||||
|
||||
function metricClass(tone: DecisionMetric['tone']) {
|
||||
if (tone === 'blue') return 'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-900/40 dark:bg-blue-950/20 dark:text-blue-300';
|
||||
if (tone === 'amber') return 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300';
|
||||
if (tone === 'emerald') return 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/40 dark:bg-emerald-950/20 dark:text-emerald-300';
|
||||
return 'border-border bg-background/80 text-muted-foreground';
|
||||
}
|
||||
|
||||
function DecisionMetricPill({ metric }: { metric: DecisionMetric }) {
|
||||
return (
|
||||
<span className={cn('inline-flex items-center gap-1 rounded-md border px-2 py-1 text-[11px]', metricClass(metric.tone))}>
|
||||
<span className="text-muted-foreground">{metric.label}</span>
|
||||
<span className="font-medium text-foreground/85 dark:text-foreground/80">{metric.value}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function DecisionPanel({
|
||||
tone = 'blue',
|
||||
icon: Icon,
|
||||
badge,
|
||||
title,
|
||||
description,
|
||||
metrics,
|
||||
children,
|
||||
actions,
|
||||
hint,
|
||||
}: {
|
||||
tone?: DecisionTone;
|
||||
icon: LucideIcon;
|
||||
badge: string;
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
metrics?: DecisionMetric[];
|
||||
children?: ReactNode;
|
||||
actions?: ReactNode;
|
||||
hint?: ReactNode;
|
||||
}) {
|
||||
const classes = PANEL_TONE[tone];
|
||||
return (
|
||||
<section className={cn('overflow-hidden rounded-lg border shadow-sm', classes.shell)}>
|
||||
<div className="p-3">
|
||||
<div className="flex items-start gap-2.5">
|
||||
<div className={cn('mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md border', classes.icon)}>
|
||||
<Icon className="size-4" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<h3 className="truncate text-sm font-semibold leading-5">{title}</h3>
|
||||
<span className={cn('shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium', classes.badge)}>
|
||||
{badge}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{metrics && metrics.length > 0 && (
|
||||
<div className="mt-3 flex flex-wrap gap-1.5">
|
||||
{metrics.map((metric) => (
|
||||
<DecisionMetricPill key={`${metric.label}-${metric.value}`} metric={metric} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{children && (
|
||||
<div className="border-y border-background/80 bg-background/72 p-3 dark:bg-background/35">
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(actions || hint) && (
|
||||
<div className="space-y-2 bg-background/55 p-3 dark:bg-background/25">
|
||||
{actions}
|
||||
{hint}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** 卡片底部的「用对话继续」提示行:告诉用户自由输入去底部输入框。 */
|
||||
function ComposerHint({ examples }: { examples: string }) {
|
||||
return (
|
||||
<div className="flex items-start gap-1.5 rounded-md border bg-muted/35 px-2.5 py-1.5 text-[11px] leading-relaxed text-muted-foreground">
|
||||
<MessageSquareText className="mt-0.5 size-3 shrink-0 text-primary/70" />
|
||||
<span>也可以直接在底部输入框用一句话操作,例如:{examples}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getOutlineStats(outline: AIOutline | null): DecisionMetric[] {
|
||||
if (!outline) return [];
|
||||
let keyPointCount = 0;
|
||||
let subPointCount = 0;
|
||||
for (const section of outline.sections) {
|
||||
const keyPoints = section.keyPoints ?? [];
|
||||
keyPointCount += keyPoints.length;
|
||||
subPointCount += keyPoints.reduce((sum, keyPoint) => sum + normalizeKeyPoint(keyPoint).subPoints.length, 0);
|
||||
}
|
||||
return [
|
||||
{ label: '章节', value: `${outline.sections.length}`, tone: 'blue' },
|
||||
{ label: '小节', value: `${keyPointCount}`, tone: 'emerald' },
|
||||
{ label: '子要点', value: `${subPointCount}`, tone: 'muted' },
|
||||
];
|
||||
}
|
||||
|
||||
function reviewMetrics(review: ReviewResult | null): DecisionMetric[] {
|
||||
if (!review) return [];
|
||||
return [
|
||||
{ label: '综合', value: `${review.overallScore}`, tone: review.verdict === 'pass' ? 'emerald' : 'amber' },
|
||||
{ label: '事实', value: `${review.factScore}` },
|
||||
{ label: '逻辑', value: `${review.logicScore}` },
|
||||
{ label: '语言', value: `${review.languageScore}` },
|
||||
{ label: '意见', value: `${review.revisionNotes.length}` },
|
||||
];
|
||||
}
|
||||
|
||||
function issueCategoryLabel(category: ReviewIssue['category']): string {
|
||||
if (category === 'fact') return '事实';
|
||||
if (category === 'logic') return '逻辑';
|
||||
return '语言';
|
||||
}
|
||||
|
||||
function issueTone(issue: ReviewIssue) {
|
||||
if (issue.severity === 'major') return 'border-red-200 bg-red-50/65 text-red-700 dark:border-red-900/40 dark:bg-red-950/20 dark:text-red-300';
|
||||
if (issue.category === 'logic') return 'border-amber-200 bg-amber-50/65 text-amber-800 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300';
|
||||
if (issue.category === 'fact') return 'border-blue-200 bg-blue-50/65 text-blue-700 dark:border-blue-900/40 dark:bg-blue-950/20 dark:text-blue-300';
|
||||
return 'border-violet-200 bg-violet-50/65 text-violet-700 dark:border-violet-900/40 dark:bg-violet-950/20 dark:text-violet-300';
|
||||
}
|
||||
|
||||
function ChatReviewDecisionView({
|
||||
review,
|
||||
revisionCount,
|
||||
selectedIndices,
|
||||
onToggleIssue,
|
||||
}: {
|
||||
review: ReviewResult;
|
||||
revisionCount?: number;
|
||||
selectedIndices?: Set<number>;
|
||||
onToggleIssue?: (index: number) => void;
|
||||
}) {
|
||||
const selectable = selectedIndices !== undefined && !!onToggleIssue;
|
||||
return (
|
||||
<div className="overflow-hidden rounded-lg border bg-background text-xs">
|
||||
<div className="border-b px-3 py-2.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<p className="font-semibold">编辑审核结果</p>
|
||||
{revisionCount !== undefined && revisionCount > 0 && (
|
||||
<p className="mt-0.5 text-[11px] text-muted-foreground">第 {revisionCount} 次修改稿</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-md px-2 py-1 text-[11px] font-medium',
|
||||
review.verdict === 'pass'
|
||||
? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300'
|
||||
: 'bg-amber-100 text-amber-800 dark:bg-amber-950/40 dark:text-amber-300',
|
||||
)}
|
||||
>
|
||||
{review.verdict === 'pass' ? '通过' : '打回'}
|
||||
</span>
|
||||
<span className="text-sm font-semibold tabular-nums">
|
||||
{review.overallScore}
|
||||
<span className="text-xs font-normal text-muted-foreground"> / 100</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 grid grid-cols-3 gap-1.5">
|
||||
{[
|
||||
['事实', review.factScore],
|
||||
['逻辑', review.logicScore],
|
||||
['语言', review.languageScore],
|
||||
].map(([label, score]) => (
|
||||
<div key={label} className="rounded-md border bg-muted/30 px-2 py-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-[11px] text-muted-foreground">{label}</span>
|
||||
<span className="font-medium tabular-nums">{score}</span>
|
||||
</div>
|
||||
<div className="mt-1 h-1 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className={cn(
|
||||
'h-full rounded-full',
|
||||
Number(score) >= review.passThreshold ? 'bg-emerald-500' : 'bg-amber-500',
|
||||
)}
|
||||
style={{ width: `${Math.max(0, Math.min(100, Number(score)))}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{review.revisionNotes.length > 0 ? (
|
||||
<div className="space-y-2 px-3 py-2.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="font-medium text-muted-foreground">修改意见</p>
|
||||
{selectable && (
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
已选 {selectedIndices.size} / {review.revisionNotes.length}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{review.revisionNotes.map((issue, index) => {
|
||||
const selected = selectedIndices?.has(index) ?? false;
|
||||
return (
|
||||
<button
|
||||
key={`${issue.category}-${issue.location}-${index}`}
|
||||
type="button"
|
||||
disabled={!selectable}
|
||||
onClick={() => onToggleIssue?.(index)}
|
||||
className={cn(
|
||||
'w-full rounded-md border p-2 text-left transition-colors',
|
||||
selectable ? 'hover:border-primary/40 hover:bg-primary/5' : 'cursor-default',
|
||||
selected && 'border-primary/50 bg-primary/5',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
{selectable && (
|
||||
<span
|
||||
className={cn(
|
||||
'mt-0.5 flex size-4 shrink-0 items-center justify-center rounded border',
|
||||
selected ? 'border-primary bg-primary text-primary-foreground' : 'border-input bg-background',
|
||||
)}
|
||||
>
|
||||
{selected && <CheckCircle2 className="size-3" />}
|
||||
</span>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className={cn('rounded border px-1.5 py-0.5 text-[10px] font-medium', issueTone(issue))}>
|
||||
{issue.severity === 'major' ? '严重' : '轻微'} · {issueCategoryLabel(issue.category)}
|
||||
</span>
|
||||
{issue.location && (
|
||||
<span className="truncate text-[10px] text-muted-foreground">位置:{issue.location}</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 leading-relaxed text-foreground/90">{issue.issue}</p>
|
||||
{issue.suggestion && (
|
||||
<p className="mt-1 rounded bg-muted/45 px-2 py-1 leading-relaxed text-muted-foreground">
|
||||
建议:{issue.suggestion}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="px-3 py-2.5 text-xs text-muted-foreground">没有需要修改的审核意见。</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── PAUSE-1 素材确认 ──────────────────────────────────────────────────────────
|
||||
|
||||
function MaterialConfirmChatCard({
|
||||
materials, skillSearchSteps, skillSearchInProgress, onSubmit, disabled,
|
||||
}: {
|
||||
materials: AIMaterial[];
|
||||
skillSearchSteps: SkillSearchStep[];
|
||||
skillSearchInProgress?: boolean;
|
||||
onSubmit: (payload: UserInterventionPayload) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(
|
||||
() => new Set(materials.map((m) => m.id)),
|
||||
);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const allSelected = materials.length > 0 && selectedIds.size === materials.length;
|
||||
|
||||
async function handleConfirm() {
|
||||
setSubmitting(true);
|
||||
await onSubmit({ action: 'confirm', approvedMaterialIds: [...selectedIds] });
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
async function handleReSearch() {
|
||||
setSubmitting(true);
|
||||
// 无输入 = 重新生成检索词、覆盖式重检;带自然语言的补充检索走底部输入框。
|
||||
await onSubmit({ action: 're_search', approvedMaterialIds: [] });
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
if (materials.length === 0) {
|
||||
return (
|
||||
<DecisionPanel
|
||||
tone="amber"
|
||||
icon={ShieldAlert}
|
||||
badge="素材确认"
|
||||
title="未检索到可用素材"
|
||||
description="素材收集专家本次没有检索到相关数据。可以重新搜索、用一句话补充检索方向,或在无素材情况下继续写作。"
|
||||
metrics={[{ label: '素材', value: '0 条', tone: 'amber' }]}
|
||||
actions={(
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button" size="sm" className="flex-1 min-w-[140px] h-8 text-xs gap-1.5"
|
||||
onClick={handleReSearch} disabled={disabled || submitting}
|
||||
>
|
||||
<RotateCcw className="size-3.5" />重新搜索
|
||||
</Button>
|
||||
<Button
|
||||
type="button" variant="outline" size="sm" className="h-8 text-xs gap-1.5 shrink-0"
|
||||
onClick={() => onSubmit({ action: 'confirm', approvedMaterialIds: [] })}
|
||||
disabled={disabled || submitting}
|
||||
>
|
||||
<ArrowRight className="size-3.5" />无数据继续写作
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
hint={<ComposerHint examples="「补充关于××的素材」「换个方向重新搜」" />}
|
||||
>
|
||||
{(skillSearchSteps.length > 0 || skillSearchInProgress) && (
|
||||
<SkillStepsCard steps={skillSearchSteps} inProgress={skillSearchInProgress} />
|
||||
)}
|
||||
</DecisionPanel>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DecisionPanel
|
||||
tone="blue"
|
||||
icon={FileText}
|
||||
badge="素材确认"
|
||||
title="确认素材范围"
|
||||
description="已搜集到候选素材,默认全选。可取消不相关素材,确认后进入三层大纲规划。"
|
||||
metrics={[
|
||||
{ label: '已检索', value: `${materials.length} 条`, tone: 'blue' },
|
||||
{ label: '已选择', value: `${selectedIds.size} 条`, tone: selectedIds.size > 0 ? 'emerald' : 'amber' },
|
||||
]}
|
||||
actions={(
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
已选 {selectedIds.size} / {materials.length} 条素材
|
||||
</span>
|
||||
<div className="flex-1" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedIds(allSelected ? new Set() : new Set(materials.map((m) => m.id)))}
|
||||
className="rounded-md px-2 py-1 text-xs text-primary hover:bg-primary/5"
|
||||
>
|
||||
{allSelected ? '取消全选' : '全选'}
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button" size="sm" className="flex-1 min-w-[180px] h-8 text-xs gap-1.5"
|
||||
onClick={handleConfirm} disabled={disabled || submitting || selectedIds.size === 0}
|
||||
>
|
||||
<CheckCircle2 className="size-3.5" />确认素材,开始规划大纲
|
||||
</Button>
|
||||
<Button
|
||||
type="button" variant="outline" size="sm" className="h-8 text-xs gap-1.5 shrink-0"
|
||||
onClick={handleReSearch} disabled={disabled || submitting}
|
||||
>
|
||||
<RotateCcw className="size-3.5" />重新搜索
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
hint={<ComposerHint examples="「补充关于××的素材」「只用第 1、3 条」「素材可以,继续」" />}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
{skillSearchSteps.length > 0 && <SkillStepsCard steps={skillSearchSteps} />}
|
||||
|
||||
<MaterialsCard
|
||||
materials={materials}
|
||||
selectedIds={selectedIds}
|
||||
onToggle={(id) => {
|
||||
setSelectedIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(id) ? next.delete(id) : next.add(id);
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</DecisionPanel>
|
||||
);
|
||||
}
|
||||
|
||||
// ── PAUSE-2 大纲确认 ──────────────────────────────────────────────────────────
|
||||
|
||||
function OutlineConfirmChatCard({
|
||||
outline: initialOutline, onSubmit, disabled,
|
||||
}: {
|
||||
outline: AIOutline | null;
|
||||
onSubmit: (payload: UserInterventionPayload) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [editedOutline, setEditedOutline] = useState<AIOutline | null>(initialOutline);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function handleConfirm() {
|
||||
setSubmitting(true);
|
||||
await onSubmit({
|
||||
action: 'confirm',
|
||||
editedOutline: editedOutline !== initialOutline ? editedOutline ?? undefined : undefined,
|
||||
});
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<DecisionPanel
|
||||
tone="blue"
|
||||
icon={ListTree}
|
||||
badge="三层大纲"
|
||||
title="确认三层大纲结构"
|
||||
description="大纲结构为「章节 → 小节 → 子要点」。可直接在大纲里微调节点,也可以通过底部输入框要求 AI 重新规划。"
|
||||
metrics={getOutlineStats(editedOutline)}
|
||||
actions={(
|
||||
<Button
|
||||
type="button" size="sm" className="w-full h-8 text-xs gap-1.5"
|
||||
onClick={handleConfirm} disabled={disabled || submitting || !editedOutline}
|
||||
>
|
||||
<CheckCircle2 className="size-3.5" />确认大纲,开始写作
|
||||
</Button>
|
||||
)}
|
||||
hint={<ComposerHint examples="「第二章拆成两节」「重新规划大纲」「加一章讲发展趋势」" />}
|
||||
>
|
||||
{editedOutline
|
||||
? <OutlineCard outline={editedOutline} onChange={setEditedOutline} />
|
||||
: <p className="text-xs text-muted-foreground text-center py-2">大纲加载中…</p>}
|
||||
</DecisionPanel>
|
||||
);
|
||||
}
|
||||
|
||||
// ── PAUSE-3 草稿确认 ──────────────────────────────────────────────────────────
|
||||
|
||||
function DraftConfirmChatCard({
|
||||
draftTitle, draftWordCount, wordCountTarget, revisionCount, reviewResult, onSubmit, disabled,
|
||||
}: {
|
||||
draftTitle: string;
|
||||
draftWordCount?: number;
|
||||
wordCountTarget?: number;
|
||||
revisionCount: number;
|
||||
reviewResult: ReviewResult | null;
|
||||
onSubmit: (payload: UserInterventionPayload) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [selectedIssueIndices, setSelectedIssueIndices] = useState<Set<number>>(
|
||||
() => makeDefaultSelection(reviewResult?.revisionNotes ?? []),
|
||||
);
|
||||
|
||||
function toggleIssue(index: number) {
|
||||
setSelectedIssueIndices((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(index) ? next.delete(index) : next.add(index);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function submit(action: string) {
|
||||
setSubmitting(true);
|
||||
await onSubmit({ action });
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
async function handleApplyReview() {
|
||||
if (!reviewResult) return;
|
||||
const formattedNotes = formatSelectedIssues(reviewResult.revisionNotes, selectedIssueIndices);
|
||||
setSubmitting(true);
|
||||
await onSubmit({
|
||||
action: 'user_revise',
|
||||
userRevisionNotes: formattedNotes,
|
||||
selectedIssueIndices: [...selectedIssueIndices],
|
||||
});
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
const hasReview = reviewResult != null && reviewResult.revisionNotes.length > 0;
|
||||
|
||||
const showWordCmp = wordCountTarget != null && wordCountTarget > 0 && draftWordCount != null && draftWordCount > 0;
|
||||
const wordDiff = showWordCmp ? draftWordCount! - wordCountTarget! : 0;
|
||||
const wordWithin = Math.abs(wordDiff) <= 100;
|
||||
|
||||
return (
|
||||
<DecisionPanel
|
||||
tone="blue"
|
||||
icon={FileCheck2}
|
||||
badge="草稿确认"
|
||||
title="草稿已完成,请确认下一步"
|
||||
description={(
|
||||
<>
|
||||
{draftTitle ? `《${draftTitle}》` : '草稿'}
|
||||
{revisionCount > 0 ? `(第 ${revisionCount} 次修改稿)` : '(初稿)'}
|
||||
· 右侧可预览完整内容。
|
||||
</>
|
||||
)}
|
||||
metrics={[
|
||||
...(draftWordCount ? [{ label: '当前字数', value: `${draftWordCount}`, tone: wordWithin ? 'emerald' as const : 'amber' as const }] : []),
|
||||
...(wordCountTarget ? [{ label: '目标字数', value: `${wordCountTarget}` }] : []),
|
||||
...(reviewResult ? reviewMetrics(reviewResult).slice(0, 2) : []),
|
||||
]}
|
||||
actions={(
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between text-[11px] text-muted-foreground">
|
||||
<span>下一步处理</span>
|
||||
{showWordCmp && wordDiff !== 0 && (
|
||||
<span className={wordWithin ? 'text-muted-foreground' : 'text-orange-600 dark:text-orange-400'}>
|
||||
{wordDiff > 0 ? '超出' : '不足'} {Math.abs(wordDiff)} 字{wordWithin ? ',在误差范围内' : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{hasReview && (
|
||||
<Button
|
||||
type="button" variant="outline" size="sm"
|
||||
className="w-full h-8 text-xs gap-1.5 border-orange-200 text-orange-700 hover:bg-orange-50 dark:border-orange-800 dark:text-orange-400 dark:hover:bg-orange-950/30"
|
||||
onClick={handleApplyReview}
|
||||
disabled={disabled || submitting || selectedIssueIndices.size === 0}
|
||||
>
|
||||
<ClipboardEdit className="size-3.5" />
|
||||
按编辑审核意见修改
|
||||
{selectedIssueIndices.size < reviewResult!.revisionNotes.length && (
|
||||
<span className="text-[10px] opacity-70">
|
||||
(已选 {selectedIssueIndices.size}/{reviewResult!.revisionNotes.length})
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="flex gap-1.5">
|
||||
<Button
|
||||
type="button" variant="outline" size="sm" className="flex-1 h-8 text-xs gap-1.5"
|
||||
onClick={() => submit('to_editor')} disabled={disabled || submitting}
|
||||
>
|
||||
<ArrowRight className="size-3.5" />让编辑继续审核
|
||||
</Button>
|
||||
<Button
|
||||
type="button" size="sm" className="flex-1 h-8 text-xs gap-1.5"
|
||||
onClick={() => submit('finalize')} disabled={disabled || submitting}
|
||||
>
|
||||
<CheckCircle2 className="size-3.5" />确认定稿
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
hint={<ComposerHint examples="「第三段太啰嗦,精简一下」「结尾补个案例」「更口语一点」" />}
|
||||
>
|
||||
{reviewResult ? (
|
||||
<ChatReviewDecisionView
|
||||
review={reviewResult}
|
||||
revisionCount={revisionCount}
|
||||
selectedIndices={hasReview ? selectedIssueIndices : undefined}
|
||||
onToggleIssue={hasReview ? toggleIssue : undefined}
|
||||
/>
|
||||
) : (
|
||||
<div className="rounded-md border bg-background/80 px-3 py-2 text-xs text-muted-foreground">
|
||||
当前草稿暂无编辑审核结果,可直接送审或定稿。
|
||||
</div>
|
||||
)}
|
||||
</DecisionPanel>
|
||||
);
|
||||
}
|
||||
|
||||
// ── PAUSE-4 编辑打回确认 ──────────────────────────────────────────────────────
|
||||
|
||||
function ReviewConfirmChatCard({
|
||||
reviewResult, revisionCount, onSubmit, disabled,
|
||||
}: {
|
||||
reviewResult: ReviewResult | null;
|
||||
revisionCount: number;
|
||||
onSubmit: (payload: UserInterventionPayload) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [selectedIssueIndices, setSelectedIssueIndices] = useState<Set<number>>(
|
||||
() => makeDefaultSelection(reviewResult?.revisionNotes ?? []),
|
||||
);
|
||||
|
||||
function toggleIssue(index: number) {
|
||||
setSelectedIssueIndices((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(index) ? next.delete(index) : next.add(index);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function handleAccept() {
|
||||
setSubmitting(true);
|
||||
const issueNotes = reviewResult
|
||||
? formatSelectedIssues(reviewResult.revisionNotes, selectedIssueIndices)
|
||||
: '';
|
||||
await onSubmit({
|
||||
action: 'accept_review',
|
||||
userRevisionNotes: issueNotes || undefined,
|
||||
selectedIssueIndices: [...selectedIssueIndices],
|
||||
});
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
async function handleForce() {
|
||||
setSubmitting(true);
|
||||
await onSubmit({ action: 'force_finalize', overrideVerdict: true });
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
const hasIssues = (reviewResult?.revisionNotes.length ?? 0) > 0;
|
||||
|
||||
return (
|
||||
<DecisionPanel
|
||||
tone="amber"
|
||||
icon={ShieldCheck}
|
||||
badge="审核确认"
|
||||
title="编辑认为文章需要修改"
|
||||
description="勾选希望采纳的意见,再让作家重写;也可以忽略编辑意见并强制定稿。"
|
||||
metrics={reviewMetrics(reviewResult)}
|
||||
actions={(
|
||||
<div className="space-y-2">
|
||||
<div className="text-[11px] text-muted-foreground">请选择审核意见处理方式</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button" size="sm" className="flex-1 h-8 text-xs gap-1.5"
|
||||
onClick={handleAccept}
|
||||
disabled={disabled || submitting || (hasIssues && selectedIssueIndices.size === 0)}
|
||||
>
|
||||
<ClipboardEdit className="size-3.5" />按编辑意见修改
|
||||
{hasIssues && selectedIssueIndices.size < reviewResult!.revisionNotes.length && (
|
||||
<span className="text-[10px] opacity-70">
|
||||
(已选 {selectedIssueIndices.size}/{reviewResult!.revisionNotes.length})
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
type="button" variant="outline" size="sm" className="h-8 text-xs gap-1.5 shrink-0 text-destructive hover:text-destructive"
|
||||
onClick={handleForce} disabled={disabled || submitting}
|
||||
>
|
||||
<ShieldAlert className="size-3.5" />强制定稿
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
hint={<ComposerHint examples="「再补一条意见:核查数据来源」「只按第 1、2 条改」「不改了,定稿」" />}
|
||||
>
|
||||
{reviewResult ? (
|
||||
<ChatReviewDecisionView
|
||||
review={reviewResult}
|
||||
revisionCount={revisionCount}
|
||||
selectedIndices={hasIssues ? selectedIssueIndices : undefined}
|
||||
onToggleIssue={hasIssues ? toggleIssue : undefined}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground text-center py-1">审核结果加载中…</p>
|
||||
)}
|
||||
</DecisionPanel>
|
||||
);
|
||||
}
|
||||
|
||||
// ── 素材不足求助 ──────────────────────────────────────────────────────────────
|
||||
|
||||
const DECISION_OPTIONS: { value: SectionDecisionKind; label: string; icon: typeof Search }[] = [
|
||||
{ value: 'supplement', label: '补充检索素材', icon: Search },
|
||||
{ value: 'loose', label: '按通用知识续写', icon: BookOpen },
|
||||
{ value: 'delete', label: '删除该章节', icon: Trash2 },
|
||||
];
|
||||
|
||||
function SectionHelpChatCard({
|
||||
blockedSections, onSubmit, disabled,
|
||||
}: {
|
||||
blockedSections: BlockedSection[];
|
||||
onSubmit: (payload: UserInterventionPayload) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [decisions, setDecisions] = useState<Record<string, SectionDecisionKind>>(
|
||||
() => Object.fromEntries(blockedSections.map((b) => [b.sectionTitle, 'supplement'])),
|
||||
);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const hasSupplement = Object.values(decisions).some((d) => d === 'supplement');
|
||||
|
||||
async function handleSubmit() {
|
||||
setSubmitting(true);
|
||||
await onSubmit({
|
||||
action: 'section_help',
|
||||
sectionDecisions: blockedSections.map((b) => ({
|
||||
sectionTitle: b.sectionTitle,
|
||||
decision: decisions[b.sectionTitle] ?? 'supplement',
|
||||
})),
|
||||
});
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<DecisionPanel
|
||||
tone="amber"
|
||||
icon={ShieldAlert}
|
||||
badge="素材不足"
|
||||
title="部分章节素材不足,需要你决定"
|
||||
description={`严格依据素材模式下,以下 ${blockedSections.length} 个章节缺少足够素材支撑写作。请为每个章节选择处理方式。`}
|
||||
metrics={[
|
||||
{ label: '受影响章节', value: `${blockedSections.length}`, tone: 'amber' },
|
||||
{ label: '需补检索', value: `${Object.values(decisions).filter((d) => d === 'supplement').length}` },
|
||||
]}
|
||||
actions={(
|
||||
<div className="space-y-2">
|
||||
{hasSupplement && (
|
||||
<p className="text-[11px] text-amber-600 dark:text-amber-400">
|
||||
含「补充检索素材」的章节将触发重新检索并重新规划大纲,本轮其它选择不生效。
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
type="button" size="sm" className="w-full h-8 text-xs gap-1.5"
|
||||
onClick={handleSubmit} disabled={disabled || submitting}
|
||||
>
|
||||
<CheckCircle2 className="size-3.5" />提交并继续
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
hint={<ComposerHint examples="「都补充检索」「都按通用知识写」「第一个删掉,其他补检索」" />}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
{blockedSections.map((b) => (
|
||||
<div key={b.sectionTitle} className="rounded-md border bg-background/85 p-2.5 space-y-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium">{b.sectionTitle}</p>
|
||||
<p className="text-[11px] text-muted-foreground mt-0.5">{b.reason}</p>
|
||||
</div>
|
||||
<div className="flex gap-1">
|
||||
{DECISION_OPTIONS.map((opt) => {
|
||||
const active = (decisions[b.sectionTitle] ?? 'supplement') === opt.value;
|
||||
const Icon = opt.icon;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
disabled={disabled || submitting}
|
||||
onClick={() => setDecisions((p) => ({ ...p, [b.sectionTitle]: opt.value }))}
|
||||
className={cn(
|
||||
'flex-1 flex items-center justify-center gap-1 rounded px-1.5 py-1 text-[11px] border transition-colors',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-input text-muted-foreground hover:bg-muted/50',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-3 shrink-0" />
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</DecisionPanel>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,20 +14,20 @@ import { cn } from '@/lib/utils';
|
||||
export interface FlowStage {
|
||||
key: string;
|
||||
label: string;
|
||||
emoji: string;
|
||||
mark: 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: '🏁' },
|
||||
{ key: 'intent', label: '意图理解', mark: '意' },
|
||||
{ key: 'research', label: '素材搜集', mark: '搜' },
|
||||
{ key: 'material_confirm', label: '素材确认', mark: '素' },
|
||||
{ key: 'outline', label: '大纲规划', mark: '纲' },
|
||||
{ key: 'outline_confirm', label: '大纲确认', mark: '确' },
|
||||
{ key: 'draft', label: '写作', mark: '写' },
|
||||
{ key: 'draft_confirm', label: '草稿确认', mark: '稿' },
|
||||
{ key: 'review', label: '编辑审核', mark: '审' },
|
||||
{ key: 'done', label: '定稿', mark: '定' },
|
||||
];
|
||||
|
||||
export const FLOW_STAGE_LABEL: Record<string, string> = Object.fromEntries(
|
||||
@@ -40,12 +40,12 @@ const LINE = 'bg-slate-300 dark:bg-border';
|
||||
|
||||
function StageNode({
|
||||
label,
|
||||
emoji,
|
||||
mark,
|
||||
state,
|
||||
note,
|
||||
}: {
|
||||
label: string;
|
||||
emoji: string;
|
||||
mark: string;
|
||||
state: StageState;
|
||||
note?: string | null;
|
||||
}) {
|
||||
@@ -55,14 +55,14 @@ function StageNode({
|
||||
{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',
|
||||
'relative flex size-11 items-center justify-center rounded-full border-2 bg-white text-base font-semibold text-primary 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}
|
||||
{mark}
|
||||
{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" />
|
||||
@@ -127,7 +127,7 @@ export function AIWritingFlowChart({
|
||||
{idx > 0 && <div className={cn('mt-[22px] h-px w-5 shrink-0', LINE)} />}
|
||||
<StageNode
|
||||
label={stage.label}
|
||||
emoji={stage.emoji}
|
||||
mark={stage.mark}
|
||||
state={stateOf(idx)}
|
||||
note={stage.key === activeKey ? note : undefined}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { PenLine, SlidersHorizontal } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { FileText, Loader2, PenLine, SlidersHorizontal, Upload } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
@@ -17,6 +17,8 @@ import { useStudioNotebooks, useNotebookSources } from '@/core/studio/hooks';
|
||||
import type { AIWritingRequest } from '../../types/ai-writing';
|
||||
import { useArticleTypes } from '../../hooks/useArticleTypes';
|
||||
import { useWritingForm } from '../../contexts/WritingFormContext';
|
||||
import { extractAIWritingSample } from '../../api/ai-writing-sample';
|
||||
import { ResearchTemplatesPanel } from './ResearchTemplatesPanel';
|
||||
|
||||
interface AIWritingFormProps {
|
||||
onSubmit: (req: AIWritingRequest) => void;
|
||||
@@ -41,14 +43,27 @@ const INPUT_CLASS =
|
||||
const DEFAULT_KEYWORD_COUNT = 1;
|
||||
const DEFAULT_AUDIENCE = '普通读者';
|
||||
type MaterialSource = 'general' | 'knowledge_base' | 'notebook';
|
||||
type WritingModeType = 'normal' | 'imitate';
|
||||
const MAX_INTENT_LENGTH = 500;
|
||||
const MAX_SAMPLE_TEXT_LENGTH = 120000;
|
||||
|
||||
const MATERIAL_SOURCE_OPTIONS: Array<{ value: MaterialSource; label: string; desc: string }> = [
|
||||
{ value: 'general', label: '通用检索', desc: '用素材收集专家配置的技能检索(默认:知识库检索)' },
|
||||
{ value: 'knowledge_base', label: '知识库检索', desc: '直连内网知识库检索接口,不走技能编排' },
|
||||
{ value: 'general', label: '通用检索', desc: '素材收集专家按配置技能检索' },
|
||||
{ value: 'knowledge_base', label: '知识库检索', desc: '直连内网知识库检索接口' },
|
||||
{ value: 'notebook', label: '我的空间', desc: '从空间中检索素材' },
|
||||
];
|
||||
|
||||
const WRITING_MODE_OPTIONS: Array<{ value: WritingModeType; label: string }> = [
|
||||
{ value: 'normal', label: '普通写作' },
|
||||
{ value: 'imitate', label: '样文仿写' },
|
||||
];
|
||||
|
||||
const IMITATE_STRENGTH_OPTIONS: Array<{ value: 'light' | 'medium' | 'strong'; label: string }> = [
|
||||
{ value: 'light', label: '轻度' },
|
||||
{ value: 'medium', label: '中度' },
|
||||
{ value: 'strong', label: '高度' },
|
||||
];
|
||||
|
||||
const FIELD_LABEL_CLASS = 'text-[16px] font-semibold leading-none text-[#222] dark:text-[#AACEFF]';
|
||||
const FIELD_TRIGGER_CLASS =
|
||||
'h-12 w-full rounded-xl border-[#e8dedd] bg-white text-sm shadow-sm';
|
||||
@@ -61,6 +76,11 @@ export function AIWritingForm({
|
||||
}: AIWritingFormProps) {
|
||||
const {
|
||||
intent, setIntent,
|
||||
writingModeType, setWritingModeType,
|
||||
sampleText, setSampleText,
|
||||
sampleFilename, setSampleFilename,
|
||||
imitateStrength, setImitateStrength,
|
||||
preserveSampleStructure, setPreserveSampleStructure,
|
||||
showOutline, setShowOutline,
|
||||
outlineText, setOutlineText,
|
||||
articleType, setArticleType,
|
||||
@@ -77,6 +97,10 @@ export function AIWritingForm({
|
||||
modelName, setModelName,
|
||||
} = useWritingForm();
|
||||
|
||||
const [sampleUploading, setSampleUploading] = useState(false);
|
||||
const [sampleMessage, setSampleMessage] = useState('');
|
||||
const [sampleError, setSampleError] = useState('');
|
||||
|
||||
const { models, isLoading: modelsLoading } = useModels();
|
||||
const { notebooks, isLoading: notebooksLoading } = useStudioNotebooks(!studioToken);
|
||||
const { sources, isLoading: sourcesLoading } = useNotebookSources(selectedNotebookId, studioToken);
|
||||
@@ -139,7 +163,7 @@ export function AIWritingForm({
|
||||
|
||||
function handleMaterialSourceChange(val: MaterialSource) {
|
||||
setMaterialSource(val);
|
||||
// studioToken 模式下空间和文档已锁定,切换素材来源时不清空
|
||||
// studioToken 模式下空间和文档已锁定,切换素材来源时不清空。
|
||||
if (val !== 'notebook' && !studioToken) {
|
||||
setSelectedNotebookId(null);
|
||||
setSelectedDocumentIds([]);
|
||||
@@ -154,13 +178,41 @@ export function AIWritingForm({
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSampleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = '';
|
||||
if (!file) return;
|
||||
setSampleUploading(true);
|
||||
setSampleError('');
|
||||
setSampleMessage('');
|
||||
try {
|
||||
const result = await extractAIWritingSample(file);
|
||||
setSampleFilename(result.filename);
|
||||
setSampleText(result.text);
|
||||
setSampleMessage(result.truncated ? '已提取样文文本,内容较长已截断。' : '已提取样文文本。');
|
||||
} catch (err) {
|
||||
setSampleError(err instanceof Error ? err.message : '样文解析失败');
|
||||
} finally {
|
||||
setSampleUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!intent.trim()) return;
|
||||
if (writingModeType === 'imitate' && !sampleText.trim()) {
|
||||
setSampleError('请上传样文或粘贴样文文本');
|
||||
return;
|
||||
}
|
||||
const wordCount = Math.max(100, parseInt(wordCountInput, 10) || 800);
|
||||
onSubmit({
|
||||
userIntent: intent.trim(),
|
||||
userOutline: outlineText.trim() || undefined,
|
||||
writingModeType,
|
||||
sampleText: writingModeType === 'imitate' ? sampleText.trim() : undefined,
|
||||
sampleFilename: writingModeType === 'imitate' ? sampleFilename || '粘贴文本' : undefined,
|
||||
imitateStrength,
|
||||
preserveSampleStructure,
|
||||
articleType,
|
||||
targetAudience: hideAdvancedFields
|
||||
? DEFAULT_AUDIENCE
|
||||
@@ -171,12 +223,10 @@ export function AIWritingForm({
|
||||
writingMode: skipResearch ? 'loose' : hideAdvancedFields ? 'loose' : strictMode ? 'strict' : 'loose',
|
||||
addReferences,
|
||||
skipResearch,
|
||||
// 跳过素材收集时检索类型无意义,归一为 general
|
||||
materialSource: skipResearch ? 'general' : materialSource,
|
||||
modelName: selectedModel?.name || modelName || undefined,
|
||||
// 只有选了"我的空间"且未跳过素材收集才传笔记参数
|
||||
noteSearchSpaceId: !skipResearch && materialSource === 'notebook' ? (selectedNotebookId ?? undefined) : undefined,
|
||||
noteSourceIds: !skipResearch && materialSource === 'notebook' && selectedNotebookId != null ? selectedDocumentIds : undefined,
|
||||
noteSearchSpaceId: !skipResearch ? (selectedNotebookId ?? undefined) : undefined,
|
||||
noteSourceIds: !skipResearch && selectedNotebookId != null ? selectedDocumentIds : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -190,6 +240,106 @@ export function AIWritingForm({
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 space-y-2">
|
||||
<label className={FIELD_LABEL_CLASS}>写作模式</label>
|
||||
<div className="grid grid-cols-2 gap-2 rounded-xl border border-[#e8dedd] bg-[#f9f5f5] p-1 dark:border-[#1B477E] dark:bg-[#022248]/40">
|
||||
{WRITING_MODE_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => setWritingModeType(opt.value)}
|
||||
className={cn(
|
||||
'h-10 rounded-lg text-sm font-medium transition-colors',
|
||||
writingModeType === opt.value
|
||||
? 'bg-white text-primary shadow-sm dark:bg-[#0B376A] dark:text-white'
|
||||
: 'text-muted-foreground hover:bg-white/70 dark:text-[#AACEFF]/70 dark:hover:bg-[#0B376A]/60',
|
||||
)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{writingModeType === 'imitate' && (
|
||||
<div className="mt-4 space-y-3 rounded-xl border border-[#e8dedd] bg-[#f9f5f5] p-3 dark:border-[#1B477E] dark:bg-[#022248]/40">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className={FIELD_LABEL_CLASS}>样文</label>
|
||||
<label
|
||||
className={cn(
|
||||
'inline-flex h-9 cursor-pointer items-center gap-2 rounded-lg border border-[#e8dedd] bg-white px-3 text-sm font-medium text-foreground shadow-sm transition-colors hover:bg-[#fff8f8]',
|
||||
'dark:border-[#1B477E] dark:bg-[#022248] dark:text-[#AACEFF]',
|
||||
disabled || sampleUploading ? 'pointer-events-none opacity-60' : '',
|
||||
)}
|
||||
>
|
||||
{sampleUploading ? <Loader2 className="size-4 animate-spin" /> : <Upload className="size-4" />}
|
||||
上传文件
|
||||
<input
|
||||
type="file"
|
||||
accept=".doc,.docx,.pdf,.md,.markdown,.txt"
|
||||
className="sr-only"
|
||||
disabled={disabled || sampleUploading}
|
||||
onChange={handleSampleFileChange}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{sampleFilename && (
|
||||
<div className="flex items-center gap-2 rounded-lg bg-white px-3 py-2 text-xs text-muted-foreground dark:bg-[#022248] dark:text-[#AACEFF]/80">
|
||||
<FileText className="size-3.5" />
|
||||
<span className="truncate">{sampleFilename}</span>
|
||||
</div>
|
||||
)}
|
||||
<Textarea
|
||||
placeholder="上传 Word/PDF/Markdown/TXT,或直接粘贴一篇样文。AI 会先分析文风,再按你的写作意图仿写一篇新文章。"
|
||||
value={sampleText}
|
||||
onChange={(e) => {
|
||||
setSampleText(e.target.value.slice(0, MAX_SAMPLE_TEXT_LENGTH));
|
||||
setSampleError('');
|
||||
if (!sampleFilename) setSampleFilename('粘贴文本');
|
||||
}}
|
||||
disabled={disabled || sampleUploading}
|
||||
rows={8}
|
||||
maxLength={MAX_SAMPLE_TEXT_LENGTH}
|
||||
className="max-h-[13.5rem] resize-none overflow-y-auto rounded-2xl border-[#e8dedd] bg-white px-4 py-3 text-sm leading-6 shadow-sm [field-sizing:fixed]"
|
||||
/>
|
||||
<div className="flex items-center justify-between gap-3 text-xs text-muted-foreground/80">
|
||||
<span>{sampleText.length} / {MAX_SAMPLE_TEXT_LENGTH} 字</span>
|
||||
{sampleMessage && <span className="text-emerald-600">{sampleMessage}</span>}
|
||||
{sampleError && <span className="text-destructive">{sampleError}</span>}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold text-foreground">仿写强度</label>
|
||||
<Select
|
||||
value={imitateStrength}
|
||||
onValueChange={(v) => setImitateStrength(v as 'light' | 'medium' | 'strong')}
|
||||
disabled={disabled}
|
||||
>
|
||||
<SelectTrigger className={FIELD_TRIGGER_CLASS}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{IMITATE_STRENGTH_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 pt-7 text-sm font-medium text-foreground">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={preserveSampleStructure}
|
||||
onChange={(e) => setPreserveSampleStructure(e.target.checked)}
|
||||
disabled={disabled}
|
||||
className="size-3.5 shrink-0 accent-primary"
|
||||
/>
|
||||
沿用样文结构
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-4 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className={FIELD_LABEL_CLASS}>
|
||||
@@ -303,82 +453,80 @@ export function AIWritingForm({
|
||||
</div>
|
||||
|
||||
{!skipResearch && (
|
||||
<div className="mt-4 space-y-2">
|
||||
<label className={FIELD_LABEL_CLASS}>检索类型</label>
|
||||
<Select
|
||||
value={materialSource}
|
||||
onValueChange={(v) => handleMaterialSourceChange(v as MaterialSource)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<SelectTrigger className={FIELD_TRIGGER_CLASS}>
|
||||
<SelectValue placeholder="选择检索类型" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MATERIAL_SOURCE_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value} className="text-sm">
|
||||
{opt.label}
|
||||
<span className="ml-1 text-xs text-muted-foreground">— {opt.desc}</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="mt-4 space-y-2">
|
||||
<label className={FIELD_LABEL_CLASS}>检索方式</label>
|
||||
<Select
|
||||
value={materialSource}
|
||||
onValueChange={(v) => handleMaterialSourceChange(v as MaterialSource)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<SelectTrigger className={FIELD_TRIGGER_CLASS}>
|
||||
<SelectValue placeholder="选择检索方式" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MATERIAL_SOURCE_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value} className="text-sm">
|
||||
{opt.label}
|
||||
<span className="ml-1 text-xs text-muted-foreground">— {opt.desc}</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 选了"我的空间"才展示空间 / 文档选择器 */}
|
||||
{materialSource === 'notebook' && (
|
||||
<div className="mt-2 space-y-2">
|
||||
{/* studioToken 模式:空间已锁定,不展示选择器 */}
|
||||
{!studioToken && (
|
||||
<Select
|
||||
value={selectedNotebookId !== null ? String(selectedNotebookId) : ''}
|
||||
onValueChange={handleNotebookChange}
|
||||
disabled={disabled || notebooksLoading}
|
||||
>
|
||||
<SelectTrigger className={FIELD_TRIGGER_CLASS}>
|
||||
<SelectValue placeholder={notebooksLoading ? '加载中…' : '选择空间'} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{notebooks.map((nb) => (
|
||||
<SelectItem key={nb.id} value={String(nb.id)} className="text-sm">
|
||||
{nb.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
{materialSource === 'notebook' && (
|
||||
<div className="mt-2 space-y-2">
|
||||
{!studioToken && (
|
||||
<Select
|
||||
value={selectedNotebookId !== null ? String(selectedNotebookId) : ''}
|
||||
onValueChange={handleNotebookChange}
|
||||
disabled={disabled || notebooksLoading}
|
||||
>
|
||||
<SelectTrigger className={FIELD_TRIGGER_CLASS}>
|
||||
<SelectValue placeholder={notebooksLoading ? '加载中…' : '选择空间'} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{notebooks.map((nb) => (
|
||||
<SelectItem key={nb.id} value={String(nb.id)} className="text-sm">
|
||||
{nb.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
|
||||
{selectedNotebookId !== null && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{sourcesLoading
|
||||
? '文档加载中…'
|
||||
: `选择文档(可多选;不选则搜整个空间${selectedDocumentIds.length > 0 ? `,已选 ${selectedDocumentIds.length} 篇` : ''})`}
|
||||
</p>
|
||||
{!sourcesLoading && (
|
||||
<div className="max-h-36 overflow-y-auto rounded-lg border border-[#e8dedd] bg-white divide-y divide-[#f0e8e7]">
|
||||
{sources.filter((s) => s.document?.id != null).map((s) => {
|
||||
const docId = s.document!.id;
|
||||
return (
|
||||
<label key={s.id} className="flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-[#f9f5f5] select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedDocumentIds.includes(docId)}
|
||||
onChange={() => toggleDocument(docId)}
|
||||
disabled={disabled}
|
||||
className="size-3.5 shrink-0 accent-primary"
|
||||
/>
|
||||
<span className="text-xs text-foreground truncate">
|
||||
{s.document?.title ?? `文档 ${docId}`}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{selectedNotebookId !== null && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{sourcesLoading
|
||||
? '文档加载中…'
|
||||
: `选择文档(可多选;不选则搜整个空间${selectedDocumentIds.length > 0 ? `,已选 ${selectedDocumentIds.length} 篇` : ''})`}
|
||||
</p>
|
||||
{!sourcesLoading && (
|
||||
<div className="max-h-36 overflow-y-auto rounded-lg border border-[#e8dedd] bg-white divide-y divide-[#f0e8e7]">
|
||||
{sources.filter((s) => s.document?.id != null).map((s) => {
|
||||
const docId = s.document!.id;
|
||||
return (
|
||||
<label key={s.id} className="flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-[#f9f5f5] select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedDocumentIds.includes(docId)}
|
||||
onChange={() => toggleDocument(docId)}
|
||||
disabled={disabled}
|
||||
className="size-3.5 shrink-0 accent-primary"
|
||||
/>
|
||||
<span className="text-xs text-foreground truncate">
|
||||
{s.document?.title ?? `文档 ${docId}`}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-4 space-y-2">
|
||||
@@ -428,7 +576,7 @@ export function AIWritingForm({
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={disabled || !intent.trim()}
|
||||
disabled={disabled || !intent.trim() || (writingModeType === 'imitate' && !sampleText.trim())}
|
||||
className="mt-5 h-12 w-full gap-2 rounded-2xl text-base font-semibold shadow-lg shadow-primary/20 transition-all hover:shadow-primary/30 active:scale-[0.98]"
|
||||
>
|
||||
<PenLine className="size-4" />
|
||||
@@ -436,6 +584,8 @@ export function AIWritingForm({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ResearchTemplatesPanel />
|
||||
|
||||
{!hideAdvancedFields && (
|
||||
<>
|
||||
<div className="flex items-start gap-2 rounded-xl border border-[#e8dedd] bg-[#f9f5f5] px-3 py-3">
|
||||
|
||||
@@ -10,6 +10,7 @@ export const STATUS_LABELS: Record<string, { label: string; color: string }> = {
|
||||
in_progress: { label: '未完成', color: 'text-slate-400' },
|
||||
// 后台挂起中:后端正自动驱动到定稿(离页/刷新/切号不打断)。
|
||||
background: { label: '挂起中', color: 'text-sky-500' },
|
||||
analyzing_sample: { label: '样文分析', color: 'text-cyan-500' },
|
||||
draft_ready: { label: '草稿', color: 'text-amber-500' },
|
||||
review_ready: { label: '审核', color: 'text-purple-500' },
|
||||
done: { label: '完成', color: 'text-green-500' },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { ChevronsDown, CloudUpload, PanelRightClose, Pause, Play, Plus, RotateCcw, Settings2, Trash2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
@@ -39,11 +39,14 @@ import { AIWritingTimeline } from './AIWritingTimeline';
|
||||
import { InterventionCard } from './InterventionCard';
|
||||
import { SkillStepsCard } from './SkillStepsCard';
|
||||
import { SkillSelectStreamingView } from './SkillSelectStreamingView';
|
||||
import { KeywordStreamingView } from './KeywordStreamingView';
|
||||
import { WritingSkeletonCard } from './WritingSkeletonCard';
|
||||
import { DraftGeneratingView } from './DraftGeneratingView';
|
||||
import { DraftSync } from './DraftSync';
|
||||
import { IntentResultCard } from './IntentResultCard';
|
||||
import { IntentStreamingView } from './IntentStreamingView';
|
||||
import { SampleAnalysisStreamingView } from './SampleAnalysisStreamingView';
|
||||
import { SampleStyleProfileCard } from './SampleStyleProfileCard';
|
||||
import { OutlineStreamingView } from './OutlineStreamingView';
|
||||
import { ReviewStreamingView } from './ReviewStreamingView';
|
||||
import { RevisionSummaryCard } from './RevisionSummaryCard';
|
||||
@@ -54,6 +57,7 @@ import type { AIWritingSessionSummary } from '../../api/ai-writing-sessions';
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
idle: '就绪',
|
||||
analyzing_sample: '样文分析师分析文风中…',
|
||||
researching: '素材收集专家搜集素材中…',
|
||||
awaiting_material_confirm: '等待确认素材',
|
||||
writing_outline: '作家规划大纲中…',
|
||||
@@ -73,11 +77,13 @@ export function AIWritingPanel({
|
||||
initialNotebookId,
|
||||
initialDocumentIds,
|
||||
studioToken,
|
||||
headerActionsBeforeCollapse,
|
||||
}: {
|
||||
hideAdvancedFields?: boolean;
|
||||
initialNotebookId?: number;
|
||||
initialDocumentIds?: number[];
|
||||
studioToken?: string;
|
||||
headerActionsBeforeCollapse?: ReactNode;
|
||||
} = {}) {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -97,93 +103,206 @@ export function AIWritingPanel({
|
||||
const isDone = state.status === 'done';
|
||||
const isError = state.status === 'error';
|
||||
const isRunning = !isIdle && !isDone && !isError;
|
||||
const shouldAutoFollow = !isIdle && !isHistoryMode;
|
||||
const showSkeleton = isRunning && !state.currentPause && !state.isPaused;
|
||||
const intentSlot = (state.intentStreamingText || state.intentThinkingText) ? (
|
||||
<IntentStreamingView text={state.intentStreamingText} thinkingText={state.intentThinkingText} />
|
||||
) : state.parsedIntent ? (
|
||||
<IntentResultCard
|
||||
intent={state.parsedIntent}
|
||||
articleTypes={articleTypes}
|
||||
hideTargetAudience={hideAdvancedFields}
|
||||
embedded
|
||||
/>
|
||||
) : null;
|
||||
const sampleAnalysisSlot = (state.sampleAnalysisStreamingText || state.sampleAnalysisThinkingText) ? (
|
||||
<SampleAnalysisStreamingView
|
||||
text={state.sampleAnalysisStreamingText}
|
||||
thinkingText={state.sampleAnalysisThinkingText}
|
||||
/>
|
||||
) : null;
|
||||
const sampleProfileSlot = state.sampleStyleProfile ? (
|
||||
<SampleStyleProfileCard profile={state.sampleStyleProfile} />
|
||||
) : null;
|
||||
|
||||
// ── 自动滚底逻辑 ────────────────────────────────────────────────────────────
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
// 程序触发滚动时置 true,阻止 scroll 事件误判为用户上划
|
||||
const isAutoScrollingRef = useRef(false);
|
||||
// 同步 ref:让 scroll/wheel 回调可以立即读取最新值,不依赖 state 异步更新
|
||||
const autoScrollRef = useRef(true);
|
||||
const shouldAutoFollowRef = useRef(shouldAutoFollow);
|
||||
shouldAutoFollowRef.current = shouldAutoFollow;
|
||||
const scrollbarDragRef = useRef(false);
|
||||
const touchYRef = useRef<number | null>(null);
|
||||
const [autoScroll, setAutoScroll] = useState(true);
|
||||
|
||||
const enableAutoScroll = useCallback(() => {
|
||||
autoScrollRef.current = true;
|
||||
setAutoScroll(true);
|
||||
}, []);
|
||||
|
||||
const disableAutoScroll = useCallback(() => {
|
||||
autoScrollRef.current = false;
|
||||
setAutoScroll(false);
|
||||
}, []);
|
||||
|
||||
const scrollToBottomNow = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
isAutoScrollingRef.current = true;
|
||||
|
||||
const jump = () => {
|
||||
if (bottomRef.current) {
|
||||
bottomRef.current.scrollIntoView({ block: 'end' });
|
||||
} else {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
};
|
||||
|
||||
jump();
|
||||
requestAnimationFrame(() => {
|
||||
jump();
|
||||
requestAnimationFrame(() => {
|
||||
isAutoScrollingRef.current = false;
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const maybeAutoScrollToBottom = useCallback(() => {
|
||||
if (!autoScrollRef.current || !shouldAutoFollowRef.current) return;
|
||||
scrollToBottomNow();
|
||||
}, [scrollToBottomNow]);
|
||||
|
||||
// 新会话 / 重置后恢复自动滚底
|
||||
useEffect(() => {
|
||||
if (isIdle) {
|
||||
autoScrollRef.current = true;
|
||||
setAutoScroll(true);
|
||||
enableAutoScroll();
|
||||
}
|
||||
}, [isIdle]);
|
||||
}, [enableAutoScroll, isIdle]);
|
||||
|
||||
// 开始写作 / 点击继续后恢复自动滚底
|
||||
useEffect(() => {
|
||||
if (isRunning && !state.isPaused) {
|
||||
autoScrollRef.current = true;
|
||||
setAutoScroll(true);
|
||||
if (shouldAutoFollow && !state.isPaused) {
|
||||
enableAutoScroll();
|
||||
requestAnimationFrame(scrollToBottomNow);
|
||||
}
|
||||
}, [isRunning, state.isPaused]);
|
||||
}, [enableAutoScroll, scrollToBottomNow, shouldAutoFollow, state.isPaused]);
|
||||
|
||||
// 监听用户手动滚动(挂载一次)
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const nearBottom = () => el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
|
||||
// wheel 事件:鼠标滚轮 / 触控板,只由用户触发
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
if (e.deltaY < 0) disableAutoScroll(); // 向上滚
|
||||
};
|
||||
|
||||
// scroll 事件:兼容拖动滚动条的场景
|
||||
// 通过对比前后 scrollTop 判断是否向上滚(排除程序触发的向下滚)
|
||||
const onTouchStart = (e: TouchEvent) => {
|
||||
touchYRef.current = e.touches[0]?.clientY ?? null;
|
||||
};
|
||||
|
||||
const onTouchMove = (e: TouchEvent) => {
|
||||
const prevY = touchYRef.current;
|
||||
const nextY = e.touches[0]?.clientY ?? null;
|
||||
if (prevY !== null && nextY !== null && nextY > prevY + 4) {
|
||||
disableAutoScroll();
|
||||
}
|
||||
touchYRef.current = nextY;
|
||||
};
|
||||
|
||||
const onPointerDown = (e: PointerEvent) => {
|
||||
if (e.target === el) {
|
||||
scrollbarDragRef.current = true;
|
||||
}
|
||||
};
|
||||
|
||||
const onPointerDone = () => {
|
||||
scrollbarDragRef.current = false;
|
||||
};
|
||||
|
||||
// scroll 事件只处理「用户拖动滚动条」和「手动回到底部」。
|
||||
// 普通布局变化也会触发 scroll,不能再把所有 scrollTop 下降都当成用户上划。
|
||||
let lastTop = el.scrollTop;
|
||||
const onScroll = () => {
|
||||
const cur = el.scrollTop;
|
||||
if (!isAutoScrollingRef.current && cur < lastTop - 2) {
|
||||
if (isAutoScrollingRef.current) {
|
||||
lastTop = cur;
|
||||
return;
|
||||
}
|
||||
if (nearBottom()) {
|
||||
enableAutoScroll();
|
||||
} else if (scrollbarDragRef.current && cur < lastTop - 2) {
|
||||
disableAutoScroll();
|
||||
}
|
||||
lastTop = cur;
|
||||
};
|
||||
|
||||
el.addEventListener('wheel', onWheel, { passive: true });
|
||||
el.addEventListener('touchstart', onTouchStart, { passive: true });
|
||||
el.addEventListener('touchmove', onTouchMove, { passive: true });
|
||||
el.addEventListener('pointerdown', onPointerDown);
|
||||
window.addEventListener('pointerup', onPointerDone);
|
||||
window.addEventListener('pointercancel', onPointerDone);
|
||||
el.addEventListener('scroll', onScroll, { passive: true });
|
||||
return () => {
|
||||
el.removeEventListener('wheel', onWheel);
|
||||
el.removeEventListener('touchstart', onTouchStart);
|
||||
el.removeEventListener('touchmove', onTouchMove);
|
||||
el.removeEventListener('pointerdown', onPointerDown);
|
||||
window.removeEventListener('pointerup', onPointerDone);
|
||||
window.removeEventListener('pointercancel', onPointerDone);
|
||||
el.removeEventListener('scroll', onScroll);
|
||||
};
|
||||
}, [disableAutoScroll]);
|
||||
}, [disableAutoScroll, enableAutoScroll]);
|
||||
|
||||
// 内容高度变化兜底:同一 timeline 节点内卡片展开、文风画像替换、流式文本变长,
|
||||
// 都可能不改变 progressEvents.length。监听 DOM 变化可以把这些情况统一托底。
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el || typeof MutationObserver === 'undefined') return;
|
||||
const observer = new MutationObserver(() => {
|
||||
maybeAutoScrollToBottom();
|
||||
});
|
||||
observer.observe(el, { childList: true, subtree: true, characterData: true });
|
||||
return () => observer.disconnect();
|
||||
}, [maybeAutoScrollToBottom]);
|
||||
|
||||
// 内容变化时若自动滚底开启则滚到底部
|
||||
useEffect(() => {
|
||||
// 检查同步 ref,避免 state 异步导致的时序竞争
|
||||
if (!autoScrollRef.current || !isRunning || !scrollRef.current) return;
|
||||
const el = scrollRef.current;
|
||||
isAutoScrollingRef.current = true;
|
||||
el.scrollTop = el.scrollHeight;
|
||||
requestAnimationFrame(() => { isAutoScrollingRef.current = false; });
|
||||
useLayoutEffect(() => {
|
||||
maybeAutoScrollToBottom();
|
||||
}, [
|
||||
maybeAutoScrollToBottom,
|
||||
autoScroll, // 点击按钮后重新触发一次
|
||||
isRunning,
|
||||
state.status,
|
||||
state.progressEvents.length,
|
||||
state.sampleAnalysisStreamingText,
|
||||
state.sampleAnalysisThinkingText,
|
||||
state.sampleStyleProfile,
|
||||
state.intentStreamingText,
|
||||
state.intentThinkingText,
|
||||
state.parsedIntent,
|
||||
state.keywordStreamingText,
|
||||
state.keywordThinkingText,
|
||||
state.skillSearchSteps.length,
|
||||
state.skillSelectStreamingText,
|
||||
state.skillSelectThinkingText,
|
||||
state.streamingDraftSections.length,
|
||||
state.streamingReviewItems.length,
|
||||
state.outlineStreamingText,
|
||||
state.outlineThinkingText,
|
||||
state.revisionSummary,
|
||||
state.currentPause,
|
||||
]);
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
isAutoScrollingRef.current = true;
|
||||
el.scrollTop = el.scrollHeight;
|
||||
requestAnimationFrame(() => { isAutoScrollingRef.current = false; });
|
||||
autoScrollRef.current = true;
|
||||
setAutoScroll(true);
|
||||
}, []);
|
||||
enableAutoScroll();
|
||||
scrollToBottomNow();
|
||||
}, [enableAutoScroll, scrollToBottomNow]);
|
||||
|
||||
const handleSelectHistory = useCallback((session: AIWritingSessionSummary) => {
|
||||
void openHistory(session);
|
||||
@@ -429,6 +548,7 @@ export function AIWritingPanel({
|
||||
onRename={rename}
|
||||
onRefresh={refresh}
|
||||
/>
|
||||
{headerActionsBeforeCollapse}
|
||||
{/* 收起写作配置:仅在 idle 配置阶段、表单展开时出现(与 AIWritingPage 的整块收起联动) */}
|
||||
{writingForm && isIdle && !isHistoryMode && writingForm.formExpanded && (
|
||||
<Button
|
||||
@@ -446,7 +566,13 @@ export function AIWritingPanel({
|
||||
|
||||
{/* 主体:relative 父容器 + absolute 滚动容器,确保滚动容器尺寸始终正确 */}
|
||||
<div className="flex-1 min-h-0 relative">
|
||||
<div ref={scrollRef} className="absolute inset-0 overflow-y-auto">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className={cn(
|
||||
'absolute inset-0 overflow-y-auto',
|
||||
autoScroll && '[overflow-anchor:none]',
|
||||
)}
|
||||
>
|
||||
{/* 历史回看:左侧时间线(与实时写作同一套 AIWritingTimeline) */}
|
||||
{isHistoryMode && historySession && (
|
||||
<AIWritingHistoryView session={historySession} />
|
||||
@@ -463,27 +589,16 @@ export function AIWritingPanel({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 意图解析:流式 → 结果卡片承接。
|
||||
放在 timeline 之上 —— 解析后 timeline 会从 step_done 起一直长,
|
||||
如果把意图块塞在 timeline 下面就会随 timeline 增长被推走;
|
||||
放上面则恒定锚定在内容最顶部,刷到底也能滚回顶部看清楚意图理解结果。 */}
|
||||
{(state.intentStreamingText || state.intentThinkingText) && (
|
||||
<IntentStreamingView text={state.intentStreamingText} thinkingText={state.intentThinkingText} />
|
||||
)}
|
||||
{state.parsedIntent && !state.intentStreamingText && (
|
||||
<IntentResultCard
|
||||
intent={state.parsedIntent}
|
||||
articleTypes={articleTypes}
|
||||
hideTargetAudience={hideAdvancedFields}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 运行中或完成后显示时间线 */}
|
||||
{!isIdle && !isHistoryMode && (
|
||||
<AIWritingTimeline
|
||||
events={state.progressEvents}
|
||||
completedInterventions={state.completedInterventions}
|
||||
currentPause={state.currentPause}
|
||||
sampleAnalysisSlot={sampleAnalysisSlot}
|
||||
sampleProfileSlot={sampleProfileSlot}
|
||||
intentSlot={intentSlot}
|
||||
intentSlotDone={!!state.parsedIntent && !state.intentStreamingText && !state.intentThinkingText}
|
||||
currentInterventionSlot={
|
||||
state.currentPause ? (
|
||||
<InterventionCard
|
||||
@@ -496,6 +611,8 @@ export function AIWritingPanel({
|
||||
wordCountTarget={state.request?.wordCountTarget}
|
||||
revisionCount={state.revisionCount}
|
||||
skillSearchSteps={state.skillSearchSteps}
|
||||
materialSource={state.request?.materialSource ?? 'general'}
|
||||
canUseNotebookSearch={state.request?.noteSearchSpaceId != null}
|
||||
skillSearchInProgress={state.status === 'researching' && state.skillSearchSteps.length > 0}
|
||||
onSubmit={submitIntervention}
|
||||
disabled={false}
|
||||
@@ -531,6 +648,16 @@ export function AIWritingPanel({
|
||||
<DraftGeneratingView sections={state.streamingDraftSections} />
|
||||
)}
|
||||
|
||||
{/* 检索词生成过程:先展示模型如何从写作意图提炼搜索方向,再进入技能匹配 / 检索。 */}
|
||||
{state.status === 'researching' && (
|
||||
state.keywordStreamingText || state.keywordThinkingText
|
||||
) && (
|
||||
<KeywordStreamingView
|
||||
text={state.keywordStreamingText}
|
||||
thinkingText={state.keywordThinkingText}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 技能选择 LLM 流式打字(含 <think> 思考分离),select_skills 完成后自动清空。
|
||||
挂载条件包含"过渡态":已经走到 match_skills 但还没出 select_skills 时也保持挂载,
|
||||
让首个空 chunk 一到就能立刻显示等待提示 + 闪烁光标,避免模型 buffer 期间静默。 */}
|
||||
@@ -564,12 +691,16 @@ export function AIWritingPanel({
|
||||
state.status !== 'writing_draft' &&
|
||||
!(state.status === 'writing_outline' && (state.outlineStreamingText || state.outlineThinkingText)) &&
|
||||
!(state.status === 'reviewing' && state.streamingReviewItems.length > 0) &&
|
||||
/* 技能检索占位卡 / 选择打字机 / 已流式的技能步骤 已经在展示,不再叠加 skeleton。
|
||||
/* 检索词生成卡 / 技能检索占位卡 / 选择打字机 / 已流式的技能步骤
|
||||
已经在展示,不再叠加 skeleton。
|
||||
(研究阶段一旦有 skill_search_step,就改由上面的 SkillStepsCard 实时呈现进度,
|
||||
研究词生成阶段 steps 还为空时仍走 skeleton 透传 researchProgress 文案。) */
|
||||
关键词 chunk 还没到之前仍走 skeleton 透传 researchProgress 文案。) */
|
||||
!state.skillSearchPending &&
|
||||
!(state.status === 'researching' && state.skillSearchSteps.length > 0) &&
|
||||
!(state.status === 'researching' && (state.keywordStreamingText || state.keywordThinkingText)) &&
|
||||
!(state.status === 'researching' && (state.skillSelectStreamingText || state.skillSelectThinkingText)) &&
|
||||
/* 样文分析已有流式过程卡时,不再叠加 skeleton */
|
||||
!state.sampleAnalysisStreamingText && !state.sampleAnalysisThinkingText &&
|
||||
/* 意图解析流式过程中(LLM 还在吐 JSON)不要显示 skeleton */
|
||||
!state.intentStreamingText && !state.intentThinkingText && (
|
||||
<div className="px-4 pb-4">
|
||||
@@ -586,6 +717,7 @@ export function AIWritingPanel({
|
||||
{state.error}
|
||||
</div>
|
||||
)}
|
||||
<div ref={bottomRef} className="h-px" aria-hidden="true" />
|
||||
</div>{/* 滚动内容区结束 */}
|
||||
|
||||
{/* 回到底部悬浮按钮:生成中且用户已上划时出现 */}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import type { CompletedIntervention, ProgressEvent } from '../../types/ai-writing';
|
||||
import { TimelineStep } from './TimelineStep';
|
||||
import { CompletedInterventionCard } from './CompletedInterventionCard';
|
||||
@@ -7,12 +9,17 @@ interface AIWritingTimelineProps {
|
||||
events: ProgressEvent[];
|
||||
completedInterventions: CompletedIntervention[];
|
||||
currentPause: ProgressEvent | null;
|
||||
currentInterventionSlot?: React.ReactNode;
|
||||
currentInterventionSlot?: ReactNode;
|
||||
sampleAnalysisSlot?: ReactNode;
|
||||
sampleProfileSlot?: ReactNode;
|
||||
intentSlot?: ReactNode;
|
||||
intentSlotDone?: boolean;
|
||||
}
|
||||
|
||||
const DISPLAYED_TYPES = new Set([
|
||||
'step_start',
|
||||
'step_done',
|
||||
'sample_profile_ready',
|
||||
'materials_ready',
|
||||
'outline_ready',
|
||||
'draft_ready',
|
||||
@@ -30,44 +37,162 @@ export function AIWritingTimeline({
|
||||
completedInterventions,
|
||||
currentPause,
|
||||
currentInterventionSlot,
|
||||
sampleAnalysisSlot,
|
||||
sampleProfileSlot,
|
||||
intentSlot,
|
||||
intentSlotDone = false,
|
||||
}: AIWritingTimelineProps) {
|
||||
const visible = events.filter((e) => DISPLAYED_TYPES.has(e.type));
|
||||
|
||||
if (visible.length === 0) return null;
|
||||
if (visible.length === 0 && !intentSlot && !sampleAnalysisSlot && !sampleProfileSlot) return null;
|
||||
|
||||
// 遍历时追踪 await_user 事件的序号,以便从 completedInterventions 取对应记录
|
||||
let awaitUserIdx = 0;
|
||||
let intentInserted = false;
|
||||
const lastSampleEventIndex = visible.reduce(
|
||||
(last, event, index) => (isSampleEvent(event) ? index : last),
|
||||
-1,
|
||||
);
|
||||
const rows: Array<{
|
||||
key: string;
|
||||
event: ProgressEvent;
|
||||
slot: ReactNode;
|
||||
extendLineThroughSlot?: boolean;
|
||||
}> = [];
|
||||
|
||||
const makeIntentEvent = (): ProgressEvent => ({
|
||||
type: intentSlotDone ? 'step_done' : 'step_start',
|
||||
sessionId: 'intent-slot',
|
||||
agentName: '系统',
|
||||
message: intentSlotDone ? '意图解析完成' : '正在解析写作意图',
|
||||
});
|
||||
|
||||
const pushIntentRow = (key: string) => {
|
||||
if (!intentSlot || intentInserted) return;
|
||||
rows.push({
|
||||
key,
|
||||
event: makeIntentEvent(),
|
||||
slot: intentSlot,
|
||||
extendLineThroughSlot: false,
|
||||
});
|
||||
intentInserted = true;
|
||||
};
|
||||
|
||||
const makeSampleAnalysisEvent = (): ProgressEvent => ({
|
||||
type: 'step_start',
|
||||
sessionId: 'sample-analysis-slot',
|
||||
agentName: '样文分析师',
|
||||
message: '正在分析样文风格',
|
||||
});
|
||||
|
||||
if (sampleAnalysisSlot && lastSampleEventIndex < 0) {
|
||||
rows.push({
|
||||
key: 'sample-analysis-live',
|
||||
event: makeSampleAnalysisEvent(),
|
||||
slot: sampleAnalysisSlot,
|
||||
extendLineThroughSlot: false,
|
||||
});
|
||||
}
|
||||
|
||||
visible.forEach((event, idx) => {
|
||||
let slot: ReactNode = null;
|
||||
let extendLineThroughSlot = true;
|
||||
|
||||
if (event.type === 'await_user') {
|
||||
const completedRecord = completedInterventions[awaitUserIdx];
|
||||
awaitUserIdx += 1;
|
||||
|
||||
if (completedRecord) {
|
||||
// 已完成的干预点 → 先以独立样式回显用户的输入要求,再渲染折叠历史卡
|
||||
slot = (
|
||||
<div className="space-y-2">
|
||||
<UserRequirementCard record={completedRecord} />
|
||||
<CompletedInterventionCard record={completedRecord} />
|
||||
</div>
|
||||
);
|
||||
} else if (currentPause && idx === visible.length - 1) {
|
||||
// 当前活跃干预点 → 渲染操作卡
|
||||
slot = currentInterventionSlot;
|
||||
}
|
||||
}
|
||||
|
||||
if (intentSlot && isIntentDoneEvent(event)) {
|
||||
slot = slot ? (
|
||||
<div className="space-y-2">
|
||||
{slot}
|
||||
{intentSlot}
|
||||
</div>
|
||||
) : intentSlot;
|
||||
extendLineThroughSlot = false;
|
||||
intentInserted = true;
|
||||
}
|
||||
|
||||
if (sampleAnalysisSlot && idx === lastSampleEventIndex) {
|
||||
slot = slot ? (
|
||||
<div className="space-y-2">
|
||||
{slot}
|
||||
{sampleAnalysisSlot}
|
||||
</div>
|
||||
) : sampleAnalysisSlot;
|
||||
extendLineThroughSlot = false;
|
||||
} else if (sampleProfileSlot && event.type === 'sample_profile_ready') {
|
||||
slot = slot ? (
|
||||
<div className="space-y-2">
|
||||
{slot}
|
||||
{sampleProfileSlot}
|
||||
</div>
|
||||
) : sampleProfileSlot;
|
||||
extendLineThroughSlot = false;
|
||||
}
|
||||
|
||||
rows.push({
|
||||
key: `event-${idx}`,
|
||||
event,
|
||||
slot,
|
||||
extendLineThroughSlot,
|
||||
});
|
||||
|
||||
if (
|
||||
intentSlot &&
|
||||
!intentSlotDone &&
|
||||
!intentInserted &&
|
||||
lastSampleEventIndex >= 0 &&
|
||||
idx === lastSampleEventIndex
|
||||
) {
|
||||
pushIntentRow(`intent-after-sample-${idx}`);
|
||||
}
|
||||
});
|
||||
|
||||
if (!intentInserted) {
|
||||
pushIntentRow('intent-fallback');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 py-3 space-y-0">
|
||||
{visible.map((event, idx) => {
|
||||
const isLast = idx === visible.length - 1;
|
||||
let slot: React.ReactNode = null;
|
||||
|
||||
if (event.type === 'await_user') {
|
||||
const completedRecord = completedInterventions[awaitUserIdx];
|
||||
awaitUserIdx += 1;
|
||||
|
||||
if (completedRecord) {
|
||||
// 已完成的干预点 → 先以独立样式回显用户的输入要求,再渲染折叠历史卡
|
||||
slot = (
|
||||
<div className="space-y-2">
|
||||
<UserRequirementCard record={completedRecord} />
|
||||
<CompletedInterventionCard record={completedRecord} />
|
||||
</div>
|
||||
);
|
||||
} else if (currentPause && isLast) {
|
||||
// 当前活跃干预点 → 渲染操作卡
|
||||
slot = currentInterventionSlot;
|
||||
}
|
||||
}
|
||||
|
||||
{rows.map((row, idx) => {
|
||||
const isLast = idx === rows.length - 1;
|
||||
return (
|
||||
<TimelineStep key={idx} event={event} isLast={isLast && !slot}>
|
||||
{slot}
|
||||
<TimelineStep
|
||||
key={row.key}
|
||||
event={row.event}
|
||||
isLast={isLast && (!row.slot || !row.extendLineThroughSlot)}
|
||||
>
|
||||
{row.slot}
|
||||
</TimelineStep>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function isSampleEvent(event: ProgressEvent): boolean {
|
||||
return event.agentName === '样文分析师' || event.type === 'sample_profile_ready';
|
||||
}
|
||||
|
||||
function isIntentDoneEvent(event: ProgressEvent): boolean {
|
||||
return (
|
||||
event.type === 'step_done' &&
|
||||
event.agentName === '系统' &&
|
||||
(event.message ?? '').includes('意图解析完成')
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ export function DraftSync({ status, markdown, title }: DraftSyncProps) {
|
||||
// 右侧保持编辑器(富文本)视图,不再切回只读 markdown。仅真正在改写正文的
|
||||
// writing_draft / revising 才只读。
|
||||
const generating =
|
||||
status === 'analyzing_sample' ||
|
||||
status === 'researching' ||
|
||||
status === 'writing_outline' ||
|
||||
streaming;
|
||||
|
||||
@@ -7,6 +7,7 @@ interface IntentResultCardProps {
|
||||
intent: ParsedIntent;
|
||||
articleTypes: ArticleType[];
|
||||
hideTargetAudience?: boolean;
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -17,13 +18,14 @@ export function IntentResultCard({
|
||||
intent,
|
||||
articleTypes,
|
||||
hideTargetAudience = false,
|
||||
embedded = false,
|
||||
}: IntentResultCardProps) {
|
||||
// article_type 后端给的是 key(如 "analysis"),UI 展示用 label(如 "分析报道")
|
||||
const typeLabel =
|
||||
articleTypes.find((t) => t.key === intent.articleType)?.label ?? intent.articleType;
|
||||
|
||||
return (
|
||||
<div className="px-4 pb-2">
|
||||
<div className={embedded ? 'mt-2' : 'px-4 pb-2'}>
|
||||
<div className="rounded-xl border border-blue-200 dark:border-blue-900 bg-blue-50/40 dark:bg-blue-950/20 overflow-hidden shadow-sm">
|
||||
<div className="flex items-center gap-2 px-3 py-2 border-b border-blue-200/60 dark:border-blue-900/60 bg-blue-100/40 dark:bg-blue-900/30">
|
||||
<Sparkles className="size-3.5 text-blue-500 shrink-0" />
|
||||
|
||||
@@ -5,6 +5,13 @@ import {
|
||||
Trash2, BookOpen,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type {
|
||||
AIMaterial, AIOutline, ReviewResult, ReviewIssue,
|
||||
@@ -30,6 +37,8 @@ interface InterventionCardProps {
|
||||
wordCountTarget?: number;
|
||||
revisionCount: number;
|
||||
skillSearchSteps?: SkillSearchStep[];
|
||||
materialSource?: MaterialSource;
|
||||
canUseNotebookSearch?: boolean;
|
||||
/** 是否正在检索中(researching/awaiting 切换之间,前端用于流式展示步骤进行中) */
|
||||
skillSearchInProgress?: boolean;
|
||||
onSubmit: (payload: UserInterventionPayload) => void;
|
||||
@@ -38,7 +47,8 @@ interface InterventionCardProps {
|
||||
|
||||
export function InterventionCard({
|
||||
pauseEvent, materials, outline, reviewResult,
|
||||
draftTitle, draftWordCount, wordCountTarget, revisionCount, skillSearchSteps, skillSearchInProgress, onSubmit, disabled,
|
||||
draftTitle, draftWordCount, wordCountTarget, revisionCount, skillSearchSteps,
|
||||
materialSource, canUseNotebookSearch, skillSearchInProgress, onSubmit, disabled,
|
||||
}: InterventionCardProps) {
|
||||
const pausePoint = pauseEvent.pausePoint;
|
||||
|
||||
@@ -47,6 +57,8 @@ export function InterventionCard({
|
||||
<MaterialConfirmCard
|
||||
materials={materials}
|
||||
skillSearchSteps={skillSearchSteps ?? []}
|
||||
initialMaterialSource={materialSource ?? 'general'}
|
||||
canUseNotebookSearch={canUseNotebookSearch}
|
||||
skillSearchInProgress={skillSearchInProgress}
|
||||
onSubmit={onSubmit}
|
||||
disabled={disabled}
|
||||
@@ -117,7 +129,11 @@ function formatSelectedIssues(issues: ReviewIssue[], selectedIndices: Set<number
|
||||
const selected = issues.filter((_, i) => selectedIndices.has(i));
|
||||
if (selected.length === 0) return '';
|
||||
return selected
|
||||
.map((iss, n) => `${n + 1}. [${iss.category}] ${iss.issue}:${iss.suggestion}`)
|
||||
.map((iss, n) => {
|
||||
const location = iss.location ? `【位置】${iss.location};` : '';
|
||||
const suggestion = iss.suggestion ? `;【建议】${iss.suggestion}` : '';
|
||||
return `${n + 1}. [${iss.category}] ${location}${iss.issue}${suggestion}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
@@ -126,17 +142,73 @@ function formatSelectedIssues(issues: ReviewIssue[], selectedIndices: Set<number
|
||||
interface MaterialConfirmCardProps {
|
||||
materials: AIMaterial[];
|
||||
skillSearchSteps: SkillSearchStep[];
|
||||
initialMaterialSource: MaterialSource;
|
||||
canUseNotebookSearch?: boolean;
|
||||
skillSearchInProgress?: boolean;
|
||||
onSubmit: (payload: UserInterventionPayload) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function MaterialConfirmCard({ materials, skillSearchSteps, skillSearchInProgress, onSubmit, disabled }: MaterialConfirmCardProps) {
|
||||
type MaterialSource = NonNullable<UserInterventionPayload['materialSource']>;
|
||||
|
||||
const MATERIAL_SOURCE_OPTIONS: Array<{ value: MaterialSource; label: string; desc: string }> = [
|
||||
{ value: 'general', label: '通用检索', desc: '素材收集专家按配置技能检索' },
|
||||
{ value: 'knowledge_base', label: '知识库检索', desc: '直连内网知识库接口' },
|
||||
{ value: 'notebook', label: '我的空间', desc: '检索当前笔记空间' },
|
||||
];
|
||||
|
||||
function MaterialSourceSwitcher({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
disabled,
|
||||
}: {
|
||||
value: MaterialSource;
|
||||
onChange: (value: MaterialSource) => void;
|
||||
options: Array<{ value: MaterialSource; label: string; desc: string }>;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const current = options.find((opt) => opt.value === value) ?? options[0];
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-md border border-input bg-muted/30 px-2.5 py-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">检索方式</span>
|
||||
<Select value={current.value} onValueChange={(v) => onChange(v as MaterialSource)} disabled={disabled}>
|
||||
<SelectTrigger className="h-7 w-[9rem] bg-background px-2 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{options.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value} className="text-xs">
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span className="min-w-0 flex-1 text-xs text-muted-foreground">
|
||||
{current.desc}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MaterialConfirmCard({
|
||||
materials,
|
||||
skillSearchSteps,
|
||||
initialMaterialSource,
|
||||
canUseNotebookSearch,
|
||||
skillSearchInProgress,
|
||||
onSubmit,
|
||||
disabled,
|
||||
}: MaterialConfirmCardProps) {
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(
|
||||
() => new Set(materials.map((m) => m.id)),
|
||||
);
|
||||
const [userQuery, setUserQuery] = useState('');
|
||||
const [materialSource, setMaterialSource] = useState<MaterialSource>(
|
||||
initialMaterialSource === 'notebook' && !canUseNotebookSearch ? 'general' : initialMaterialSource,
|
||||
);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const sourceOptions = MATERIAL_SOURCE_OPTIONS.filter((opt) => opt.value !== 'notebook' || canUseNotebookSearch);
|
||||
|
||||
async function handleConfirm() {
|
||||
setSubmitting(true);
|
||||
@@ -148,7 +220,12 @@ function MaterialConfirmCard({ materials, skillSearchSteps, skillSearchInProgres
|
||||
setSubmitting(true);
|
||||
// 带输入 = 后端在素材收集专家配置的技能中匹配检索、新素材追加到列表;
|
||||
// 无输入 = 重新生成检索词、覆盖式重检
|
||||
await onSubmit({ action: 're_search', approvedMaterialIds: [], userQuery: userQuery.trim() || undefined });
|
||||
await onSubmit({
|
||||
action: 're_search',
|
||||
approvedMaterialIds: [],
|
||||
userQuery: userQuery.trim() || undefined,
|
||||
materialSource,
|
||||
});
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
@@ -163,7 +240,7 @@ function MaterialConfirmCard({ materials, skillSearchSteps, skillSearchInProgres
|
||||
<div>
|
||||
<p className="text-xs font-medium">未检索到任何素材</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
素材收集专家本次没有检索到相关数据。你可以在输入框描述想检索的内容(自动匹配已配置的技能),或在无素材的情况下直接继续写作。
|
||||
素材收集专家本次没有检索到相关数据。你可以切换检索方式并描述想检索的内容,或在无素材的情况下直接继续写作。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -172,6 +249,13 @@ function MaterialConfirmCard({ materials, skillSearchSteps, skillSearchInProgres
|
||||
<SkillStepsCard steps={skillSearchSteps} inProgress={skillSearchInProgress} />
|
||||
)}
|
||||
|
||||
<MaterialSourceSwitcher
|
||||
value={materialSource}
|
||||
onChange={setMaterialSource}
|
||||
options={sourceOptions}
|
||||
disabled={disabled || submitting}
|
||||
/>
|
||||
|
||||
<MaterialsToolbar
|
||||
materials={materials}
|
||||
selectedIds={selectedIds}
|
||||
@@ -211,7 +295,7 @@ function MaterialConfirmCard({ materials, skillSearchSteps, skillSearchInProgres
|
||||
<p className="text-xs font-medium">需要您确认素材,才能继续</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
已搜集到 {materials.length} 条素材(默认全选)。您可以取消勾选不相关的素材,
|
||||
或在下方描述想补充检索的内容——系统会匹配素材收集专家配置的技能检索,并把新素材追加进列表。
|
||||
或在下方切换检索方式并描述想补充检索的内容,系统会把新素材追加进列表。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -226,6 +310,13 @@ function MaterialConfirmCard({ materials, skillSearchSteps, skillSearchInProgres
|
||||
});
|
||||
}} />
|
||||
|
||||
<MaterialSourceSwitcher
|
||||
value={materialSource}
|
||||
onChange={setMaterialSource}
|
||||
options={sourceOptions}
|
||||
disabled={disabled || submitting}
|
||||
/>
|
||||
|
||||
<MaterialsToolbar
|
||||
materials={materials}
|
||||
selectedIds={selectedIds}
|
||||
|
||||
Loaded 100 of 936 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user