Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2fea6a801 | ||
|
|
a1fa13a238 | ||
|
|
264e2200d6 | ||
|
|
da6521b6cb | ||
|
|
42f2a26fa8 | ||
|
|
ab6068a7c1 | ||
|
|
5ab3d7f254 | ||
|
|
30e1c2dd90 | ||
|
|
673adef7df | ||
|
|
6f7919ded2 | ||
|
|
014d754707 | ||
|
|
8859c13cfb | ||
|
|
b0970de677 | ||
|
|
53cac5f81a | ||
|
|
33dea724a1 |
No files matched your search
@@ -85,12 +85,26 @@ offline-backend-20260512/backend/.deer-flow/*
|
||||
|
||||
# Per-user skill_evolution overrides — runtime data written by the API
|
||||
offline-backend-20260512/backend/skill_evolution.json
|
||||
# Automatic config.yaml backups written by the admin models page on every save
|
||||
offline-backend-20260512/backend/.model-config-backups/
|
||||
skills/
|
||||
# Harness skill-versioning logic is product source, not a runtime skill package.
|
||||
!offline-backend-20260512/backend/packages/harness/deerflow/skills/
|
||||
offline-backend-20260512/backend/packages/harness/deerflow/skills/*
|
||||
!offline-backend-20260512/backend/packages/harness/deerflow/skills/versioning.py
|
||||
hermes-agent-main/
|
||||
.gitignore
|
||||
offline-backend-20260512/backend/tests/*
|
||||
!offline-backend-20260512/backend/tests/test_goview_projects.py
|
||||
!offline-backend-20260512/backend/tests/test_goview_templates.py
|
||||
!offline-backend-20260512/backend/tests/test_goview_assets.py
|
||||
!offline-backend-20260512/backend/tests/test_skill_versioning.py
|
||||
!offline-backend-20260512/backend/tests/test_large_file_safety.py
|
||||
!offline-backend-20260512/backend/tests/test_account_authentication.py
|
||||
# HTML 结构化模板(no.1)引擎/存储/路由回归
|
||||
!offline-backend-20260512/backend/tests/test_structured_templates.py
|
||||
!offline-backend-20260512/backend/tests/test_html_runtime_addresses.py
|
||||
!offline-backend-20260512/backend/tests/test_app_identity.py
|
||||
!offline-backend-20260512/backend/tests/test_roundtable_room_limit.py
|
||||
!offline-backend-20260512/backend/tests/test_admin_audit_retention_control.py
|
||||
# Seeder-owned Agent Skills are product source; keep them out of the broad
|
||||
@@ -150,6 +164,8 @@ offline-backend-20260512/backend/tests/*
|
||||
# Keep the model configuration regression coverage versioned even though
|
||||
# this deployment repository otherwise ignores newly added backend tests.
|
||||
!offline-backend-20260512/backend/tests/test_model_management.py
|
||||
# Keep the model-stream truncation event (persistence + classification) coverage versioned.
|
||||
!offline-backend-20260512/backend/tests/test_stream_truncation.py
|
||||
# Keep the forced-research agent runtime gate and sandbox-policy regressions versioned.
|
||||
!offline-backend-20260512/backend/tests/test_forced_research_agent.py
|
||||
# Keep strategy-selection built-in agent seed and safety-contract regressions versioned.
|
||||
@@ -181,6 +197,10 @@ offline-backend-20260512/backend/tests/*
|
||||
# Keep database-backed upload-policy, enforcement and bounded-preview regressions versioned.
|
||||
!offline-backend-20260512/backend/tests/test_upload_policy.py
|
||||
!offline-backend-20260512/backend/tests/test_uploads_policy_enforcement.py
|
||||
!offline-backend-20260512/backend/tests/test_upload_responsiveness.py
|
||||
!offline-backend-20260512/backend/tests/test_conversion_responsiveness.py
|
||||
!offline-backend-20260512/backend/tests/test_async_agent_entrypoints.py
|
||||
!offline-backend-20260512/backend/tests/test_async_tool_initialization.py
|
||||
!offline-backend-20260512/backend/tests/test_artifact_preview.py
|
||||
# Independent enterprise-research persistence, HTTP and race regressions.
|
||||
!offline-backend-20260512/backend/tests/test_enterprise_research_tasks.py
|
||||
@@ -262,6 +282,7 @@ offline-backend-20260512/backend/uv.lock
|
||||
!offline-backend-20260512/backend/tests/test_wiki_package_roundtrip.py
|
||||
!offline-backend-20260512/backend/tests/test_llmwiki_incremental_sync_scheduler.py
|
||||
!offline-backend-20260512/backend/tests/test_worker_pool.py
|
||||
!offline-backend-20260512/backend/tests/test_chat_step_limit.py
|
||||
!offline-backend-20260512/backend/tests/test_worker_storage.py
|
||||
!offline-backend-20260512/backend/tests/test_worker_discovery.py
|
||||
!offline-backend-20260512/backend/tests/test_worker_diagnostics.py
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
## 背景
|
||||
|
||||
配置管理页(`/page/strategy/custom-deeplink-entry` 的上游配置工具)允许用户自定义任意多个业务类型,每个类型绑定一个执行智能体,深链落地到 `AgentChatPage` 的 landing 态。目前所有智能体的落地页完全一样(红色调 BotIcon 头像 + 「Hi,我是XX」+ 描述 + 输入框),用户从不同类型进来看到同一张脸,会觉得奇怪。
|
||||
|
||||
类型数量不定、由用户自由创建,人工逐个挑样式不可扩展。方案:**预设 6 套落地页风格 + 按智能体 id 确定性自动分配**——同一智能体永远同一套风格(深链入口、智能体管理「对话」按钮进入都一致),不同智能体尽量落在不同套;零配置、零后端改动。
|
||||
|
||||
纯前端改动,只用显式 hex/rgba 色值(遵循 globals.css:1840 注释的旧 Chrome 兼容铁律,不用 color-mix)。
|
||||
|
||||
## 实施步骤
|
||||
|
||||
### 1. 新增 `frontend-web/src/core/agents/appearance.ts`
|
||||
- FNV-1a 字符串 hash(项目里无现成工具);
|
||||
- `AGENT_LANDING_STYLE_COUNT = 6`;
|
||||
- `agentLandingStyleIndex(id: string): number` = hash % 6(稳定,id 不变风格不变);
|
||||
- 每套风格对应的头像图标表(lucide:Bot / Sparkles / Brain / Compass / MessagesSquare / Workflow),导出 `agentLandingStyleIcon(index)`。
|
||||
|
||||
### 2. `frontend-web/src/pages/AgentChatPage.tsx`
|
||||
- 在 `<main>`(~1471 行)上加 `data-agent-style={agentLandingStyleIndex(agent_id)}`,同时内联覆盖 `--primary: var(--agent-accent)`(CSS 里按风格定义)——让页头智能体胶囊图标、发送按钮等**纯色** primary 元素自动跟随风格(纯色工具类不依赖 color-mix,旧 Chrome 安全);
|
||||
- landing 分支(~1635 行)里加一个绝对定位、`pointer-events-none` 的氛围光斑 div(`.agent-style-glow`),按风格给页面顶部一层淡淡的对应色径向渐变,增强「换了个地方」的观感。
|
||||
|
||||
### 3. `frontend-web/src/components/workspace/agent-welcome.tsx`
|
||||
- 头像图标从写死 `BotIcon` 改为按风格轮换(`agentLandingStyleIcon(index)`);
|
||||
- 给问候语标题加 `agent-welcome-name` class 钩子(供 CSS 做渐变字等风格差异);
|
||||
- `.agent-avatar` 结构不动。
|
||||
|
||||
### 4. `frontend-web/src/styles/globals.css`
|
||||
- `.gemini-gradient-border::before` 的 conic-gradient 改为 `var(--agent-gemini-gradient, <现有四色默认>)`(默认值 = 现状,不影响其他页面);
|
||||
- 文件末尾新增一个非 layer 块「智能体专属落地页风格」,6 套风格 × 明/暗两版(沿用 `.dark` 前缀模式),每套定义:
|
||||
- `--agent-accent`(主色)、`--agent-accent-soft`(浅底)、`--agent-accent-border`(描边 rgba)、`--agent-gemini-gradient`(输入框专属旋转描边渐变);
|
||||
- `[data-agent-style="N"] .agent-avatar` 的底色/图标色/内描边(显式 hex,放在现有 `.agent-avatar` 主题块之后,非 layer 规则优先级高于工具类);
|
||||
- `[data-agent-style="N"] .agent-style-glow` 的径向渐变;
|
||||
- 2-3 套风格给 `.agent-welcome-name` 加渐变字/下划线装饰等排版差异,头像圆角形状在圆角方/圆形间轮换,让 6 套不只是换色。
|
||||
- 顺带处理 `input-box.tsx:754` 唯一的透明度主色用法(`border-primary/20 bg-primary/5 hover:bg-primary/10` 的 promptPrefix 横幅)→ 改用 `var(--agent-accent-border/-soft)` 显式变量 + 默认兜底,旧 Chrome 下不会退化成实色块。
|
||||
|
||||
### 5. 单测(轻量)
|
||||
- `frontend-web/src/core/agents/appearance.test.ts`:hash 稳定性(同一 id 结果恒定)、索引落在 0–5、不同 id 有分散性;沿用 vitest(参考 `core/settings/composer-scope.test.ts` 的位置与写法)。
|
||||
|
||||
## 明确不做 / 后续可选
|
||||
- 不改后端、不加配置字段。若以后想让管理员在配置管理页手动指定某类型的风格,可在此基础上把「风格号」存进业务映射配置、路由透传覆盖 hash 值即可(本次不做)。
|
||||
- 多个类型绑定同一智能体时共享同一套风格(这是智能体的身份,属预期行为);确实需要区分可创建不同智能体。
|
||||
- 会话开始后的消息流保持全局主题不变,只有页头智能体胶囊保留专属色 + landing 态整页风格化。
|
||||
|
||||
## 验证
|
||||
1. `cd frontend-web && pnpm typecheck` + `pnpm test:composer-session` 同款方式跑新增单测(或 `pnpm test` 过滤 appearance)。
|
||||
2. `pnpm dev` 起前端,打开 `http://localhost:5173/#/page/strategy/custom-deeplink-entry?goPath=测试`,确认落到绑定智能体且 landing 风格与全局红色主题不同;
|
||||
3. 在智能体管理临时建 2-3 个测试智能体分别进入问答页,确认不同 id 落到不同风格、同一智能体刷新/换入口风格恒定;
|
||||
4. 切深色主题复查 6 套风格的暗色变体;发送一条消息进入会话态,确认消息流恢复全局主题、页头胶囊保留专属色、输入框描边过渡正常。
|
||||
@@ -88,10 +88,32 @@ 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)
|
||||
- **智能体对话跳转**: 创建页、智能体管理编辑框和问答页详情面板都可以给智能体配置「对话跳转」链接、打开方式(新窗口 / 当前窗口)和路由参数(登录参数、主题参数,解析方式与应用管理相同)。配置保存在该智能体 `config.yaml` 的 `chat_link`,并镜像到 `agent_extras.chat_link` 供列表读取。留空时智能体管理的「对话」按钮仍进入本系统问答;填了地址后,按钮按解析后的链接跳转。
|
||||
- **模型流完整性检测 + 截断记录 (stream truncation)**: 模型配置页(`/page/workspace/admin/models`,`ModelManagementPage.tsx`)每张模型卡片新增「流完整性检测」开关 — `PUT /api/admin/models/strict-stream-integrity/{name}` 写 config.yaml 的 `strict_stream_integrity: true/false`(`app/gateway/routers/model_management.py`,仅 OpenAI 兼容 Chat Completions 模型可开;显式 `false` 也会覆盖 qwen3.8-flash-next 的自动开启;卡片显示值 = 显式配置 ?? qwen3.8-flash-next 自动规则,前端 `isAutoStrictIntegrityModel` 复刻后端判定)。开启后上游流未发终止帧就结束时抛可重试 `IncompleteChatStreamError`(`chat_stream_state.py`),LLM 错误中间件按 upstream 重试,避免半截回答静默入库。同时每次流异常结束都由 `patched_openai.py` 的 `_ToolCallStreamDiagnostics._record_truncation_event` 落库 `stream_truncation_events`(分类:`silent_no_terminal` 静默截断 / `incomplete_stream_error` 完整性拦截 / `length_truncated` / `content_filter` / `midstream_error`;write_file 兼容桥故意提前收流与用户取消不计;经 `fire_and_forget_db_write` 从任意 loop/thread 安全写入,store 在 `deerflow/persistence/stream_truncation/`,**每次写入顺手删除 30 天前的行,硬上限一个月**)。查看页 `pages/StreamTruncationLogPage.tsx`(路由 `/page/workspace/admin/stream-truncations`,admin gate 同模型配置页;简洁模式「设置和更多」下拉的「模型截断记录」入口在 `workspace-nav-menu.tsx`),client `core/stream-truncation-log/api.ts`;后端 API `GET /api/admin/stream-truncations`(分页 + 模型/类型过滤)与 `/breakdown`(按模型汇总,`app/gateway/routers/stream_truncations.py`)。测试 `tests/test_stream_truncation.py`、`tests/test_model_management.py`。配套「保留中间正文」(管理员设置弹窗同名分区,`GET/PUT /api/system-settings/retry-keep-partial`,默认开启,关闭即恢复旧行为):①正常路径——原先「消息带可见工具调用就不给正文气泡」的分组规则会把步骤条执行中已流出的正文清掉;现 `groupMessages` 新增 `keepIntermediateText` 选项(MessageList 按开关传入):本轮全部过程正文**合并成一个气泡**挂在步骤条正下方(合成消息剥思考/工具调用,组 id 加 `:keep-text` 后缀避免 React key 冲突),步骤条保持一条不被拆开(正文气泡对工具消息/后续轮次的累积「透明」,`lastOpenGroup`/`lastNonKeepBubbleGroup` 向前跳过),分组完成后把合并气泡**重排到 present-files/subagent/document-rewrite 附属组之后**(正文块与最终回答相邻、不被文件卡片隔开),仅本轮「最终正文消息」(回扫到的最后一条有正文且无可见工具调用的 ai 消息)保留独立气泡;②重试路径——LLM 错误中间件静默重试时,上一次尝试已流出的半截正文从未进 checkpoint、会被前端 values 对账清掉,`core/threads/hooks.ts` 在收到 `llm_retry` 事件时快照在途消息,被丢弃后按原位插回(纯函数 `core/threads/retry-kept-messages.ts`,快照只在本轮流式期间有效,刷新即失)。测试 `tests/test_strategy_project_settings.py` 尾部、`src/core/messages/utils-group.test.ts`、`src/core/threads/retry-kept-messages.test.ts`(`pnpm test:retry-kept`)。
|
||||
- **知识库深度研究(普通知识库限定问答)**: 每个可读知识库从卡片或详情页进入 `/page/workspace/knowledge/:noteId/research`。它不复用原“深度研究”流程,而是把普通 Lead Agent 问答在服务端强制绑定到单个知识库、经典检索并关闭工具/记忆;私有会话与草稿仅创建者可见。首个完整回答自动成为 Markdown 草稿,后续回答须显式“应用为文档”。可写用户保存时在该知识库 Wiki 下创建保留根目录「深度研究」,用独立 publication id 的稳定 slug 创建/覆盖文章;文件名独立于问答标题。书架文章随知识库读权限共享,但“更多”及原问答仅创建者可见;只读用户可问答和整理草稿,不能发布。前端核心页 `pages/KnowledgeResearchPage.tsx`,client `strategy-components/api/knowledge-research.ts`;后端 REST 在 `app/gateway/routers/llmwiki.py`,运行时约束 `app/gateway/knowledge_research.py`,持久化 `deerflow/persistence/knowledge_research.py`。
|
||||
- **AI 写作·对话版(对话驱动写作台)**: a **parallel new entry** beside the classic AI-writing page (classic page/routes untouched) — route `/page/canvas/ai-writing-chat`, sidebar 「问答管理 → 课题研究(对话版)」. Page `open-canvas/pages/AIWritingChatPage.tsx` reuses the engine (`AIWritingContext` + `useStream` + `AIWritingDraftPanel`); **idle keeps the classic setup layout** (`WritingSetupChat` + collapsible form) and switches to the chat workbench once writing starts; left panel `components/ai-writing-chat/WritingChatPanel.tsx` = **unified chronological feed** (`ChatFlowTimeline.tsx`, chat bubbles anchor-interleaved into the progress timeline so triggered events render below the user's message) + button-only intervention cards (`ChatInterventionCards.tsx`, inline textareas removed) + bottom unified smart composer. Intent resolution: frontend fast path + `POST /api/ai-writing/sessions/{id}/intent` → `deerflow/agents/ai_writing/intent_router.py` (per-pause action whitelist, high-cost confidence gates, payload cleaning); supports QA bypass, clarify follow-ups, control intents, and material-stage auto re-search + pending-intent resume. Tests `tests/test_ai_writing_intent.py`; plan doc `frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md`.
|
||||
- **AI 写作·对话版(对话驱动写作台)**: a **parallel new entry** beside the classic AI-writing page (classic page/routes untouched) — route `/page/canvas/ai-writing-chat`, sidebar 「问答管理 → 课题研究(对话版)」. Page `open-canvas/pages/AIWritingChatPage.tsx` reuses the engine (`AIWritingContext` + `useStream` + `AIWritingDraftPanel`); **idle keeps the classic setup layout** (`WritingSetupChat` + collapsible form) and switches to the chat workbench once writing starts; left panel `components/ai-writing-chat/WritingChatPanel.tsx` = **unified chronological feed** (`ChatFlowTimeline.tsx`, chat bubbles anchor-interleaved into the progress timeline so triggered events render below the user's message) + button-only intervention cards (`ChatInterventionCards.tsx`, inline textareas removed) + bottom unified smart composer. Intent resolution: frontend fast path + `POST /api/ai-writing/sessions/{id}/intent` → `deerflow/agents/ai_writing/intent_router.py` (per-pause action whitelist, high-cost confidence gates, payload cleaning); supports QA bypass, clarify follow-ups, control intents, and material-stage auto re-search + pending-intent resume. Tests `tests/test_ai_writing_intent.py`; plan doc `frontend-web/docs/ai-writing-对话驱动写作台-实现方案.md`. **素材检索技能池限定白名单**:`researcher_node` 通用检索的候选池 = **ai-writing-researcher 智能体 config.yaml `skills` 白名单里的启用技能**(管理员在智能体管理页增删,内置 `knowledge-base-search` 保底且始终排最前),不再列全部启用技能——300+ 技能部署把选择提示词撑爆导致素材检索不可用;容错兜底 `_fallback_candidate_skills` 同样限定白名单;白名单未配置/加载失败回退仅内置知识库检索。实现 `deerflow/agents/ai_writing/nodes/researcher.py::_load_candidate_skills/_researcher_skill_whitelist`,测试 `tests/test_ai_writing_knowledge_base.py`。
|
||||
- **轻应用中心 (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 defaults + personal layouts)**: `MenuManagementPage` (`pages/MenuManagementPage.tsx`) is available from「设置和更多」and the global Header account dropdown. Administrators edit the shared default menu; ordinary users edit only their own full/compact menu snapshot. For users with a saved snapshot, known node ids keep the personal `label`/`disabled`/`parentId`/`sortOrder` (or compact placement/order), while administrator defaults for node ids absent from that snapshot flow through—so newly-added code menus and iframe light apps follow the current default without overwriting older personal choices. Temporarily absent dynamic nodes are preserved when an unrelated personal edit is saved;「恢复默认」deletes only that user's snapshot. The static tree (`core/page-layout/sidebar-menu.ts`) remains the source of icons/routes and administrator defaults remain sparse per-node deltas. Merge/snapshot helpers live in `core/page-layout/menu-overrides.ts` and `compact-menu-overrides.ts`; full-menu writes carry the complete effective parent hierarchy for cycle/strict three-level validation while persisting only the sparse admin delta or full personal snapshot. Backend `/api/menu-overrides` uses `menu_overrides` (default) + `user_menu_override_configs` (per-user snapshot); `/api/compact-menu-overrides` uses `compact_menu_overrides` (type `A` / `B` defaults) + `user_compact_menu_override_configs` (per-user/type snapshots). Each website selects its compact type via `runtime-config.js` `VITE_COMPACT_MENU_TYPE`; `CompactToolbox` renders `toolbox` items.
|
||||
- **生成网页标识 (Generated Page Branding, admin-only write)**: 管理员在设置弹窗「生成网页标识」中填写网页展示名称、上传 PNG/JPG/WebP Logo(≤10MB)、单独移除 Logo 或整体清除配置。配置保存在 runtime `system_settings.json -> generated_page_branding`,图片保存在 runtime `generated-page-branding/`,`GET /api/system-settings/generated-page-branding` 全员可读,`PUT/DELETE` 仅管理员;生成 HTML 通过公开只读 `/api/public/html-runtime/generated-page-logo` 获取图片。**只有网页展示名称非空且 Logo 文件真实存在时功能才启用**;缺少任意一项(含单独移除 Logo)都不注入任何内容,完全保持原有网页生成逻辑。该配置只约束后续生成的 HTML 网页内容,不修改 DeerFlow 自身的系统名称、主导航、欢迎区、工作区标题或 Logo。启用时,HTML 写入与 `page_report_template validate` 会由 `html_runtime/generated_page_chrome.py` 确定性注入平台套壳:页头**通栏全宽、贴顶、无圆角**,**背景直接用全量模式导航栏设计图**(`html_runtime/assets/topbar-light.svg` 浅色红调 / `topbar-dark.svg` 深色深蓝,已注册进网关 `html_runtime.py` 的 `_STATIC_ASSETS` 白名单以 `/api/public/html-runtime/topbar-*.svg` 提供;页头运行时按 body 明暗 tone 自动切图),**只注入页头、不注入页脚**;设置弹窗不再提供「品牌位置」选择,新配置默认使用 `center`:「Logo+系统名称」居中锁孔(26px 白色金属渐变字 + 深浅辉光,落在设计图中央发光基座上)+ 页面导航**分列两侧**白字页签(当前项白色加粗 + 白色墨条)。`generated_page_branding.header_layout` 字段继续兼容存量配置,既有 `left` 仍按品牌居左 + 导航居中单行渲染。页签均为通栏等高下划线式(当前项主色 + 底部渐变墨条),多页强制首个逻辑页初始可见。开关 `chrome_enabled` **默认开启**;明确关闭时完全回归无注入:不注入页头、也不对页面提任何品牌要求(校验不检查品牌,模型不会被迫自写)。页脚与「网页页脚文字」设置项均已按需求移除(`FOOTER_MARKER` 常量仅为旧页面兼容保留)。模板套件的兜底导航条同款(品牌左 + 导航中、通栏贴顶),平台注入时经 `body:has([data-df-generated-header])` + 兜底脚本双保险自动隐藏。后处理会隐藏旧的多页导航、移除模型写入的 `data-df-brand` 重复标识且保持幂等;lead prompt 只让模型生成正文和逻辑页。注入点共四处且全部**账号无关**(admin 配置对全部账号生效,非 admin 仅无配置入口):**`page_report_template prepare`(工作副本创建时即预注入页头,模型从第一秒起编辑的就是带品牌导航的页面,brief 的 `platform_branding.pre_injected` 标记此状态)**、`write_file`/`str_replace`(`sandbox/tools.py` 的 `maybe_fix_generated_html`)、`page_report_template validate`、以及 `present_files` 交付兜底(`present_file_tool._ensure_generated_html_chrome`,覆盖模型经 bash 等旁路写出的 HTML;幂等,>4MB 跳过);注入时还会**归一化 body/html 顶部 padding/margin(清零)**(防弱模型为自想页头留白)并**隐藏模型自写的顶部 nav/header**(仅正文首个内容容器之前的,正文内导航不受影响);品牌配置每次实时读取 `system_settings.json`,无缓存无账号隔离。
|
||||
- **生成网页默认明暗模式 (Generated Page Theme)**: `ChatPage` 与 `AgentChatPage` 每次发送只把当前界面的明暗模式作为 `presentation_theme=light|dark` 上下文传入。用户未明确指定网页主题时,自由生成 HTML、显式模板的 `auto` 选择以及平台注入的品牌页眉/页脚按该明暗模式生成;用户明确指定浅色、深色或其他配色时以用户要求为准。不得跟随系统的红、蓝、绿等主题主色或自定义主色,网页强调色由页面内容与可读性决定;科技、数据、看板、驾驶舱或地图题材本身不得再触发深色默认。
|
||||
- **生成网页离线下载包 (Generated HTML Offline Bundle)**: 产物面板下载 `.htm/.html/.xhtml` 时不再只保存单个 HTML,而是请求 `GET /api/threads/{thread_id}/artifacts/{path}?download=true&offline_bundle=true`(公开只读分享的文件端点同样支持),下载 `{原名}-离线包.zip`。纯引擎 `deerflow/html_runtime/offline_bundle.py` 把入口统一为 `index.html`,只将平台信任的 `/api/public/html-runtime/*` JS/CSS/GeoJSON/品牌资源、认知态势图运行目录和签名 `/api/public/html-images/*` 图片复制到 `assets/` 并改写为相对地址;不得联网抓取任意第三方 URL。包内还带 `manifest.json`、中文 `README.txt` 和实际使用库的许可证。Leaflet 在线瓦片及用户主动引用的公网图片/API 不复制,保留原地址并列入 `external_urls`。非 HTML 下载、HTML 预览/新窗口打开及流式未落盘的临时下载行为不变。
|
||||
- **系统名称与 Logo(与生成网页标识分开)**: 管理员在设置弹窗「系统名称」里填写本系统导航、侧栏和欢迎区使用的名称,并可上传一张 PNG/JPG/WebP Logo。顶部导航名称字号可选 `adaptive`(默认,30px 上限、24px 下限)或 `fixed`(16–40px);配置字段为 `app_identity.header_title_font_mode/header_title_font_size`,固定模式不再按分辨率缩放,超长名称仍单行完整显示。红色主题还可分别上传导航栏背景图与菜单选中样式图(PNG/JPG/WebP/SVG,不设应用层文件大小限制),字段为 `light_red_header_background_*` / `light_red_nav_active_*`;选择文件或恢复默认时顶部导航即时预览,未配置时继续使用 `top-bg-light-red.svg` / `nav-active-light-red.svg`。其余配置在 `system_settings.json -> app_identity`,图片统一放在运行目录 `app-identity/`,接口 `GET/PUT/DELETE /api/system-settings/app-identity`(写仅管理员),图片通过 `/api/public/app-identity/*` 读取。名称留空继续用「CM业务中心」/「CM 助手」;未上传 Logo 继续用各主题静态图片和既有 `runtime-config.js` 覆盖。不读写 `generated_page_branding`,也不改已生成的 HTML。
|
||||
- **平台模板套件 (Bootstrap page-template-suite 技能)**: 内置技能 `skills/public/page-template-suite`(public 类,缺省启用)让「画页面」走平台预制 Bootstrap 模板而不是从零手写。**套件只提供多页面门户(最低 2 个逻辑页),不做单页面 HTML**(单页请求自动回落共享响应式文档模板):5 套设计 × 明暗两版共 10 个 `deerflow/page_reports/assets/report-bootstrap-*-template.html`(图表门户 3 页 / 甘特双页「进度总览+里程碑风险」/ 瓦片地图门户 3 页 / 文字杂志双页「正文论述+脉络结论」/ 研判简报双页「核心结论+风险行动」),profile 注册于 `page_reports/templates.py`(id `bootstrap-charts-portal-{light,dark}`、`bootstrap-gantt-{light,dark}`、`bootstrap-map-portal-{light,dark}`、`bootstrap-text-magazine-{light,dark}`、`bootstrap-text-briefing-{light,dark}`)。显式 `template_id` 时**页数以模板为准**(prepare 会把 brief 的页数对齐到模板页数,技能无需依赖用户说出「多页」)。模板源文件用 `__DF_HTML_RUNTIME_BASE__` 占位符引用 Gateway 运行库(Bootstrap/Alpine/ECharts/Leaflet/deerflow-runtime.js),`page_report_template prepare` 在会话副本中替换为设置里保存的 HTML 运行库地址,部署无关;图表走 `data-df-chart` 严格 JSON(甘特 = 时间轴 + 阶段重叠柱 `barGap:-100%`),地图门户走 `data-df-map` Leaflet 瓦片契约(瓦片地址来自设置里保存的地图瓦片地址,需管理员在「外观设置 → HTML 地图」选择「地图网页」引擎,引擎不符时 prepare 的 brief 会带 `map_engine_warning`)。prepare 的 brief 还带 `platform_branding`(管理员「生成网页标识」的名称/Logo/页脚文字与注入规则,正文禁止自写品牌)和 `runtime_base_url`;`_choose_page_profile` 现在**显式 `template_id` 优先**(单页文档模式也能选中套件模板,此前单页一律回落共享文档模板),未显式指定时旧选择行为不变。多页门户模板自带锚点切页兜底脚本(检测 `data-df-generated-header` 让位平台套壳,勿用 `data-df-generated-chrome` 字面量——会被注入幂等检查误判)。测试 `tests/test_page_template_suite.py`(10 模板 prepare→validate 全绿 + 品牌注入 + 居左/居中布局 + 引擎门控)。
|
||||
- **Docker 内置技能同步**: Linux Docker 启动时不能让旧的持久化 `/app/skills` 遮住当前版本的 `backend/skills/public`。共享实现 `app/builtin_skill_sync.py` 会把 bundled public 覆盖同步到 live public 根、保留 `custom/`,并强制校验 Facebook/X/TikTok/YouTube/Threads/CNN/BBC/新华社/白宫官网/马尼拉时报/GMA News/雅虎日本/读卖新闻共 13 个硬路由页面技能;它使用跨进程文件锁和必需包内容摘要,多 worker 首次只复制一次,后续相同版本只校验跳过。两个受支持启动脚本仍在 Gateway 前调用 `backend/scripts/sync_builtin_skills.py`,把当前源码 `backend/skills` 只读挂载为 `/app/bundled-skills`、live skills 读写挂载到 `/app/skills`;同时 Gateway lifespan 在加载配置后、技能 ownership 迁移/MySQL 目录投影/提示词缓存之前再次调用同一共享实现,所以镜像默认入口、Compose 或外部发版脚本绕过 Shell 时也会自动补齐。任一硬路由技能缺失会 fail-fast 并打印名单,不能静默启动成“技能不可用”。
|
||||
- **自定义技能迭代与版本切换**: 管理员设置弹窗的「自定义技能迭代」总开关默认关闭(`GET/PUT /api/system-settings/skill-versioning`);关闭时保持原同名覆盖逻辑。开启后仅 `skills/custom` 参与:本人上传同名技能可选「迭代为新版本」(保留完整历史包并激活新版)或「直接覆盖」(清除旧版本链,以本次内容重新作为 v1);本人技能详情顶部也提供「迭代新版本」安装包入口,详情弹窗「版本」页可切换任一快照。历史包保存在 runtime `skill-versions/<name>/vNNNNNN`,位于技能扫描/沙箱挂载目录之外;`skills/custom/<name>` 永远只保留一个活动包,所以大模型只能发现当前激活版本。版本元数据与调用统计解耦并继续以稳定技能名计数,上传迭代和版本切换都不清零外部调用次数。实现 `deerflow/skills/versioning.py`、`app/gateway/routers/skills.py` 的 `/versions` 接口,测试 `tests/test_skill_versioning.py` 与 `tests/test_strategy_project_settings.py`。
|
||||
- **Facebook 页面生成技能**: 内置公共技能 `skills/public/facebook-page-generator` 只在用户明确要求 Facebook/Facebook 风格网页时触发;`lead_agent/prompt.py` 的普通问答 HTML 分流会强制读取该技能,并排除通用 `page-report-generation`、模板套件和从零手写 HTML。单账号单动态场景强制只写小型中文规格 JSON,再调用一次 `scripts/fast_single_post.py --spec`;脚本可将总评论数与实际展示数分离,按 `commentTopics` 自动补齐最多 100 条中文热评,也接受用户指定的逐条评论,并在一次进程内完成七模块 JSON、内部校验和 HTML 渲染。用户已提供素材或明确不搜索时禁止联网、图像生成、读模板/脚本源码和临时构建脚本;动态与评论正文必须为简体中文。多帖子场景仍使用 `scripts/render_facebook_page.py` 的 `init → validate → render` 流程确定性注入 `assets/facebook-template.html`,模型不得重写模板 DOM/CSS;渲染器拒绝覆盖已有文件并对 `</script>` 注入做转义。最终单文件 HTML 保留右上角设置按钮、分模块 JSON 编辑弹窗、实时校验与「应用并渲染」,以及响应式、深浅主题、发布/点赞/评论/搜索交互;浏览器缓存键包含初始 JSON 的 FNV-1a 指纹,同一制品刷新保留手动编辑,不同新制品不会再被沙箱同源旧 JSON 覆盖。测试 `tests/test_facebook_page_generator_skill.py`。
|
||||
- **X 页面生成技能**: 内置公共技能 `skills/public/x-page-generator` 只在用户明确要求 X 平台、Twitter/推特或 X 风格社交时间线网页时触发;专用路由会强制读取技能并绕开通用 HTML 生成器。单账号单推文场景强制只写小型中文规格 JSON,再调用一次 `scripts/fast_single_post.py --spec`;脚本可将总回复数与实际展示数分离,按 `replyTopics` 自动补齐最多 100 条中文热评,也接受用户指定的逐条回复,并在一次进程内完成六模块 JSON、内部校验和 HTML 渲染。用户已提供素材或明确不搜索时禁止联网、图像生成、读模板/脚本源码和临时构建脚本;推文与回复正文必须为简体中文。多帖子场景仍通过 `scripts/render_x_page.py` 的 `init → validate → render` 流程注入固定三栏模板与内联运行时。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、实时校验和「应用并渲染」,保留深浅主题、发布、回复、点赞、转发、收藏、搜索、关注与响应式移动布局;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_x_page_generator_skill.py`。
|
||||
- **TikTok 页面生成技能**: 内置公共技能 `skills/public/tiktok-page-generator` 只在用户明确要求 TikTok、抖音国际版或 TikTok 风格短视频信息流网页时触发。默认只写小型六模块补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_tiktok_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、实时校验和「应用并渲染」,保留滚动吸附、播放/暂停、双击点赞、静音、收藏、关注、评论、分享、搜索、方向键切换和移动端全屏布局;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_tiktok_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **YouTube 页面生成技能**: 内置公共技能 `skills/public/youtube-page-generator` 只在用户明确要求 YouTube 或 YouTube 风格视频门户、视频首页、频道页时触发。默认只写小型七模块补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_youtube_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、分类筛选、搜索、响应式视频网格、Shorts 横向列表、观看弹窗、点赞、收藏、订阅和评论;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_youtube_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **Threads 页面生成技能**: 内置公共技能 `skills/public/threads-page-generator` 只在用户明确要求 Threads 或 Threads 风格串文首页、文本社交信息流时触发。默认只写 `accountName`、`postText`、`topic`、`displayReplyCount` 等高层规格 JSON,并调用一次专用 `scripts/fast_page.py --spec`;脚本自动映射六模块、补齐作者/统计/中文热评、保留示例视觉并一次完成校验与渲染,禁止模型猜测 `$set` 深层路径或读取默认数据。只有结构改造才回退 `scripts/render_threads_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、深浅主题、发帖、搜索、点赞、回复、转发、分享、关注、动态面板和移动端导航;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_threads_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **CNN 页面生成技能**: 内置公共技能 `skills/public/cnn-page-generator` 只在用户明确要求 CNN 或 CNN 风格全球新闻门户、新闻首页时触发。默认只写以 `topic` 为核心、可选 `headline`/`breaking`/栏目标题数组的高层规格 JSON,并调用一次专用 `scripts/fast_page.py --spec`;脚本自动生成完整中文十模块与明确标注的非实时示意数据,禁止模型猜测 `$set` 深层路径、读取生成后的合并数据或探路后二次渲染。只有结构改造才回退 `scripts/render_cnn_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、突发条、搜索、直播弹窗、字幕切换、收藏、分享、移动菜单、市场快照和订阅表单;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_cnn_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **BBC 页面生成技能**: 内置公共技能 `skills/public/bbc-page-generator` 只在用户明确要求 BBC 或 BBC 风格国际公共新闻门户、新闻首页时触发。默认只写小型十模块补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_bbc_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、搜索、快讯、直播弹窗、字幕切换、音频进度、移动抽屉、新闻排行、地区天气和订阅反馈;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_bbc_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **新华社页面生成技能**: 内置公共技能 `skills/public/xinhua-page-generator` 只在用户明确要求新华社、新华网或新华社风格中文通讯社门户、新闻首页时触发。默认只写小型十模块中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_xinhua_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、多语种顶栏、报道专集、焦点图、要闻分类、名专栏、专题、记者工作室、地方切换、行业频道、媒体矩阵、直播字幕和订阅反馈;缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_xinhua_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **白宫官网页面生成技能**: 内置公共技能 `skills/public/white-house-page-generator` 只在用户明确要求白宫官网、White House 风格政府首页或美国行政机构门户时触发。技能把材料整理为 `site/navigation/hero/notice/updates/priorities/administration/calendar/participation/footer` 十模块 JSON;键名、`id`、锚点和视觉枚举保留英文技术值,所有读者可见内容强制使用简体中文,英文来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_white_house_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、透明转吸顶导航、建筑主视觉、公告、官方动态、优先事项、行政团队、公共日历、全屏菜单搜索、直播字幕和订阅反馈;默认内容明确为概念模板,不冒充政府官网,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_white_house_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **马尼拉时报页面生成技能**: 内置公共技能 `skills/public/manila-times-page-generator` 只在用户明确要求马尼拉时报、The Manila Times 或其风格的菲律宾大报门户时触发。技能把材料整理为 `site/navigation/ticker/lead/pulse/regions/opinion/sections/media/footer` 十模块 JSON;键名、`id`、锚点、视觉和涨跌枚举保留英文技术值,所有读者可见内容强制使用简体中文,英文或菲律宾语来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_manila_times_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、菲律宾旗色带、衬线报头、三栏头条、地区切换、评论、商业体育、视频弹窗、数字报翻页和订阅反馈;默认内容明确为概念模板,不冒充官方网站,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_manila_times_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **GMA News 页面生成技能**: 内置公共技能 `skills/public/gma-news-page-generator` 只在用户明确要求 GMA News、GMA 新闻或菲律宾广播新闻门户风格页面时触发。技能把材料整理为 `site/navigation/justIn/lead/news/services/broadcast/channels/media/footer` 十模块 JSON;键名、`id`、锚点和视觉枚举保留英文技术值,品牌缩写 `GMA` 可保留,其余读者可见内容强制使用简体中文,英文或菲律宾语来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_gma_news_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、即时新闻条、天气切换、吸顶导航、头条视频、最新/热门/地方切换、公共服务、电视直播字幕、频道卡片、播客、彩票开奖和订阅反馈;默认内容明确为概念模板,不冒充官方网站,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_gma_news_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **雅虎日本页面生成技能**: 内置公共技能 `skills/public/yahoo-japan-page-generator` 只在用户明确要求雅虎日本、Yahoo! JAPAN、Yahoo Japan 或日本综合门户风格页面时触发。技能把材料整理为 `site/search/services/news/account/weather/utilities/shopping/pulse/footer` 十模块 JSON;键名、`id`、锚点和视觉枚举保留英文技术值,品牌 `Yahoo! JAPAN` 可保留,其余读者可见内容强制使用简体中文,日文或英文来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_yahoo_japan_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、多类型搜索、服务展开、分类新闻、推荐轮换、演示登录、城市天气、路线查询、市场切换、商品收藏、体育比分、实时热榜、移动抽屉和返回顶部;默认内容明确为概念模板,不冒充官方网站,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_yahoo_japan_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **读卖新闻页面生成技能**: 内置公共技能 `skills/public/yomiuri-news-page-generator` 只在用户明确要求读卖新闻、读买新闻、Yomiuri、Yomiuri Shimbun 或日本全国大报风格页面时触发。技能把材料整理为 `site/navigation/breaking/lead/edition/features/news/opinion/media/footer` 十模块 JSON;键名、`id`、锚点和视觉枚举保留英文技术值,品牌罗马字 `YOMIURI ONLINE` 可保留,其余读者可见内容强制使用简体中文,日文或英文来源先翻译,`site.language` 固定为 `zh-CN`。默认只写小型中文补丁规格 JSON,并调用一次 `scripts/fast_page.py --spec` 在内部合并、校验和渲染;只有结构改造才回退 `scripts/render_yomiuri_news_page.py` 的 `init → validate → render`。最终单文件 HTML 自带右上角设置按钮、按模块 JSON 编辑弹窗、字号切换、速报展开、三栏头条、文章收藏、吸顶导航、全屏菜单、搜索、演示登录、数字报翻页、专题与分类切换、社论、视频字幕和邮件订阅;默认内容明确为概念模板,不冒充官方网站,缓存键包含初始 JSON 指纹并兼容禁止 localStorage 的沙箱。测试 `tests/test_yomiuri_news_page_generator_skill.py` 与 `tests/test_fast_page_generator_specs.py`。
|
||||
- **舆情分析智能体(前端虚拟智能体)**: 智能体管理页新增「舆情分析」类型 tab,固定一张虚拟智能体卡片(名称/简介可编辑,存 localStorage)。对话页 `pages/SentimentAgentChatPage.tsx`(路由 `agents/sentiment-analysis/chats/:thread_id`)复用普通问答布局 + `MessageList`,**输入框只有发送按钮**;问答经 Gateway `POST /api/sentiment-agent/stream` 转发外部 AG-UI 网关(不经过 LangGraph),会话仅存 sessionStorage。接口地址 + Basic Auth 在 `runtime-config.js` 配置(`VITE_SENTIMENT_AGENT_API_URL` / `_AUTH_USERNAME` / `_AUTH_PASSWORD`)并随请求传给后台;后台按传入地址转发、关闭 TLS 校验,失败时把完整错误回传。核心模块 `src/core/sentiment-agent/`。
|
||||
- **简洁模式用户引导 (Compact-mode onboarding tour)**: 简洁模式(外观设置的「全量/简洁」= compact,无全局导航栏 + 页面侧边栏)新增 TDesign React `Guide` 组件驱动的分步引导。组件 `components/workspace/compact-mode-guide.tsx`(挂在 `ChatPage`):9 步 —— 欢迎弹窗(dialog 模式)→ 左侧功能导航 → 聊天记录 → 设置和更多 → 换肤 → 界面模式(切回全量)→ 常用提示词栏 → 提示词管理弹窗 → 输入框;高亮目标由各组件上的 `data-compact-guide` 标记定位(`workspace-nav-chat-list` / `recent-chat-list` / `workspace-nav-menu` / `appearance-controls` / `custom-prompt-menu.tsx` 的 `CustomPromptBar`(提示词栏,仅新对话落地态渲染)与其 `ManagePromptsDialog`(`prompt-dialog` 锚点)/ ChatPage 输入框容器),**启动时按目标是否存在过滤步骤**(如新用户无聊天记录、侧栏收起时自动剔除该步 —— Guide 对缺失元素会抛错,不能盲传)。**提示词管理弹窗步骤是动态目标**:弹窗平时不渲染,引导切到该步前先广播 `PROMPT_DIALOG_GUIDE_EVENT`(`custom-prompt-menu.tsx` 导出)让 `CustomPromptBar` 打开 `ManagePromptsDialog` 并**接管**(`owner: true` 期间 ESC/点遮罩不关闭,防止高亮目标消失导致 Guide 报错),轮询锚点真正挂载后才切步;离开该步 / 跳过 / 完成 / 中途卸载时以 `owner: false` 收回弹窗,4 秒打不开则跳过该步防卡死。**TDesign Guide × Radix 模态互操作**:Radix 模态弹窗打开时会把 `body` 置 `pointer-events:none`(滚动锁定),Guide 直接挂在 body 下的遮罩/高亮/弹层会一并继承失活(引导按钮点不动),`styles/tdesign-theme.css` 末尾对 `.t-guide__overlay/__highlight/__popup/__wrapper` 显式 `pointer-events:auto` 兜底。触发:① 自动 —— 简洁模式新对话落地页自动演示,直到用户显式点「完成」或「跳过」才写 localStorage `deerflow.compact-guide-finished` 记忆(浏览器级);**中途刷新/离开不记忆,下次进入还会再演示**。② 手动 —— 「设置和更多」下拉新增「界面使用引导」(该下拉仅存在于简洁模式工作区侧栏 footer):已在问答页时广播 `compact-guide:start` 窗口事件直接启动,否则写 sessionStorage 请求并导航 `/chats/new` 由挂载的引导消费(消费在定时器真正启动时才执行,规避 StrictMode effect 双跑吞请求)。`eligible` 排除 embed=1 / hideChrome=1 / chats_iframe / FORCE_COLLAPSED_SIDEBAR(无界)等同样无全局 chrome 的特殊环境;启动延迟 800ms 等侧栏宽度过渡稳定后再测量高亮框。
|
||||
- **智能体使用引导 (Agent onboarding tour, 三段式)**: 智能体「浏览管理 → 创建与配置 → 发起问答」全流程分步引导,组件 `components/workspace/agents/agent-guide.tsx`(同一 TDesign `Guide` 封装模式,与简洁模式引导共享记忆语义:**仅显式点「完成/跳过」才写 localStorage** `deerflow.agent-guide.<stage>.finished`,中途刷新/离开不记忆)。**自动演示仅 create / chat 两段**(进智能体列表页不弹引导,点「创建智能体」进入新建页时才自动演示;list 段的 `AgentGuide` 传 `autoStart={false}`,只能由头部「使用引导」按钮手动触发)。三段各自挂载、各自记忆:① `list`(`agent-gallery.tsx`,/page/workspace/agents)——分区 Tabs、搜索排序、智能体卡片操作、右上「创建智能体」按钮;**完成/跳过就地结束(不跳转创建页,与 create 段无联动)**,最后一步仅提示进入创建页后会有配置引导;② `create`(`NewAgentPage.tsx`,/page/workspace/agents/new)——左侧对话式创建输入区、基本信息、运行模型+入库模板名、知识空间、SOUL.md、技能穿梭框、保存按钮(9 步);③ `chat`(`AgentChatPage.tsx`,agents/:id/chats)——左栏切换与历史、常用问题 chips、输入框(落地态/会话态两个挂点同一 `chat-input` 标记)、右侧详情面板;`eligible` 限定普通智能体对话页(`showAgentList && !isEmbedded && !taskCtxOn`,即排除通用问答原地嵌入与任务深链工作区),三段共用 `isAgentGuideEnvironment()` 排除 embed/hideChrome/无界环境。高亮锚点 `data-agent-guide`:列表页 `tabs`/`search`/`agent-card`(卡片+列表两种布局的根元素)/`new-agent-btn`,创建页 `create-chat-input`/`create-basic`/`create-model`/`create-knowledge`/`create-soul`/`create-skills`/`create-save-btn`,对话页 `chat-sidebar`/`chat-questions`/`chat-input`/`chat-detail`;同样**启动时按目标存在性过滤步骤**(新用户无卡片/无预设问题时自动剔除)。手动重放:三个页面头部各有「使用引导」按钮(列表页创建按钮左侧、创建页 header 右侧、对话页 header),广播 `agent-guide:start:<stage>` 窗口事件强制重放(忽略已看过记忆)。
|
||||
@@ -99,8 +121,10 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA:
|
||||
- **技能上下线 (Skill Availability, owner/admin)**: the global `Skill.enabled` flag is the online/offline switch. Taking a skill offline persists `skills.<name>.enabled=false` in `extensions_config.json` but does **not** delete its directory or remove it from existing agent/workflow configurations; the row remains visible and bringing it online restores those references. Administrators may toggle every skill from 「技能管理」; ordinary users may toggle only their own non-built-in `custom` skills from 「技能 → 技能列表 → 我的」. Offline skills must be absent from every model-facing skill catalogue (`lead` prompt, `search_skills`, `skill_list`, `skill_view`, subagents, AI writing/deep research/roundtable and Workflow run-start validation), from agent skill pickers, and from direct sandbox access: `read_file`/`ls`/`glob`/`grep`/`bash` reject offline, unknown, root-wide and category-wide `/mnt/skills` paths. The backend mutation is `PUT /api/skills/{name}`, authorizes either an administrator or the persisted owner of the target custom skill, patches the raw document so MCP placeholders and unrelated extension fields survive, uses atomic replacement when supported plus a Docker single-file-bind fallback, and refreshes the skill prompt cache. Launchers keep the runtime extensions file in a writable persisted directory. Existing agent/strategy-agent references stay visible as 「已下线」 and may be removed but not newly selected.
|
||||
- **技能地址管理 (Skill Address Management, admin-only)**: 扫描运行中的技能(`skills/{public,custom}` 下所有 `.md`/`.py`)里的 **http(s) URL 与 IP/IP:端口**,按唯一地址聚合全部出现位置(跨 .md/.py),支持**批量替换**(如把 UAT 地址一次性改成生产)。主体抽成可复用组件 `SkillAddressesPanel`(`pages/SkillAddressesPage.tsx` 导出,默认导出 `SkillAddressesPage` 仍保留旧路由 `/page/strategy/admin/skill-addresses` 作直链回退),**作为「技能地址管理」标签页嵌入管理员「技能管理」页 `pages/AdminSkillsPage.tsx`**(该页加 Tabs:「技能列表」+「技能地址管理」;入口在「设置和更多」下拉的「技能管理」`workspace-nav-menu.tsx` → `/page/workspace/admin/skills`,不再单列于 `components/page-sidebar.tsx` 左下角设置下拉):打开自动扫描并带**进度条**(扫描逐技能 / 应用逐文件 X/N,应对 150+ 技能),URL/IP 类型过滤 + 搜索 + 「片段批量套用」(如所有 `uat.4.cn` → `prod.4.cn`)、每地址「替换为」输入框(可展开看 `file:line` 片段)、内联**预览**、**应用**、**多关键词检索**(空格分隔全部命中),以及**修改记录**面板——每次应用生成一条记录(显示时间/改了哪些地址 from→to/文件数/处数),可**针对单次记录回退**(二次确认)。client + NDJSON 流式解析在 `strategy-components/api/skill-addresses.ts`。后端 `/api/skill-addresses`(**仅管理员**):所有文件 IO 走 `asyncio.to_thread` 不阻塞事件循环;`GET /scan`(+`/scan/stream`)、`POST /preview`、`POST /apply`(+`/apply/stream`)、`GET /backups`、`POST /rollback/{id}`;**子串安全替换**(基于 token span,不会误伤子串)、`expected_total` 乐观锁(409)、写前自动磁盘备份到 `{skills_root}/.address-edits/`(同时写一份 `{id}.manifest.json` 记录本次替换明细,供修改记录展示)、应用后刷新技能系统提示缓存。纯引擎 `deerflow/skills/address_scan.py`,router `app/gateway/routers/skill_addresses.py`,tests `tests/test_skill_addresses.py`。范围仅运行中技能,不动 `deploy/minimal/skills/`。
|
||||
- **按钮管理 (Task Button Management, admin-only)**: configures the **可配置跳转按钮** rendered in the left task panel of the task deep-link workspaces (rwfx / 3qfx / xdfx, see `TaskFxWorkspace`). Each button = `{business, label, linkType, target, appendTaskId, idParam, idKind, enabled, sortOrder}`; `linkType` is `url` (外链 `window.open`, optional append of `?{idParam}={id}` — **`idParam` is the editable query-param name**, e.g. `id`/`task_id`), `business` (内部切换到另一业务, reuses `resolveTaskDeeplinkTarget`, always task id), or `purpose` (弹出当前任务的「任务目的」表格 via the shared `TaskPurposeDialog`, no target — configurable for any page incl. xdfx). **`host`(宿主路由)** asks the embedding parent to navigate: `runTaskButton` sends `window.parent.postMessage({ type:'HOST_NAVIGATE', path, queryParams:{ [idParam]: Number(taskId) } }, hostOrigin)` — `target` is the host route, `appendTaskId`/`idParam` become numeric `queryParams` (task id, or action id when `idKind:"action"` — same selector as url buttons, xdfx only), origin from `runtime-config.js` `VITE_HOST_NAVIGATE_ORIGIN` (else ancestorOrigins/referrer; never `*`). **`idKind` (`task`/`action`) only matters for xdfx**: its deep-link `?taskId=` is an 行动id and the 任务id is resolved at login (`fetchTaskIdFromAction`) — `TaskContext` now also stashes the raw `actionId`, so a url **or host** button can append either (default `task`). Page `TaskButtonsPage.tsx` (route `/page/strategy/admin/task-buttons`, **admin-gated**, entry「按钮管理」in the bottom-left settings dropdown of `components/page-sidebar.tsx`, both full + collapsed modes) has per-business tabs, edits name/type/target/启停/排序/增删, saves the **whole set atomically** (replace-all), plus 「导入默认」 to merge code-seed defaults. **Seed/fallback** (like 敏感词管理): only when the whole table is empty (fresh deploy, never saved) do the workspace + page fall back to `defaultTaskButtons(cfg)` — rwfx's url buttons (编辑/下一步/3q详情) built from the **live** `/api/public/config/task-deeplink` plus cross-business switch buttons for **all three** businesses (each switches to the other two — rwfx→三情/行动, 3qfx→任务/行动, xdfx→任务/三情). Once saved, the store is the sole source of truth. The old hardcoded jump buttons were migrated out: `TaskFxWorkspace` no longer hardcodes 切换到三情分析, `TaskActionsPanel` keeps only the non-jump 清除记录, and `TaskPurposePanel` dropped its 3q详情 button (now configurable) **and defaults the 目的树 table to collapsed** (chevron toggle). Helpers `core/auth/task-buttons.ts` (`TaskButton`, `defaultTaskButtons`, `resolveTaskButtons`, `buttonsForBusiness`, `runTaskButton`), client+hooks `strategy-components/api/task-buttons.ts`. Backend: `/api/task-buttons` (global/shared; open read, admin replace-all), store `deerflow.persistence.task_buttons` (table `task_buttons`, auto-created by `create_all`), wired `app.state.task_button_store`. Tests: `tests/test_task_buttons.py`.
|
||||
- **HTML 模板管理 (HTML Template Management, admin-only)**: 定时任务「HTML 模板」库的可视化管理——列表/预览(iframe srcDoc sandbox)/在线编辑/上传 .html 覆盖/新建/删除/重置内置,改完**即时生效**(调度器每次执行直接读文件,无需重启)。模板从纯代码注册表升级为**文件型存储**:harness 纯引擎 `deerflow/runtime/scheduler/template_store.py`(`{base_dir}/html-templates/<id>/{template.html,meta.json}`,gitignored),app.py lifespan 把随包 `scheduler/templates/` 的全部内置模板(目前 27 个)seed 进存储——**目录缺失才复制,绝不覆盖管理页/线上修改**;`template_fill.py` 的 `get_template/list_templates/read_template_text` 改为存储优先、随包注册表兜底,写操作后 `invalidate_cache()` 清引擎 lru_cache。**convertible 自动探测**:上传/编辑正文时检测单行 `const DATA={…};` 注入行(当前引擎唯一注入点,`const MANIFEST=` 同理),带注入行即「可转换填充」(定时任务 JSON 转换管线零代码接入),否则「只展示」;数据存 `<script type="application/json">` 元素或 `let DATA`/带空格写法的模板仍探测为只展示。内置模板可编辑/覆盖/重置回随包原版但**不可删除**(防引用它的任务挂掉),自建模板可删。页面 `pages/HtmlTemplatesPage.tsx`(入口**仅官方 DeerFlow 入口**:`OfficialDeerFlowEntry.tsx` 侧栏「模板管理」→ `#/official/workspace/task-analysis/html-templates`,页面 id `html-templates` 的路径判断必须先于 `task-analysis-detail` 的 `/:id` 正则,仅 admin 可见;主应用的简洁/全量模式**不加侧栏入口**,仅保留直链路由 `/page/strategy/admin/html-templates` 作回退,admin-gated),client+hooks `strategy-components/api/html-templates.ts`。后端 `/api/html-templates`(读开放、写仅 admin;`app/gateway/routers/html_templates.py`),旧端点 `GET /api/scheduled-tasks/html-templates` 不变(内部同样读存储),定时任务表单的下拉自动看到新建模板。测试 `tests/test_html_templates_admin.py`。
|
||||
- **单智能体任务深链聊天记录(2026-10-19)**: `3qfx` / `rwfx` / `xdfx` 的会话历史使用独立 `task_deeplink_threads` 索引表及 `GET /api/task-deeplink-threads?task_id=&go_path=`,前端由 `useTaskDeeplinkThreads` 读取,不再筛选通用聊天列表。LangGraph thread/checkpoint 仍是消息权威数据;专用表仅按 `(task_id, go_path)` 定位 thread。`3qfx/rwfx` 按任务 id,`xdfx` 按 URL 原始行动 id;新 thread 写 `metadata.{taskRecordId,taskGoPath,thread_type:"task_deeplink"}` 并自动登记,通用最近对话默认隐藏。迁移 `20261019_01` 只建表、**不迁移/回填旧数据**。
|
||||
- **上下文近 3 轮滑窗(管理员全局开关)**: 「设置 → 上下文管理」可开启 `system_settings.json -> conversation_context.recent_turn_window_enabled`(默认关闭;`GET/PUT /api/system-settings/conversation-context`,PUT 仅管理员)。开启后 `RecentTurnsMiddleware` 只改变单次模型请求,保留含当前轮在内的最近 3 个真实用户回合及其 assistant/tool 链;checkpoint 与前端完整聊天记录不删。该模式优先于聊天框「上下文压缩」,且不会调用摘要模型;关闭后沿用原压缩行为。实现 `deerflow/agents/middlewares/recent_turns_middleware.py`,回归 `tests/test_summarization_multiturn.py` / `tests/test_prompt_prefix.py`。
|
||||
- **上下文与对话轮数(管理员全局设置)**: 「设置 → 上下文管理」可开启 `system_settings.json -> conversation_context.recent_turn_window_enabled`(默认关闭),并调整 `max_conversation_rounds`(单个普通对话的真实用户提问上限,默认 20,范围 1–50);统一走 `GET/PUT /api/system-settings/conversation-context`,PUT 仅管理员。轮数上限由 `ChatPage` 读取,达到后禁止继续发送并引导新建对话;旧配置缺字段时仍按 20。近 3 轮模式开启后,`RecentTurnsMiddleware` 只改变单次模型请求,保留含当前轮在内的最近 3 个真实用户回合及其 assistant/tool 链;checkpoint 与前端完整聊天记录不删。该模式优先于聊天框「上下文压缩」,且不会调用摘要模型;关闭后沿用原压缩行为。实现 `deerflow/agents/middlewares/recent_turns_middleware.py`,回归 `tests/test_summarization_multiturn.py` / `tests/test_prompt_prefix.py`。
|
||||
- **输入框选项按窗口隔离(per-tab composer options)**: 输入框工具条的「写作 / 文件 / 参考文献 / 上下文压缩」开关与「模型 / 快速(模式) / 思考强度」选择器原本存 `localStorage`(`deerflow.local-settings`)且 store.ts 监听 `storage` 事件跨窗口同步——一个窗口切换、所有窗口生效。现这 7 个字段拆入 `sessionStorage`(`deerflow.composer-session`):纯函数拆分/合并/解析在 `core/settings/composer-scope.ts`,`core/settings/local.ts` 的 `getLocalSettings`/`saveLocalSettings` 负责路由(全局文档读写时强制剥离这 7 个字段,历史残留值失效)。**每个浏览器窗口独立**——复制链接新开的窗口从默认值开始、互不影响;同一窗口刷新保留;`useLocalSettings` API 与全部使用方(input-box / chat-box / message-list / hooks / IframeChatPage 等)零改动。「选择 Agent」的新对话预选 `deerflow.last-agent-id` 同样改 sessionStorage。其余 LocalSettings(字号 / 布局模式 / composer 宽度等外观偏好)保持浏览器全局并继续跨窗口同步;一次性迁移标志 `deerflow.composer-session.migrated` 把升级前旧值搬进升级后第一个打开的窗口。「经典检索/智能检索」与「知识空间」选择本来就是页面 state + 线程 metadata,天然按窗口隔离,未改动。测试 `pnpm test:composer-session`(`core/settings/composer-scope.test.ts`)。
|
||||
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
|
||||
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
|
||||
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
|
||||
|
||||
@@ -118,8 +118,10 @@ 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)
|
||||
- **普通问答地图可视化**: shared `MarkdownContent` recognizes only dedicated `map-json` fences and otherwise preserves the legacy Markdown/Streamdown path byte-for-byte. `components/workspace/visualizations/` validates the bounded map contract with Zod, lazy-loads MapLibre, and provides loading/error/text fallbacks so malformed or unreachable maps never blank the message. The lead-agent prompt emits `map-json` only when the user explicitly asks for a map; flowcharts and other graphics continue through the existing Markdown/Mermaid path. The raster tile template comes from the single post-build setting `runtime-config.js` → `VITE_MAP_TILE_URL` (Google by default); replace it with the intranet `{z}/{x}/{y}` endpoint for disconnected deployments.
|
||||
- **HTML 成品离线绘图运行时**: 新生成的 `.html` 源码直接引用 Gateway `/api/public/html-runtime/` 下的浏览器版 `g6.min.js`、`echarts.min.js`、`leaflet.js/css` 和 `deerflow-runtime.js`;文件随后台源码存放于 `vendor/html-runtime/`,不再依赖前端 Vite/node_modules 产物或公网 CDN。`config.yaml -> html_runtime.base_url` 是写入新 HTML 的浏览器可访问绝对地址,`html_runtime.map_tile_url` 是地图网页模式读取的瓦片模板。设置 → 外观的管理员选项「HTML 地图」可选 `echarts`(本地 GeoJSON,`data-df-geo`,默认)或 `leaflet`(地图网页,`data-df-map`);运行时同时保留两种初始化,已生成页面不因切换失效。用户上传的栅格图若要作为页面背景,使用同一 Gateway 源下的签名地址 `/api/public/html-images/{token}` 写入 `background-image`。流程图使用 `data-df-flow` + G6(不用 Mermaid),图表使用 `data-df-chart`。普通问答保持独立:消息列表 `map-json` 继续由前端原逻辑渲染,普通流程图/图表仍走 Markdown/Mermaid。
|
||||
- **智能体对话跳转**: 创建页、智能体管理编辑框和问答页详情面板都可以给智能体配置「对话跳转」链接、打开方式(新窗口 / 当前窗口)和路由参数(登录参数、主题参数,解析方式与应用管理相同)。配置保存在该智能体 `config.yaml` 的 `chat_link`,并镜像到 `agent_extras.chat_link` 供列表读取。留空时智能体管理的「对话」按钮仍进入本系统问答;填了地址后,按钮按解析后的链接跳转。
|
||||
- **普通问答地图可视化**: shared `MarkdownContent` recognizes only dedicated `map-json` fences and otherwise preserves the legacy Markdown/Streamdown path byte-for-byte. `components/workspace/visualizations/` validates the bounded map contract with Zod after recovering common marker/line aliases (`coords`, `from`/`to`, `lng`/`lat`) and dropping unusable lines so markers still render; markers accept per-point `color`; lines are emitted only when the user explicitly asks to connect places, then render as colored SVG arrows that loop along the path (honoring `prefers-reduced-motion`); it lazy-loads MapLibre, and provides loading/error/text fallbacks so malformed or unreachable maps never blank the message. The lead-agent prompt emits `map-json` only when the user explicitly asks for a map; flowcharts and other graphics continue through the existing Markdown/Mermaid path. The raster tile template comes from the single post-build setting `runtime-config.js` → `VITE_MAP_TILE_URL` (Google by default); replace it with the intranet `{z}/{x}/{y}` endpoint for disconnected deployments.
|
||||
- **HTML 成品离线绘图运行时**: 新生成的 `.html` 源码直接引用 Gateway `/api/public/html-runtime/` 下的浏览器版 `g6.min.js`、`echarts.min.js`、`leaflet.js/css` 和 `deerflow-runtime.js`;文件随后台源码存放于 `vendor/html-runtime/`,不再依赖前端 Vite/node_modules 产物或公网 CDN。设置 → 外观的「HTML 运行地址」保存在 `system_settings.json -> html_runtime`(`GET|PUT /api/system-settings/html-runtime`,管理员可写):`base_url` 是写入新 HTML 的浏览器可访问绝对地址,`map_tile_url` 是地图网页模式读取的瓦片模板。未保存时才回退到旧的 `config.yaml`,最后才用本机默认地址。设置 → 外观的管理员选项「HTML 地图」可选 `echarts`(本地 GeoJSON,`data-df-geo`,默认)或 `leaflet`(地图网页,`data-df-map`);运行时同时保留两种初始化,已生成页面不因切换失效。用户上传的栅格图若要作为页面背景,使用同一 Gateway 源下的签名地址 `/api/public/html-images/{token}` 写入 `background-image`。流程图使用 `data-df-flow` + G6(不用 Mermaid),图表使用 `data-df-chart`。普通问答保持独立:消息列表 `map-json` 继续由前端原逻辑渲染,普通流程图/图表仍走 Markdown/Mermaid。
|
||||
- **系统名称与 Logo**: 管理员在设置弹窗「系统名称」里填写本系统导航、侧栏和欢迎区使用的名称,并可上传一张 PNG/JPG/WebP Logo。配置在 `system_settings.json -> app_identity`,图片在运行目录 `app-identity/`,接口 `GET/PUT/DELETE /api/system-settings/app-identity`(写仅管理员),图片地址 `GET /api/public/app-identity/logo`。名称留空继续用「CM业务中心」/「CM 助手」;未上传 Logo 继续用各主题静态图片和既有 `runtime-config.js` 覆盖。不改已生成的 HTML。
|
||||
- **定时任务「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`.
|
||||
- **策略优选**: route `/page/strategy/qa/strategy-selection`, sidebar 「问答管理 → 策略优选」. The standalone `src/strategy-selection/` workbench has two horizontal split stages: Step 1 keeps intent-understanding conversation cards on the left and an editable task draft plus angle selection on the right; Step 2 keeps multiplexed parallel strategy cards and automatic judging on the left while the right stays dedicated to the selected-strategy basket and final Markdown synthesis. It consumes the existing `POST /api/parallel-agents/run/stream` protocol, isolates output by stable agent id, supports expanded per-agent dialogs, user selection, Markdown editing/copy/download, and shared server-side DOCX export. A clearly marked neutral Taiwan-Strait risk-management demo is loaded by default for offline UI acceptance. Administrators can edit the SOUL and skills of the nine built-in functional agents through the page dialog; the backend seeds `strategy-selection-{intent,angle-*,judge,solution}` only when their directories are missing, preserving later admin changes. Pure parsing/SSE tests live in `src/strategy-selection/lib.test.ts`; backend seed tests live in `tests/test_strategy_selection_seed.py`.
|
||||
|
||||
@@ -2,6 +2,12 @@ importScripts("config.js", "shared.js");
|
||||
|
||||
const ALARM_NAME = "deer-browser-task-poll";
|
||||
const SERVICE_DISCOVERY_TTL_MS = 10 * 60 * 1000;
|
||||
const STATUS_CACHE_TTL_MS = 60 * 1000;
|
||||
const STATUS_RETRY_MS = 5 * 60 * 1000;
|
||||
const STATUS_MANUAL_MIN_INTERVAL_MS = 30 * 1000;
|
||||
const statusCache = new Map();
|
||||
const statusRequests = new Map();
|
||||
const discoveryRequests = new Map();
|
||||
const LEGACY_LOCAL_API_BASE_URL = "http://localhost:8001";
|
||||
const LEGACY_LOCAL_WEB_BASE_URL = "http://localhost:5174";
|
||||
let pollTimer = null;
|
||||
@@ -21,6 +27,7 @@ async function getSettings() {
|
||||
discoveredWebBaseUrl: "",
|
||||
lastServiceSyncAt: "",
|
||||
lastServiceSyncSource: "",
|
||||
lastServiceSyncContext: "",
|
||||
});
|
||||
if (settings.autoDiscoverServiceUrl) {
|
||||
settings.apiBaseUrl = discovered.discoveredApiBaseUrl || settings.apiBaseUrl;
|
||||
@@ -38,6 +45,7 @@ async function getSettings() {
|
||||
}
|
||||
settings.lastServiceSyncAt = discovered.lastServiceSyncAt || "";
|
||||
settings.lastServiceSyncSource = discovered.lastServiceSyncSource || "";
|
||||
settings.lastServiceSyncContext = discovered.lastServiceSyncContext || "";
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await chrome.storage.sync.set(updates);
|
||||
Object.assign(settings, updates);
|
||||
@@ -105,28 +113,77 @@ function apiCandidatesForWebBase(webBase, currentApiBase) {
|
||||
return candidates;
|
||||
}
|
||||
|
||||
async function browserContextStatus(apiBaseUrl) {
|
||||
async function serviceCacheKey(settings, apiBaseUrl, webBaseUrl = "") {
|
||||
const cookie = await getCookieToken({ ...settings, apiBaseUrl });
|
||||
const auth = JSON.stringify([settings.accessToken || "", cookie?.token || ""]);
|
||||
// Persist only a credential fingerprint with the discovery timestamp. A new
|
||||
// login or cookie must not reuse another account's cached status/backoff.
|
||||
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(auth));
|
||||
const fingerprint = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
return JSON.stringify([normalizeServiceBase(apiBaseUrl), normalizeServiceBase(webBaseUrl), fingerprint]);
|
||||
}
|
||||
|
||||
function statusRetryMs(response) {
|
||||
const value = response.headers?.get("Retry-After");
|
||||
if (!value) return STATUS_RETRY_MS;
|
||||
const seconds = Number(value);
|
||||
const delay = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
|
||||
return Number.isFinite(delay) ? Math.max(STATUS_RETRY_MS, Math.min(delay, 60 * 60 * 1000)) : STATUS_RETRY_MS;
|
||||
}
|
||||
|
||||
async function browserContextStatus(apiBaseUrl, settings = {}, force = false) {
|
||||
const base = normalizeServiceBase(apiBaseUrl);
|
||||
const key = await serviceCacheKey(settings, base);
|
||||
const cached = statusCache.get(key);
|
||||
const now = Date.now();
|
||||
if (cached && now < (force ? cached.manualRetryAt : cached.expiresAt)) {
|
||||
return cached.value;
|
||||
}
|
||||
if (statusRequests.has(key)) return statusRequests.get(key);
|
||||
|
||||
const request = (async () => {
|
||||
let value = null;
|
||||
let ttl = STATUS_RETRY_MS;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 10000);
|
||||
try {
|
||||
const response = await fetch(`${apiBaseUrl}/api/browser-context/status`, {
|
||||
const response = await fetch(`${base}/api/browser-context/status`, {
|
||||
credentials: "include",
|
||||
signal: controller.signal,
|
||||
});
|
||||
// The gateway may enforce authentication globally before this otherwise
|
||||
// public discovery endpoint is reached. A 401/403 still proves that this
|
||||
// candidate is the zncm API paired with the open frontend tab.
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
return { enabled: true, authenticationRequired: true };
|
||||
}
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
const data = await response.json().catch(() => null);
|
||||
if (data && typeof data.enabled === "boolean") {
|
||||
return data;
|
||||
ttl = statusRetryMs(response);
|
||||
if (response.status === 403 && data?.detail?.code === "browser_status_disabled") {
|
||||
value = { enabled: false, statusAccessDisabled: true };
|
||||
} else if (response.status === 401 || response.status === 403) {
|
||||
// Authentication still establishes a candidate's API identity. Do not
|
||||
// mistake the explicit administrative status switch for a login error.
|
||||
value = { enabled: true, authenticationRequired: true };
|
||||
} else if (response.ok && data && typeof data.enabled === "boolean") {
|
||||
value = data;
|
||||
if (data.enabled) ttl = STATUS_CACHE_TTL_MS;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
// Failed candidates are negative-cached too: an unreachable deployment
|
||||
// must not cause every open tab's three-second wake-up to probe it again.
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
const checkedAt = Date.now();
|
||||
statusCache.set(key, {
|
||||
value,
|
||||
expiresAt: checkedAt + ttl,
|
||||
manualRetryAt: checkedAt + (ttl === STATUS_CACHE_TTL_MS ? STATUS_MANUAL_MIN_INTERVAL_MS : ttl),
|
||||
});
|
||||
if (statusCache.size > 100) statusCache.delete(statusCache.keys().next().value);
|
||||
return value;
|
||||
})();
|
||||
statusRequests.set(key, request);
|
||||
try {
|
||||
return await request;
|
||||
} finally {
|
||||
statusRequests.delete(key);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function tabLooksLikeZncm(tab) {
|
||||
@@ -178,17 +235,34 @@ async function findOpenZncmTabs(settings) {
|
||||
}
|
||||
|
||||
async function discoverServiceBases(settings, force = false) {
|
||||
if (!settings.autoDiscoverServiceUrl && !force) return settings;
|
||||
const key = await serviceCacheKey(settings, settings.apiBaseUrl, settings.webBaseUrl);
|
||||
if (discoveryRequests.has(key)) return discoveryRequests.get(key);
|
||||
const request = discoverServiceBasesOnce(settings, force, key);
|
||||
discoveryRequests.set(key, request);
|
||||
try {
|
||||
return await request;
|
||||
} finally {
|
||||
discoveryRequests.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
async function discoverServiceBasesOnce(settings, force, contextKey) {
|
||||
if (!settings.autoDiscoverServiceUrl && !force) {
|
||||
return settings;
|
||||
}
|
||||
const lastSync = Date.parse(settings.lastServiceSyncAt || "");
|
||||
const discoveryAge = Date.now() - lastSync;
|
||||
const discoveryTtl = /browser_context_disabled|api_not_verified/.test(settings.lastServiceSyncSource || "")
|
||||
? STATUS_RETRY_MS
|
||||
: SERVICE_DISCOVERY_TTL_MS;
|
||||
if (
|
||||
!force &&
|
||||
Number.isFinite(lastSync) &&
|
||||
settings.lastServiceSyncSource &&
|
||||
settings.lastServiceSyncContext === contextKey &&
|
||||
discoveryAge >= 0 &&
|
||||
discoveryAge < SERVICE_DISCOVERY_TTL_MS
|
||||
discoveryAge < discoveryTtl
|
||||
) {
|
||||
return settings;
|
||||
}
|
||||
@@ -208,7 +282,7 @@ async function discoverServiceBases(settings, force = false) {
|
||||
let apiBaseUrl = normalizeServiceBase(settings.apiBaseUrl || DEER_CLIPPER_DEFAULTS.apiBaseUrl);
|
||||
let verified = false;
|
||||
for (const candidate of apiCandidatesForWebBase(discoveredWebBaseUrl, apiBaseUrl)) {
|
||||
const status = await browserContextStatus(candidate);
|
||||
const status = await browserContextStatus(candidate, settings, force);
|
||||
if (status) {
|
||||
apiBaseUrl = candidate;
|
||||
webBaseUrl = discoveredWebBaseUrl;
|
||||
@@ -217,7 +291,7 @@ async function discoverServiceBases(settings, force = false) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!verified && force) {
|
||||
if (!verified) {
|
||||
source = `${source}:api_not_verified`;
|
||||
}
|
||||
|
||||
@@ -229,22 +303,16 @@ async function discoverServiceBases(settings, force = false) {
|
||||
lastServiceSyncSource: source,
|
||||
};
|
||||
|
||||
if (
|
||||
force ||
|
||||
settings.apiBaseUrl !== next.apiBaseUrl ||
|
||||
settings.webBaseUrl !== next.webBaseUrl ||
|
||||
settings.lastServiceSyncSource !== next.lastServiceSyncSource
|
||||
) {
|
||||
// Discovered endpoints are runtime state, not user-authored preferences.
|
||||
// Keep them in storage.local so Chrome sync write quotas cannot break task
|
||||
// polling. The options page may still persist explicit user choices.
|
||||
next.lastServiceSyncContext = await serviceCacheKey(next, next.apiBaseUrl, next.webBaseUrl);
|
||||
// Refresh the timestamp even when the address/source did not change. Without
|
||||
// this write the first expired TTL causes status probes on every later poll.
|
||||
await chrome.storage.local.set({
|
||||
discoveredApiBaseUrl: next.apiBaseUrl,
|
||||
discoveredWebBaseUrl: next.webBaseUrl,
|
||||
lastServiceSyncAt: next.lastServiceSyncAt,
|
||||
lastServiceSyncSource: next.lastServiceSyncSource,
|
||||
lastServiceSyncContext: next.lastServiceSyncContext,
|
||||
});
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,13 +3,17 @@ const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const vm = require("node:vm");
|
||||
const { webcrypto } = require("node:crypto");
|
||||
|
||||
const BACKGROUND_PATH = path.join(__dirname, "background.js");
|
||||
|
||||
function createHarness() {
|
||||
function createHarness(options = {}) {
|
||||
let storageChangedListener;
|
||||
let alarmCreateCount = 0;
|
||||
const localData = {};
|
||||
let clock = options.now ?? Date.now();
|
||||
let fetchHandler = options.fetch;
|
||||
let cookieToken = "";
|
||||
const localData = options.localData || {};
|
||||
const fetchUrls = [];
|
||||
const settings = {
|
||||
apiBaseUrl: "http://localhost:8001",
|
||||
@@ -20,6 +24,7 @@ function createHarness() {
|
||||
taskPollingEnabled: true,
|
||||
workerId: "test-worker",
|
||||
taskPollIntervalSeconds: 5,
|
||||
...options.settings,
|
||||
};
|
||||
|
||||
const chrome = {
|
||||
@@ -30,7 +35,7 @@ function createHarness() {
|
||||
},
|
||||
onAlarm: { addListener: () => {} },
|
||||
},
|
||||
cookies: { get: async () => null },
|
||||
cookies: { get: async () => cookieToken ? { value: cookieToken } : null },
|
||||
runtime: {
|
||||
onInstalled: { addListener: () => {} },
|
||||
onMessage: { addListener: () => {} },
|
||||
@@ -58,8 +63,9 @@ function createHarness() {
|
||||
const context = {
|
||||
chrome,
|
||||
console,
|
||||
fetch: async (url) => {
|
||||
fetch: async (url, init) => {
|
||||
fetchUrls.push(String(url));
|
||||
if (fetchHandler) return fetchHandler(url, init);
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
@@ -70,6 +76,13 @@ function createHarness() {
|
||||
setTimeout: () => 1,
|
||||
clearTimeout: () => {},
|
||||
URL,
|
||||
AbortController,
|
||||
TextEncoder,
|
||||
crypto: webcrypto,
|
||||
Date: class extends Date {
|
||||
constructor(...args) { super(...(args.length ? args : [clock])); }
|
||||
static now() { return clock; }
|
||||
},
|
||||
DEER_CLIPPER_DEFAULTS: settings,
|
||||
deerNormalizeBaseUrl: (value) => String(value || "").replace(/\/+$/, ""),
|
||||
deerMakeWorkerId: () => "test-worker",
|
||||
@@ -88,6 +101,13 @@ function createHarness() {
|
||||
getAlarmCreateCount: () => alarmCreateCount,
|
||||
getFetchUrls: () => [...fetchUrls],
|
||||
getSettings: () => context.getSettings(),
|
||||
setSettings: (updates) => Object.assign(settings, updates),
|
||||
getLocalData: () => ({ ...localData }),
|
||||
advanceTime: (ms) => { clock += ms; },
|
||||
getTime: () => clock,
|
||||
setFetch: (handler) => { fetchHandler = handler; },
|
||||
setCookie: (token) => { cookieToken = token; },
|
||||
status: (url, settings = {}, force = false) => context.browserContextStatus(url, settings, force),
|
||||
discoverServiceBases: (settings, force = false) =>
|
||||
context.discoverServiceBases(settings, force),
|
||||
resetAlarmCreateCount: () => {
|
||||
@@ -151,6 +171,108 @@ test("automatic service discovery checks status once per ten minutes, not on eve
|
||||
await harness.discoverServiceBases(await harness.getSettings());
|
||||
assert.equal(harness.getFetchUrls().length, 1);
|
||||
|
||||
await harness.discoverServiceBases(await harness.getSettings(), true);
|
||||
assert.equal(harness.getFetchUrls().length, 1);
|
||||
harness.advanceTime(30_000);
|
||||
await harness.discoverServiceBases(await harness.getSettings(), true);
|
||||
assert.equal(harness.getFetchUrls().length, 2);
|
||||
});
|
||||
|
||||
test("unchanged service discovery refreshes its timestamp after TTL expiry", async () => {
|
||||
const harness = createHarness();
|
||||
await settle();
|
||||
harness.setSettings({ autoDiscoverServiceUrl: true });
|
||||
await harness.discoverServiceBases(await harness.getSettings());
|
||||
const firstSync = harness.getLocalData().lastServiceSyncAt;
|
||||
harness.advanceTime(10 * 60_000 + 1);
|
||||
await harness.discoverServiceBases(await harness.getSettings());
|
||||
assert.notEqual(harness.getLocalData().lastServiceSyncAt, firstSync);
|
||||
assert.equal(harness.getFetchUrls().length, 2);
|
||||
for (let i = 0; i < 20; i++) {
|
||||
harness.advanceTime(3_000);
|
||||
await harness.discoverServiceBases(await harness.getSettings());
|
||||
}
|
||||
assert.equal(harness.getFetchUrls().length, 2);
|
||||
});
|
||||
|
||||
test("concurrent status callers share a request and successful results expire", async () => {
|
||||
const harness = createHarness();
|
||||
const url = "http://example.test";
|
||||
const results = await Promise.all(Array.from({ length: 30 }, () => harness.status(url)));
|
||||
assert.ok(results.every((result) => result.enabled));
|
||||
assert.equal(harness.getFetchUrls().length, 1);
|
||||
harness.advanceTime(59_000);
|
||||
await harness.status(`${url}/`);
|
||||
assert.equal(harness.getFetchUrls().length, 1);
|
||||
harness.advanceTime(1_001);
|
||||
await harness.status(url);
|
||||
assert.equal(harness.getFetchUrls().length, 2);
|
||||
});
|
||||
|
||||
test("disabled status respects Retry-After even for manual calls and later recovers", async () => {
|
||||
const harness = createHarness({
|
||||
fetch: async () => ({
|
||||
ok: false,
|
||||
status: 403,
|
||||
headers: { get: () => "300" },
|
||||
json: async () => ({ detail: { code: "browser_status_disabled" } }),
|
||||
}),
|
||||
});
|
||||
const url = "http://example.test";
|
||||
const status = await harness.status(url);
|
||||
assert.equal(status.enabled, false);
|
||||
assert.equal(status.statusAccessDisabled, true);
|
||||
assert.equal(status.authenticationRequired, undefined);
|
||||
harness.advanceTime(299_999);
|
||||
await harness.status(url, {}, true);
|
||||
assert.equal(harness.getFetchUrls().length, 1);
|
||||
harness.setFetch(async () => ({ ok: true, status: 200, json: async () => ({ enabled: true }) }));
|
||||
harness.advanceTime(1);
|
||||
assert.equal((await harness.status(url)).enabled, true);
|
||||
assert.equal(harness.getFetchUrls().length, 2);
|
||||
});
|
||||
|
||||
test("network and server failures back off for five minutes", async () => {
|
||||
for (const fetch of [
|
||||
async () => { throw new Error("offline"); },
|
||||
async () => ({ ok: false, status: 500, json: async () => ({ detail: "unavailable" }) }),
|
||||
]) {
|
||||
const harness = createHarness({ fetch });
|
||||
for (let i = 0; i < 10; i++) assert.equal(await harness.status("http://example.test", {}, true), null);
|
||||
assert.equal(harness.getFetchUrls().length, 1);
|
||||
harness.advanceTime(300_000);
|
||||
assert.equal(await harness.status("http://example.test"), null);
|
||||
assert.equal(harness.getFetchUrls().length, 2);
|
||||
}
|
||||
});
|
||||
|
||||
test("status cache separates service addresses, login tokens and cookies", async () => {
|
||||
const harness = createHarness();
|
||||
await harness.status("http://one.test", { accessToken: "account-a" });
|
||||
await harness.status("http://one.test", { accessToken: "account-b" });
|
||||
await harness.status("http://two.test", { accessToken: "account-b" });
|
||||
harness.setCookie("new-login");
|
||||
await harness.status("http://two.test", { accessToken: "account-b" });
|
||||
assert.equal(harness.getFetchUrls().length, 4);
|
||||
await harness.status("http://two.test", { accessToken: "account-b" });
|
||||
assert.equal(harness.getFetchUrls().length, 4);
|
||||
});
|
||||
|
||||
test("discovery survives worker restarts but refreshes after account changes", async () => {
|
||||
const harness = createHarness();
|
||||
await settle();
|
||||
harness.setSettings({ autoDiscoverServiceUrl: true, accessToken: "account-a" });
|
||||
await harness.discoverServiceBases(await harness.getSettings());
|
||||
const localData = harness.getLocalData();
|
||||
assert.ok(!JSON.stringify(localData).includes("account-a"));
|
||||
const restarted = createHarness({
|
||||
localData,
|
||||
now: harness.getTime(),
|
||||
settings: { autoDiscoverServiceUrl: true, accessToken: "account-a" },
|
||||
});
|
||||
await restarted.discoverServiceBases(await restarted.getSettings());
|
||||
assert.equal(restarted.getFetchUrls().length, 0);
|
||||
restarted.setSettings({ accessToken: "account-b" });
|
||||
await restarted.discoverServiceBases(await restarted.getSettings());
|
||||
assert.equal(restarted.getFetchUrls().length, 1);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
# 接口性能管理
|
||||
|
||||
管理员入口:**设置 → Redis 与性能**。页面集中管理 Redis 读取缓存、浏览器状态接口访问、历史统计数据定时清理。
|
||||
|
||||
## 控制项
|
||||
|
||||
- Redis 总开关及有效期:1–3600 秒,默认 300 秒。已有管理员设置优先于 YAML 默认值。
|
||||
- 接口列表:15 组,支持搜索和单独开关。同组路径共用一个开关;总开关关闭时保留每组选择。列表由后端实际接入目录返回。
|
||||
- 浏览器状态:允许/拒绝 `GET /api/browser-context/status`,保存后生效。为兼容现有插件,升级默认允许;关闭时返回 403,错误码 `browser_status_disabled`,并建议客户端 300 秒后重试。此开关只控制状态查询,不改变 capture/ask/task 接口的原有权限。
|
||||
- 定时清理:复用原有审计清理调度及持久化暂停标记。关闭时在当前小批次完成后停止;重启保持关闭。清理范围仍是超过 90 天的工具调用、模型调用、已结束运行摘要和排行榜快照,不清理对话消息。页面仅打开时或手动刷新状态,不新增轮询。
|
||||
|
||||
## 缓存覆盖
|
||||
|
||||
智能体列表、技能列表、展示脱敏词、个人偏好、常用提示词、推荐问题、轻应用列表/侧栏/详情、完整菜单、简洁菜单、任务按钮、业务映射、HTML 模板、模型能力目录、标签及资源标签、浏览器状态。
|
||||
|
||||
模型配置仍按当前配置即时组装,缓存的是其数据库能力目录。智能体、技能和推荐问题保留原有可缓存请求条件。用户相关数据保持用户隔离,菜单同时按角色和菜单类型隔离。对话、流式响应和写入操作不缓存。
|
||||
|
||||
写入后使相关缓存失效;同键并发未命中请求合并填充。Redis 未配置、超时或不可用时回到原读取逻辑。超出大小限制的结果不缓存。
|
||||
|
||||
## 持久化和升级
|
||||
|
||||
`api_read_cache_settings` 保存总开关、有效期、逐组配置和浏览器状态开关。迁移 `20261029_01` 增加有效期,`20261029_02` 增加逐组配置、浏览器开关和缓存代次。沿用项目正常数据库迁移流程后再启动新版服务。
|
||||
|
||||
每次保存配置都会轮换持久化缓存代次,避免在 Redis 离线时关闭/开启缓存、随后 Redis 恢复或 Gateway 重启后重新命中旧数据。设置写入在进程内串行化,并使用数据库行锁合并更新;其他 Gateway 进程最多约 2 秒刷新设置。
|
||||
|
||||
浏览器扩展也应同步更新:修复服务地址不变时探测时间戳未更新的问题,成功状态短暂缓存、同地址鉴权请求合并,禁用/失败至少退避 5 分钟。旧扩展仍可能发送请求,服务端关闭开关会拒绝这些请求。
|
||||
|
||||
## 管理员排行榜
|
||||
|
||||
移除 `GET /api/admin/users/{user_id}/analytics` 及用户详情展示/调用;排行榜聚合统计和用户管理保留。旧详情 URL 返回 404。
|
||||
|
||||
## 回归入口
|
||||
|
||||
后端:`test_api_read_cache.py`、`test_api_performance_controls.py`、`test_api_performance_edge_cases.py`、`test_catalog_cache_routes.py`、`test_admin_analytics_removed.py`,以及菜单、模型管理和审计清理现有测试。
|
||||
|
||||
浏览器扩展:`node --test browser-extension/deer-web-clipper/background.test.cjs`。
|
||||
@@ -0,0 +1,366 @@
|
||||
# GoView 第一阶段离线项目模板与发布实施方案
|
||||
|
||||
## 1. 阶段目标
|
||||
|
||||
第一阶段只解决 GoView 的离线可用和内容管理闭环。
|
||||
|
||||
用户在保留原有画布编辑器的前提下,能够完成:
|
||||
|
||||
1. 我的项目:新建、编辑、重命名、删除、保存、预览和发布;
|
||||
2. 我的模板:把自己的项目保存为模板、查看、编辑模板信息和用模板创建项目;
|
||||
3. 模板市场:查看内置模板、用模板创建个人项目;
|
||||
4. 离线部署:项目 JSON、缩略图、模板封面和地图瓦片均由本地部署提供;
|
||||
5. 发布链接:项目发布后获得可直接访问的只读预览链接;
|
||||
6. 地图瓦片背景:在原有画布的组件库中增加一张可离线使用的 Leaflet 瓦片地图背景组件。
|
||||
|
||||
现有画布的拖拽、缩放、分组、样式、数据面板和事件面板不在本阶段改造范围内。
|
||||
|
||||
### 原生数据面板完整保留
|
||||
|
||||
截图中的“数据”标签页属于每个 GoView 组件自身的画布配置,不属于项目、模板或发布后台。第一阶段必须完整保留:
|
||||
|
||||
- 静态数据和 JSON 在线编辑;
|
||||
- JSON 或 TXT 导入、下载;
|
||||
- 动态请求;
|
||||
- 公共接口和数据池;
|
||||
- 数据字段映射及匹配状态;
|
||||
- 组件原有的刷新与轮询配置。
|
||||
|
||||
项目保存接口把整份 ChartEditStorage 作为 content_json 原样保存,其中已包含组件的 request、filter、option.dataset、字段映射和其它数据配置。模板创建和“使用模板”也只深拷贝同一份 JSON,不能删除、重置或改写这些数据配置。
|
||||
|
||||
后续如要增加新的数据来源,只能在这个数据面板中新增选项或适配器,不能替换、收窄或移除现有的静态数据、动态请求和公共接口能力。
|
||||
|
||||
## 2. 已核实的 GoView 基线
|
||||
|
||||
前端基线使用 H:\code\go-view 的官方 origin/master-fetch 分支。
|
||||
|
||||
| 功能 | 开源现状 | 第一阶段处理 |
|
||||
| --- | --- | --- |
|
||||
| 我的项目 | 已有项目卡片、创建、保存、删除、发布和预览请求 | 本地 Gateway 实现兼容接口 |
|
||||
| 我的模板 | 页面仅显示“暂时还没有东西呢” | 新增模板列表和模板操作 |
|
||||
| 模板市场 | 页面只展示 GoView Pro 宣传图和外链 | 替换为本地模板卡片列表 |
|
||||
| 新建弹窗模板入口 | “我的模板”和“模板市场”按钮处于禁用状态 | 启用并跳转到可用模板页 |
|
||||
| 项目发布 | 已有 state 字段和发布按钮 | 保存状态,并生成公开预览链接 |
|
||||
| 地图组件 | 有 ECharts 和高德地图组件,无离线 XYZ 瓦片背景组件 | 新增 Leaflet 瓦片背景组件 |
|
||||
|
||||
因此,项目画布本身不需要重写;模板中心不是“补一个后端开关”即可完成,必须同时补前端页面和接口。
|
||||
|
||||
## 3. 总体结构
|
||||
|
||||
~~~text
|
||||
GoView master-fetch 前端
|
||||
|
|
||||
| /api/goview/*
|
||||
v
|
||||
DeerFlow Gateway
|
||||
|
|
||||
+-- 项目和项目内容
|
||||
+-- 个人模板和市场模板
|
||||
+-- 本地图片与缩略图
|
||||
+-- 已发布项目的只读数据
|
||||
+-- 离线地图瓦片
|
||||
~~~
|
||||
|
||||
GoView 保持为独立的 Vue 前端。其他现有前端工程不参与第一阶段改造。
|
||||
|
||||
## 4. 接口兼容策略
|
||||
|
||||
### 4.1 保留现有项目接口前缀
|
||||
|
||||
GoView master-fetch 的请求前缀是 /api/goview,项目页和画布保存逻辑已经依赖下面的路径。Gateway 应优先兼容这些接口,避免改动画布同步逻辑。
|
||||
|
||||
| 方法和路径 | 请求 | 响应用途 |
|
||||
| --- | --- | --- |
|
||||
| GET /api/goview/project/list | page、limit | 我的项目卡片和分页 |
|
||||
| POST /api/goview/project/create | JSON:projectName、remarks、indexImage | 新建项目,返回 id |
|
||||
| GET /api/goview/project/getData | projectId | 编辑器读取项目元信息和 content |
|
||||
| POST /api/goview/project/save/data | 表单:projectId、content | 自动保存画布 JSON |
|
||||
| POST /api/goview/project/edit | JSON:id 和可编辑元信息 | 修改名称、说明或封面 |
|
||||
| POST /api/goview/project/rename | JSON:id、projectName | 快速重命名 |
|
||||
| DELETE /api/goview/project/delete | ids | 删除自己的项目 |
|
||||
| PUT /api/goview/project/publish | JSON:id、state | 发布或取消发布 |
|
||||
| POST /api/goview/project/upload | multipart:object | 上传本地缩略图或图片 |
|
||||
|
||||
响应保持 GoView 的 ResultEnum 约定:
|
||||
|
||||
~~~json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "获取成功",
|
||||
"data": {},
|
||||
"count": 0
|
||||
}
|
||||
~~~
|
||||
|
||||
项目列表的 count 与 data 同级,保持现有项目页的读取方式。项目详情使用现有字段 id、projectName、state、createTime、indexImage、createUserId、remarks 和 content。
|
||||
|
||||
### 4.2 新增模板接口
|
||||
|
||||
模板页面当前没有可复用接口,因此新增清晰的模板 API,不伪装成项目接口。
|
||||
|
||||
| 方法和路径 | 权限 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| GET /api/goview/templates/mine | 登录用户 | 我的模板列表和分页 |
|
||||
| POST /api/goview/templates/from-project | 项目所有者 | 从一个项目创建个人模板 |
|
||||
| GET /api/goview/templates/{id} | 模板所有者或市场可见 | 读取模板详情与 canvas JSON |
|
||||
| PUT /api/goview/templates/{id} | 模板所有者 | 修改名称、说明、封面 |
|
||||
| DELETE /api/goview/templates/{id} | 模板所有者 | 删除个人模板 |
|
||||
| GET /api/goview/templates/market | 登录用户或公开读取 | 模板市场列表 |
|
||||
| POST /api/goview/templates/{id}/create-project | 登录用户 | 深拷贝模板为新项目并返回项目 id |
|
||||
| POST /api/goview/templates/admin/seed | 管理员或启动期内部调用 | 导入内置模板,不在普通 UI 展示 |
|
||||
|
||||
市场模板只能“使用并创建项目”,不能直接编辑模板内容。个人模板只能由模板创建者编辑或删除。管理员维护市场模板不需要引入租户、空间和成员模型。
|
||||
|
||||
### 4.3 已发布项目访问链接
|
||||
|
||||
编辑器继续使用:
|
||||
|
||||
~~~text
|
||||
/#/chart/home/{projectId}
|
||||
~~~
|
||||
|
||||
发布后的用户访问链接使用原有预览路由:
|
||||
|
||||
~~~text
|
||||
/#/chart/preview/{projectId}
|
||||
~~~
|
||||
|
||||
为了让链接在没有登录态时可直接访问,新增只读接口:
|
||||
|
||||
~~~text
|
||||
GET /api/goview/project/published/{projectId}
|
||||
~~~
|
||||
|
||||
该接口仅当项目 state 为 1 时返回项目元信息和 content;未发布、已取消发布或不存在的项目统一返回 404。编辑器接口 getData 保持登录和所有者校验,不能为了预览方便而开放草稿。
|
||||
|
||||
预览页面启动时根据路由判断:
|
||||
|
||||
1. 编辑预览或已登录所有者预览,读取 getData;
|
||||
2. 直接打开已发布链接,读取 published/{projectId};
|
||||
3. published 接口返回 404 时显示“项目未发布或不存在”页面。
|
||||
|
||||
发布接口成功后返回 relative_view_url,例如 /#/chart/preview/id_38xq54e9uoo000。前端用当前站点 origin 拼成完整链接并提供“复制链接”按钮,不在后端写死域名、端口或部署前缀。
|
||||
|
||||
## 5. 持久化设计
|
||||
|
||||
第一阶段只需要项目、项目内容、模板和本地资源存储。
|
||||
|
||||
### 5.1 goview_projects
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| id | 字符串主键,兼容 GoView 的 id 路由参数 |
|
||||
| project_name | 项目名 |
|
||||
| remarks | 说明 |
|
||||
| state | -1 未发布,1 已发布 |
|
||||
| index_image | 缩略图资源地址 |
|
||||
| owner_id | 当前登录用户 ID |
|
||||
| created_at / updated_at | 创建和更新时间 |
|
||||
|
||||
### 5.2 goview_project_contents
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| project_id | 一对一关联项目,唯一 |
|
||||
| content_json | GoView ChartEditStorage 的完整 JSON,使用 PortableLongText |
|
||||
| updated_at | 最后保存时间 |
|
||||
|
||||
列表查询不读取 content_json,只有编辑器和预览页读取,避免大画布 JSON 进入列表响应。
|
||||
|
||||
### 5.3 goview_templates
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| id | 模板主键 |
|
||||
| name / description | 模板名称和描述 |
|
||||
| cover_image | 模板封面资源地址 |
|
||||
| content_json | 可直接复制为项目内容的 GoView JSON |
|
||||
| owner_id | 个人模板的创建者;内置市场模板可为空 |
|
||||
| scope | personal 或 market |
|
||||
| is_builtin | 内置模板标记;内置模板不可由普通用户删除 |
|
||||
| sort_order | 市场排序 |
|
||||
| created_at / updated_at | 创建和更新时间 |
|
||||
|
||||
### 5.4 本地资源目录
|
||||
|
||||
上传的图片、缩略图和模板封面保存到运行时可持久化目录,例如:
|
||||
|
||||
~~~text
|
||||
{runtime_dir}/goview-assets/
|
||||
~~~
|
||||
|
||||
上传服务校验文件类型、大小、文件名和真实图片格式,使用服务端生成的随机文件名,禁止保留用户路径。资源通过 Gateway 的受控 GET 接口提供,不依赖 OSS、CDN 或公网地址。
|
||||
|
||||
离线发版的镜像、离线依赖和部署脚本与业务源码分开维护;业务源码仓库只保留接口、数据库迁移、内置模板定义和前端源码。
|
||||
|
||||
## 6. 身份与权限
|
||||
|
||||
不新建 GoView 用户系统。项目和模板直接复用平台现有登录态。
|
||||
|
||||
| 场景 | 规则 |
|
||||
| --- | --- |
|
||||
| 我的项目 | 只列出 owner_id 为当前用户的项目 |
|
||||
| 我的模板 | 只列出 owner_id 为当前用户且 scope 为 personal 的模板 |
|
||||
| 模板市场 | 所有登录用户可读 market 模板 |
|
||||
| 创建项目 | 当前用户成为 owner |
|
||||
| 发布、保存、删除、重命名 | 仅项目 owner;无鉴权单用户部署按单管理空间规则处理 |
|
||||
| 维护市场模板 | 管理员 |
|
||||
| 发布项目预览 | 无需登录,但只读且仅返回已发布 content |
|
||||
|
||||
GoView 现有 axios 登录逻辑依赖自己的 GO_SYSTEM_STORE 和 /login。第一阶段替换为平台现有 Bearer Token 与 Cookie 逻辑;这个改动只影响网络层和路由守卫,不改编辑器画布。
|
||||
|
||||
## 7. 前端最小改造清单
|
||||
|
||||
### 7.1 保持不动的部分
|
||||
|
||||
- /chart/home/:id 的画布、左侧组件库、右侧样式/动画/数据/事件面板;
|
||||
- ChartEditStorage 的序列化结构;
|
||||
- useSync 中动态注册组件、恢复画布和自动保存机制;
|
||||
- 现有项目卡片布局和发布状态展示。
|
||||
|
||||
### 7.2 项目页
|
||||
|
||||
项目页继续调用现有 project.api.ts。适配 axios 的平台鉴权后,项目列表、新建、保存、删除、发布和缩略图上传可直接对接 Gateway。
|
||||
|
||||
项目卡片新增两个轻量操作:
|
||||
|
||||
1. 复制发布链接:仅已发布时显示;
|
||||
2. 保存为模板:把当前项目的最新 content 创建为个人模板。
|
||||
|
||||
### 7.3 我的模板
|
||||
|
||||
替换 src/views/project/mtTemplate/index.vue 的空状态页。
|
||||
|
||||
页面提供模板卡片列表、分页、预览、编辑名称/描述/封面、删除和“使用模板”按钮。点击使用模板调用 create-project,成功后直接跳转 /chart/home/{newProjectId}。
|
||||
|
||||
新建弹窗中“我的模板”按钮解除禁用,跳转到该页面或直接打开模板选择抽屉。
|
||||
|
||||
### 7.4 模板市场
|
||||
|
||||
替换 src/views/project/templateMarket/index.vue 的 Pro 宣传图和外链。
|
||||
|
||||
页面读取 market 接口,以与项目卡片相同的视觉语言展示内置模板。市场模板至少准备:
|
||||
|
||||
1. 深色通用数据驾驶舱;
|
||||
2. 地图基础概览大屏;
|
||||
3. 指标总览与趋势分析大屏;
|
||||
4. 时间轴与进度概览大屏。
|
||||
|
||||
模板内容作为版本化的内置 seed 文件随 Gateway 发布。首次启动只插入不存在的内置模板,后续升级不覆盖管理员已修改或新增的模板。
|
||||
|
||||
新建弹窗中“模板市场”按钮解除禁用,跳转到该页面或打开市场模板选择抽屉。
|
||||
|
||||
### 7.5 公开预览
|
||||
|
||||
预览页保留现有 /chart/preview/:id 和原始画布渲染。只修改加载项目数据的入口:未登录时走 published 接口,已登录编辑场景继续走 getData。预览页不显示编辑、保存、删除、模板和管理员操作。
|
||||
|
||||
## 8. 离线地图瓦片背景组件
|
||||
|
||||
### 8.1 目标
|
||||
|
||||
新增一个“地图瓦片背景”组件。第一阶段只提供离线底图和通用显示配置。
|
||||
|
||||
### 8.2 实现方式
|
||||
|
||||
在 GoView 组件库新增 Leaflet 组件:
|
||||
|
||||
~~~text
|
||||
src/packages/components/Business/Maps/LeafletTileBackground/
|
||||
config.ts
|
||||
index.vue
|
||||
config.vue
|
||||
~~~
|
||||
|
||||
依赖使用 Leaflet 1.9,并在 GoView 入口加载 Leaflet CSS。组件作为普通 GoView 图层,可调整位置、尺寸、层级、边框、透明度和隐藏状态。
|
||||
|
||||
配置面板只暴露:
|
||||
|
||||
- 底图样式:默认离线底图、管理员配置的其他离线底图;
|
||||
- 初始中心点和缩放级别;
|
||||
- 最小和最大缩放;
|
||||
- 是否允许鼠标缩放和拖拽;
|
||||
- 明暗遮罩、透明度和灰度效果。
|
||||
|
||||
不允许用户输入任意瓦片 URL,避免离线部署失效、内网地址泄漏和任意外部请求。
|
||||
|
||||
### 8.3 瓦片服务
|
||||
|
||||
Gateway 新增受控瓦片路由:
|
||||
|
||||
~~~text
|
||||
GET /api/goview/map-tiles/{style}/{z}/{x}/{y}.png
|
||||
~~~
|
||||
|
||||
瓦片数据位于部署的可持久化目录或只读地图资源卷。路由严格校验 style、z、x、y 范围并阻止路径穿越。
|
||||
|
||||
第一期配置一个默认样式,对接部署时挂载的 XYZ 瓦片目录。GoView 组件始终只使用 Gateway 的受控地址。
|
||||
|
||||
编辑器内默认关闭地图拖拽,避免和画布选择、移动组件冲突;预览页可按组件配置开启交互。组件卸载时必须调用 map.remove(),避免切换项目时保留 DOM、瓦片和事件监听。
|
||||
|
||||
## 9. 后端代码落点
|
||||
|
||||
建议新增:
|
||||
|
||||
~~~text
|
||||
offline-backend-20260512/backend/
|
||||
app/gateway/routers/goview_projects.py
|
||||
app/gateway/routers/goview_templates.py
|
||||
app/gateway/routers/goview_assets.py
|
||||
app/gateway/routers/goview_map_tiles.py
|
||||
packages/harness/deerflow/persistence/goview/
|
||||
__init__.py
|
||||
models.py
|
||||
project_store.py
|
||||
template_store.py
|
||||
packages/harness/deerflow/persistence/migrations/versions/
|
||||
YYYYMMDD_NN_goview_projects_and_templates.py
|
||||
app/gateway/goview_builtin_templates.py
|
||||
tests/test_goview_projects.py
|
||||
tests/test_goview_templates.py
|
||||
tests/test_goview_assets.py
|
||||
~~~
|
||||
|
||||
并在 app/gateway/deps.py 创建 Store,在 app/gateway/app.py 注册路由,在 persistence/models/__init__.py 导入 ORM 模型。Harness 只保存数据和仓储,HTTP 表单解析、上传、鉴权、公开预览和瓦片文件响应只放在 app/gateway。
|
||||
|
||||
## 10. 实施顺序
|
||||
|
||||
### A. 项目闭环
|
||||
|
||||
1. 实现 goview_projects 和 goview_project_contents;
|
||||
2. 兼容 project/list、create、getData、save/data、edit、rename、delete、publish、upload;
|
||||
3. 替换 GoView axios 登录逻辑为 DeerFlow 登录态;
|
||||
4. 实现 published 接口和复制发布链接。
|
||||
|
||||
验收:用户在当前画布编辑页保存,回到“全部项目”可以看到项目;发布后,无登录浏览器可通过 /#/chart/preview/{id} 查看同一画布。
|
||||
|
||||
### B. 模板闭环
|
||||
|
||||
1. 实现模板表和模板接口;
|
||||
2. 完成“保存为模板”和“我的模板”页面;
|
||||
3. 替换模板市场宣传页;
|
||||
4. 内置至少四套离线模板;
|
||||
5. 从任意模板创建独立项目。
|
||||
|
||||
验收:模板市场的模板不会被用户编辑;点击“使用模板”后生成新项目,修改新项目不会改变模板或其他用户的项目。
|
||||
|
||||
### C. 地图瓦片背景
|
||||
|
||||
1. 接入 Leaflet;
|
||||
2. 实现受控瓦片路由和默认离线瓦片配置;
|
||||
3. 新增 LeafletTileBackground 组件;
|
||||
4. 把地图背景加入至少一套内置模板。
|
||||
|
||||
验收:断开公网后,地图背景仍能显示;编辑器与预览页都不会因地图组件引发拖拽冲突或内存泄漏。
|
||||
|
||||
## 11. 测试清单
|
||||
|
||||
1. 项目列表只返回当前用户的项目;
|
||||
2. 项目所有者外的登录用户不能读取、保存、删除或发布草稿;
|
||||
3. 已发布预览只返回 state 为 1 的项目;
|
||||
4. 取消发布后原公开链接返回 404;
|
||||
5. 项目 content 为大 JSON 时能完整保存和恢复;
|
||||
6. 模板创建项目为深拷贝,模板 content 不被后续项目保存覆盖;
|
||||
7. 内置模板重复启动不重复插入,不覆盖已存在记录;
|
||||
8. 上传拒绝非图片、超大文件和路径穿越文件名;
|
||||
9. 瓦片路由拒绝非法 style、缩放层级和路径穿越;
|
||||
10. 无公网网络下,项目缩略图、模板封面和默认瓦片可正常加载。
|
||||
@@ -0,0 +1,21 @@
|
||||
# 按模型追加全局提示词
|
||||
|
||||
管理员打开「设置 → 模型追加提示词」,选择模型,填写提示词并开启开关,点击「保存此模型设置」。每个模型独立保存,关闭开关会保留文本。
|
||||
|
||||
设置按模型配置的 `name` 精确匹配,而不是显示名或供应商模型名。所有用户通过平台统一模型入口调用该模型时,都会在系统提示词末尾追加该文本;切换到其他模型不会携带它。未设置的模型保持原有行为。
|
||||
|
||||
设置保存在运行目录的 `system_settings.json` 的 `model_prompt_suffixes` 中,默认空、默认关闭。每次模型请求读取最新设置,已经创建的模型实例也能在下一次请求使用新值,无需重启。不会改写用户问题或持久化聊天记录,也不会修改原有智能体提示词文件。提示词用于引导回答方式,无法保证上游模型一定回答。
|
||||
|
||||
## 接口与实现
|
||||
|
||||
- `GET /api/system-settings/model-prompt-suffixes`:读取全部设置,仅管理员。
|
||||
- `PUT /api/system-settings/model-prompt-suffixes/{model_name}`:保存单个模型,正文为 `{ "enabled": true, "prompt": "自定义要求" }`,仅管理员;模型名需 URL 编码,支持包含 `/` 的名称。文本最多 20000 字符,启用时不可为空。
|
||||
- 统一入口 `deerflow.models.factory.create_chat_model` 保留原供应商模型的工具绑定与流式能力;OpenAI 兼容请求在传输适配提示词处理后追加,支持 Chat Completions 和 Responses;其他适配器在输入转换与批量生成入口追加。
|
||||
- 外部系统自行调用模型、绕过此统一入口的调用不受该设置控制。
|
||||
- 回归测试:`packages/harness/tests/test_model_prompt_suffix.py`,覆盖权限、持久化、模型隔离、重复追加防护、原始消息不变、即时更新、同步/异步/流式/批量调用及工具绑定。
|
||||
|
||||
## 普通问答与智能体问答的末尾顺序验证
|
||||
|
||||
两种页面均传递当前输入框的 `model_name`。Lead Agent 按「请求选择 → 智能体默认 → 系统默认」解析实际模型,然后调用同一 `create_chat_model`。普通问答使用通用模板,智能体问答使用其 SOUL.md 模板;主题、知识库范围、项目上下文及运行时中间件继续组装提示词。追加设置在模型请求层处理,因此位于这些内容之后。
|
||||
|
||||
回归测试运行两种 Lead Agent 分支的真实 LangGraph 图、模型工厂与 OpenAI 请求序列化,用模拟 HTTP 接口捕获最终请求,覆盖普通/智能体、默认/目标/其他模型、同步响应/流式响应共 12 种组合。测试注入后置系统要求和检索上下文,断言最终系统文本以管理员提示词结尾且只出现一次,用户问题保持原样。另验证 text_bridge、buffered_gateway、artifact_renderer 三种文件传输适配提示词均位于管理员提示词之前。测试不访问真实上游模型。
|
||||
@@ -62,6 +62,9 @@
|
||||
# 问答页「极速」模式:true=在模式菜单显示并直连大模型;false 或未设=隐藏。
|
||||
# 部署后优先改 dist/runtime-config.js 的 VITE_TURBO_MODE_VISIBLE,刷新即可。
|
||||
# VITE_TURBO_MODE_VISIBLE=false
|
||||
# 知识库视图切换:true=显示“列表 / 卡片”切换;false 或未设=固定为列表(默认)。
|
||||
# 部署后优先改 dist/runtime-config.js 的 VITE_KNOWLEDGE_VIEW_SWITCH_ENABLED,刷新即可。
|
||||
# VITE_KNOWLEDGE_VIEW_SWITCH_ENABLED=false
|
||||
# VITE_GITHUB_OAUTH_TOKEN=
|
||||
|
||||
# --- 官方 DeerFlow 风格页面入口(仅 Vite,不引入 Next.js)---
|
||||
|
||||
@@ -889,7 +889,7 @@ Step 2(chat 步骤)
|
||||
| `@tanstack/react-query` | - | 服务端状态缓存 |
|
||||
| `@langchain/langgraph-sdk` | - | LangGraph WebSocket 连接 |
|
||||
| `next-themes` | - | 主题管理 |
|
||||
| `sonner` | - | Toast 通知 |
|
||||
| `tdesign-react` | - | 全局消息、确认对话框与输入提示 |
|
||||
| `lucide-react` | - | 图标库 |
|
||||
| `tailwindcss` | - | CSS 框架 |
|
||||
| `rehype` 系列 | - | Markdown 渲染 |
|
||||
|
||||
@@ -290,7 +290,7 @@ chain 模式的 Step 2 init **完全复用** `initMultiAgent`:`agentNames = ch
|
||||
**目标**:能创建/编辑/保存/删除链条。
|
||||
- [x] 路由:`WorkspaceRoutes.tsx` 注册 `roundtable/chains`(套 `WorkspaceLayout`;本页**不需要** `ChatRuntime`,无沙箱依赖)。
|
||||
- [x] 页面 `roundtable-planning/pages/BusinessChainEditorPage.tsx`:
|
||||
- [x] 顶部:链条列表下拉(`<select>` 列出已存链条 + 新建项)/ 新建按钮 / 标题+描述输入 / 保存 / 删除(`window.confirm`)。
|
||||
- [x] 顶部:链条列表下拉(`<select>` 列出已存链条 + 新建项)/ 新建按钮 / 标题+描述输入 / 保存 / 删除(TDesign 确认对话框)。
|
||||
- [x] **左栏**:候选智能体(`listAgents()` + `filterRecommendCandidates`),竖排卡片,可拖、可点「+」快捷加入;已加入的置灰「已加入」。
|
||||
- [x] **右栏**:有序长条卡片(序号 tag + 名称 + 描述 + 移除),`SortableContext` 内拖拽排序;空态有占位提示。
|
||||
- [x] 拖拽用 `@dnd-kit`:左栏 `useDraggable`,右栏 `useDroppable` + `SortableContext`/`useSortable`,`onDragEnd` 计算插入 index(pool→右栏按落点插入;seat→seat `arrayMove`);`DragOverlay` 跟手卡片。
|
||||
|
||||
@@ -591,7 +591,7 @@ isOrchestrating = false
|
||||
| Step 2 干预 | 底部输入框 → `runOrchestration` 新 seed,wrap 进「用户人工干预新指令:...」 prompt |
|
||||
| Step 2 Persona | 点圆桌头像打开抽屉;保存后下一轮该席位使用所选模型 |
|
||||
| 新建任务 | `handleStartNewTask`:abort 全部、清 state、`runStep1Init`,与 Step 3「重新起草」共用 |
|
||||
| 历史草稿 | 顶栏下拉:加载 / 重命名 / 删除(删除带 `window.confirm`) |
|
||||
| 历史草稿 | 顶栏下拉:加载 / 重命名 / 删除(删除使用 TDesign 确认对话框) |
|
||||
| Step 3 预览 | 文本类 → 模态预览;其它 → 新窗口下载 |
|
||||
|
||||
---
|
||||
|
||||
@@ -343,7 +343,7 @@ const [thread, sendMessage, isUploading] = useThreadStream({
|
||||
|
||||
5. **附件上传**:先 `uploadFiles(threadId, files)` 上传到 Gateway `/api/threads/:threadId/uploads`,然后将 `path/filename/size` 写入 `messages[0].additional_kwargs.files`,与 lead_agent 后端约定一致。
|
||||
6. **TanStack Query 失效**:流式完成或新建会话时调用 `queryClient.invalidateQueries({ queryKey: ["threads", "search"] })`,让侧边栏「最近会话」自动刷新。
|
||||
7. **错误降级**:`onError` 弹 sonner toast;`getStreamErrorMessage(error)` 兜底解析对象/嵌套字段。
|
||||
7. **错误降级**:`onError` 通过项目反馈层弹出 TDesign Message;`getStreamErrorMessage(error)` 兜底解析对象/嵌套字段。
|
||||
|
||||
### 7.4 重要回调事件
|
||||
|
||||
@@ -423,7 +423,7 @@ LocalSettings = {
|
||||
|
||||
### 9.1 `src/components/ui/`
|
||||
|
||||
shadcn 风格的「无业务」基础组件:`button`、`badge`、`avatar`、`card`、`carousel`、`command`、`dialog`、`dropdown-menu`、`hover-card`、`input`、`input-group`、`item`、`progress`、`resizable`、`scroll-area`、`select`、`separator`、`sidebar`、`skeleton`、`sonner`、`switch`、`tabs`、`textarea`、`toggle`、`toggle-group`、`tooltip` 等。
|
||||
shadcn 风格的「无业务」基础组件:`button`、`badge`、`avatar`、`card`、`carousel`、`command`、`dialog`、`dropdown-menu`、`hover-card`、`input`、`input-group`、`item`、`progress`、`resizable`、`scroll-area`、`select`、`separator`、`sidebar`、`skeleton`、`switch`、`tabs`、`textarea`、`toggle`、`toggle-group`、`tooltip` 等。全局消息、确认框和输入提示统一使用 `src/core/ui/feedback.tsx` 封装的 TDesign 反馈层。
|
||||
|
||||
特色组件:
|
||||
- `aurora-text` / `flickering-grid` / `magic-bento` / `spotlight-card` / `shine-border` / `confetti-button` —— Landing 视觉效果
|
||||
@@ -695,7 +695,7 @@ URL 加 `?mock=true` 时,`useThreadChat()` 设 `isMock=true`,`getAPIClient(t
|
||||
|
||||
### 18.4 在浏览器调试 SSE
|
||||
|
||||
LangGraph SDK 走标准 SSE。开发期通过 Chrome DevTools `Network -> EventSource` 可以直接查看 frames。失败原因(如 422)可在 sonner toast 看到 `getStreamErrorMessage()` 的解析结果。
|
||||
LangGraph SDK 走标准 SSE。开发期通过 Chrome DevTools `Network -> EventSource` 可以直接查看 frames。失败原因(如 422)可在 TDesign Message 中看到 `getStreamErrorMessage()` 的解析结果。
|
||||
|
||||
---
|
||||
|
||||
@@ -795,7 +795,7 @@ setSettings("context", { model_name: "gpt-5" }); // 仅当前线程
|
||||
| 发起 GET/POST | `apiFetch(`${getBackendBaseURL()}/api/...`, { method, body })` |
|
||||
| 发起 SSE 聊天 | `useThreadStream({ threadId, context, ... })` |
|
||||
| 跨标签同步偏好 | `useLocalSettings()` / `useThreadSettings(threadId)` |
|
||||
| 弹 toast | `import { toast } from "sonner"; toast.success("done")` |
|
||||
| 弹全局消息 | `import { toast } from "@/core/ui/feedback"; toast.success("done")` |
|
||||
| 弹浏览器通知 | `useNotification().showNotification(title, { body })` |
|
||||
| 国际化 | `const { t } = useI18n(); t.common.loading` |
|
||||
| 合并 className | `cn("base", cond && "x-y")` |
|
||||
|
||||
@@ -77,17 +77,19 @@
|
||||
</script>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<script>
|
||||
// Relative production assets need a directory URL. Normalize a mounted
|
||||
// prefix such as /web to /web/ before the browser resolves asset URLs.
|
||||
// Relative production assets need a directory URL. A mounted prefix such
|
||||
// as /web must resolve against /web/. history.replaceState during parsing
|
||||
// makes old Firefox abort the document (NS_BINDING_ABORTED) before the
|
||||
// login bundle runs, so install a base URL instead of rewriting history.
|
||||
(function () {
|
||||
try {
|
||||
var path = window.location.pathname;
|
||||
if (path !== "/" && !path.endsWith("/") && !/\.[^/]+$/.test(path)) {
|
||||
window.history.replaceState(
|
||||
window.history.state,
|
||||
"",
|
||||
path + "/" + window.location.search + window.location.hash,
|
||||
);
|
||||
}
|
||||
if (path === "/" || /\/$/.test(path) || /\.[^/]+$/.test(path)) return;
|
||||
if (document.querySelector("base")) return;
|
||||
var base = document.createElement("base");
|
||||
base.href = path + "/";
|
||||
document.head.appendChild(base);
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
<link rel="icon" type="image/svg+xml" href="%BASE_URL%favicon.svg" />
|
||||
|
||||
@@ -88,7 +88,6 @@
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-math": "^6.0.0",
|
||||
"shiki": "3.15.0",
|
||||
"sonner": "^2.0.7",
|
||||
"streamdown": "1.4.0",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tdesign-react": "^1.12.3",
|
||||
@@ -9743,14 +9742,6 @@
|
||||
"@types/hast": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/sonner": {
|
||||
"version": "2.0.7",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc",
|
||||
"react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc"
|
||||
}
|
||||
},
|
||||
"node_modules/sortablejs": {
|
||||
"version": "1.15.7",
|
||||
"resolved": "https://registry.npmjs.org/sortablejs/-/sortablejs-1.15.7.tgz",
|
||||
|
||||
@@ -17,13 +17,18 @@
|
||||
"test:retrieval-debug": "node --experimental-strip-types --test src/core/llmwiki/retrieval-debug.test.ts",
|
||||
"test:abort-signal": "node --experimental-strip-types --test src/core/compat/abort-signal.test.ts",
|
||||
"test:business-chain": "npx esbuild src/roundtable-planning/lib/business-chain.test.ts --bundle --platform=node --format=esm --outfile=.runtime/unit-tests/business-chain.test.mjs && node --test .runtime/unit-tests/business-chain.test.mjs",
|
||||
"test:users-paged": "node scripts/test-users-paged.mjs",
|
||||
"test:auth-entry": "node scripts/test-auth-entry.mjs",
|
||||
"test:b5-1-theme": "node --experimental-strip-types --test src/core/auth/b5-1-theme.test.mjs",
|
||||
"test:task-entry": "node --experimental-strip-types --test src/core/auth/task-entry.test.mjs",
|
||||
"test:html-preview": "pnpm exec esbuild src/core/utils/legacy-html-preview.test.ts --bundle --platform=node --format=esm --outfile=.runtime/unit-tests/legacy-html-preview.test.mjs && node --test .runtime/unit-tests/legacy-html-preview.test.mjs",
|
||||
"test:visualizations": "node --experimental-strip-types --test src/components/workspace/visualizations/visualization-spec.test.ts",
|
||||
"test:visualizations": "node --experimental-strip-types --test src/components/workspace/visualizations/visualization-spec.test.ts src/components/workspace/visualizations/map-style.test.ts",
|
||||
"test:composer-session": "node --experimental-strip-types --test src/core/settings/composer-scope.test.ts",
|
||||
"test:agent-appearance": "node --experimental-strip-types --test src/core/agents/appearance.test.ts",
|
||||
"test:report-collaboration": "npx esbuild src/report-collaboration/tests/event-reducer.test.ts --bundle --platform=node --format=esm --outfile=.runtime/unit-tests/event-reducer.test.mjs && npx esbuild src/report-collaboration/tests/message-adapter.test.ts --bundle --platform=node --format=esm --outfile=.runtime/unit-tests/message-adapter.test.mjs && node --test .runtime/unit-tests/event-reducer.test.mjs .runtime/unit-tests/message-adapter.test.mjs",
|
||||
"check:chrome109-css": "node scripts/check-chrome109-css.mjs",
|
||||
"check:legacy-chrome-css": "node scripts/check-chrome109-css.mjs"
|
||||
"check:legacy-chrome-css": "node scripts/check-chrome109-css.mjs",
|
||||
"test:retry-kept": "npx esbuild src/core/threads/retry-kept-messages.test.ts --bundle --platform=node --format=esm --outfile=.runtime/unit-tests/retry-kept-messages.test.mjs && node --test .runtime/unit-tests/retry-kept-messages.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
@@ -107,7 +112,6 @@
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-math": "^6.0.0",
|
||||
"shiki": "3.15.0",
|
||||
"sonner": "^2.0.7",
|
||||
"streamdown": "1.4.0",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tdesign-react": "^1.12.3",
|
||||
|
||||
@@ -42,7 +42,7 @@ window.__CM_RUNTIME_CONFIG__ = {
|
||||
|
||||
// 地图瓦片地址模板:仅供普通问答消息列表中的交互地图使用。
|
||||
// 后续接入内网瓦片服务时,只需替换此项并保留 {z}/{x}/{y} 占位符。
|
||||
VITE_MAP_TILE_URL: "http://119.254.86.251:8023/tiles/{z}/{x}/{y}.png?v=zh-z14-13",
|
||||
VITE_MAP_TILE_URL: "http://119.254.86.251:8023/tiles/{z}/{x}/{y}.png",
|
||||
|
||||
// routeKey 短路由的用户名直登口令:例如 #/login/admin?routeKey=a。
|
||||
// 填值时优先使用这里的 password;留空时使用 URL 中的 ?password=。
|
||||
@@ -112,6 +112,9 @@ window.__CM_RUNTIME_CONFIG__ = {
|
||||
// A 系统跳转地址:人物、组织、事件等列表项打开链接使用。
|
||||
VITE_AIPI_PRESENT_URL: "http://present.a.uat.4.cn/present/domain",
|
||||
|
||||
// B 系统(XWT检索)头像代理;按部署环境设置为浏览器可访问的地址。
|
||||
VITE_AIPI_MINIO_PROXY_URL: "http://minio-proxy.b.sit.4.cn/facebook-proxy",
|
||||
|
||||
// B 系统 knowes 根地址。
|
||||
VITE_AIPI_KNOWES_URL: "http://ch1.b.uat.4.cn/knowes",
|
||||
|
||||
@@ -128,6 +131,7 @@ window.__CM_RUNTIME_CONFIG__ = {
|
||||
VITE_USE_REAL_DATA: "true",
|
||||
|
||||
// 登录深链任务详情是否使用本地 mock:false=真实接口;true=本地 mock。
|
||||
// 为 true 时同时拦截 xdfx 的 task-action/actionDetail 与 mainnets/narratives-by-name。
|
||||
VITE_MOCK_COP_TASK_DETAIL: "false",
|
||||
|
||||
// 岗位会商完整演示数据:true=启动时幂等写入后端;后端不可用时直接使用前端 JSON 兜底。
|
||||
@@ -143,6 +147,10 @@ window.__CM_RUNTIME_CONFIG__ = {
|
||||
// 静态站点模式开关;一般部署业务系统时保持 false。
|
||||
VITE_STATIC_WEBSITE_ONLY: "false",
|
||||
|
||||
// 知识库页面是否显示“列表 / 卡片”视图切换。默认 false:固定使用紧凑列表;
|
||||
// 改为 true 并刷新页面后,才允许用户切换到卡片视图。
|
||||
VITE_KNOWLEDGE_VIEW_SWITCH_ENABLED: "false",
|
||||
|
||||
// 紧凑导航开关:true 时固定使用简洁布局,工作台左侧栏收起为菜单图标,
|
||||
// 隐藏系统 Logo、换肤按钮以及“全量/简洁模式”切换。修改后刷新页面即可生效。
|
||||
VITE_FORCE_COLLAPSED_SIDEBAR: "false",
|
||||
|
||||
@@ -93,6 +93,21 @@ const requiredLegacyFallbacks = [
|
||||
pattern: /AbortSignal\.timeout = function/,
|
||||
description: "Chrome 102 needs AbortSignal.timeout before any module loads",
|
||||
},
|
||||
{
|
||||
file: "vite.config.ts",
|
||||
pattern: /export function jsx\(\)\{return null\}/,
|
||||
description: "Stale Vite deps chunks must locally export jsx for Chrome 102",
|
||||
},
|
||||
{
|
||||
file: "vite.config.ts",
|
||||
pattern: /export const \$\{name\} = __jsxRuntime\.\$\{name\}/,
|
||||
description: "Vite jsx-runtime CJS interop must expose a named jsx export",
|
||||
},
|
||||
{
|
||||
file: "src/components/workspace/question-navigator.tsx",
|
||||
pattern: /animateScrollTop\(parent, Math\.max\(0, Math\.min\(nextTop, maxScrollTop\(parent\)\)\)\)/,
|
||||
description: "Question list anchors must set nested scrollTop for Chrome 102",
|
||||
},
|
||||
{
|
||||
file: "src/styles/globals.css",
|
||||
pattern: /\.workspace-chat-bg,\s*\n\s*\.canvas-writing-bg\s*\{\s*background-color:\s*var\(--background\);/,
|
||||
|
||||
@@ -14,6 +14,7 @@ const testEntries = {
|
||||
"login-entry": "src/core/auth/login-entry.test.ts",
|
||||
"session-validation": "src/core/auth/session-validation.test.ts",
|
||||
"auth-request-policy": "src/core/api/auth-request-policy.test.ts",
|
||||
"login-transport": "src/core/auth/login-transport.test.ts",
|
||||
};
|
||||
const outputDirectory = path.join(root, ".runtime/unit-tests");
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const require = createRequire(import.meta.url);
|
||||
const viteRequire = createRequire(require.resolve("vite/package.json"));
|
||||
const { build, stop } = viteRequire("esbuild");
|
||||
const outfile = path.join(root, ".runtime/unit-tests/users-paged-api.mjs");
|
||||
try {
|
||||
await build({
|
||||
absWorkingDir: root,
|
||||
entryPoints: ["src/core/auth/api.ts"],
|
||||
outfile,
|
||||
bundle: true,
|
||||
platform: "node",
|
||||
format: "esm",
|
||||
plugins: [{
|
||||
name: "mock-user-api-dependencies",
|
||||
setup(builder) {
|
||||
builder.onResolve({ filter: /^@\/core\/(api\/fetch-client|config)$/ }, ({ path }) => ({ path, namespace: "mock" }));
|
||||
builder.onLoad({ filter: /.*/, namespace: "mock" }, ({ path }) => ({
|
||||
contents: path.endsWith("config")
|
||||
? 'export const getBackendBaseURL = () => "https://example.test";'
|
||||
: 'export const apiFetch = (...args) => globalThis.usersPagedFetch(...args);',
|
||||
}));
|
||||
},
|
||||
}],
|
||||
});
|
||||
} finally {
|
||||
stop();
|
||||
}
|
||||
const { listUsersPaged } = await import(pathToFileURL(outfile).href);
|
||||
const fetchPage = (signal) => listUsersPaged({ q: "alice", limit: 20, offset: 40 }, signal);
|
||||
|
||||
test("whitelist requests pagination and search without statistics", async () => {
|
||||
const users = { items: [{ id: "u1", email: "one@example.test", approved: false }], total: 41, approved_count: 40, limit: 20, offset: 40 };
|
||||
globalThis.usersPagedFetch = async (url, init) => {
|
||||
assert.equal(url, "https://example.test/api/v1/auth/users?limit=20&offset=40&include_counts=false&q=alice");
|
||||
assert.ok(init.signal instanceof AbortSignal);
|
||||
return Response.json(users);
|
||||
};
|
||||
assert.deepEqual(await fetchPage(), users);
|
||||
});
|
||||
|
||||
test("server timeout detail reaches the retry UI", async () => {
|
||||
globalThis.usersPagedFetch = async () => Response.json({ detail: "用户基础信息查询超时,请稍后重试" }, { status: 503 });
|
||||
await assert.rejects(fetchPage(), /用户基础信息查询超时/);
|
||||
});
|
||||
|
||||
test("client deadline aborts pending request and clears its timer", async (t) => {
|
||||
let deadline;
|
||||
const timer = {};
|
||||
t.mock.method(globalThis, "setTimeout", (callback, delay) => {
|
||||
assert.equal(delay, 20_000);
|
||||
deadline = callback;
|
||||
return timer;
|
||||
});
|
||||
const cleared = t.mock.method(globalThis, "clearTimeout", (value) => assert.equal(value, timer));
|
||||
globalThis.usersPagedFetch = (_url, { signal }) => new Promise((_resolve, reject) => {
|
||||
signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
|
||||
});
|
||||
const pending = fetchPage();
|
||||
deadline();
|
||||
await assert.rejects(pending, /用户列表加载超时/);
|
||||
assert.equal(cleared.mock.callCount(), 1);
|
||||
});
|
||||
|
||||
test("query cancellation propagates without being reported as a timeout", async () => {
|
||||
const query = new AbortController();
|
||||
globalThis.usersPagedFetch = (_url, { signal }) => new Promise((_resolve, reject) => {
|
||||
signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
|
||||
});
|
||||
const pending = fetchPage(query.signal);
|
||||
query.abort();
|
||||
await assert.rejects(pending, { name: "AbortError" });
|
||||
});
|
||||
|
||||
test("non-JSON errors preserve HTTP status", async () => {
|
||||
globalThis.usersPagedFetch = async () => new Response("unavailable", { status: 502 });
|
||||
await assert.rejects(fetchPage(), /HTTP 502/);
|
||||
});
|
||||
test("already cancelled requests remain cancellation errors", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
globalThis.usersPagedFetch = async (_url, { signal }) => { signal.throwIfAborted(); };
|
||||
await assert.rejects(fetchPage(controller.signal), { name: "AbortError" });
|
||||
});
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
const LandingPage = lazy(() => import("./pages/LandingPage"));
|
||||
const LoginPage = lazy(() => import("./pages/LoginPage"));
|
||||
const PageRoutes = lazy(() => import("./pages/PageRoutes"));
|
||||
const MarkdownDocxEditorPage = lazy(() => import("./pages/MarkdownDocxEditorPage"));
|
||||
const PublicScheduledTaskPage = lazy(() => import("./pages/PublicScheduledTaskPage"));
|
||||
const PublicScheduledTaskFullscreenPage = lazy(() =>
|
||||
import("./pages/PublicScheduledTaskPage").then((module) => ({
|
||||
@@ -81,6 +82,7 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
||||
const location = useLocation();
|
||||
const publicEmbedTheme = usePublicEmbedTheme();
|
||||
const positionStandaloneMode = isPositionRoundtableStandaloneMode();
|
||||
const markdownToolMode = location.pathname.replace(/\/+$/, "") === "/tools/md-to-word";
|
||||
// iframe 嵌入会话(按标签页 sessionStorage)集中在此同步:任何带 `&embed=1` 的入口(深链登录页
|
||||
// 或直接深链路由)一进来就启用、`embed=0` 关闭,后续干净路由靠会话维持去 chrome + 强制主题。
|
||||
useEffect(() => {
|
||||
@@ -89,9 +91,9 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
||||
// 操作日志(Y-Log):启动早期预热上报配置,使 writeYLog 同步读缓存即可工作
|
||||
// (刷新后 module 缓存清空,token 登录用户也能继续上报)。失败静默。
|
||||
useEffect(() => {
|
||||
if (positionStandaloneMode) return;
|
||||
if (positionStandaloneMode || markdownToolMode) return;
|
||||
void fetchYLogConfig();
|
||||
}, [positionStandaloneMode]);
|
||||
}, [positionStandaloneMode, markdownToolMode]);
|
||||
const forcedTheme = useMemo(() => {
|
||||
// b5-1 任务分析深链最高优先:接入方传 ?theme= 用传入值,不传默认深蓝。
|
||||
// 先于 embed 判定,避免 embed=1 缺省 light 盖掉本页的深蓝默认。
|
||||
@@ -135,8 +137,9 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
||||
forcedTheme={forcedTheme}
|
||||
>
|
||||
<QueryClientProvider>
|
||||
<AuthSyncWatcher disabled={positionStandaloneMode}>
|
||||
<AuthSyncWatcher disabled={positionStandaloneMode || markdownToolMode}>
|
||||
<I18nProvider initialLocale={locale}>
|
||||
{markdownToolMode ? children : (
|
||||
<ThemeProvider>
|
||||
<ChatProvider>
|
||||
{!positionStandaloneMode && <DesensitizeWordsLoader />}
|
||||
@@ -144,6 +147,7 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
||||
{children}
|
||||
</ChatProvider>
|
||||
</ThemeProvider>
|
||||
)}
|
||||
</I18nProvider>
|
||||
</AuthSyncWatcher>
|
||||
</QueryClientProvider>
|
||||
@@ -198,6 +202,15 @@ export function App() {
|
||||
}
|
||||
/>
|
||||
<Route path="/landing" element={<LandingPage />} />
|
||||
{/* Anonymous standalone tool: no workspace navigation or login gate. */}
|
||||
<Route
|
||||
path="/tools/md-to-word"
|
||||
element={
|
||||
<div className="h-dvh overflow-hidden">
|
||||
<MarkdownDocxEditorPage />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<Route path="/share/:shareCode" element={<PublicSharePage />} />
|
||||
<Route path="/public/leaderboard" element={<PublicLeaderboardPage />} />
|
||||
<Route
|
||||
|
||||
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 53 KiB |
@@ -0,0 +1,4 @@
|
||||
<svg width="28" height="20" viewBox="0 0 28 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M1 2L17 10L1 18V2Z" fill="#F5222D"/>
|
||||
<path d="M8 2L24 10L8 18V2Z" fill="#FDDADC"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 199 B |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="152" height="42.359" viewBox="0 0 152 42.359" fill="none">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="152" y2="42.359" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#A90F1A"/>
|
||||
<stop offset="0.5" stop-color="#D82932"/>
|
||||
<stop offset="1" stop-color="#941019"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="shine" x1="76" y1="0" x2="76" y2="42.359" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#FFF" stop-opacity=".34"/>
|
||||
<stop offset="1" stop-color="#FFF" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d="M5 0h142a5 5 0 0 1 5 5v32.359a5 5 0 0 1-5 5H5a5 5 0 0 1-5-5V5a5 5 0 0 1 5-5Z" fill="url(#bg)"/>
|
||||
<path d="M5 .75h142a4.25 4.25 0 0 1 4.25 4.25v32.359a4.25 4.25 0 0 1-4.25 4.25H5A4.25 4.25 0 0 1 .75 37.359V5A4.25 4.25 0 0 1 5 .75Z" stroke="#FFF" stroke-opacity=".34" stroke-width="1.5"/>
|
||||
<path d="M1 1h150v18.5c-29.8 10.6-119.1 10.6-150 0V1Z" fill="url(#shine)" opacity=".62"/>
|
||||
<path d="M22 40.859h108" stroke="#FFF" stroke-opacity=".8" stroke-width="2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1920" height="64" viewBox="0 0 1920 64"><image width="1920" height="64" preserveAspectRatio="none" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB4AAAABACAYAAAD77Wr8AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAP+lSURBVHhe7P1VdJxJuif89lqz9+5iM4Mkg2zLIGZmxmRmVIJYJpktMrOLqauaqpmqqbq4u6D3/jbOnHVuz8C5mIuZOff/s54n4s18M5WS5erqge+ci9+KiCfifVMm2c5/Rrzf+O//5T//1/8T/DdpubraSnOr819WkHyNR1+XXk//+v9LRpmvXV7qdZnn0qWvW4l6/eNem36f9NfPVHtcj3OPldZlmlvu3plqK0v/vZL2+/Q/C/9dsdLaDB41r16zmrXLyXR9ptpX81/+63/7f6ss+TkUP4+pr5WcW+7XKtOa9PpfKvN90398qV9v6vVLf33+j5P2+3eJ5ebU160k/TrpfzzOPb4W/ylDTakr/vN//R8sWaO+InVtZunr0q9V3+//7y/wn6T0+tdpuddQ6n+x/ygtN17q/yOl1v6jirhPau2rS35NS+f+9/D/UrVKXz33fyP/MUMtHa1ZSfq69OsfNfe4vs57/c+W/nP3KOrrlrtPhtf4H1LGNbKmrElZtwrq6zJJX/9VpN/z/xf891VIv2Yl6deudB917VHrVjP3l0i/X/rrfBXpr/G/2v/OX1d6TT230vz/DF/Hr2nK9f/pP6rQOL0m/cfUsfLvlyXr/o/znxL91B8T1ZdS/n2YXn8syv9d0uvLzWf4P9H/Ksq/19Pr//eX6f+36f/v/frQ/5nTa1+LR71HsNL7Eem15d5zeNQ90usZ3st4pPRrl7vPcvW/pvSv7a+Aft755/5/pcSvoerPQsoa1Xt/6fPyz5D6vV7lvd/U94CTfwb/25I/k+l/DtPry1F/7cnrkt/bls59HVK/b6Z/DX8d4r23pfWvw196b+X6v+Qej/L13TvTr9vSX+OVLHnPa9XUP470ucwyvWZy/PjvyS53f+XnIn0+fd1q65mkfy0rXbfadcpapf+N30yPI5PfTo+x9HrClJRez2hCWqauvg/fl2rKNcJvpyeF4xMJv6OW5+T6KTlWrXkk1bUpr7Oc4yrpc8utSyfX/Ob4FH57QvgNm5amEmvT66njdMr8FN+bayePJ6WvP6mguQzzmZycxq9Xcuq4ROMp0So1mj8hKeszjN89cRzvniTTwqnjePfUCdU9pvDrk3TPE/j16TS8Tkqfe5w1X4Xqvu+eJifx61Mn8bvpSbw/EcNHo2H2wdgwPhwNS0F8OBLEh3ESkq2sjYQEWjMWwofjIXwwEcb7ZDKEDydkbTyMDyekcVFjPFYk6x9NhFmiPhHEhxMBfDgeXGos1UcK1XyilhDAR2N+ifrquqo/TvcRaz8e9eODyWH87uQE3p05hV+dPY1fnTmFX505yX49cxK/Pk2/Ryfxu+kxvDcZx3tTI/jd8XH5e/KE+D3BfWqFR/++Ta4Rvw/TruM6/X4jqnsr66XEev5zp/wZpD/j0gmFaj7lz6tqLf/Zl9+fTkyylHnV90WBakLyexB9D1/BVKrfTY2x306NCpOj+N3EKH5LJkfwu8kR/F6ivlL73cQIfjcex2/HYimoxnWJx1RXzYlaHL8fjeH3I1EhHhFGo0lUp3Ysg/Eo3hun+Qh+PyKufW8kgvd4PIzfxyWaY6pamvfiYSE2rELjdCG8F1WhcSyEP6hFQ3ifRIL4Q1R4PxrA+9zKWiSwovcyjN8b9ifG76twbVh4P+JnfyC0ftiP99XCxMc+CPsZj0NefCBRn8dhFXVd5UNqg168H/SImmo91cmHkrKeUS1xvQfvBwTqfxgSqJ+cc+ODgBsfEr8bH5BEzYUP/RL1FUotzUd+p+Bz4iOvRH11Xc3rYB96nQlKTe1D1RoxtgseOz4iXoW8xm3LwKpiw0ceicYeyW3BR64M+BoLPnSZ8RHLtEb42GXBx04LPnKaEz52mASnCR/T9U4TPnIY8JHdgI8dEvV5rMcndjWDpMfHdh0+tumSrU2Hj2xafGTT4GObBp9YNfjEomWfWrX41EY0+NRKhvAJsZBBfErMwiemAfapeQCfmvrZJ8Y+fMp62SeGXnxq6MEfib47SdeNT7ntZH8i2g72GWtnf9K0JXymacMXQ6QVnw+14POhZnwx1IzPB4Uvhprw+WAjPh9oxBeDjfhyQPhC+nKgAX/ur8eXffX4gvQr6vBFX9KXsv28t5Z90VuLL0mPogZfkO501fhSov7n3K+RqvFlVxX7QrZCNb7orJIqVarweWclo/HnHcIXHRX4klE/6fPOCnzeUYHP26WOCnzRUY4vpS/ak76U1H3yZ/Vcm9RelpCcK8OXajwn17UJ6nmlpvZ5axk+z1RXXZ8+l7xvKb5oK8VnraX4vG2pL6jeKub/1FoiKeNSfNpSwv4ofSL9saWUUf+j5hJ80lyCP7WI6/5IWkr4vvTa9BqftZbgj63iXsr9ldekOt3nY9W96VoF3ZeuU16b8H1aSvCZRH2FUlPQ+g+aS/Bhs/haFcqYvtbEta2rIb9++vHKa5SfjxTKz4X8MdDP0YdN4nW5bUr9elLQnFyb6Mv2k6YSfNpcij82l3KbiuYk+WuW+vUK9PUsh+5L/iQpY3X9k6ZSfNBYkqD8eD5gxfiouTjxeyJd+v2UH8fH8lrysfw9RT8Omv+8pYwpX4/yY+U18veh+D2R/lrK7xf6cZfhy9YyfNlSxn26j/o65X5M/hryPej3kHwdNWVejX5uP2+h3/Nlq8ZfUyaqP9v0PYDXUi0xX54g/rwrY/HnXkiv0/ce9fey5PcqJr+X0feWz9sF8f1EfA/kOs+V4zNel/xeSTXFZyl9+f1Wou/LRN1X1/j7M3+PrsRnEn1v/yzxPV75O0CSf0983lW9FP/dUoPPJOoLtfi8py7hM0VvHf7E6vGZok/RgM/7GxM+U/cHmvB5vzTQjM8HWvDZQAs+H1TQ38MC/d38+VA7+0xDOvC5pgNfaDvwubYTn2m78Lmum30mW6bvwWeGXvzJ0IvPjH34zEit0u8XTP34k7kffzINCGbJMphkHUr4I9PgT3Ztwh9tevYnux5/sukEux5/tOvxKXEY8KnTyD5xiJa5zCom9onLLLipZuGW+x5rwiduFRozGz712tkn1HoE7ifqDnyc4MQnxOfExz4H+8RPYwfjmrKW+n5nqoBLxY2Pgx4hpBL04CMppS/neaysDXuTQl58RMLEt2ofhtJQTZFeS58P+4VhSV1LkGsTa5I+GFaJkMCqpPx/jaj+r/dBVFDXkv8PFP+/TEjMUV+F5tL/z6r6vyujfjwsxMJLaxkNCzEir+P/W6v+Ty3HYo3wHv2/PR5JXE/z4v/loq5c896IkJij/+vLWgrlOvlewHtjsqUxvb+gvB9A7xOQsQi/l8CU9xzU7ztkeh9CvY6MRfG7cfEex5J7jMfwe/l+x+9GYwL1FWnviSytJ99b+c1YHL/hVukLifdZlPdjqD8xgt/TezQTynsxI0kTAr+Po3pfh2vj8r0d1VzK+z7Ke0ET6tcUeEx19XX8NSxzT+X1lNdUKD8edS2d6msRP85HX/f7iVGBX1OspWsVia9FjesxvDc6jA/ofdpYEH+IBfn9JH6/i34uJ+m9szFu6df7/XgQH0U8+CTixsdRKeLCJxEXPh52c53nhiX1Ol4r6h8pcxHRV8afRD0S9YXEdYqoi9HrfDrsYZ8Q+XV9EnZJ9LWIuljjxifDLon6bnwapnsISo0p9wi58GnIhT9Kn4bFmHwSFD4O0X08+GPYw+3Hw158SO+F8Xt+8r1Apnr/j6n+rEr05/kPaiP0/UN+H6E+SVujfO9Y8v1iJfSe4IjE7xGqvofJ73vK9yuujSjCSfw9VH6/GxnG+0w1z2voe2sIfxiRrfL9WHkN1XuQie+tsTDejytCCR+MyH5MigeFmGyVPv99IN+rpHXK3xvKuhi9ZxkQYwW/j6nUZct/Z2Wg+vvqkWIS9fnvwSATX+PSvyNTpP2dmF4T46CQ+Ps1/e9c5WtOvk8q/t5WviYf3h8mNB9k4lr5d3tUtnytWJuoyznl7/PENYnrfPiA1itzUfEebvJrUd0v5Z7iutT3d+W91K+hQvdU+t8Y8fox4g1ixBeSgmLsDciW5hTKfAAjHj9GPMoaauk+/tR1Kdel11aop7+uN4hRX2iJMX8IY74gxvwBjPkCGPUHpRBG/WFJ1MZSBBLXJAUxRvdk1FdRrvMFMe4PCYFwsu+nPqH5IMYDRKkra5a5jtYx6g/LeWVNGGMBxbCqvwry2vHgMMaDEYn6S02o8deQoa6Scn1ISMxTX5E+XiIspV3zqOt4PiKEhzHJIpgMR5c1NRzFJFHXJHVfbenaCKbCw7JNXZN6bUzWY5gajuFkMITLLgfumDR4Rd+NVwzduG/sx3WTBlfMWly36HHHqsddq5Hdthpwm2s63LXqcMdqwB2LmLtrN+G23YRbNlqnT7hlEfg6iy5Nav2uWcvumJV5Le4SqpskuSaVBvfMGtxnWtyTdWqpLua0khgzkwb3jKK9b9LggXTfNIS71Jo1eNE4gJcMvbhtGsJ5px0TwRBGonGMxEYwGo1jNBLDaCQqhMKY8vlxyuPBWY8LM14vjvuDmMz0+0b9+1b5vaqqJ38vRzAWikryzwr/mQxjLBjGWGiY6wL1wxgNDjP6s8nrAmGMBmRNdb24h6jxvRLEn+nRQBgj9L2KrvUPY8QX5u+L/H1MuWdgmNfwnDeU/B7JaJwq7g0g7vVLQcLine truncated
|
||||
|
After Width: | Height: | Size: 193 KiB |
|
After Width: | Height: | Size: 8.0 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
@@ -78,7 +78,7 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
// ============================================================================
|
||||
// Provider Context & Types
|
||||
@@ -998,11 +998,24 @@ export const PromptInputTextarea = ({
|
||||
|
||||
// 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.
|
||||
// stuck at its minimum height. A custom appearance height replaces that range.
|
||||
let minBound = 64;
|
||||
let maxBound = 192;
|
||||
if (textarea.hasAttribute("data-composer-height")) {
|
||||
const computed = window.getComputedStyle(textarea);
|
||||
const minHeight = Number.parseFloat(computed.minHeight);
|
||||
const maxHeight = Number.parseFloat(computed.maxHeight);
|
||||
if (Number.isFinite(minHeight)) minBound = minHeight;
|
||||
if (Number.isFinite(maxHeight)) maxBound = maxHeight;
|
||||
}
|
||||
textarea.style.height = "auto";
|
||||
const height = Math.max(64, Math.min(textarea.scrollHeight, 192));
|
||||
const height = Math.max(
|
||||
minBound,
|
||||
Math.min(textarea.scrollHeight, maxBound),
|
||||
);
|
||||
textarea.style.height = `${height}px`;
|
||||
textarea.style.overflowY = textarea.scrollHeight > 192 ? "auto" : "hidden";
|
||||
textarea.style.overflowY =
|
||||
textarea.scrollHeight > maxBound ? "auto" : "hidden";
|
||||
}, []);
|
||||
|
||||
// onInput does not run for a controlled value filled by a suggested question
|
||||
@@ -1212,7 +1225,7 @@ export const PromptInputButton = ({
|
||||
}: PromptInputButtonProps) => {
|
||||
return (
|
||||
<InputGroupButton
|
||||
className={cn(className)}
|
||||
className={cn("agent-composer-tool", className)}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant={variant}
|
||||
@@ -1293,9 +1306,10 @@ export const PromptInputSubmit = ({
|
||||
<InputGroupButton
|
||||
aria-label={ariaLabel}
|
||||
className={cn(
|
||||
"transition-all duration-300",
|
||||
status === "streaming" &&
|
||||
"animate-breathe-stop bg-primary/10 text-primary border-primary/25 shadow-[0_0_0_0_rgba(217,33,33,0.25)] hover:bg-primary/14",
|
||||
// 皮肤本体在 globals.css 的 .agent-composer-send(主题色扁平渐变
|
||||
// 圆钮);流式态切 .agent-composer-send--stop 低对比停止钮。
|
||||
"agent-composer-send transition-all duration-300",
|
||||
status === "streaming" && "agent-composer-send--stop",
|
||||
className,
|
||||
)}
|
||||
size={size}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FileOutput } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import responsibilityIcon from "@/assets/position-roundtable/责任岗位.svg";
|
||||
import resultTimeIcon from "@/assets/position-roundtable/时间.svg";
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/* DialogContent is rendered in a portal. Use the root theme selectors directly
|
||||
* so deep-blue styles work regardless of Tailwind's variant compilation order. */
|
||||
:root.dark .document-upload-dialog,
|
||||
:root[theme-mode="dark"] .document-upload-dialog {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #0c1836 !important;
|
||||
color: #c5cfe0 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__search,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__search {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #122347 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__search:hover,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__search:hover {
|
||||
border-color: #4a6491 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__search-input,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__search-input {
|
||||
color: #c5cfe0 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__search-input::placeholder,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__search-input::placeholder,
|
||||
:root.dark .document-upload-dialog__search-icon,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__search-icon {
|
||||
color: #6e88b0 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__search-button,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__search-button {
|
||||
background-color: #1677ff !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__search-button:hover,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__search-button:hover {
|
||||
background-color: #0958d9 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__tabs,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__tabs {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #122347 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__tab,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__tab {
|
||||
color: #6e88b0 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__tab:hover,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__tab:hover {
|
||||
color: #c5cfe0 !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__tab--active,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__tab--active {
|
||||
color: #91caff !important;
|
||||
}
|
||||
|
||||
:root.dark .document-upload-dialog__tab-indicator,
|
||||
:root[theme-mode="dark"] .document-upload-dialog__tab-indicator {
|
||||
background-color: #4096ff !important;
|
||||
}
|
||||
@@ -24,9 +24,10 @@ import {
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
import "./document-upload-popup.css";
|
||||
import { queryClient } from "@/components/query-client-provider";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import Empty from "./empty";
|
||||
@@ -599,13 +600,13 @@ const DocumentUploadPopupContent: FC<{
|
||||
};
|
||||
|
||||
const yUserId = getYUserId();
|
||||
const userToken = getStoredAuth()?.access_token;
|
||||
const iframeTokenParam = userToken ? `&token=${encodeURIComponent(userToken)}` : "";
|
||||
const notebookToken = getNotebookToken();
|
||||
const iframeTokenParam = notebookToken ? `&token=${encodeURIComponent(notebookToken)}` : "";
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
className="w-[90vw] max-w-[90vw] sm:max-w-[90vw] h-[90vh] flex flex-col p-0 gap-0 overflow-hidden border border-border bg-muted text-foreground [&>button]:right-3 [&>button]:top-4 [&>button]:opacity-80 hover:[&>button]:opacity-100 [&>button]:z-[100] [&>button_svg]:size-4"
|
||||
className="document-upload-dialog w-[90vw] max-w-[90vw] sm:max-w-[90vw] h-[90vh] flex flex-col p-0 gap-0 overflow-hidden border border-border bg-muted text-foreground dark:border-[#2d4473] dark:bg-[#0c1836] dark:text-[#c5cfe0] [&>button]:right-3 [&>button]:top-4 [&>button]:opacity-80 hover:[&>button]:opacity-100 [&>button]:z-[100] [&>button_svg]:size-4 dark:[&>button]:text-[#c5cfe0]"
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
>
|
||||
@@ -615,7 +616,7 @@ const DocumentUploadPopupContent: FC<{
|
||||
<div className="h-full overflow-y-auto">
|
||||
<div className="px-3 sm:px-12 pt-12 sm:pt-24 pb-6 sm:pb-16">
|
||||
{/* 搜索框 */}
|
||||
<div className="relative rounded-lg border border-neutral-200 bg-white mb-[10px] transition-colors hover:border-neutral-300">
|
||||
<div className="document-upload-dialog__search relative rounded-lg border border-neutral-200 bg-white mb-[10px] transition-colors hover:border-neutral-300 dark:border-[#2d4473] dark:bg-[#122347] dark:hover:border-[#4a6491]">
|
||||
<Textarea
|
||||
placeholder="搜索资料..."
|
||||
value={searchText}
|
||||
@@ -626,24 +627,24 @@ const DocumentUploadPopupContent: FC<{
|
||||
searchDataChange();
|
||||
}
|
||||
}}
|
||||
className="max-h-[160px] resize-none border-0 bg-transparent px-10 py-3 pr-20 text-sm text-neutral-700 placeholder:text-neutral-400 focus-visible:ring-0 focus-visible:outline-none"
|
||||
className="document-upload-dialog__search-input max-h-[160px] resize-none border-0 bg-transparent px-10 py-3 pr-20 text-sm text-neutral-700 placeholder:text-neutral-400 focus-visible:ring-0 focus-visible:outline-none dark:text-[#c5cfe0] dark:placeholder:text-[#6e88b0]"
|
||||
rows={1}
|
||||
/>
|
||||
<div className="absolute left-3 top-3 text-neutral-400 pointer-events-none">
|
||||
<div className="document-upload-dialog__search-icon absolute left-3 top-3 text-neutral-400 pointer-events-none dark:text-[#6e88b0]">
|
||||
<Search className="h-4 w-4" strokeWidth={1.5} />
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={searchDataChange}
|
||||
disabled={isSearching || !searchText.trim()}
|
||||
className="absolute right-2 top-2 h-7 rounded-md bg-neutral-900 px-3 text-xs font-medium text-white transition-colors hover:bg-neutral-800 disabled:pointer-events-none disabled:opacity-40"
|
||||
className="document-upload-dialog__search-button absolute right-2 top-2 h-7 rounded-md bg-neutral-900 px-3 text-xs font-medium text-white transition-colors hover:bg-neutral-800 disabled:pointer-events-none disabled:opacity-40 dark:bg-[#1677ff] dark:hover:bg-[#0958d9]"
|
||||
>
|
||||
{isSearching ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <span>搜索</span>}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Tab 标签页 */}
|
||||
<div className="border-b border-gray-200 rounded-t-xl px-4 bg-gray-50">
|
||||
<div className="document-upload-dialog__tabs border-b border-gray-200 rounded-t-xl px-4 bg-gray-50 dark:border-[#2d4473] dark:bg-[#122347]">
|
||||
<div className="flex flex-nowrap overflow-x-auto">
|
||||
{(
|
||||
[
|
||||
@@ -657,12 +658,12 @@ const DocumentUploadPopupContent: FC<{
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => void searchActiveChange(key)}
|
||||
className={`relative pb-3 px-6 pt-4 text-sm font-medium transition-colors ${activeTab === key ? "text-gray-900" : "text-gray-400 hover:text-gray-600"
|
||||
className={`document-upload-dialog__tab ${activeTab === key ? "document-upload-dialog__tab--active" : ""} relative pb-3 px-6 pt-4 text-sm font-medium transition-colors ${activeTab === key ? "text-gray-900 dark:text-[#91caff]" : "text-gray-400 hover:text-gray-600 dark:text-[#6e88b0] dark:hover:text-[#c5cfe0]"
|
||||
}`}
|
||||
>
|
||||
{label}
|
||||
{activeTab === key && (
|
||||
<span className="absolute bottom-0 left-0 right-0 h-0.5 bg-gray-900 rounded-full" />
|
||||
<span className="document-upload-dialog__tab-indicator absolute bottom-0 left-0 right-0 h-0.5 bg-gray-900 rounded-full dark:bg-[#4096ff]" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
/* 深蓝主题下,XWT 检索面板使用全局 deep-blue token,与弹窗外壳保持一致。 */
|
||||
:root.dark .network-actor,
|
||||
:root[theme-mode="dark"] .network-actor {
|
||||
color: #c5cfe0;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__filter-surface,
|
||||
:root[theme-mode="dark"] .network-actor__filter-surface {
|
||||
background-color: #122347 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__filter-panel,
|
||||
:root[theme-mode="dark"] .network-actor__filter-panel {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #0f1d3e;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__filter-label,
|
||||
:root.dark .network-actor__section-title,
|
||||
:root.dark .network-actor__metric-label,
|
||||
:root[theme-mode="dark"] .network-actor__filter-label,
|
||||
:root[theme-mode="dark"] .network-actor__section-title,
|
||||
:root[theme-mode="dark"] .network-actor__metric-label {
|
||||
color: #c5cfe0 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__filter-chip,
|
||||
:root[theme-mode="dark"] .network-actor__filter-chip {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #1a2f5a !important;
|
||||
color: #c5cfe0 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__filter-chip:hover,
|
||||
:root[theme-mode="dark"] .network-actor__filter-chip:hover {
|
||||
border-color: #4a6491 !important;
|
||||
background-color: #243b68 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__filter-chip[aria-pressed="true"],
|
||||
:root[theme-mode="dark"] .network-actor__filter-chip[aria-pressed="true"] {
|
||||
border-color: #1677ff !important;
|
||||
background-color: #122347 !important;
|
||||
color: #91caff !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__filter-chip:focus-visible,
|
||||
:root[theme-mode="dark"] .network-actor__filter-chip:focus-visible,
|
||||
:root.dark .network-actor__sort-button:focus-visible,
|
||||
:root[theme-mode="dark"] .network-actor__sort-button:focus-visible {
|
||||
outline: 2px solid #69b1ff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__platform-divider,
|
||||
:root[theme-mode="dark"] .network-actor__platform-divider,
|
||||
:root.dark .network-actor__metric-divider,
|
||||
:root[theme-mode="dark"] .network-actor__metric-divider {
|
||||
background-color: #4a6491 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__results-surface,
|
||||
:root[theme-mode="dark"] .network-actor__results-surface {
|
||||
background-color: #122347 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__results-header,
|
||||
:root[theme-mode="dark"] .network-actor__results-header {
|
||||
border-color: #2d4473 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__title-accent,
|
||||
:root[theme-mode="dark"] .network-actor__title-accent {
|
||||
background-color: #1677ff !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__sort-button,
|
||||
:root[theme-mode="dark"] .network-actor__sort-button {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #1a2f5a !important;
|
||||
color: #c5cfe0 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__sort-button:hover,
|
||||
:root[theme-mode="dark"] .network-actor__sort-button:hover {
|
||||
border-color: #4a6491 !important;
|
||||
background-color: #243b68 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__sort-button--active,
|
||||
:root[theme-mode="dark"] .network-actor__sort-button--active {
|
||||
border-color: #1677ff !important;
|
||||
background-color: #122347 !important;
|
||||
color: #91caff !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__sort-button svg path,
|
||||
:root[theme-mode="dark"] .network-actor__sort-button svg path {
|
||||
fill: #4a6491;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__sort-button--active svg[data-direction="asc"] path:first-child,
|
||||
:root[theme-mode="dark"] .network-actor__sort-button--active svg[data-direction="asc"] path:first-child,
|
||||
:root.dark .network-actor__sort-button--active svg[data-direction="desc"] path:last-child,
|
||||
:root[theme-mode="dark"] .network-actor__sort-button--active svg[data-direction="desc"] path:last-child {
|
||||
fill: #4096ff;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__metric-value--selected,
|
||||
:root[theme-mode="dark"] .network-actor__metric-value--selected {
|
||||
color: #ffc53d !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__metric-value--total,
|
||||
:root[theme-mode="dark"] .network-actor__metric-value--total,
|
||||
:root.dark .network-actor__meta-icon,
|
||||
:root[theme-mode="dark"] .network-actor__meta-icon {
|
||||
color: #69b1ff !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__selection-bar,
|
||||
:root[theme-mode="dark"] .network-actor__selection-bar {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #1a2f5a !important;
|
||||
color: #c5cfe0;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__card,
|
||||
:root[theme-mode="dark"] .network-actor__card {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #1a2f5a !important;
|
||||
box-shadow: 0 1px 4px rgba(6, 14, 36, 0.3);
|
||||
color: #c5cfe0;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__card:hover,
|
||||
:root[theme-mode="dark"] .network-actor__card:hover {
|
||||
border-color: #4a6491 !important;
|
||||
box-shadow: 0 4px 12px rgba(6, 14, 36, 0.45);
|
||||
}
|
||||
|
||||
:root.dark .network-actor__card[data-selected="true"],
|
||||
:root[theme-mode="dark"] .network-actor__card[data-selected="true"] {
|
||||
border-color: #1677ff !important;
|
||||
box-shadow: 0 0 0 1px rgba(22, 119, 255, 0.24);
|
||||
}
|
||||
|
||||
:root.dark .network-actor__avatar,
|
||||
:root[theme-mode="dark"] .network-actor__avatar {
|
||||
border-color: #2d4473 !important;
|
||||
background-color: #122347 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__classification,
|
||||
:root[theme-mode="dark"] .network-actor__classification {
|
||||
background-color: rgba(245, 34, 45, 0.16) !important;
|
||||
color: #ff7875 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor__tag,
|
||||
:root[theme-mode="dark"] .network-actor__tag {
|
||||
background-color: rgba(19, 194, 194, 0.14) !important;
|
||||
color: #5cdbd3 !important;
|
||||
}
|
||||
|
||||
:root.dark .network-actor input[type="checkbox"],
|
||||
:root[theme-mode="dark"] .network-actor input[type="checkbox"] {
|
||||
accent-color: #1677ff;
|
||||
}
|
||||
@@ -6,12 +6,33 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Loader2, Plus, Search, Trash2 } from "lucide-react";
|
||||
import {
|
||||
CirclePlay,
|
||||
FileText,
|
||||
FolderTree,
|
||||
Globe2,
|
||||
Loader2,
|
||||
Network,
|
||||
Plus,
|
||||
Tag,
|
||||
Trash2,
|
||||
UserRoundCheck,
|
||||
UsersRound,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { authenticatedFetch } from "@/components/assistant-ui/document-upload-popup";
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
import xLogo from "@/assets/platform/x.png";
|
||||
import facebookLogo from "@/assets/platform/facebook.png";
|
||||
import redditLogo from "@/assets/platform/reddit.png";
|
||||
import pttLogo from "@/assets/platform/ptt.png";
|
||||
import dcardLogo from "@/assets/platform/dcard.png";
|
||||
import mobile01Logo from "@/assets/platform/mobile01.png";
|
||||
import threadsLogo from "@/assets/platform/threads.png";
|
||||
import instagramLogo from "@/assets/platform/ins.png";
|
||||
import "./network-actor.css";
|
||||
|
||||
|
||||
interface NetworkActorProps {
|
||||
@@ -22,7 +43,6 @@ interface NetworkActorProps {
|
||||
|
||||
interface platformItem {
|
||||
title: string;
|
||||
icon: string;
|
||||
checked: boolean;
|
||||
}
|
||||
|
||||
@@ -31,6 +51,14 @@ interface languageItem {
|
||||
checked: boolean;
|
||||
}
|
||||
|
||||
interface ActorSearchFilters {
|
||||
platforms: string[];
|
||||
languages: string[];
|
||||
direction: string;
|
||||
sortBy: string;
|
||||
sortDirection: "asc" | "desc";
|
||||
}
|
||||
|
||||
interface PoliticsDirItem {
|
||||
地区: string;
|
||||
语言: string;
|
||||
@@ -68,6 +96,86 @@ interface hx_info {
|
||||
用户画像: 用户画像;
|
||||
}
|
||||
|
||||
// 图片必须经 import 走 Vite 打包才能拼上 base(服务器带路径前缀时 public/ 绝对路径会 404)
|
||||
const PLATFORM_LOGOS: Record<string, string> = {
|
||||
x: xLogo,
|
||||
facebook: facebookLogo,
|
||||
reddit: redditLogo,
|
||||
ptt: pttLogo,
|
||||
dcard: dcardLogo,
|
||||
mobile01: mobile01Logo,
|
||||
threads: threadsLogo,
|
||||
instagram: instagramLogo,
|
||||
};
|
||||
|
||||
// 后端返回的平台名与筛选 chips 的大小写/缩写不完全一致(如 FB、INS、YT、TH),统一归一到上面的 key
|
||||
const PLATFORM_KEY_RULES: Array<[RegExp, string]> = [
|
||||
[/instagram|\bins\b|\big\b/, "instagram"],
|
||||
[/facebook|\bfb\b/, "facebook"],
|
||||
[/youtube|\byt\b|油管/, "youtube"],
|
||||
[/threads|\bth\b/, "threads"],
|
||||
[/mobile01|\bmobile\b/, "mobile01"],
|
||||
[/dcard/, "dcard"],
|
||||
[/ptt/, "ptt"],
|
||||
[/reddit|\bre\b/, "reddit"],
|
||||
[/twitter|推特/, "x"],
|
||||
];
|
||||
|
||||
function platformLogoKey(platform: string): string {
|
||||
const key = platform.trim().toLowerCase();
|
||||
if (PLATFORM_LOGOS[key]) return key;
|
||||
for (const [pattern, canonical] of PLATFORM_KEY_RULES) {
|
||||
if (pattern.test(key)) return canonical;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function PlatformIcon({ platform, className = "" }: { platform: string; className?: string }) {
|
||||
const key = platformLogoKey(platform);
|
||||
const src = PLATFORM_LOGOS[key];
|
||||
|
||||
if (src) {
|
||||
return <img src={src} className={`h-5 w-5 shrink-0 object-contain ${className}`} alt="" aria-hidden="true" />;
|
||||
}
|
||||
|
||||
if (key === "youtube") {
|
||||
return <CirclePlay className={`h-5 w-5 shrink-0 text-red-600 ${className}`} aria-hidden="true" />;
|
||||
}
|
||||
|
||||
return <Globe2 className={`h-5 w-5 shrink-0 text-slate-500 ${className}`} aria-hidden="true" />;
|
||||
}
|
||||
|
||||
function MetaIcon({
|
||||
type,
|
||||
className = "",
|
||||
}: {
|
||||
type: "followers" | "person" | "category" | "tags" | "summary" | "network";
|
||||
className?: string;
|
||||
}) {
|
||||
const iconClassName = `network-actor__meta-icon h-4 w-4 shrink-0 ${className}`;
|
||||
const icons = {
|
||||
followers: <UsersRound className={iconClassName} aria-hidden="true" />,
|
||||
person: <UserRoundCheck className={iconClassName} aria-hidden="true" />,
|
||||
category: <FolderTree className={iconClassName} aria-hidden="true" />,
|
||||
tags: <Tag className={iconClassName} aria-hidden="true" />,
|
||||
summary: <FileText className={iconClassName} aria-hidden="true" />,
|
||||
network: <Network className={iconClassName} aria-hidden="true" />,
|
||||
};
|
||||
return icons[type];
|
||||
}
|
||||
|
||||
function SortDirectionIcon({ direction, active }: { direction: "asc" | "desc"; active: boolean }) {
|
||||
const ascendingColor = active && direction === "asc" ? "#cf1322" : "#cbd5e1";
|
||||
const descendingColor = active && direction === "desc" ? "#cf1322" : "#cbd5e1";
|
||||
|
||||
return (
|
||||
<svg viewBox="0 0 12 18" data-direction={direction} className="h-5 w-3 shrink-0" aria-hidden="true">
|
||||
<path d="M6 2 10 7H2L6 2Z" fill={ascendingColor} />
|
||||
<path d="m6 16-4-5h8l-4 5Z" fill={descendingColor} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
interface UserDataItem {
|
||||
comment_count: number;
|
||||
country: string | null;
|
||||
@@ -114,9 +222,9 @@ interface UserDataItem {
|
||||
birthday: string | null;
|
||||
is_virtual: number;
|
||||
isMedia: number;
|
||||
hx_info: hx_info;
|
||||
hx_info?: hx_info | null;
|
||||
gender: string | null;
|
||||
agentInfo: PoliticsDirItem;
|
||||
agentInfo?: PoliticsDirItem | null;
|
||||
profile_url: string | null;
|
||||
tagId: string[];
|
||||
user_name: string;
|
||||
@@ -152,15 +260,15 @@ interface UserDataItem {
|
||||
|
||||
export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkActorProps) {
|
||||
const [platforms, setPlatforms] = useState<platformItem[]>([
|
||||
{ title: 'X', icon: 'x.png', checked: false },
|
||||
{ title: 'Facebook', icon: 'facebook.png', checked: false },
|
||||
{ title: 'Reddit', icon: 'reddit.png', checked: false },
|
||||
{ title: 'PTT', icon: 'ptt.png', checked: false },
|
||||
{ title: 'YouTube', icon: 'youtube.png', checked: false },
|
||||
{ title: 'Dcard', icon: 'dcard.png', checked: false },
|
||||
{ title: 'Mobile01', icon: 'mobile01.png', checked: false },
|
||||
{ title: 'Threads', icon: 'threads.png', checked: false },
|
||||
{ title: 'Instagram', icon: 'ins.png', checked: false },
|
||||
{ title: 'X', checked: false },
|
||||
{ title: 'Facebook', checked: false },
|
||||
{ title: 'Reddit', checked: false },
|
||||
{ title: 'PTT', checked: false },
|
||||
{ title: 'YouTube', checked: false },
|
||||
{ title: 'Dcard', checked: false },
|
||||
{ title: 'Mobile01', checked: false },
|
||||
{ title: 'Threads', checked: false },
|
||||
{ title: 'Instagram', checked: false },
|
||||
]);
|
||||
const platformList = useRef<string[]>([]);
|
||||
const [languages, setLanguages] = useState<languageItem[]>([
|
||||
@@ -188,25 +296,37 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
const [directionType, setDirectionType] = useState<string>('TW');
|
||||
const directionValue = useRef<string>('TW');
|
||||
const consumerUrl = readRuntimeEnv("VITE_AIPI_CONSUMER_URL") || 'https://ch1.b.uat.4.cn/consumer';
|
||||
const backendUrl = typeof window !== 'undefined'
|
||||
? (readRuntimeEnv("VITE_BACKEND_BASE_URL") || 'http://localhost:8001')
|
||||
: 'http://localhost:8001';
|
||||
const minioProxyUrl = readRuntimeEnv("VITE_AIPI_MINIO_PROXY_URL") || 'http://minio-proxy.b.sit.4.cn/facebook-proxy';
|
||||
const actorBaseUrl = readRuntimeEnv("VITE_AIPI_B2ACTOR_URL") || 'http://ty.b.uat.4.cn';
|
||||
const avatarUrl = (profileImage: string | null) => profileImage
|
||||
? `${minioProxyUrl}?${new URLSearchParams({ url: profileImage, is_avatar: 'true' })}`
|
||||
: `${actorBaseUrl}/manage/img/default.png`;
|
||||
const backendUrl = readRuntimeEnv("VITE_AIPI_BACKENP_URL") || 'http://localhost:8001';
|
||||
const [selectedSearchSources, setSelectedSearchSources] = useState<UserDataItem[]>([]);
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
|
||||
const searchChange = async () => {
|
||||
const resolveSearchFilters = (overrides: Partial<ActorSearchFilters> = {}): ActorSearchFilters => ({
|
||||
platforms: overrides.platforms ?? platformList.current,
|
||||
languages: overrides.languages ?? languageList.current,
|
||||
direction: overrides.direction ?? directionValue.current,
|
||||
sortBy: overrides.sortBy ?? sortTypeValue.current,
|
||||
sortDirection: overrides.sortDirection ?? sortValue.current as ActorSearchFilters["sortDirection"],
|
||||
});
|
||||
|
||||
const searchChange = async (overrides: Partial<ActorSearchFilters> = {}) => {
|
||||
setIsSearching(true);
|
||||
const filters = resolveSearchFilters(overrides);
|
||||
if (searchValue.current === 'network') {
|
||||
await agentUserSearch();
|
||||
await agentUserSearch(filters);
|
||||
} else {
|
||||
await agentGroupSearch();
|
||||
await agentGroupSearch(filters);
|
||||
}
|
||||
};
|
||||
|
||||
const setDirectionChange = async (type: string) => {
|
||||
setDirectionType(type);
|
||||
directionValue.current = type;
|
||||
await searchChange();
|
||||
await searchChange({ direction: type });
|
||||
};
|
||||
|
||||
const searchTypeChange = async (value: string) => {
|
||||
@@ -216,135 +336,128 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
};
|
||||
|
||||
const allPlatformChange = async () => {
|
||||
const nextPlatforms = platforms.map((item) => ({ ...item, checked: false }));
|
||||
setAllPlatforms(true);
|
||||
setPlatforms((prev) => prev.map((item) => ({ ...item, checked: false })));
|
||||
setPlatforms(nextPlatforms);
|
||||
platformList.current = [];
|
||||
await searchChange();
|
||||
await searchChange({ platforms: [] });
|
||||
};
|
||||
|
||||
const handleTogglePlatform = async (index: number) => {
|
||||
setPlatforms((prev) => {
|
||||
const newPlatforms = prev.map((item, i) =>
|
||||
i === index ? { ...item, checked: !item.checked } : item
|
||||
);
|
||||
const checkedTitles = newPlatforms.filter((item) => item.checked).map((item) => item.title);
|
||||
const nextPlatforms = platforms.map((item, itemIndex) => (
|
||||
itemIndex === index ? { ...item, checked: !item.checked } : item
|
||||
));
|
||||
const checkedTitles = nextPlatforms.filter((item) => item.checked).map((item) => item.title);
|
||||
setPlatforms(nextPlatforms);
|
||||
platformList.current = checkedTitles;
|
||||
setAllPlatforms(newPlatforms.every((item) => !item.checked));
|
||||
return newPlatforms;
|
||||
});
|
||||
await searchChange();
|
||||
setAllPlatforms(checkedTitles.length === 0);
|
||||
await searchChange({ platforms: checkedTitles });
|
||||
};
|
||||
|
||||
const allLanguageChange = async () => {
|
||||
const nextLanguages = languages.map((item) => ({ ...item, checked: false }));
|
||||
setAllLanguage(true);
|
||||
setLanguages((prev) => prev.map((item) => ({ ...item, checked: false })));
|
||||
setLanguages(nextLanguages);
|
||||
languageList.current = [];
|
||||
await searchChange();
|
||||
await searchChange({ languages: [] });
|
||||
};
|
||||
|
||||
const handleToggleLanguage = async (index: number) => {
|
||||
setLanguages((prev) => {
|
||||
const newItems = prev.map((item, i) =>
|
||||
i === index ? { ...item, checked: !item.checked } : item
|
||||
);
|
||||
const checkedTitles = newItems.filter((item) => item.checked).map((item) => item.title);
|
||||
const nextLanguages = languages.map((item, itemIndex) => (
|
||||
itemIndex === index ? { ...item, checked: !item.checked } : item
|
||||
));
|
||||
const checkedTitles = nextLanguages.filter((item) => item.checked).map((item) => item.title);
|
||||
setLanguages(nextLanguages);
|
||||
languageList.current = checkedTitles;
|
||||
setAllLanguage(newItems.every((item) => !item.checked));
|
||||
return newItems;
|
||||
});
|
||||
await searchChange();
|
||||
setAllLanguage(checkedTitles.length === 0);
|
||||
await searchChange({ languages: checkedTitles });
|
||||
};
|
||||
|
||||
const sortTypeChange = async (type: string) => {
|
||||
const nextSortDirection = (sortValue.current === 'desc' ? 'asc' : 'desc') as ActorSearchFilters["sortDirection"];
|
||||
setSortType(type);
|
||||
sortTypeValue.current = type;
|
||||
sortValue.current = sortValue.current === 'desc' ? 'asc' : 'desc';
|
||||
if (type === 'fans_count') setFansSort(sortValue.current);
|
||||
else if (type === '_score') setRelevanceSort(sortValue.current);
|
||||
await searchChange();
|
||||
sortValue.current = nextSortDirection;
|
||||
if (type === 'fans_count') setFansSort(nextSortDirection);
|
||||
else if (type === '_score') setRelevanceSort(nextSortDirection);
|
||||
await searchChange({ sortBy: type, sortDirection: nextSortDirection });
|
||||
};
|
||||
|
||||
const agentUserSearch = async () => {
|
||||
const agentUserSearch = async (filters: ActorSearchFilters) => {
|
||||
try {
|
||||
const response = await authenticatedFetch(`${consumerUrl}/portrait/agentUser`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer admin' },
|
||||
body: JSON.stringify({
|
||||
historyKey: [],
|
||||
historyKey: ['党政要员'],
|
||||
historyTitle: '',
|
||||
keyword: searchText,
|
||||
language: languageList.current,
|
||||
language: filters.languages,
|
||||
page: 1,
|
||||
limit: 12,
|
||||
platform: platformList.current,
|
||||
politicalStand: directionValue.current,
|
||||
sort: sortTypeValue.current,
|
||||
asc: sortValue.current,
|
||||
platform: filters.platforms,
|
||||
politicalStand: filters.direction,
|
||||
sort: filters.sortBy,
|
||||
asc: filters.sortDirection,
|
||||
typeKeyword: 9,
|
||||
}),
|
||||
});
|
||||
if (response.ok) {
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
setIsSearching(false);
|
||||
const result: UserDataItem[] = data.data.list;
|
||||
const result: UserDataItem[] = Array.isArray(data?.data?.list) ? data.data.list : [];
|
||||
result.forEach((item) => {
|
||||
item.profile_image = item.profile_image
|
||||
? `http://minio-proxy.b.sit.4.cn/facebook-proxy?url=${item.profile_image}&is_avatar=true`
|
||||
: 'http://ty.b.uat.4.cn/manage/img/default.png';
|
||||
item.classification = `${item.political_stand}-${item.history_key}-${item.history_title}`;
|
||||
item.profile_image = avatarUrl(item.profile_image);
|
||||
item.classification = `${item.political_stand ?? ''}-${item.history_key ?? ''}-${item.history_title ?? ''}`;
|
||||
item.title = item.user_name || item.screen_name || item.user_id;
|
||||
item.content = item.agentInfo['账号描述'];
|
||||
item.content = item.agentInfo?.['账号描述'] || item.hx_info?.['用户画像']?.['账号描述'] || '';
|
||||
item.url = `http://ty.b.uat.4.cn/fromB/toDetail?user_id=${item.user_id}&platform=${item.platform}`;
|
||||
});
|
||||
setUserList(result);
|
||||
setSelNetCount(data.data.total);
|
||||
setActorCount(data.data.zs_total);
|
||||
}
|
||||
setSelNetCount(data?.data?.total ?? 0);
|
||||
setActorCount(data?.data?.zs_total ?? 0);
|
||||
} catch (error) {
|
||||
console.error('Search error:', error);
|
||||
} finally {
|
||||
setIsSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
const agentGroupSearch = async () => {
|
||||
const agentGroupSearch = async (filters: ActorSearchFilters) => {
|
||||
try {
|
||||
const response = await authenticatedFetch(`${consumerUrl}/portrait/agentGroup`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer admin' },
|
||||
body: JSON.stringify({
|
||||
historyKey: [],
|
||||
historyKey: ['党政要员'],
|
||||
historyTitle: '',
|
||||
keyword: searchText,
|
||||
language: languageList.current,
|
||||
language: filters.languages,
|
||||
page: 1,
|
||||
limit: 12,
|
||||
platform: platformList.current,
|
||||
politicalStand: directionValue.current,
|
||||
sort: sortTypeValue.current,
|
||||
asc: sortValue.current,
|
||||
platform: filters.platforms,
|
||||
politicalStand: filters.direction,
|
||||
sort: filters.sortBy,
|
||||
asc: filters.sortDirection,
|
||||
typeKeyword: 9,
|
||||
}),
|
||||
});
|
||||
if (response.ok) {
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
setIsSearching(false);
|
||||
const result: UserDataItem[] = data.data.data;
|
||||
const result: UserDataItem[] = Array.isArray(data?.data?.data) ? data.data.data : [];
|
||||
result.forEach((item) => {
|
||||
item.hobbies = item.groupDiscussTags || [];
|
||||
item.profile_image = item.profile_image
|
||||
? `http://minio-proxy.b.sit.4.cn/facebook-proxy?url=${item.profile_image}&is_avatar=true`
|
||||
: 'http://ty.b.uat.4.cn/manage/img/default.png';
|
||||
item.classification = `${item.political_stand}`;
|
||||
item.profile_image = avatarUrl(item.profile_image);
|
||||
item.classification = `${item.political_stand ?? ''}`;
|
||||
item.title = item.group_name || item.groupName;
|
||||
if (item.hx_info?.['用户画像']) {
|
||||
item.content = item.hx_info['用户画像']['账号描述'];
|
||||
}
|
||||
item.content = item.hx_info?.['用户画像']?.['账号描述'] || item.agentInfo?.['账号描述'] || '';
|
||||
item.url = '';
|
||||
});
|
||||
setUserList(result);
|
||||
setActorCount(data.data.total);
|
||||
}
|
||||
setActorCount(data?.data?.total ?? 0);
|
||||
} catch (error) {
|
||||
console.error('Search error:', error);
|
||||
} finally {
|
||||
setIsSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -411,122 +524,128 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="bg-white rounded-[5px] p-[10px]">
|
||||
<div className="border border-[#e8e8e8] rounded-[5px] p-[10px]">
|
||||
<div className="network-actor">
|
||||
<div className="network-actor__filter-surface bg-white rounded-[5px] p-[10px]">
|
||||
<div className="network-actor__filter-panel border border-[#e8e8e8] rounded-[5px] p-[10px]">
|
||||
<div className="mb-[10px] flex">
|
||||
<span className="text-[#3D3D3D]">所属平台:</span>
|
||||
<span className="network-actor__filter-label text-[#3D3D3D]">所属平台:</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="flex items-center gap-[10px] flex-wrap">
|
||||
<span
|
||||
className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${allPlatforms ? 'platform-active' : ''}`}
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={allPlatforms}
|
||||
className={`network-actor__filter-chip flex cursor-pointer items-center rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${allPlatforms ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`}
|
||||
onClick={() => void allPlatformChange()}
|
||||
>全部</span>
|
||||
>全部</button>
|
||||
{platforms.map((item, index) => (
|
||||
<span
|
||||
<button
|
||||
type="button"
|
||||
key={index}
|
||||
className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${item.checked ? 'platform-active' : ''}`}
|
||||
aria-pressed={item.checked}
|
||||
className={`network-actor__filter-chip flex cursor-pointer items-center rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${item.checked ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`}
|
||||
onClick={() => void handleTogglePlatform(index)}
|
||||
>
|
||||
<img src={`/platform/${item.icon}`} className="w-[24px]" alt="" />
|
||||
<span className="w-[2px] h-[12px] ml-[5px] mr-[5px] bg-[#dbdbdb]"></span>
|
||||
<span className="ml-[5px]">{item.title}</span>
|
||||
</span>
|
||||
<PlatformIcon platform={item.title} className="h-5 w-5" />
|
||||
<span className="network-actor__platform-divider mx-2 h-3 w-px bg-[#dbdbdb]" aria-hidden="true"></span>
|
||||
<span>{item.title}</span>
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mb-[10px] flex">
|
||||
<span className="text-[#3D3D3D]">常用语言:</span>
|
||||
<span className="network-actor__filter-label text-[#3D3D3D]">常用语言:</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="flex items-center gap-[10px] flex-wrap">
|
||||
<span
|
||||
className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${allLanguage ? 'platform-active' : ''}`}
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={allLanguage}
|
||||
className={`network-actor__filter-chip cursor-pointer rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${allLanguage ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`}
|
||||
onClick={() => void allLanguageChange()}
|
||||
>全部</span>
|
||||
>全部</button>
|
||||
{languages.map((item, index) => (
|
||||
<span
|
||||
<button
|
||||
type="button"
|
||||
key={index}
|
||||
className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${item.checked ? 'platform-active' : ''}`}
|
||||
aria-pressed={item.checked}
|
||||
className={`network-actor__filter-chip cursor-pointer rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${item.checked ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`}
|
||||
onClick={() => void handleToggleLanguage(index)}
|
||||
>
|
||||
<span>{item.title}</span>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mb-[10px] flex">
|
||||
<span className="text-[#3D3D3D]">方向:</span>
|
||||
<span className="network-actor__filter-label text-[#3D3D3D]">方向:</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="flex items-center gap-[10px] flex-wrap">
|
||||
<span className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${directionType === 'TW' ? 'platform-active' : ''}`} onClick={() => void setDirectionChange('TW')}>W方向</span>
|
||||
<span className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${directionType === 'US' ? 'platform-active' : ''}`} onClick={() => void setDirectionChange('US')}>U方向</span>
|
||||
<span className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${directionType === '其他' ? 'platform-active' : ''}`} onClick={() => void setDirectionChange('其他')}>其他</span>
|
||||
<button type="button" aria-pressed={directionType === 'TW'} className={`network-actor__filter-chip cursor-pointer rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${directionType === 'TW' ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`} onClick={() => void setDirectionChange('TW')}>W方向</button>
|
||||
<button type="button" aria-pressed={directionType === 'US'} className={`network-actor__filter-chip cursor-pointer rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${directionType === 'US' ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`} onClick={() => void setDirectionChange('US')}>U方向</button>
|
||||
<button type="button" aria-pressed={directionType === '其他'} className={`network-actor__filter-chip cursor-pointer rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${directionType === '其他' ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`} onClick={() => void setDirectionChange('其他')}>其他</button>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mb-[10px] flex">
|
||||
<span className="text-[#3D3D3D]">类型:</span>
|
||||
<span className="network-actor__filter-label text-[#3D3D3D]">类型:</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="flex items-center gap-[10px] flex-wrap">
|
||||
<span className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${searchType === 'network' ? 'platform-active' : ''}`} onClick={() => void searchTypeChange('network')}>网络XWT</span>
|
||||
<span className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${searchType === 'group' ? 'platform-active' : ''}`} onClick={() => void searchTypeChange('group')}>群组XWT</span>
|
||||
<button type="button" aria-pressed={searchType === 'network'} className={`network-actor__filter-chip cursor-pointer rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${searchType === 'network' ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`} onClick={() => void searchTypeChange('network')}>网络XWT</button>
|
||||
<button type="button" aria-pressed={searchType === 'group'} className={`network-actor__filter-chip cursor-pointer rounded-none border px-2.5 py-1 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${searchType === 'group' ? 'border-[#cf1322] bg-[#fff5f5] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:bg-slate-50'}`} onClick={() => void searchTypeChange('group')}>群组XWT</button>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-[5px] pt-[15px] mt-[10px]">
|
||||
<div className="flex items-center justify-between pb-[10px] mb-[10px] border-b border-b-[#f1f3f5]">
|
||||
<div className="network-actor__results-surface bg-white rounded-[5px] pt-[15px] mt-[10px]">
|
||||
<div className="network-actor__results-header flex items-center justify-between pb-[10px] mb-[10px] border-b border-b-[#f1f3f5]">
|
||||
<div className="flex items-center ml-[10px]">
|
||||
<div className="title-bar mr-[8px]"></div>
|
||||
<div className="text-[#454859]">用户表格管理</div>
|
||||
<div className="network-actor__title-accent mr-2 h-5 w-1 rounded-full bg-[#cf1322]"></div>
|
||||
<div className="network-actor__section-title text-[#454859]">用户表格管理</div>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<div
|
||||
className={`relative flex items-center cursor-pointer border ${sortType === 'fans_count' ? 'border-[#cf1322]' : ''} p-[7px] pl-[10px] pr-[20px] rounded-[5px]`}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`按粉丝数排序,当前${fansSort === 'asc' ? '升序' : '降序'}`}
|
||||
className={`network-actor__sort-button ${sortType === 'fans_count' ? 'network-actor__sort-button--active' : ''} relative flex cursor-pointer items-center rounded-md border px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${sortType === 'fans_count' ? 'border-[#cf1322] bg-[#fffafa] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:border-slate-300 hover:bg-slate-50'}`}
|
||||
onClick={() => void sortTypeChange('fans_count')}
|
||||
>
|
||||
<span className="leading-[16px]">粉丝数排序</span>
|
||||
<div className="ml-[10px]">
|
||||
<div className={`sort-up ${fansSort === 'asc' ? 'sort-up-active' : ''}`}></div>
|
||||
<div className={`mt-[4px] sort-down ${fansSort === 'desc' ? 'sort-down-active' : ''}`}></div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={`relative flex items-center ml-[10px] cursor-pointer border ${sortType === '_score' ? 'border-[#cf1322]' : ''} p-[7px] pl-[10px] pr-[20px] rounded-[5px]`}
|
||||
<span className="ml-2"><SortDirectionIcon direction={fansSort as "asc" | "desc"} active={sortType === 'fans_count'} /></span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`按相关度排序,当前${relevanceSort === 'asc' ? '升序' : '降序'}`}
|
||||
className={`network-actor__sort-button ${sortType === '_score' ? 'network-actor__sort-button--active' : ''} relative ml-2 flex cursor-pointer items-center rounded-md border px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#cf1322]/40 ${sortType === '_score' ? 'border-[#cf1322] bg-[#fffafa] text-[#cf1322]' : 'border-[#e5e7eb] text-[#3d3d3d] hover:border-slate-300 hover:bg-slate-50'}`}
|
||||
onClick={() => void sortTypeChange('_score')}
|
||||
>
|
||||
<span className="leading-[16px]">相关度排序</span>
|
||||
<div className="ml-[10px]">
|
||||
<div className={`sort-up ${relevanceSort === 'asc' ? 'sort-up-active' : ''}`}></div>
|
||||
<div className={`mt-[4px] sort-down ${relevanceSort === 'desc' ? 'sort-down-active' : ''}`}></div>
|
||||
</div>
|
||||
</div>
|
||||
<span className="ml-2"><SortDirectionIcon direction={relevanceSort as "asc" | "desc"} active={sortType === '_score'} /></span>
|
||||
</button>
|
||||
{searchType === 'network' && (
|
||||
<>
|
||||
<div className="flex items-center ml-[35px]">
|
||||
<img className="w-[24px] h-[24px]" src="/icon/group-yellow-logo.svg" alt="" />
|
||||
<div className="network-actor__metric flex items-center ml-[35px]">
|
||||
<MetaIcon type="network" className="h-6 w-6 text-[#d97b00]" />
|
||||
<div className="ml-[5px]">
|
||||
<div className="text-[#454859] leading-[16px]">当前选中网络XWT数</div>
|
||||
<div className="text-[#d97b00] leading-[16px] mt-[5px]">{selNetCount}</div>
|
||||
<div className="network-actor__metric-label text-[#454859] leading-[16px]">当前选中网络XWT数</div>
|
||||
<div className="network-actor__metric-value network-actor__metric-value--selected text-[#d97b00] leading-[16px] mt-[5px]">{selNetCount}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-[5px] mr-[5px] h-[30px] w-[2px] -skew-x-[30deg] bg-[#dbdbdb]"></div>
|
||||
<div className="network-actor__metric-divider ml-[5px] mr-[5px] h-[30px] w-[2px] -skew-x-[30deg] bg-[#dbdbdb]"></div>
|
||||
</>
|
||||
)}
|
||||
<div className={`flex items-center ${searchType === 'network' ? 'ml-[5px]' : 'ml-[20px]'} mr-[25px]`}>
|
||||
<img className="w-[24px] h-[24px]" src="/icon/group-red-logo.svg" alt="" />
|
||||
<div className={`network-actor__metric flex items-center ${searchType === 'network' ? 'ml-[5px]' : 'ml-[20px]'} mr-[25px]`}>
|
||||
<MetaIcon type="network" className="h-6 w-6 text-[#cf1322]" />
|
||||
<div className="ml-[5px]">
|
||||
<div className="text-[#454859] leading-[16px]">网络XWT总数</div>
|
||||
<div className="text-[#cf1322] leading-[16px] mt-[5px]">{actorCount}</div>
|
||||
<div className="network-actor__metric-label text-[#454859] leading-[16px]">网络XWT总数</div>
|
||||
<div className="network-actor__metric-value network-actor__metric-value--total text-[#cf1322] leading-[16px] mt-[5px]">{actorCount}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{selectedSearchSources.length > 0 && (
|
||||
<div className="flex items-center justify-between px-4 py-2 bg-gray-50 border-b border-gray-100">
|
||||
<div className="network-actor__selection-bar flex items-center justify-between px-4 py-2 bg-gray-50 border-b border-gray-100">
|
||||
<span className="text-sm text-gray-600">已选中 {selectedSearchSources.length} 项</span>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" variant="outline" onClick={handleBatchDelete} className="h-8 px-3 text-sm">
|
||||
@@ -551,9 +670,13 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : null}
|
||||
<div className={`grid grid-cols-4 gap-[10px] user-list${isSearching ? ' hidden' : ''}`}>
|
||||
<div className={`grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4${isSearching ? ' hidden' : ''}`}>
|
||||
{userList.map((item, index) => (
|
||||
<div key={index} className="user-item p-[10px] relative">
|
||||
<div
|
||||
key={index}
|
||||
data-selected={item.checked ?? false}
|
||||
className={`network-actor__card relative rounded-lg border bg-white p-4 shadow-sm transition-[border-color,box-shadow] duration-200 motion-reduce:transition-none hover:border-[#f1b5ba] hover:shadow-md ${item.checked ? 'border-[#cf1322] ring-1 ring-[#cf1322]/15' : 'border-[#e5e7eb]'}`}
|
||||
>
|
||||
<div className="absolute top-[5px] right-[10px]">
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -563,21 +686,21 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center mb-[10px] cursor-pointer" onClick={() => linkToB2(item)}>
|
||||
<img src={item.profile_image ?? ''} className="w-[97px] h-[97px] rounded-[5px]" alt="" />
|
||||
<img src={item.profile_image ?? ''} className="network-actor__avatar h-[97px] w-[97px] rounded-md border border-[#e5e7eb] bg-slate-50 object-cover" alt="" />
|
||||
<div className="flex-1 min-w-0 pl-[10px]">
|
||||
<div className="truncate mb-[10px] text-[18px]">{item.user_name || item.screen_name || item.user_id || item.group_name || item.groupName}</div>
|
||||
<div className="flex justify-between mb-[10px]">
|
||||
<div className="flex items-center">
|
||||
<img src="/icon/group-yellow-logo.svg" className="w-[16px] h-[16px] mr-[5px]" alt="" />
|
||||
<MetaIcon type="followers" className="mr-[5px] text-[#d97b00]" />
|
||||
<span>粉丝数:{item.fans_count || '-'}</span>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<img src={`/platform/${item.platform}.png`} className="w-[25px] mr-[5px]" alt="" />
|
||||
<PlatformIcon platform={item.platform} className="mr-[5px]" />
|
||||
<span>{item.platform}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<img src="/icon/person-red-logo.svg" className="w-[16px] mr-[5px]" alt="" />
|
||||
<MetaIcon type="person" className="mr-[5px] text-[#cf1322]" />
|
||||
<span>实体人:{item.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -585,29 +708,29 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
<div className="cursor-pointer" onClick={() => linkToB2(item)}>
|
||||
<div className="flex items-center mb-[10px]">
|
||||
<div className="w-[70px] flex items-center">
|
||||
<img src="/icon/classification-logo.png" className="w-[16px] mr-[5px]" alt="" />
|
||||
<MetaIcon type="category" className="mr-[5px] text-[#cf1322]" />
|
||||
<span>分类:</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="inline-block h-[28px] pl-[8px] pr-[8px] bg-[#fef6f6] text-[#cf1322]">{item.classification}</div>
|
||||
<div className="network-actor__classification inline-block h-[28px] pl-[8px] pr-[8px] bg-[#fef6f6] text-[#cf1322]">{item.classification}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center mb-[10px]">
|
||||
<div className="w-[70px] flex items-center">
|
||||
<img src="/icon/user-green-logo.png" className="w-[16px] mr-[5px]" alt="" />
|
||||
<MetaIcon type="tags" className="mr-[5px] text-[#1eb07f]" />
|
||||
<span>标签:</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-[5px]">
|
||||
{(item.hobbies ?? []).map((hobbie) => (
|
||||
<div key={hobbie} className="h-[28px] pl-[8px] pr-[8px] bg-[#f6fdfb] text-[#1eb07f]">{hobbie}</div>
|
||||
<div key={hobbie} className="network-actor__tag h-[28px] pl-[8px] pr-[8px] bg-[#f6fdfb] text-[#1eb07f]">{hobbie}</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-baseline mb-[10px]">
|
||||
<div className="w-[70px] flex items-center">
|
||||
<img src="/icon/user-green-logo.png" className="w-[16px] mr-[5px]" alt="" />
|
||||
<MetaIcon type="summary" className="mr-[5px] text-slate-500" />
|
||||
<span>简介:</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
|
||||
@@ -38,6 +38,7 @@ export function HtmlPreviewFrame({
|
||||
|
||||
return (
|
||||
<iframe
|
||||
key={url ?? "html-preview"}
|
||||
title="HTML 预览"
|
||||
sandbox="allow-scripts allow-forms"
|
||||
src={url}
|
||||
|
||||
@@ -443,6 +443,25 @@
|
||||
background-size: 152px 42px;
|
||||
}
|
||||
|
||||
/* 浅红科技感顶栏保持深色版的尺寸与排布,只替换文字光效和选中底图。 */
|
||||
.strategy-app-header--light-red-top-nav .top-submenu-item {
|
||||
color: rgba(255, 255, 255, 0.86);
|
||||
}
|
||||
|
||||
.strategy-app-header--light-red-top-nav .top-submenu-item:hover {
|
||||
color: #ffffff;
|
||||
text-shadow: 0 0 10px rgba(196, 51, 40, 0.4);
|
||||
}
|
||||
|
||||
.strategy-app-header--light-red-top-nav .top-submenu-item--active {
|
||||
color: #ffffff;
|
||||
text-shadow: 0 0 12px rgba(177, 38, 28, 0.48);
|
||||
background-image: var(
|
||||
--light-red-nav-active-background-image,
|
||||
url("../assets/img/nav-active-light-red.svg")
|
||||
);
|
||||
}
|
||||
|
||||
.third-submenu-bar {
|
||||
position: relative;
|
||||
z-index: 34;
|
||||
|
||||
@@ -52,6 +52,7 @@ function ResizablePanel({
|
||||
function ResizableHandle({
|
||||
withHandle,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.Separator> & {
|
||||
withHandle?: boolean;
|
||||
@@ -70,6 +71,7 @@ function ResizableHandle({
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{withHandle && (
|
||||
<div className="bg-border z-10 flex h-8 w-4 items-center justify-center rounded-sm border shadow-sm">
|
||||
<GripVerticalIcon className="size-3.5" />
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import { useTheme } from "next-themes";
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner";
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme();
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { Toaster };
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { confirmAction, promptAction, toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -136,7 +136,12 @@ export function FolderManageDialog({
|
||||
};
|
||||
|
||||
const handleRename = async (folderId: string, current: string) => {
|
||||
const next = window.prompt("重命名 / 移动目录(输入新的完整路径,斜杠分隔)", current);
|
||||
const next = await promptAction("输入新的完整路径,使用斜杠分隔层级。", {
|
||||
title: "重命名 / 移动目录",
|
||||
defaultValue: current,
|
||||
placeholder: "例如:业务资料/项目文档",
|
||||
confirmText: "保存",
|
||||
});
|
||||
if (next === null) return;
|
||||
try {
|
||||
await rename.mutateAsync({ folderId, path: next });
|
||||
@@ -147,7 +152,11 @@ export function FolderManageDialog({
|
||||
};
|
||||
|
||||
const handleDelete = async (folderId: string, path: string) => {
|
||||
if (!window.confirm(`删除目录「${path}」?其中的知识将变为未归类(不会被删除)。`)) return;
|
||||
if (!(await confirmAction(`删除目录「${path}」?其中的知识将变为未归类(不会被删除)。`, {
|
||||
title: "删除目录?",
|
||||
confirmText: "删除",
|
||||
danger: true,
|
||||
}))) return;
|
||||
try {
|
||||
await remove.mutateAsync({ folderId });
|
||||
toast.success("目录已删除");
|
||||
@@ -292,7 +301,11 @@ export function ExtractTemplateManageDialog({
|
||||
};
|
||||
|
||||
const handleDelete = async (t: KnowledgeExtractTemplate) => {
|
||||
if (!window.confirm(`删除模板「${t.name}」?`)) return;
|
||||
if (!(await confirmAction(`删除模板「${t.name}」?`, {
|
||||
title: "删除模板?",
|
||||
confirmText: "删除",
|
||||
danger: true,
|
||||
}))) return;
|
||||
try {
|
||||
await remove.mutateAsync(t.id);
|
||||
if (selectedId === t.id) setSelectedId(null);
|
||||
|
||||
@@ -4,7 +4,7 @@ import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { languages } from "@codemirror/language-data";
|
||||
import { basicLightInit } from "@uiw/codemirror-theme-basic";
|
||||
import { monokaiInit } from "@uiw/codemirror-theme-monokai";
|
||||
import CodeMirror from "@uiw/react-codemirror";
|
||||
import CodeMirror, { EditorView } from "@uiw/react-codemirror";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useMemo } from "react";
|
||||
|
||||
@@ -29,13 +29,13 @@ export function MarkdownCodeEditor({
|
||||
}) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const extensions = useMemo(
|
||||
() => [markdown({ base: markdownLanguage, codeLanguages: languages })],
|
||||
() => [markdown({ base: markdownLanguage, codeLanguages: languages }), EditorView.lineWrapping],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={cn("grid min-h-[46vh] overflow-hidden rounded-lg border bg-background lg:grid-cols-2", className)}>
|
||||
<section className="flex min-h-0 flex-col border-b lg:border-r lg:border-b-0">
|
||||
<div className={cn("grid min-w-0 min-h-[46vh] overflow-hidden rounded-lg border bg-background lg:grid-cols-2", className)}>
|
||||
<section className="flex min-w-0 min-h-0 flex-col border-b lg:border-r lg:border-b-0">
|
||||
<div className="flex h-9 shrink-0 items-center border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground">
|
||||
Markdown 编辑
|
||||
</div>
|
||||
@@ -50,14 +50,14 @@ export function MarkdownCodeEditor({
|
||||
highlightActiveLineGutter: false,
|
||||
lineNumbers: true,
|
||||
}}
|
||||
className="min-h-[42vh] flex-1 overflow-auto font-mono text-sm [&_.cm-editor]:min-h-[42vh] [&_.cm-focused]:outline-none!"
|
||||
className="min-w-0 min-h-[42vh] flex-1 overflow-auto font-mono text-sm [&_.cm-editor]:min-h-[42vh] [&_.cm-focused]:outline-none!"
|
||||
/>
|
||||
</section>
|
||||
<section className="flex min-h-0 flex-col bg-muted/10">
|
||||
<section className="flex min-w-0 min-h-0 flex-col bg-muted/10">
|
||||
<div className="flex h-9 shrink-0 items-center border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground">
|
||||
实时渲染
|
||||
</div>
|
||||
<div className="min-h-[42vh] flex-1 overflow-auto p-4">
|
||||
<div className="min-w-0 min-h-[42vh] flex-1 overflow-auto p-4">
|
||||
<MarkdownContent
|
||||
content={value || "*暂无正文*"}
|
||||
isLoading={false}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ExternalLink, Sparkles } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
|
||||
@@ -45,6 +45,8 @@ function HeaderButton({
|
||||
|
||||
/** Light 56px wiki header: plain page title on the left, action entries on the right. */
|
||||
export function WikiHeader({
|
||||
title = "知识库管理",
|
||||
description,
|
||||
onToggleSidebar,
|
||||
onImportFile,
|
||||
onBatchImport,
|
||||
@@ -55,6 +57,8 @@ export function WikiHeader({
|
||||
onManageTemplates,
|
||||
extraActions,
|
||||
}: {
|
||||
title?: string;
|
||||
description?: string;
|
||||
onToggleSidebar: () => void;
|
||||
onImportFile: () => void;
|
||||
onBatchImport: () => void;
|
||||
@@ -66,8 +70,13 @@ export function WikiHeader({
|
||||
extraActions?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<header className="flex h-14 shrink-0 items-center justify-between border-b border-slate-100 bg-white px-4 sm:px-6 dark:border-slate-800 dark:bg-slate-900">
|
||||
<div className="flex items-center gap-3">
|
||||
<header
|
||||
className={cn(
|
||||
"flex shrink-0 items-center justify-between border-b border-slate-100 bg-white px-4 sm:px-6 dark:border-slate-800 dark:bg-slate-900",
|
||||
description ? "min-h-14 py-2" : "h-14",
|
||||
)}
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleSidebar}
|
||||
@@ -76,8 +85,15 @@ export function WikiHeader({
|
||||
>
|
||||
<Menu className="size-5" />
|
||||
</button>
|
||||
<div className="min-w-0">
|
||||
<div className="text-base font-semibold tracking-tight text-slate-900 dark:text-slate-100">
|
||||
知识库管理
|
||||
{title}
|
||||
</div>
|
||||
{description ? (
|
||||
<p className="mt-0.5 max-w-xl truncate text-xs text-slate-500 dark:text-slate-400">
|
||||
{description}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { Check, Loader2, Pencil, Plus, Trash2, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -3,18 +3,15 @@
|
||||
import {
|
||||
Activity,
|
||||
Gauge,
|
||||
Loader2,
|
||||
OctagonX,
|
||||
RefreshCw,
|
||||
Square,
|
||||
Zap,
|
||||
} from "lucide-react";
|
||||
import { useId, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button, Switch, Tag } from "tdesign-react";
|
||||
import { confirmAction, toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import type {
|
||||
ActiveRunItem,
|
||||
ConcurrencyPoint,
|
||||
@@ -35,6 +32,9 @@ import { cn } from "@/lib/utils";
|
||||
/** lookback window (hours) per granularity. */
|
||||
const LOOKBACK: Record<Granularity, number> = { minute: 3, hour: 48 };
|
||||
|
||||
/** 主题色(浅红主题下为深红),SVG 引用以跟随换肤。 */
|
||||
const BRAND_COLOR = "var(--td-brand-color, #C1121F)";
|
||||
|
||||
function fmtBucket(iso: string, granularity: Granularity): string {
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return iso;
|
||||
@@ -103,7 +103,11 @@ function latestOf(values: (number | null)[]): number | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Minimal dependency-free SVG line chart: legend + 1–2 series + area + caption. */
|
||||
/**
|
||||
* Dependency-free SVG line chart in the 浅红 UI spec style: soft area fill
|
||||
* under the first series, dashed gridlines, hollow hover markers and a dark
|
||||
* hover tooltip (ref: 8.2 图表-折线图 mock).
|
||||
*/
|
||||
function LineChart({
|
||||
labels,
|
||||
series,
|
||||
@@ -119,6 +123,7 @@ function LineChart({
|
||||
note?: string;
|
||||
emptyHint: string;
|
||||
}) {
|
||||
const [hoverIdx, setHoverIdx] = useState<number | null>(null);
|
||||
const gradId = `cm-area-${useId().replace(/:/g, "")}`;
|
||||
const width = 760;
|
||||
const height = 220;
|
||||
@@ -132,17 +137,25 @@ function LineChart({
|
||||
const ticks = buildTicks(dataMax, integer);
|
||||
const axisMax = ticks[ticks.length - 1] || 1;
|
||||
|
||||
const handleMove = (event: React.MouseEvent<HTMLDivElement>) => {
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
const vx = ((event.clientX - rect.left) / rect.width) * width;
|
||||
const rel = (vx - pad.left) / cw;
|
||||
const idx = Math.round(rel * (n - 1));
|
||||
setHoverIdx(Math.max(0, Math.min(n - 1, idx)));
|
||||
};
|
||||
|
||||
// Legend always renders (even with no data) so the lines are self-explanatory.
|
||||
const legend = (
|
||||
<div className="mb-2 flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||
{series.map((s) => {
|
||||
const latest = latestOf(s.values);
|
||||
return (
|
||||
<span key={s.name} className="flex items-center gap-1.5 text-xs text-[#5F6368] dark:text-slate-300">
|
||||
<span key={s.name} className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span className="inline-block h-[3px] w-4 rounded-full" style={{ backgroundColor: s.color }} />
|
||||
{s.name}
|
||||
{latest != null && (
|
||||
<span className="font-semibold tabular-nums text-[#231815] dark:text-white">
|
||||
<span className="font-semibold tabular-nums text-card-foreground">
|
||||
{Number.isInteger(latest) ? latest : latest.toFixed(1)}
|
||||
{unit}
|
||||
</span>
|
||||
@@ -154,14 +167,14 @@ function LineChart({
|
||||
);
|
||||
|
||||
const caption = note ? (
|
||||
<p className="mt-2 text-[11px] leading-4 text-[#8B6B6B] dark:text-[#7FACF2]">{note}</p>
|
||||
<p className="mt-2 text-[11px] leading-4 text-muted-foreground">{note}</p>
|
||||
) : null;
|
||||
|
||||
if (n === 0) {
|
||||
return (
|
||||
<div>
|
||||
{legend}
|
||||
<div className="flex h-[160px] items-center justify-center rounded-lg border border-dashed border-[#F1D6D6] text-sm text-[#5F6368] dark:border-[#213D5E] dark:text-slate-400">
|
||||
<div className="flex h-[160px] items-center justify-center rounded-[5px] border border-dashed border-border/70 text-sm text-muted-foreground">
|
||||
{emptyHint}
|
||||
</div>
|
||||
{caption}
|
||||
@@ -194,16 +207,22 @@ function LineChart({
|
||||
return `${line} L ${xFor(n - 1).toFixed(1)} ${(pad.top + ch).toFixed(1)} L ${xFor(0).toFixed(1)} ${(pad.top + ch).toFixed(1)} Z`;
|
||||
})();
|
||||
|
||||
const hoverX = hoverIdx != null ? xFor(hoverIdx) : null;
|
||||
const labelStep = Math.max(1, Math.ceil(n / 7));
|
||||
|
||||
return (
|
||||
<div>
|
||||
{legend}
|
||||
<div
|
||||
className="relative"
|
||||
onMouseMove={handleMove}
|
||||
onMouseLeave={() => setHoverIdx(null)}
|
||||
>
|
||||
<svg viewBox={`0 0 ${width} ${height}`} className="w-full" role="img" aria-label="时序折线图">
|
||||
<defs>
|
||||
<linearGradient id={gradId} x1="0" x2="0" y1="0" y2="1">
|
||||
<stop offset="0%" stopColor={first?.color ?? "#C1121F"} stopOpacity="0.18" />
|
||||
<stop offset="100%" stopColor={first?.color ?? "#C1121F"} stopOpacity="0.02" />
|
||||
<stop offset="0%" stopColor={first?.color ?? BRAND_COLOR} stopOpacity="0.14" />
|
||||
<stop offset="100%" stopColor={first?.color ?? BRAND_COLOR} stopOpacity="0.01" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
{ticks.map((t) => {
|
||||
@@ -216,19 +235,33 @@ function LineChart({
|
||||
y1={y}
|
||||
y2={y}
|
||||
stroke="currentColor"
|
||||
className="text-[#E5E7EB] dark:text-[#3F3F46]"
|
||||
className="text-border/70"
|
||||
strokeWidth="1"
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
<text x={pad.left - 6} y={y + 3} textAnchor="end" className="fill-[#9CA3AF] text-[10px]">
|
||||
<text x={pad.left - 6} y={y + 3} textAnchor="end" className="fill-muted-foreground text-[10px]">
|
||||
{fmtAxis(t, integer)}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{areaPath && <path d={areaPath} fill={`url(#${gradId})`} />}
|
||||
{series.map((s) => (
|
||||
{hoverX != null && (
|
||||
<line
|
||||
x1={hoverX}
|
||||
x2={hoverX}
|
||||
y1={pad.top}
|
||||
y2={pad.top + ch}
|
||||
stroke={BRAND_COLOR}
|
||||
strokeWidth="1"
|
||||
strokeDasharray="3 3"
|
||||
opacity="0.45"
|
||||
/>
|
||||
)}
|
||||
{series.map((s, sIndex) => (
|
||||
<g key={s.name}>
|
||||
{/* 基线:实色线 */}
|
||||
<path
|
||||
key={s.name}
|
||||
d={linePath(s.values)}
|
||||
fill="none"
|
||||
stroke={s.color}
|
||||
@@ -236,50 +269,90 @@ function LineChart({
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
{/* 流动高光:同路径短划沿 dashoffset 无限循环,白亮光带从左向右流过 */}
|
||||
<path
|
||||
d={linePath(s.values)}
|
||||
fill="none"
|
||||
stroke="rgba(255, 255, 255, 0.75)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
pathLength={1}
|
||||
className="lb-line-flow"
|
||||
style={{ animationDelay: `${sIndex * -2.75}s` }}
|
||||
/>
|
||||
</g>
|
||||
))}
|
||||
{hoverIdx != null &&
|
||||
series.map((s) => {
|
||||
const v = s.values[hoverIdx];
|
||||
if (v == null) return null;
|
||||
return (
|
||||
<circle
|
||||
key={`${s.name}-hover`}
|
||||
cx={xFor(hoverIdx)}
|
||||
cy={yFor(v)}
|
||||
r="4"
|
||||
fill="var(--td-bg-color-container, #fff)"
|
||||
stroke={s.color}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{labels.map((label, i) => {
|
||||
if (i !== 0 && i !== n - 1 && i % labelStep !== 0) return null;
|
||||
return (
|
||||
<text key={`${label}-${i}`} x={xFor(i)} y={height - 8} textAnchor="middle" className="fill-[#6B7280] text-[10px]">
|
||||
<text key={`${label}-${i}`} x={xFor(i)} y={height - 8} textAnchor="middle" className="fill-muted-foreground text-[10px]">
|
||||
{label}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
{series.map((s) =>
|
||||
s.values.map((v, i) =>
|
||||
v == null ? null : (
|
||||
<circle key={`${s.name}-${i}`} cx={xFor(i)} cy={yFor(v)} r={2.5} fill={s.color}>
|
||||
<title>{`${labels[i]} · ${s.name}: ${v}${unit}`}</title>
|
||||
</circle>
|
||||
),
|
||||
),
|
||||
)}
|
||||
</svg>
|
||||
{hoverIdx != null && (
|
||||
<div
|
||||
className="pointer-events-none absolute top-2 z-10 min-w-[110px] -translate-x-1/2 rounded-[5px] bg-[#1D2939]/95 px-2.5 py-1.5 text-xs text-white shadow-lg"
|
||||
style={{ left: `${Math.min(92, Math.max(8, (xFor(hoverIdx) / width) * 100))}%` }}
|
||||
>
|
||||
<div className="mb-1 font-medium text-white/90">{labels[hoverIdx]}</div>
|
||||
{series.map((s) => {
|
||||
const v = s.values[hoverIdx];
|
||||
return (
|
||||
<div key={s.name} className="flex items-center gap-1.5 whitespace-nowrap">
|
||||
<span className="size-1.5 rounded-full" style={{ backgroundColor: s.color }} aria-hidden />
|
||||
<span className="text-white/75">{s.name}</span>
|
||||
<span className="ml-auto font-semibold tabular-nums">{v == null ? "-" : `${Number.isInteger(v) ? v : v.toFixed(1)}${unit}`}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{caption}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ChartCard({
|
||||
icon: Icon,
|
||||
/** 浅红 UI 规范的「▎标题」小节头(面板内使用)。 */
|
||||
function ChartSection({
|
||||
title,
|
||||
subtitle,
|
||||
icon: Icon,
|
||||
extra,
|
||||
children,
|
||||
}: {
|
||||
icon: typeof Activity;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
icon?: typeof Activity;
|
||||
extra?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="rounded-lg border border-[#F1D6D6] bg-white p-4 shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<Icon className="size-4 text-[#C1121F] dark:text-[#7FACF2]" />
|
||||
<h3 className="font-semibold text-[#231815] dark:text-white">{title}</h3>
|
||||
<span className="ml-auto text-xs text-[#8B6B6B] dark:text-[#7FACF2]">{subtitle}</span>
|
||||
<div className="rounded-[5px] bg-muted/30 p-4">
|
||||
<div className="mb-3 flex items-center gap-2.5">
|
||||
<span className="h-3.5 w-[3px] shrink-0 rounded-full bg-primary" aria-hidden />
|
||||
{Icon ? <Icon className="size-4 shrink-0 text-muted-foreground" /> : null}
|
||||
<h3 className="text-sm font-semibold text-card-foreground">{title}</h3>
|
||||
<span className="ml-auto text-xs text-muted-foreground">{extra}</span>
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -293,36 +366,35 @@ function ActiveRunRow({
|
||||
stopping: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid grid-cols-[minmax(0,1.4fr)_minmax(0,1.2fr)_72px_64px_64px_72px] items-center gap-3 border-b border-[#F1D6D6] px-3 py-2 text-sm last:border-b-0 dark:border-[#213D5E]">
|
||||
<div className="grid grid-cols-[minmax(0,1.4fr)_minmax(0,1.2fr)_72px_64px_64px_72px] items-center gap-3 border-b border-border/60 px-3 py-2 text-sm transition-colors last:border-b-0 hover:bg-muted/40">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-medium text-[#202124] dark:text-white">{run.user_name || "未知用户"}</div>
|
||||
<div className="truncate text-xs text-[#5F6368] dark:text-slate-400" title={run.thread_title}>
|
||||
<div className="truncate font-medium text-card-foreground">{run.user_name || "未知用户"}</div>
|
||||
<div className="truncate text-xs text-muted-foreground" title={run.thread_title}>
|
||||
{run.thread_title || run.thread_id}
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0 truncate text-[#202124] dark:text-slate-100">{run.agent_name}</div>
|
||||
<Badge variant="outline" className="justify-center">
|
||||
<div className="min-w-0 truncate text-card-foreground">{run.agent_name}</div>
|
||||
<Tag variant="outline" size="small" className="justify-center">
|
||||
{run.kind}
|
||||
</Badge>
|
||||
<span
|
||||
className={cn(
|
||||
"text-center text-xs font-medium",
|
||||
run.status === "running" ? "text-[#0F766E] dark:text-teal-300" : "text-[#B45309] dark:text-amber-300",
|
||||
</Tag>
|
||||
<span className="text-center">
|
||||
{run.status === "running" ? (
|
||||
<Tag theme="success" variant="light" size="small">运行中</Tag>
|
||||
) : (
|
||||
<Tag theme="warning" variant="light" size="small">排队中</Tag>
|
||||
)}
|
||||
>
|
||||
{run.status === "running" ? "运行中" : "排队中"}
|
||||
</span>
|
||||
<span className="text-center text-xs tabular-nums text-[#5F6368] dark:text-slate-400">
|
||||
<span className="text-center text-xs tabular-nums text-muted-foreground">
|
||||
{fmtElapsed(run.elapsed_seconds)}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
size="small"
|
||||
variant="outline"
|
||||
className="h-7 border-[#C1121F]/40 text-[#C1121F] hover:bg-[#FFF1F1] dark:border-rose-400/40 dark:text-rose-200"
|
||||
theme="danger"
|
||||
disabled={stopping}
|
||||
icon={<Square className="size-3.5" />}
|
||||
onClick={() => onStop(run.run_id)}
|
||||
>
|
||||
{stopping ? <Loader2 className="size-3.5 animate-spin" /> : <Square className="size-3.5" />}
|
||||
停止
|
||||
</Button>
|
||||
</div>
|
||||
@@ -363,8 +435,8 @@ export function ConcurrencyMonitorPanel() {
|
||||
return {
|
||||
labels: points.map((p) => fmtBucket(p.bucket, granularity)),
|
||||
series: [
|
||||
{ name: "平均速度", color: "#2563EB", values: points.map((p) => p.avg_tokens_per_sec) },
|
||||
{ name: "最慢", color: "#9333EA", values: points.map((p) => p.min_tokens_per_sec) },
|
||||
{ name: "平均速度", color: "#2F6BFF", values: points.map((p) => p.avg_tokens_per_sec) },
|
||||
{ name: "最慢", color: "#7C3AED", values: points.map((p) => p.min_tokens_per_sec) },
|
||||
] as LineSeries[],
|
||||
};
|
||||
}, [tokenSpeed.data, granularity]);
|
||||
@@ -383,7 +455,11 @@ export function ConcurrencyMonitorPanel() {
|
||||
|
||||
const handleStopAll = async () => {
|
||||
if (runs.length === 0) return;
|
||||
if (!window.confirm(`确定要停止当前全部 ${count} 个并发调用吗?这会中断这些用户正在生成的回答。`)) return;
|
||||
if (!(await confirmAction(`确定要停止当前全部 ${count} 个并发调用吗?这会中断这些用户正在生成的回答。`, {
|
||||
title: "停止全部调用?",
|
||||
confirmText: "全部停止",
|
||||
danger: true,
|
||||
}))) return;
|
||||
try {
|
||||
const res = await cancelAll.mutateAsync();
|
||||
toast.success(`已停止 ${res.cancelled_count} 个调用`);
|
||||
@@ -402,52 +478,56 @@ export function ConcurrencyMonitorPanel() {
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="space-y-4 rounded-xl border border-[#F1D6D6] bg-[#FFF7F7] p-4 shadow-sm dark:border-[#213D5E] dark:bg-[#011226]">
|
||||
<section className="lb-icon-gap space-y-4 rounded-[5px] bg-card p-4 shadow-[0_2px_8px_rgba(15,23,42,0.06)]">
|
||||
{/* header */}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex size-9 items-center justify-center rounded-lg bg-[#C1121F] text-white dark:bg-[#2563EB]">
|
||||
<span className="flex size-9 items-center justify-center rounded-lg bg-primary text-primary-foreground">
|
||||
<Activity className="size-5" />
|
||||
</span>
|
||||
<div>
|
||||
<div className="font-semibold text-[#231815] dark:text-white">实时并发监控</div>
|
||||
<div className="text-xs text-[#8B6B6B] dark:text-[#7FACF2]">
|
||||
<div className="font-semibold text-card-foreground">实时并发监控</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
监控大模型并发压力,可直接停止任意对话调用
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ml-auto flex flex-wrap items-center gap-3">
|
||||
<div className="flex items-center gap-2 rounded-lg border border-[#F1D6D6] bg-white px-3 py-1.5 dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||
<span className="text-xs text-[#5F6368] dark:text-slate-300">当前并发</span>
|
||||
<div className="ml-auto flex h-8 flex-wrap items-center gap-2">
|
||||
<div className="flex h-8 items-center gap-2 rounded-[5px] bg-muted/40 px-3">
|
||||
<span className="text-xs text-muted-foreground">当前并发</span>
|
||||
<span
|
||||
className={cn(
|
||||
"text-2xl font-semibold tabular-nums",
|
||||
count > 0 ? "text-[#C1121F] dark:text-[#7FACF2]" : "text-[#202124] dark:text-white",
|
||||
"text-lg font-semibold leading-none tabular-nums",
|
||||
count > 0 ? "text-primary" : "text-card-foreground",
|
||||
)}
|
||||
>
|
||||
{count}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 rounded-lg border border-[#F1D6D6] bg-white px-3 py-1.5 dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||
<span className="text-xs text-[#5F6368] dark:text-slate-300">后台采样</span>
|
||||
<Switch checked={samplerOn} onCheckedChange={handleToggleSampler} disabled={updateSettings.isPending} />
|
||||
<div className="flex h-8 items-center gap-2 rounded-[5px] bg-muted/40 px-3">
|
||||
<span className="text-xs text-muted-foreground">后台采样</span>
|
||||
<Switch value={samplerOn} onChange={handleToggleSampler} loading={updateSettings.isPending} />
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => refetch()} disabled={isRefetching}>
|
||||
<RefreshCw className={cn("mr-1 size-4", isRefetching && "animate-spin")} />
|
||||
<Button
|
||||
variant="outline"
|
||||
theme="default"
|
||||
icon={<RefreshCw className={cn("size-4", isRefetching && "animate-spin")} />}
|
||||
onClick={() => refetch()}
|
||||
disabled={isRefetching}
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="border-[#C1121F]/50 text-[#C1121F] hover:bg-[#FFF1F1] dark:border-rose-400/40 dark:text-rose-200"
|
||||
theme="danger"
|
||||
icon={<OctagonX className="size-4" />}
|
||||
onClick={handleStopAll}
|
||||
disabled={cancelAll.isPending || runs.length === 0}
|
||||
>
|
||||
<OctagonX className="mr-1 size-4" />
|
||||
全部停止
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setOpen((v) => !v)}>
|
||||
<Button variant="text" theme="default" onClick={() => setOpen((v) => !v)}>
|
||||
{open ? "收起" : "展开"}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -456,36 +536,38 @@ export function ConcurrencyMonitorPanel() {
|
||||
{open && (
|
||||
<>
|
||||
{!samplerOn && (
|
||||
<div className="rounded-lg border border-amber-300/60 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-300/30 dark:bg-amber-300/10 dark:text-amber-100">
|
||||
<div className="rounded-[5px] bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:bg-amber-400/10 dark:text-amber-100">
|
||||
后台采样默认关闭:实时并发数与「停止」功能始终可用。需要并发量历史折线图时,打开右上角「后台采样」开关即可开始记录(对线上服务影响极小,可随时关闭)。
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* granularity toggle */}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-[#5F6368] dark:text-slate-300">统计粒度</span>
|
||||
<span className="text-xs text-muted-foreground">统计粒度</span>
|
||||
<div className="lb-pill-group flex items-center gap-1.5">
|
||||
{(["minute", "hour"] as Granularity[]).map((g) => (
|
||||
<Button
|
||||
key={g}
|
||||
size="sm"
|
||||
variant={granularity === g ? "default" : "outline"}
|
||||
className={cn("h-7", granularity === g && "bg-[#C1121F] hover:bg-[#A50F1A] dark:bg-[#2563EB]")}
|
||||
size="small"
|
||||
variant={granularity === g ? "base" : "outline"}
|
||||
theme={granularity === g ? "primary" : "default"}
|
||||
onClick={() => setGranularity(g)}
|
||||
>
|
||||
{g === "minute" ? "按分钟" : "按小时"}
|
||||
</Button>
|
||||
))}
|
||||
<span className="text-xs text-[#8B6B6B] dark:text-[#7FACF2]">
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{granularity === "minute" ? "近 3 小时" : "近 48 小时"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* charts */}
|
||||
<div className="grid gap-3 xl:grid-cols-2">
|
||||
<ChartCard icon={Gauge} title="并发量(系统压力)" subtitle={`每${granularity === "hour" ? "小时" : "分钟"}一个点`}>
|
||||
<ChartSection icon={Gauge} title="并发量(系统压力)" extra={`每${granularity === "hour" ? "小时" : "分钟"}一个点`}>
|
||||
{concurrency.isLoading ? (
|
||||
<div className="flex h-[220px] items-center justify-center text-sm text-[#5F6368] dark:text-slate-400">
|
||||
<Loader2 className="mr-2 size-4 animate-spin" /> 加载中
|
||||
<div className="flex h-[220px] items-center justify-center text-sm text-muted-foreground">
|
||||
加载中…
|
||||
</div>
|
||||
) : (
|
||||
<LineChart
|
||||
@@ -497,11 +579,11 @@ export function ConcurrencyMonitorPanel() {
|
||||
emptyHint="暂无并发采样数据(需打开「后台采样」开关后才开始记录)"
|
||||
/>
|
||||
)}
|
||||
</ChartCard>
|
||||
<ChartCard icon={Zap} title="大模型出字速度" subtitle={`每${granularity === "hour" ? "小时" : "分钟"}一个点`}>
|
||||
</ChartSection>
|
||||
<ChartSection icon={Zap} title="大模型出字速度" extra={`每${granularity === "hour" ? "小时" : "分钟"}一个点`}>
|
||||
{tokenSpeed.isLoading ? (
|
||||
<div className="flex h-[220px] items-center justify-center text-sm text-[#5F6368] dark:text-slate-400">
|
||||
<Loader2 className="mr-2 size-4 animate-spin" /> 加载中
|
||||
<div className="flex h-[220px] items-center justify-center text-sm text-muted-foreground">
|
||||
加载中…
|
||||
</div>
|
||||
) : (
|
||||
<LineChart
|
||||
@@ -512,23 +594,24 @@ export function ConcurrencyMonitorPanel() {
|
||||
emptyHint="暂无大模型调用记录"
|
||||
/>
|
||||
)}
|
||||
</ChartCard>
|
||||
</ChartSection>
|
||||
</div>
|
||||
|
||||
{/* active run list */}
|
||||
<section className="rounded-lg border border-[#F1D6D6] bg-white dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||
<div className="flex items-center gap-2 border-b border-[#F1D6D6] px-3 py-2 dark:border-[#213D5E]">
|
||||
<span className="font-semibold text-[#231815] dark:text-white">正在进行的调用</span>
|
||||
<Badge variant="outline">{count}</Badge>
|
||||
{liveLoading && <Loader2 className="size-3.5 animate-spin text-[#8B6B6B]" />}
|
||||
<section className="overflow-hidden rounded-[5px] bg-muted/20">
|
||||
<div className="flex items-center gap-2 border-b border-border/70 px-3 py-2">
|
||||
<span className="h-3.5 w-[3px] rounded-full bg-primary" aria-hidden />
|
||||
<span className="text-sm font-semibold text-card-foreground">正在进行的调用</span>
|
||||
<Tag variant="outline" size="small">{count}</Tag>
|
||||
{liveLoading && <span className="text-xs text-muted-foreground">加载中…</span>}
|
||||
</div>
|
||||
{runs.length === 0 ? (
|
||||
<div className="py-10 text-center text-sm text-[#5F6368] dark:text-slate-400">
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">
|
||||
当前没有正在进行的大模型调用
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="grid grid-cols-[minmax(0,1.4fr)_minmax(0,1.2fr)_72px_64px_64px_72px] gap-3 border-b border-[#F1D6D6] px-3 py-2 text-xs text-[#8B6B6B] dark:border-[#213D5E] dark:text-[#7FACF2]">
|
||||
<div className="grid grid-cols-[minmax(0,1.4fr)_minmax(0,1.2fr)_72px_64px_64px_72px] gap-3 border-b border-border/60 bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
|
||||
<span>用户 / 会话</span>
|
||||
<span>智能体</span>
|
||||
<span className="text-center">类型</span>
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
UsersIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { confirmAction, toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -391,7 +391,11 @@ export function PositionManagementPage() {
|
||||
}, [positions, selectedId]);
|
||||
|
||||
const handleDelete = async (p: Position) => {
|
||||
if (!window.confirm(`确认删除岗位「${p.name}」?其成员将回退到默认岗位。`)) return;
|
||||
if (!(await confirmAction(`确认删除岗位「${p.name}」?其成员将回退到默认岗位。`, {
|
||||
title: "删除岗位?",
|
||||
confirmText: "删除",
|
||||
danger: true,
|
||||
}))) return;
|
||||
try {
|
||||
await deletePosition.mutateAsync(p.id);
|
||||
if (selectedId === p.id) setSelectedId(null);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { Loader2, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { confirmAction, toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -172,7 +172,11 @@ export function TagManagementPage() {
|
||||
setDialogOpen(true);
|
||||
};
|
||||
const handleDelete = async (tag: Tag) => {
|
||||
if (!window.confirm(t.adminTags.deleteConfirm)) return;
|
||||
if (!(await confirmAction(t.adminTags.deleteConfirm, {
|
||||
title: "删除标签?",
|
||||
confirmText: "删除",
|
||||
danger: true,
|
||||
}))) return;
|
||||
try {
|
||||
await deleteTag.mutateAsync(tag.id);
|
||||
} catch (e) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { AlertCircle,CheckCircle2, Download, Loader2 } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -1,11 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import { BotIcon } from "lucide-react";
|
||||
import {
|
||||
BotIcon,
|
||||
BrainIcon,
|
||||
CompassIcon,
|
||||
MessagesSquareIcon,
|
||||
SparklesIcon,
|
||||
WorkflowIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import { type Agent } from "@/core/agents";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Per-style avatar glyphs — the landing style index (derived from the agent
|
||||
* id in globals.css' [data-agent-style] block) also swaps the hero mark so
|
||||
* two agents on different styles don't just differ by color. Keep in sync
|
||||
* with AGENT_LANDING_STYLE_COUNT.
|
||||
*/
|
||||
const STYLE_ICONS = [
|
||||
BotIcon,
|
||||
SparklesIcon,
|
||||
BrainIcon,
|
||||
CompassIcon,
|
||||
MessagesSquareIcon,
|
||||
WorkflowIcon,
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Landing (home) hero shown above the input box before the first message of an
|
||||
* agent conversation: centered avatar, a "Hi,我是{name}" greeting and the
|
||||
@@ -13,20 +35,33 @@ import { cn } from "@/lib/utils";
|
||||
* (full text on hover) so a long blurb can never push the input box below the
|
||||
* fold. The agent's 常用问题 are rendered by the page as a list beside the
|
||||
* input box, not here.
|
||||
*
|
||||
* The avatar color/shape, greeting treatment and page glow are themed per
|
||||
* agent via the ancestor `[data-agent-style]` attribute (AgentChatPage) —
|
||||
* see the 智能体专属落地页风格 block in globals.css.
|
||||
*/
|
||||
export function AgentWelcome({
|
||||
className,
|
||||
agent,
|
||||
agentName,
|
||||
styleIndex,
|
||||
}: {
|
||||
className?: string;
|
||||
agent: Agent | null | undefined;
|
||||
agentName: string;
|
||||
/** 仅自定义业务深链入口传入(风格分配完成后的档位;未分配完成时为
|
||||
* undefined):启用按风格轮换的头像图标;缺省保持全局原样的 BotIcon。 */
|
||||
styleIndex?: number;
|
||||
}) {
|
||||
const displayName = desensitize(agent?.name ?? agentName);
|
||||
const description = agent?.description
|
||||
? desensitize(agent.description)
|
||||
: undefined;
|
||||
const styleIcon =
|
||||
styleIndex === undefined
|
||||
? BotIcon
|
||||
: (STYLE_ICONS[styleIndex % STYLE_ICONS.length] ?? BotIcon);
|
||||
const StyleIcon = styleIcon;
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -35,15 +70,15 @@ export function AgentWelcome({
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<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 className="agent-avatar rounded-3xl mb-2 flex h-[72px] w-[72px] items-center justify-center">
|
||||
<StyleIcon className="h-9 w-9" />
|
||||
</div>
|
||||
<div className="text-3xl font-bold tracking-tight">
|
||||
<div className="agent-welcome-name text-3xl font-bold tracking-tight">
|
||||
Hi,我是{displayName}
|
||||
</div>
|
||||
{description && (
|
||||
<p
|
||||
className="text-muted-foreground line-clamp-2 max-w-xl text-base leading-relaxed"
|
||||
className="agent-welcome-description text-muted-foreground line-clamp-2 max-w-xl text-base leading-relaxed"
|
||||
title={description}
|
||||
>
|
||||
{description}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import agentAvatarDark from "@/assets/agents-plaza/blue/robot.png";
|
||||
import agentAvatarLight from "@/assets/agents-plaza/robot-orange.png";
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type AgentBrandIconProps = {
|
||||
className?: string;
|
||||
size?: "md" | "lg";
|
||||
};
|
||||
|
||||
const SIZE_STYLES = {
|
||||
md: "size-12",
|
||||
lg: "size-16",
|
||||
} as const;
|
||||
|
||||
/** The master-zl agent gallery mark, switching artwork with the app theme. */
|
||||
export function AgentBrandIcon({
|
||||
className,
|
||||
size = "md",
|
||||
}: AgentBrandIconProps) {
|
||||
const { theme } = useTheme();
|
||||
const avatarSrc = theme === "light" ? agentAvatarLight : agentAvatarDark;
|
||||
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"relative inline-flex shrink-0 overflow-hidden rounded-full",
|
||||
SIZE_STYLES[size],
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src={avatarSrc}
|
||||
alt=""
|
||||
className="size-full object-contain"
|
||||
draggable={false}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
BotIcon,
|
||||
ClockIcon,
|
||||
CopyIcon,
|
||||
EyeIcon,
|
||||
@@ -9,6 +8,7 @@ import {
|
||||
GlobeIcon,
|
||||
LockIcon,
|
||||
MessageSquareIcon,
|
||||
MoreHorizontalIcon,
|
||||
PinIcon,
|
||||
ShieldIcon,
|
||||
SparklesIcon,
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
import { confirmAction, toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -47,6 +47,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 { Textarea } from "@/components/ui/textarea";
|
||||
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 { AgentChatLinkFields } from "@/components/workspace/agents/agent-chat-link-fields";
|
||||
import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor";
|
||||
import { SkillTransferSelector } from "@/components/workspace/agents/skill-transfer-selector";
|
||||
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
||||
@@ -76,7 +84,15 @@ import {
|
||||
useUpdateAgent,
|
||||
} from "@/core/agents";
|
||||
import { getAgent } from "@/core/agents/api";
|
||||
import type { Agent, AgentQuestion, UpdateAgentRequest } from "@/core/agents";
|
||||
import type { Agent, AgentChatLink, AgentQuestion, UpdateAgentRequest } from "@/core/agents";
|
||||
import {
|
||||
agentChatLinksEqual,
|
||||
canonicalAgentChatLink,
|
||||
isAllowedAgentChatUrl,
|
||||
openResolvedAgentChatUrl,
|
||||
} from "@/core/agents/chat-link";
|
||||
import { emptyAgentChatLink } from "@/core/agents/types";
|
||||
import { appendResolvedRouteParams } from "@/strategy-components/lib/light-app";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
@@ -85,6 +101,8 @@ import { formatDateTime } from "@/core/utils/datetime";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { AgentBrandIcon } from "./agent-brand-icon";
|
||||
|
||||
interface AgentCardProps {
|
||||
agent: Agent;
|
||||
/** "card" (default) renders the full gallery card; "list" renders a compact
|
||||
@@ -248,6 +266,12 @@ export function AgentCard({
|
||||
const [editSeatSkillDirective, setEditSeatSkillDirective] = useState(
|
||||
agent.seat_skill_directive ?? false,
|
||||
);
|
||||
const [editModelPromptSuffixEnabled, setEditModelPromptSuffixEnabled] = useState(
|
||||
agent.model_prompt_suffix_enabled ?? true,
|
||||
);
|
||||
const [editChatLink, setEditChatLink] = useState<AgentChatLink>(
|
||||
() => agent.chat_link ?? emptyAgentChatLink(),
|
||||
);
|
||||
const [editSquareId, setEditSquareId] = useState(agent.square_id ?? "");
|
||||
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
|
||||
const { data: publishSquares } = usePublishSquares();
|
||||
@@ -296,6 +320,8 @@ export function AgentCard({
|
||||
setSelectedSkills(agent.skills ?? []);
|
||||
setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions));
|
||||
setEditSeatSkillDirective(agent.seat_skill_directive ?? false);
|
||||
setEditModelPromptSuffixEnabled(agent.model_prompt_suffix_enabled ?? true);
|
||||
setEditChatLink(agent.chat_link ?? emptyAgentChatLink());
|
||||
}, [
|
||||
agent.common_questions,
|
||||
agent.description,
|
||||
@@ -305,6 +331,8 @@ export function AgentCard({
|
||||
agent.square_id,
|
||||
agent.skills,
|
||||
agent.seat_skill_directive,
|
||||
agent.model_prompt_suffix_enabled,
|
||||
agent.chat_link,
|
||||
editOpen,
|
||||
]);
|
||||
|
||||
@@ -320,12 +348,28 @@ export function AgentCard({
|
||||
setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions));
|
||||
// 列表响应不带 config 额外字段(seat_skill_directive 为 null),详情才有真值。
|
||||
setEditSeatSkillDirective(agentDetail.seat_skill_directive ?? false);
|
||||
setEditModelPromptSuffixEnabled(agentDetail.model_prompt_suffix_enabled ?? true);
|
||||
setEditChatLink(agentDetail.chat_link ?? emptyAgentChatLink());
|
||||
} else {
|
||||
setEditSoul(agent.soul ?? "");
|
||||
}
|
||||
}, [agent.soul, agentDetail, editOpen]);
|
||||
|
||||
function handleChat() {
|
||||
async function handleChat() {
|
||||
let link = agent.chat_link;
|
||||
if (link === undefined) {
|
||||
try {
|
||||
link = (await getAgent(agent.id)).chat_link ?? null;
|
||||
} catch {
|
||||
link = null;
|
||||
}
|
||||
}
|
||||
const target = canonicalAgentChatLink(link);
|
||||
if (target && isAllowedAgentChatUrl(target.url)) {
|
||||
const href = appendResolvedRouteParams(target.url, target.route_params);
|
||||
openResolvedAgentChatUrl(href, target.open_mode, (path) => router.push(path));
|
||||
return;
|
||||
}
|
||||
router.push(`/page/workspace/agents/${agent.id}/chats/new`);
|
||||
}
|
||||
|
||||
@@ -348,9 +392,11 @@ export function AgentCard({
|
||||
// row to carry the source agent's personality into the copy. Fall back
|
||||
// to whatever the list happened to include if the detail fetch fails.
|
||||
let soul = agent.soul ?? "";
|
||||
let chatLink = canonicalAgentChatLink(agent.chat_link);
|
||||
try {
|
||||
const detail = await getAgent(agent.id);
|
||||
soul = detail.soul ?? soul;
|
||||
chatLink = canonicalAgentChatLink(detail.chat_link);
|
||||
} catch {
|
||||
// keep the list fallback
|
||||
}
|
||||
@@ -361,6 +407,7 @@ export function AgentCard({
|
||||
skills: agent.skills ?? [],
|
||||
model: agent.model ?? null,
|
||||
tool_groups: agent.tool_groups ?? null,
|
||||
chat_link: chatLink,
|
||||
// A copy starts as a private, unpublished draft the owner can refine
|
||||
// before sharing — never inherit the source's published/private state.
|
||||
published: false,
|
||||
@@ -413,6 +460,24 @@ export function AgentCard({
|
||||
request.common_questions = nextQuestions;
|
||||
if (editSeatSkillDirective !== ((agentDetail?.seat_skill_directive ?? agent.seat_skill_directive) ?? false))
|
||||
request.seat_skill_directive = editSeatSkillDirective;
|
||||
if (editModelPromptSuffixEnabled !== ((agentDetail?.model_prompt_suffix_enabled ?? agent.model_prompt_suffix_enabled) ?? true))
|
||||
request.model_prompt_suffix_enabled = editModelPromptSuffixEnabled;
|
||||
const nextChatLink = canonicalAgentChatLink(editChatLink);
|
||||
if (nextChatLink && !isAllowedAgentChatUrl(nextChatLink.url)) {
|
||||
toast.error("对话链接只支持 http(s) 地址,或以 /、#/ 开头的站内路径");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
editChatLink.route_params.some((param) => !param.key.trim()) &&
|
||||
nextChatLink
|
||||
) {
|
||||
toast.error("路由参数键名不可为空");
|
||||
return;
|
||||
}
|
||||
const baselineChatLink = agentDetail?.chat_link ?? agent.chat_link;
|
||||
if (!agentChatLinksEqual(nextChatLink, baselineChatLink)) {
|
||||
request.chat_link = nextChatLink;
|
||||
}
|
||||
|
||||
if (Object.keys(request).length === 0) {
|
||||
setEditOpen(false);
|
||||
@@ -441,7 +506,7 @@ export function AgentCard({
|
||||
setPublishPickerOpen(true);
|
||||
return;
|
||||
}
|
||||
if (!warnIfAccountSwitched()) {
|
||||
if (!(await warnIfAccountSwitched())) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -459,18 +524,22 @@ export function AgentCard({
|
||||
|
||||
// 发布操作以实时 token 执行。若会话中途账号被切换(常见于另一标签页登录了别的
|
||||
// 账号),先弹一次确认 —— 避免误以本人之外的账号执行发布。返回 false = 用户取消。
|
||||
function warnIfAccountSwitched(): boolean {
|
||||
function warnIfAccountSwitched(): boolean | Promise<boolean> {
|
||||
if (!live.switched) {
|
||||
return true;
|
||||
}
|
||||
return window.confirm(
|
||||
return confirmAction(
|
||||
`当前登录账号已从「${live.mountDisplayName}」切换为「${live.displayName}」。\n` +
|
||||
`本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。\n\n仍要继续吗?`,
|
||||
`本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。`,
|
||||
{
|
||||
title: "登录账号已切换",
|
||||
confirmText: "继续发布",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function handlePublishToSquare(squareId: string) {
|
||||
if (!warnIfAccountSwitched()) {
|
||||
if (!(await warnIfAccountSwitched())) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -552,6 +621,12 @@ export function AgentCard({
|
||||
// both the card header and the compact list row.
|
||||
const statusBadges = (
|
||||
<>
|
||||
{isPinned && (
|
||||
<Badge className="border border-primary/20 bg-primary/5 px-2.5 py-1 text-xs font-medium text-primary hover:bg-primary/5 dark:border-primary/40 dark:bg-primary/15">
|
||||
<PinIcon className="mr-1 size-3.5 fill-current" />
|
||||
置顶
|
||||
</Badge>
|
||||
)}
|
||||
{isBuiltin && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
内置
|
||||
@@ -674,7 +749,12 @@ export function AgentCard({
|
||||
...(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="rounded-full border-border/50 bg-muted/40 text-muted-foreground text-xs"
|
||||
title="工具组"
|
||||
>
|
||||
{desensitize(group)}
|
||||
</Badge>
|
||||
),
|
||||
@@ -684,8 +764,8 @@ export function AgentCard({
|
||||
node: (
|
||||
<Badge
|
||||
key={`sk:${skill}`}
|
||||
variant="secondary"
|
||||
className="hover:bg-secondary/70 cursor-pointer text-xs"
|
||||
variant="outline"
|
||||
className="cursor-pointer rounded-full border-primary/20 bg-primary/5 text-primary hover:border-primary/40 hover:bg-primary/15 text-xs"
|
||||
title={t.settings.skills.viewDetailAction}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
@@ -860,74 +940,193 @@ export function AgentCard({
|
||||
|
||||
const chatButton = (
|
||||
<Button
|
||||
variant={isList ? "default" : "outline"}
|
||||
size="sm"
|
||||
className={cn(isList ? "shrink-0" : "w-full")}
|
||||
onClick={handleChat}
|
||||
className={cn(
|
||||
isList
|
||||
? "shrink-0 rounded-xl bg-primary px-4 font-medium text-primary-foreground hover:bg-primary/90"
|
||||
: "h-11 w-full rounded-lg border-primary/35 bg-background font-medium text-primary shadow-none hover:border-primary/55 hover:bg-primary/5 dark:bg-slate-900",
|
||||
)}
|
||||
onClick={() => void handleChat()}
|
||||
>
|
||||
<MessageSquareIcon className="mr-1.5 h-3.5 w-3.5" />
|
||||
{t.agents.chat}
|
||||
{isList ? 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 px-2.5 py-1 text-xs font-normal text-primary hover:bg-primary/5 dark:bg-primary/15">
|
||||
<span className="mr-1.5 size-1.5 rounded-full bg-primary" />
|
||||
已发布
|
||||
</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>
|
||||
)}
|
||||
{onToggleHidden && (
|
||||
<DropdownMenuItem
|
||||
disabled={toggleHiddenPending}
|
||||
onSelect={() => void onToggleHidden(!agent.hidden)}
|
||||
>
|
||||
{agent.hidden ? <EyeIcon className="size-4" /> : <EyeOffIcon className="size-4" />}
|
||||
{agent.hidden ? "恢复展示" : "隐藏智能体"}
|
||||
</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={cn(
|
||||
"group flex min-w-0 flex-col transition-shadow hover:shadow-md",
|
||||
"group flex min-h-[300px] min-w-0 flex-col gap-0 overflow-hidden rounded-[5px] border-0 bg-gradient-to-br from-primary/[0.04] via-card to-card py-0 shadow-[0_2px_8px_rgba(15,23,42,0.06)] transition-[background-color,border-color,box-shadow] duration-200 hover:!shadow-[0_4px_14px_rgba(15,23,42,0.10)] dark:from-primary/[0.07] dark:via-card dark:to-card",
|
||||
(agent.featured_order != null || agent.is_pinned) && "ring-1 ring-primary/25",
|
||||
agent.hidden && "opacity-60",
|
||||
)}
|
||||
data-agent-guide="agent-card"
|
||||
>
|
||||
<CardHeader className="min-w-0 pb-2">
|
||||
<div className="flex min-w-0 items-start justify-between gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
|
||||
<div className="agent-avatar bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
||||
<BotIcon className="h-5 w-5" />
|
||||
<CardHeader className="min-w-0 gap-0 px-5 pb-2 pt-5">
|
||||
{(isPinned || agent.featured_order != null) && (
|
||||
<div className="mb-2 flex h-7 items-center justify-between">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
{isPinned && (
|
||||
<Badge className="border border-primary/20 bg-primary/5 px-2.5 py-1 text-xs font-medium text-primary hover:bg-primary/5 dark:border-primary/40 dark:bg-primary/15">
|
||||
<PinIcon className="mr-1 size-3.5 fill-current" />
|
||||
置顶
|
||||
</Badge>
|
||||
)}
|
||||
{agent.featured_order != null && (
|
||||
<Badge className="border border-primary/20 bg-primary/5 px-2.5 py-1 text-xs font-medium text-primary hover:bg-primary/5 dark:border-primary/40 dark:bg-primary/15">
|
||||
<SparklesIcon className="mr-1 size-3.5 fill-current" />
|
||||
推荐
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
{cardActionsMenu}
|
||||
</div>
|
||||
)}
|
||||
{/* 标题与 logo 同行,避免头部留白过高 */}
|
||||
<div className="flex w-full items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<AgentBrandIcon size="lg" className="shrink-0" />
|
||||
<CardTitle
|
||||
className="block w-full min-w-0 overflow-hidden text-base text-ellipsis whitespace-nowrap"
|
||||
className="min-w-0 flex-1 overflow-hidden text-[17px] 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.model && (
|
||||
<Badge variant="secondary" className="mt-0.5 text-xs">
|
||||
{desensitize(agent.model)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap items-center justify-end gap-1">
|
||||
{statusBadges}
|
||||
</div>
|
||||
{!isPinned && agent.featured_order == null && cardActionsMenu}
|
||||
</div>
|
||||
{agent.description && (
|
||||
<CardDescription className="mt-2 line-clamp-2 text-sm">
|
||||
<CardDescription className="mt-2 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>}
|
||||
{(agent.tags?.length ?? 0) > 0 && (
|
||||
<div className="mt-2.5">
|
||||
<TagChipList tags={agent.tags!} />
|
||||
</div>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
{(agent.tags?.length ?? 0) > 0 && (
|
||||
<CardContent className="pt-0 pb-2">
|
||||
<TagChipList tags={agent.tags!} />
|
||||
</CardContent>
|
||||
)}
|
||||
|
||||
{hasSkillsOrTools && (
|
||||
<CardContent className="pt-0 pb-2">
|
||||
<CardContent className="px-5 pb-2 pt-0">
|
||||
<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}
|
||||
<CardFooter className="mt-auto flex flex-col items-stretch gap-4 px-5 pb-4 pt-2">
|
||||
<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}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{chatButton}
|
||||
</CardFooter>
|
||||
</Card>
|
||||
@@ -936,14 +1135,14 @@ export function AgentCard({
|
||||
const listLayout = (
|
||||
<div
|
||||
className={cn(
|
||||
"group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]",
|
||||
"group flex min-w-0 items-center gap-3 rounded-[5px] border-0 p-2.5 shadow-[0_2px_8px_rgba(15,23,42,0.06)] transition-shadow hover:shadow-[0_4px_14px_rgba(15,23,42,0.10)]",
|
||||
"bg-gradient-to-br from-primary/[0.04] via-card to-card dark:from-primary/[0.07] dark:via-card dark:to-card",
|
||||
agent.is_pinned && "ring-1 ring-primary/25",
|
||||
agent.hidden && "opacity-60",
|
||||
)}
|
||||
data-agent-guide="agent-card"
|
||||
>
|
||||
<div className="agent-avatar bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
||||
<BotIcon className="h-5 w-5" />
|
||||
</div>
|
||||
<AgentBrandIcon size="md" className="agent-avatar" />
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
@@ -1040,6 +1239,19 @@ export function AgentCard({
|
||||
onChange={setEditCommonQuestions}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3 rounded-md border p-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium">使用模型追加提示词</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
默认开启。关闭后,该智能体的问答不会附加管理员为所选模型设置的全局提示词。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={editModelPromptSuffixEnabled}
|
||||
onCheckedChange={setEditModelPromptSuffixEnabled}
|
||||
aria-label="使用模型追加提示词"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3 rounded-md border p-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium">会商技能识别强化</p>
|
||||
@@ -1120,6 +1332,7 @@ export function AgentCard({
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/* <AgentChatLinkFields value={editChatLink} onChange={setEditChatLink} /> */}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"use client";
|
||||
|
||||
import { PlusIcon, XIcon } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import type { AgentChatLink, AgentChatRouteParam } from "@/core/agents/types";
|
||||
import { emptyAgentChatLink } from "@/core/agents/types";
|
||||
import {
|
||||
APP_THEME_COLORS,
|
||||
LOGIN_SOURCE_OPTIONS,
|
||||
parseThemeMap,
|
||||
stringifyThemeMap,
|
||||
} from "@/strategy-components/lib/light-app";
|
||||
|
||||
function newParam(): AgentChatRouteParam {
|
||||
return {
|
||||
key: "",
|
||||
paramType: "login",
|
||||
source: "access_token",
|
||||
customValue: "",
|
||||
themeValue: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function AgentChatLinkFields({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: AgentChatLink;
|
||||
onChange: (next: AgentChatLink) => void;
|
||||
}) {
|
||||
const link = value ?? emptyAgentChatLink();
|
||||
|
||||
function patch(partial: Partial<AgentChatLink>) {
|
||||
onChange({ ...link, ...partial });
|
||||
}
|
||||
|
||||
function patchParam(index: number, partial: Partial<AgentChatRouteParam>) {
|
||||
patch({
|
||||
route_params: link.route_params.map((param, i) =>
|
||||
i === index ? { ...param, ...partial } : param,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3 rounded-md border p-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium">对话跳转</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
配置后,智能体管理里的「对话」按钮会打开这个地址。留空则仍进入本系统问答。
|
||||
</p>
|
||||
</div>
|
||||
<Input
|
||||
value={link.url}
|
||||
onChange={(event) => patch({ url: event.currentTarget.value })}
|
||||
placeholder="https://... ,或以 / 开头的站内路径"
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<p className="text-muted-foreground text-xs">打开方式</p>
|
||||
<Select
|
||||
value={link.open_mode}
|
||||
onValueChange={(next) => patch({ open_mode: next === "self" ? "self" : "blank" })}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="blank">新窗口</SelectItem>
|
||||
<SelectItem value="self">当前窗口</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium">路由参数</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
点击「对话」时拼到地址后面。登录参数取当前登录信息,主题参数跟随当前主题。
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => patch({ route_params: [...link.route_params, newParam()] })}
|
||||
>
|
||||
<PlusIcon className="h-3.5 w-3.5" />
|
||||
添加
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{link.route_params.length === 0 ? (
|
||||
<p className="text-muted-foreground rounded-md border border-dashed px-3 py-3 text-center text-xs">
|
||||
暂无路由参数
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{link.route_params.map((param, index) => {
|
||||
const themeMap = param.paramType === "theme" ? parseThemeMap(param.themeValue) : {};
|
||||
return (
|
||||
<div key={index} className="space-y-2 rounded-md border p-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={param.key}
|
||||
onChange={(event) => patchParam(index, { key: event.currentTarget.value })}
|
||||
placeholder="参数名"
|
||||
className="h-8 font-mono text-xs"
|
||||
/>
|
||||
<Select
|
||||
value={param.paramType}
|
||||
onValueChange={(next) =>
|
||||
patchParam(index, {
|
||||
paramType: next === "theme" ? "theme" : "login",
|
||||
source: next === "login" ? param.source || "access_token" : null,
|
||||
themeValue:
|
||||
next === "theme"
|
||||
? param.themeValue || stringifyThemeMap({})
|
||||
: null,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-[120px] shrink-0">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="login">登录参数</SelectItem>
|
||||
<SelectItem value="theme">主题参数</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
onClick={() =>
|
||||
patch({
|
||||
route_params: link.route_params.filter((_, i) => i !== index),
|
||||
})
|
||||
}
|
||||
title="移除参数"
|
||||
>
|
||||
<XIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{param.paramType === "login" && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
value={param.source || "access_token"}
|
||||
onValueChange={(next) => patchParam(index, { source: next })}
|
||||
>
|
||||
<SelectTrigger className="h-8 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) =>
|
||||
patchParam(index, { customValue: event.currentTarget.value })
|
||||
}
|
||||
placeholder="自定义值"
|
||||
className="h-8 w-[140px] text-xs"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{param.paramType === "theme" && (
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-muted-foreground text-[11px]">
|
||||
各系统主题色跳转时传给目标地址的值
|
||||
</p>
|
||||
{APP_THEME_COLORS.map((color) => (
|
||||
<div key={color.key} className="flex items-center gap-2">
|
||||
<span className="flex w-[72px] shrink-0 items-center gap-1.5 text-xs">
|
||||
<span
|
||||
className="h-2.5 w-2.5 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: color.dot }}
|
||||
/>
|
||||
{color.label}
|
||||
</span>
|
||||
<Input
|
||||
value={themeMap[color.key] ?? color.key}
|
||||
onChange={(event) =>
|
||||
patchParam(index, {
|
||||
themeValue: stringifyThemeMap({
|
||||
...themeMap,
|
||||
[color.key]: event.currentTarget.value,
|
||||
}),
|
||||
})
|
||||
}
|
||||
className="h-7 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
import Link from "next/link";
|
||||
import { useParams, usePathname, useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { agentColor } from "@/components/workspace/agent-icon-color";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
CheckIcon,
|
||||
DatabaseIcon,
|
||||
GlobeIcon,
|
||||
GripVertical,
|
||||
InfoIcon,
|
||||
// Link2Icon,
|
||||
Loader2Icon,
|
||||
LockIcon,
|
||||
MessageCircleQuestionIcon,
|
||||
@@ -22,9 +24,19 @@ import {
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent as ReactKeyboardEvent,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { confirmAction, toast } from "@/core/ui/feedback";
|
||||
|
||||
// import { AgentChatLinkFields } from "@/components/workspace/agents/agent-chat-link-fields";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -59,9 +71,16 @@ import {
|
||||
useSetAgentFeatured,
|
||||
useUpdateAgent,
|
||||
type Agent,
|
||||
type AgentChatLink,
|
||||
type AgentQuestion,
|
||||
type UpdateAgentRequest,
|
||||
} from "@/core/agents";
|
||||
import {
|
||||
agentChatLinksEqual,
|
||||
canonicalAgentChatLink,
|
||||
isAllowedAgentChatUrl,
|
||||
} from "@/core/agents/chat-link";
|
||||
import { emptyAgentChatLink } from "@/core/agents/types";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||
import { isAgentSkillCandidate } from "@/core/skills";
|
||||
@@ -70,6 +89,30 @@ import { usePublishSquares } from "@/core/system-settings/hooks";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const AGENT_DETAIL_WIDTH_STORAGE_KEY = "workspace:agent-detail-panel-width";
|
||||
const AGENT_DETAIL_MIN_WIDTH = 280;
|
||||
const AGENT_DETAIL_DEFAULT_WIDTH = 360;
|
||||
const AGENT_DETAIL_MAX_WIDTH = 640;
|
||||
const AGENT_DETAIL_KEYBOARD_STEP = 16;
|
||||
|
||||
function readStoredAgentDetailWidth(): number {
|
||||
if (typeof window === "undefined") return AGENT_DETAIL_DEFAULT_WIDTH;
|
||||
const raw = window.localStorage.getItem(AGENT_DETAIL_WIDTH_STORAGE_KEY);
|
||||
if (!raw) return AGENT_DETAIL_DEFAULT_WIDTH;
|
||||
const parsed = Number(raw);
|
||||
return Number.isFinite(parsed)
|
||||
? Math.min(AGENT_DETAIL_MAX_WIDTH, Math.max(AGENT_DETAIL_MIN_WIDTH, Math.round(parsed)))
|
||||
: AGENT_DETAIL_DEFAULT_WIDTH;
|
||||
}
|
||||
|
||||
function maximumAgentDetailWidth(): number {
|
||||
const viewportBound = Math.max(
|
||||
AGENT_DETAIL_MIN_WIDTH,
|
||||
window.innerWidth - 520,
|
||||
);
|
||||
return Math.min(AGENT_DETAIL_MAX_WIDTH, viewportBound);
|
||||
}
|
||||
|
||||
|
||||
/** Local edit-mode draft — committed in one `updateAgent` call on 保存. */
|
||||
interface AgentDraft {
|
||||
@@ -81,9 +124,11 @@ interface AgentDraft {
|
||||
published: boolean;
|
||||
featured: boolean;
|
||||
templateName: string;
|
||||
modelPromptSuffixEnabled: boolean;
|
||||
/** 会商席位「技能识别强化」开关。 */
|
||||
seatSkillDirective: boolean;
|
||||
knowledgeBaseIds: string[];
|
||||
chatLink: AgentChatLink;
|
||||
}
|
||||
|
||||
function draftFromAgent(agent: Agent): AgentDraft {
|
||||
@@ -96,8 +141,10 @@ function draftFromAgent(agent: Agent): AgentDraft {
|
||||
published: agent.published,
|
||||
featured: agent.featured_order != null,
|
||||
templateName: agent.template_name ?? "",
|
||||
modelPromptSuffixEnabled: agent.model_prompt_suffix_enabled ?? true,
|
||||
seatSkillDirective: agent.seat_skill_directive ?? false,
|
||||
knowledgeBaseIds: agent.llmwiki_knowledge_base_ids ?? [],
|
||||
chatLink: agent.chat_link ?? emptyAgentChatLink(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -115,7 +162,7 @@ function Section({
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className={cn("bg-card/60 rounded-xl border p-4", className)}>
|
||||
<section className={cn("agent-detail-section bg-card/60 rounded-xl border p-4", className)}>
|
||||
<div className="mb-3 flex items-center justify-between gap-2">
|
||||
<h4 className="text-foreground flex items-center gap-1.5 text-sm font-semibold">
|
||||
{icon}
|
||||
@@ -212,6 +259,109 @@ export function AgentDetailPanel({
|
||||
if (collapsedProp === undefined) setInternalCollapsed(next);
|
||||
onCollapsedChange?.(next);
|
||||
};
|
||||
// 智能体问答页的右侧信息栏可拖宽。宽度记在本面板,不走对话/预览那条分隔条。
|
||||
const [panelWidth, setPanelWidth] = useState(readStoredAgentDetailWidth);
|
||||
const [isResizingPanel, setIsResizingPanel] = useState(false);
|
||||
const panelResizeStart = useRef<{ x: number; width: number } | null>(null);
|
||||
const latestPanelWidth = useRef(panelWidth);
|
||||
const bodyStyleBeforeResize = useRef<{ cursor: string; userSelect: string } | null>(null);
|
||||
|
||||
const constrainPanelWidth = useCallback(
|
||||
(width: number) =>
|
||||
Math.min(
|
||||
maximumAgentDetailWidth(),
|
||||
Math.max(AGENT_DETAIL_MIN_WIDTH, Math.round(width)),
|
||||
),
|
||||
[],
|
||||
);
|
||||
|
||||
const setAndPersistPanelWidth = useCallback(
|
||||
(width: number, persist = false) => {
|
||||
const next = constrainPanelWidth(width);
|
||||
latestPanelWidth.current = next;
|
||||
setPanelWidth(next);
|
||||
if (persist) {
|
||||
window.localStorage.setItem(AGENT_DETAIL_WIDTH_STORAGE_KEY, String(next));
|
||||
}
|
||||
},
|
||||
[constrainPanelWidth],
|
||||
);
|
||||
|
||||
const finishPanelResize = useCallback(() => {
|
||||
const previousBodyStyle = bodyStyleBeforeResize.current;
|
||||
if (previousBodyStyle) {
|
||||
document.body.style.cursor = previousBodyStyle.cursor;
|
||||
document.body.style.userSelect = previousBodyStyle.userSelect;
|
||||
bodyStyleBeforeResize.current = null;
|
||||
}
|
||||
panelResizeStart.current = null;
|
||||
setIsResizingPanel(false);
|
||||
window.localStorage.setItem(
|
||||
AGENT_DETAIL_WIDTH_STORAGE_KEY,
|
||||
String(latestPanelWidth.current),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const handlePanelResizeStart = useCallback(
|
||||
(event: ReactPointerEvent<HTMLElement>) => {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
const width = constrainPanelWidth(latestPanelWidth.current);
|
||||
latestPanelWidth.current = width;
|
||||
panelResizeStart.current = { x: event.clientX, width };
|
||||
bodyStyleBeforeResize.current = {
|
||||
cursor: document.body.style.cursor,
|
||||
userSelect: document.body.style.userSelect,
|
||||
};
|
||||
document.body.style.cursor = "col-resize";
|
||||
document.body.style.userSelect = "none";
|
||||
setIsResizingPanel(true);
|
||||
},
|
||||
[constrainPanelWidth],
|
||||
);
|
||||
|
||||
const handlePanelResizeMove = useCallback(
|
||||
(event: ReactPointerEvent<HTMLElement>) => {
|
||||
if (!panelResizeStart.current || event.buttons !== 1) return;
|
||||
// 面板在右侧:向左拖变宽,向右拖变窄。
|
||||
setAndPersistPanelWidth(
|
||||
panelResizeStart.current.width - (event.clientX - panelResizeStart.current.x),
|
||||
);
|
||||
},
|
||||
[setAndPersistPanelWidth],
|
||||
);
|
||||
|
||||
const handlePanelResizeEnd = useCallback(
|
||||
(event: ReactPointerEvent<HTMLElement>) => {
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
if (!panelResizeStart.current) return;
|
||||
finishPanelResize();
|
||||
},
|
||||
[finishPanelResize],
|
||||
);
|
||||
|
||||
const handlePanelResizeKeyDown = useCallback(
|
||||
(event: ReactKeyboardEvent<HTMLElement>) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault();
|
||||
setAndPersistPanelWidth(latestPanelWidth.current + AGENT_DETAIL_KEYBOARD_STEP, true);
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault();
|
||||
setAndPersistPanelWidth(latestPanelWidth.current - AGENT_DETAIL_KEYBOARD_STEP, true);
|
||||
} else if (event.key === "Home") {
|
||||
event.preventDefault();
|
||||
setAndPersistPanelWidth(AGENT_DETAIL_MIN_WIDTH, true);
|
||||
} else if (event.key === "End") {
|
||||
event.preventDefault();
|
||||
setAndPersistPanelWidth(maximumAgentDetailWidth(), true);
|
||||
}
|
||||
},
|
||||
[setAndPersistPanelWidth],
|
||||
);
|
||||
const [mobileOpen, setMobileOpen] = useState(false);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState<AgentDraft | null>(null);
|
||||
@@ -367,8 +517,22 @@ export function AgentDetailPanel({
|
||||
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
|
||||
if (draft.templateName.trim() !== (agent.template_name ?? ""))
|
||||
request.template_name = draft.templateName.trim();
|
||||
if (draft.modelPromptSuffixEnabled !== (agent.model_prompt_suffix_enabled ?? true))
|
||||
request.model_prompt_suffix_enabled = draft.modelPromptSuffixEnabled;
|
||||
if (draft.seatSkillDirective !== (agent.seat_skill_directive ?? false))
|
||||
request.seat_skill_directive = draft.seatSkillDirective;
|
||||
const nextChatLink = canonicalAgentChatLink(draft.chatLink);
|
||||
if (nextChatLink && !isAllowedAgentChatUrl(nextChatLink.url)) {
|
||||
toast.error("对话链接只支持 http(s) 地址,或以 /、#/ 开头的站内路径");
|
||||
return;
|
||||
}
|
||||
if (draft.chatLink.route_params.some((param) => !param.key.trim()) && nextChatLink) {
|
||||
toast.error("路由参数键名不可为空");
|
||||
return;
|
||||
}
|
||||
if (!agentChatLinksEqual(nextChatLink, agent.chat_link)) {
|
||||
request.chat_link = nextChatLink;
|
||||
}
|
||||
if (
|
||||
JSON.stringify(draft.knowledgeBaseIds) !==
|
||||
JSON.stringify(agent.llmwiki_knowledge_base_ids ?? [])
|
||||
@@ -417,7 +581,7 @@ export function AgentDetailPanel({
|
||||
setPublishPickerOpen(true);
|
||||
return;
|
||||
}
|
||||
if (!warnIfAccountSwitched()) {
|
||||
if (!(await warnIfAccountSwitched())) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -435,19 +599,23 @@ export function AgentDetailPanel({
|
||||
|
||||
// 发布以实时 token 执行。会话中途账号被切换(常见于另一标签页登录了别的账号)时
|
||||
// 先弹确认,避免误以本人之外的账号执行发布。返回 false = 用户取消。
|
||||
function warnIfAccountSwitched(): boolean {
|
||||
function warnIfAccountSwitched(): boolean | Promise<boolean> {
|
||||
if (!live.switched) {
|
||||
return true;
|
||||
}
|
||||
return window.confirm(
|
||||
return confirmAction(
|
||||
`当前登录账号已从「${live.mountDisplayName}」切换为「${live.displayName}」。\n` +
|
||||
`本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。\n\n仍要继续吗?`,
|
||||
`本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。`,
|
||||
{
|
||||
title: "登录账号已切换",
|
||||
confirmText: "继续发布",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function handlePublishToSquare(squareId: string) {
|
||||
if (!agent) return;
|
||||
if (!warnIfAccountSwitched()) {
|
||||
if (!(await warnIfAccountSwitched())) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -598,7 +766,7 @@ export function AgentDetailPanel({
|
||||
) : (
|
||||
<div className="space-y-4 px-4 py-4">
|
||||
{/* ── Identity / 基础信息 ─────────────────────────────────────────── */}
|
||||
<section className="bg-card/60 rounded-xl border p-4">
|
||||
<section className="agent-detail-section agent-detail-identity bg-card/60 rounded-xl border p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="agent-avatar bg-primary/10 ring-primary/15 flex size-12 shrink-0 items-center justify-center rounded-2xl ring-1">
|
||||
{avatarSrc ? (
|
||||
@@ -619,7 +787,7 @@ export function AgentDetailPanel({
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="truncate text-base font-bold"
|
||||
className="agent-detail-name truncate text-base font-bold"
|
||||
title={displayName}
|
||||
>
|
||||
{displayName}
|
||||
@@ -654,7 +822,7 @@ export function AgentDetailPanel({
|
||||
className="min-h-16 text-sm"
|
||||
/>
|
||||
) : agent.description ? (
|
||||
<p className="text-muted-foreground text-sm leading-relaxed">
|
||||
<p className="agent-detail-description text-muted-foreground text-sm leading-relaxed">
|
||||
{desensitize(agent.description)}
|
||||
</p>
|
||||
) : (
|
||||
@@ -663,6 +831,13 @@ export function AgentDetailPanel({
|
||||
</div>
|
||||
|
||||
{/* 入库模板名 — view mode shows a hint row when configured. */}
|
||||
{/* {!editing && agent.chat_link?.url?.trim() && (
|
||||
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
|
||||
<Link2Icon className="size-3 shrink-0" />
|
||||
对话跳转:{agent.chat_link.open_mode === "self" ? "当前窗口" : "新窗口"}
|
||||
</div>
|
||||
)} */}
|
||||
|
||||
{!editing && agent.template_name?.trim() && (
|
||||
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
|
||||
<UploadCloudIcon className="size-3 shrink-0" />
|
||||
@@ -702,6 +877,21 @@ export function AgentDetailPanel({
|
||||
}
|
||||
variant="panel"
|
||||
/>
|
||||
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
|
||||
<div className="pr-3">
|
||||
<p className="text-sm font-medium">使用模型追加提示词</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
默认开启。关闭后,该智能体的问答不会附加管理员为所选模型设置的全局提示词。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={draft.modelPromptSuffixEnabled}
|
||||
onCheckedChange={(checked) =>
|
||||
setDraft({ ...draft, modelPromptSuffixEnabled: checked })
|
||||
}
|
||||
aria-label="使用模型追加提示词"
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
|
||||
<div className="pr-3">
|
||||
<p className="text-sm font-medium">会商技能识别强化</p>
|
||||
@@ -806,7 +996,7 @@ export function AgentDetailPanel({
|
||||
<button
|
||||
type="button"
|
||||
onClick={beginEdit}
|
||||
className="text-muted-foreground hover:text-foreground hover:border-border w-full rounded-lg border border-dashed px-3 py-4 text-center text-xs transition-colors"
|
||||
className="agent-detail-empty-add text-muted-foreground hover:text-foreground hover:border-border w-full rounded-lg border border-dashed px-3 py-4 text-center text-xs transition-colors"
|
||||
>
|
||||
<PlusIcon className="mr-1 inline size-3.5 align-[-2px]" />
|
||||
添加常用问题
|
||||
@@ -818,7 +1008,7 @@ export function AgentDetailPanel({
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className="border-border/60 bg-background/60 rounded-xl border p-2"
|
||||
className="agent-detail-question-item border-border/60 bg-background/60 rounded-xl border p-2"
|
||||
>
|
||||
{isEditingThis ? (
|
||||
<div className="space-y-2">
|
||||
@@ -948,6 +1138,13 @@ export function AgentDetailPanel({
|
||||
/>
|
||||
</Section>
|
||||
|
||||
{/* {editing && draft && (
|
||||
<AgentChatLinkFields
|
||||
value={draft.chatLink}
|
||||
onChange={(chatLink) => setDraft({ ...draft, chatLink })}
|
||||
/>
|
||||
)} */}
|
||||
|
||||
{/* ── 技能列表下方插槽(8BF 产物提交 position 等)────────────────── */}
|
||||
{belowSkillsSlot}
|
||||
|
||||
@@ -989,11 +1186,17 @@ export function AgentDetailPanel({
|
||||
header「新对话」按钮右侧。 */
|
||||
<div
|
||||
className={cn(
|
||||
"hidden h-full shrink-0 overflow-hidden transition-[width] duration-300 ease-in-out lg:block",
|
||||
collapsed ? "w-0" : "w-[360px]",
|
||||
"relative hidden h-full shrink-0 lg:block",
|
||||
isResizingPanel ? "transition-none" : "transition-[width] duration-300 ease-in-out",
|
||||
collapsed && "pointer-events-none",
|
||||
)}
|
||||
style={{ width: collapsed ? 0 : panelWidth }}
|
||||
>
|
||||
<div className="h-full overflow-hidden">
|
||||
<aside
|
||||
className="bg-card/40 flex h-full flex-col border-l"
|
||||
style={{ width: panelWidth }}
|
||||
>
|
||||
<aside className="bg-card/40 flex h-full w-[360px] flex-col border-l">
|
||||
{panelChrome(
|
||||
<Tooltip content="收起">
|
||||
<Button
|
||||
@@ -1009,6 +1212,39 @@ export function AgentDetailPanel({
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<div className="group/detail-edge absolute inset-y-0 -left-1 z-30 w-8 cursor-default">
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="调整智能体信息宽度"
|
||||
aria-valuenow={panelWidth}
|
||||
aria-valuemin={AGENT_DETAIL_MIN_WIDTH}
|
||||
aria-valuemax={AGENT_DETAIL_MAX_WIDTH}
|
||||
tabIndex={0}
|
||||
title="拖拽调整智能体信息宽度"
|
||||
className="absolute top-1/2 left-1 z-30 flex h-16 w-10 -translate-x-1/2 -translate-y-1/2 cursor-col-resize touch-none items-center justify-center outline-none"
|
||||
onPointerDown={handlePanelResizeStart}
|
||||
onPointerMove={handlePanelResizeMove}
|
||||
onPointerUp={handlePanelResizeEnd}
|
||||
onPointerCancel={handlePanelResizeEnd}
|
||||
onKeyDown={handlePanelResizeKeyDown}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"bg-border pointer-events-none z-10 flex h-8 w-4 items-center justify-center rounded-sm border shadow-sm transition-opacity",
|
||||
isResizingPanel
|
||||
? "opacity-100"
|
||||
: "opacity-0 group-hover/detail-edge:opacity-100 group-focus-within/detail-edge:opacity-100",
|
||||
)}
|
||||
>
|
||||
<GripVertical className="size-3.5" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : collapsed ? (
|
||||
<div className="hidden shrink-0 items-start border-l px-2 pt-3 lg:flex">
|
||||
<div className="flex items-center gap-1">
|
||||
|
||||
@@ -3,22 +3,30 @@
|
||||
import { ArrowDownUpIcon, BotIcon, Compass, Loader2, LockIcon, PlusIcon, RefreshCwIcon, ShieldIcon, XIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Pagination } from "@/components/ui/pagination";
|
||||
import { Pagination as TPagination } from "tdesign-react";
|
||||
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 { getStoredAuth } from "@/core/auth";
|
||||
import { useAgentsPaginated, usePrivateAgentsPaginated, useSyncAgentDirectory } from "@/core/agents";
|
||||
import { useLocalSettings } from "@/core/settings";
|
||||
import { resolveAgentGridLayout } from "@/core/settings/agent-grid";
|
||||
import { useAppearanceSettings } from "@/core/system-settings/hooks";
|
||||
import type { Agent, AgentSort } from "@/core/agents";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { useRouteBase } from "@/core/route-base";
|
||||
import { isSentimentAgentVisible } from "@/core/sentiment-agent/config";
|
||||
import { usePrivateSquareStatus, usePublishSquares, useViewMode } from "@/core/system-settings/hooks";
|
||||
import {
|
||||
usePageDescriptionsSettings,
|
||||
usePrivateSquareStatus,
|
||||
usePublishSquares,
|
||||
useViewMode,
|
||||
} from "@/core/system-settings/hooks";
|
||||
import {
|
||||
WX_RESTRICTED_TAB_DEFAULT_SQUARE,
|
||||
WX_RESTRICTED_TAB_NANJING_DB,
|
||||
@@ -51,6 +59,8 @@ export function AgentGallery({
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
const routeBase = useRouteBase();
|
||||
const pageDescriptions = usePageDescriptionsSettings();
|
||||
const pageDescription = pageDescriptions.data?.agents;
|
||||
const sentimentAgentVisible = isSentimentAgentVisible();
|
||||
// 「内置智能体」筛选仅管理员可见(后端 scope=builtin 也做了 admin 闸门兜底)。
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
@@ -257,10 +267,20 @@ export function AgentGallery({
|
||||
const handlePublisherClick = (p: { id: string; label: string }) =>
|
||||
setPublisher(p);
|
||||
|
||||
// 置顶的智能体始终排在最前(后端按创建/更新时间分页,这里做展示层重排)。
|
||||
const pinFirst = (items: Agent[]) =>
|
||||
[...items].sort(
|
||||
(a, b) => Number(b.is_pinned ?? false) - Number(a.is_pinned ?? false),
|
||||
);
|
||||
|
||||
const [gridSettings] = useLocalSettings();
|
||||
const { data: gridAppearance } = useAppearanceSettings();
|
||||
const agentGrid = resolveAgentGridLayout(gridSettings.display, gridAppearance);
|
||||
|
||||
const renderGrid = (list: Agent[]) =>
|
||||
viewMode === "list" ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{list.map((agent) => (
|
||||
{pinFirst(list).map((agent) => (
|
||||
<AgentCard
|
||||
key={agent.id}
|
||||
agent={agent}
|
||||
@@ -269,9 +289,29 @@ export function AgentGallery({
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : agentGrid.adaptive ? (
|
||||
<div
|
||||
className="grid w-full grid-cols-4 gap-4 min-[3072px]:grid-cols-5"
|
||||
data-agent-grid="adaptive"
|
||||
>
|
||||
{pinFirst(list).map((agent) => (
|
||||
<AgentCard
|
||||
key={agent.id}
|
||||
agent={agent}
|
||||
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) => (
|
||||
<div
|
||||
className="grid w-full gap-4"
|
||||
data-agent-grid="fixed"
|
||||
data-agent-grid-columns={agentGrid.columns}
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${agentGrid.columns}, minmax(0, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{pinFirst(list).map((agent) => (
|
||||
<AgentCard
|
||||
key={agent.id}
|
||||
agent={agent}
|
||||
@@ -332,11 +372,12 @@ export function AgentGallery({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Pagination
|
||||
page={pages[tab] ?? 1}
|
||||
<TPagination
|
||||
current={pages[tab] ?? 1}
|
||||
pageSize={PAGE_SIZE}
|
||||
total={total}
|
||||
onPageChange={(p) => setTabPage(tab, p)}
|
||||
showJumper
|
||||
onChange={(pageInfo) => setTabPage(tab, pageInfo.current)}
|
||||
className="pt-2"
|
||||
/>
|
||||
</div>
|
||||
@@ -360,7 +401,7 @@ export function AgentGallery({
|
||||
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"
|
||||
onClick={handleNewAgent}
|
||||
>
|
||||
<PlusIcon className="mr-1.5 h-4 w-4" />
|
||||
<PlusIcon className="mr-2.5 h-4 w-4" />
|
||||
{t.agents.newAgent}
|
||||
</Button>
|
||||
)}
|
||||
@@ -451,20 +492,32 @@ export function AgentGallery({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex size-full min-h-0 flex-col">
|
||||
<div className="flex size-full min-h-0 flex-col bg-muted/40">
|
||||
{/* Page header */}
|
||||
<div className="flex items-center justify-between border-b px-6 py-4">
|
||||
<div className="relative overflow-hidden border-b border-border/60 bg-card px-6 py-4">
|
||||
{/* 顶部主题色渐变:自上而下淡出(跟随换肤) */}
|
||||
<div
|
||||
className="pointer-events-none absolute inset-x-0 top-0 h-24 bg-gradient-to-b from-primary/[0.09] via-primary/[0.03] to-transparent"
|
||||
aria-hidden
|
||||
/>
|
||||
<div className="relative flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold">{t.agents.title}</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="h-4 w-[3px] rounded-full bg-primary" aria-hidden />
|
||||
<h1 className="text-xl font-semibold">
|
||||
{pageDescription?.title || t.agents.title}
|
||||
</h1>
|
||||
</div>
|
||||
<p className="text-muted-foreground mt-0.5 text-sm">
|
||||
{t.agents.description}
|
||||
{pageDescription?.description || t.agents.description}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="outline"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-9 gap-2.5 rounded-[5px] px-3 text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
title="扫描 .deer-flow/agents 目录,把目录里的智能体同步进列表"
|
||||
disabled={syncDirectory.isPending}
|
||||
onClick={() => {
|
||||
@@ -483,14 +536,15 @@ export function AgentGallery({
|
||||
}}
|
||||
>
|
||||
<RefreshCwIcon
|
||||
className={`mr-1.5 h-4 w-4 ${syncDirectory.isPending ? "animate-spin" : ""}`}
|
||||
className={`h-4 w-4 ${syncDirectory.isPending ? "animate-spin" : ""}`}
|
||||
/>
|
||||
{syncDirectory.isPending ? "扫描中…" : "重新扫描智能体目录"}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-9 rounded-[5px] px-3 text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
title="打开智能体广场视图"
|
||||
onClick={() => router.push(`${routeBase}/agents/plaza`)}
|
||||
>
|
||||
@@ -499,19 +553,24 @@ export function AgentGallery({
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
className="h-9 gap-2.5 rounded-[5px] px-3 text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
title="重新播放智能体使用引导"
|
||||
onClick={() => startAgentGuide("list")}
|
||||
>
|
||||
<Compass className="mr-1.5 h-4 w-4" />
|
||||
<Compass className="h-4 w-4" />
|
||||
使用引导
|
||||
</Button>
|
||||
<Button onClick={handleNewAgent} data-agent-guide="new-agent-btn">
|
||||
<PlusIcon className="mr-1.5 h-4 w-4" />
|
||||
<Button
|
||||
className="ml-1 h-9 gap-2.5 rounded-[5px] px-4 shadow-[0_2px_6px_rgba(193,18,31,0.25)] hover:shadow-[0_4px_12px_rgba(193,18,31,0.35)]"
|
||||
onClick={handleNewAgent}
|
||||
data-agent-guide="new-agent-btn"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
{t.agents.newAgent}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<Tabs
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { Bot, Loader2 } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
import { Select } from "tdesign-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -87,12 +87,12 @@ export function EnabledSkillList({
|
||||
<div
|
||||
key={name}
|
||||
className={cn(
|
||||
"group/skill bg-background/60 flex items-start gap-2.5 rounded-xl border p-2.5 transition-colors",
|
||||
"agent-skill-row group/skill bg-background/60 flex items-start gap-2.5 rounded-xl border p-2.5 transition-colors",
|
||||
onViewDetail && "hover:border-primary/40 hover:bg-accent/40",
|
||||
offline && "bg-muted/60 border-dashed dark:bg-[#071D36]",
|
||||
)}
|
||||
>
|
||||
<div className="bg-primary/10 text-primary flex size-8 shrink-0 items-center justify-center rounded-lg text-sm font-semibold">
|
||||
<div className="agent-skill-avatar bg-primary/10 text-primary flex size-8 shrink-0 items-center justify-center rounded-lg text-sm font-semibold">
|
||||
{skill ? skillInitial(skill) : "?"}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -43,7 +43,7 @@ const triggerToneClass = (tone: AppearanceControlTone) =>
|
||||
tone === "banner-dark"
|
||||
? "text-slate-400 hover:bg-slate-800/50 hover:text-slate-400"
|
||||
: tone === "banner-light"
|
||||
? "text-white hover:bg-[var(--brand-950)] hover:text-white active:bg-[#8a0618]"
|
||||
? "text-white hover:bg-[var(--brand-900)] hover:text-white active:bg-[var(--brand-950)]"
|
||||
: tone === "banner-custom"
|
||||
? "text-[var(--navigation-foreground)] hover:bg-white/20 hover:text-[var(--navigation-foreground)] active:bg-white/30"
|
||||
: "text-muted-foreground hover:bg-muted hover:text-foreground";
|
||||
|
||||
@@ -21,7 +21,7 @@ import { useParams } from "next/navigation";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
import { defaultUrlTransform } from "react-markdown";
|
||||
|
||||
import {
|
||||
@@ -362,11 +362,27 @@ export function ArtifactFileDetail({
|
||||
isMock,
|
||||
writeFileInFlight,
|
||||
]);
|
||||
/** write_file 流式预览走 tool args 文本;图片等二进制产物始终走 artifacts API;
|
||||
* 圆桌结束后可编辑的 md(editVirtualMarkdown)亦回到真实 API(可加载 + PATCH 保存)。 */
|
||||
const isVirtualHtmlArtifact = useMemo(() => {
|
||||
if (!isWriteFileVirtual) return false;
|
||||
return (writeFileLanguageHint ?? checkCodeFile(filepath).language) === "html";
|
||||
}, [filepath, isWriteFileVirtual, writeFileLanguageHint]);
|
||||
/** write_file 流式阶段走 tool args 文本;图片等二进制产物始终走 artifacts API;
|
||||
* HTML 写完后也必须切回真实文件,因为后续渲染脚本可能在同一路径覆盖最终数据;
|
||||
* 圆桌结束后可编辑的 md(editVirtualMarkdown)同样回到真实 API(可加载 + PATCH 保存)。 */
|
||||
const useWriteFileStreaming = useMemo(() => {
|
||||
return isWriteFileVirtual && !isImageFile(filepath) && !editVirtualMarkdown;
|
||||
}, [filepath, isWriteFileVirtual, editVirtualMarkdown]);
|
||||
return (
|
||||
isWriteFileVirtual &&
|
||||
!isImageFile(filepath) &&
|
||||
!editVirtualMarkdown &&
|
||||
(!isVirtualHtmlArtifact || writeFileInFlight)
|
||||
);
|
||||
}, [
|
||||
filepath,
|
||||
isWriteFileVirtual,
|
||||
editVirtualMarkdown,
|
||||
isVirtualHtmlArtifact,
|
||||
writeFileInFlight,
|
||||
]);
|
||||
const { isCodeFile, language } = useMemo(() => {
|
||||
if (useWriteFileStreaming) {
|
||||
let nextLanguage =
|
||||
@@ -398,11 +414,10 @@ export function ArtifactFileDetail({
|
||||
refetch: refetchArtifactContent,
|
||||
} = useArtifactContent({
|
||||
threadId,
|
||||
// editVirtualMarkdown:用解码后的真实路径走 artifacts API(而非 write-file 虚拟
|
||||
// URL),这样保存后 useUpdateArtifactContent 写入的查询缓存才能命中,编辑内容
|
||||
// 不会被旧的内存 stub 值覆盖回退。
|
||||
filepath:
|
||||
editVirtualMarkdown || !isWriteFileVirtual ? filepath : filepathFromProps,
|
||||
// 流式结束后统一用解码后的真实路径走 artifacts API(而非 write-file 虚拟
|
||||
// URL)。HTML 可能已被后续渲染脚本覆盖;Markdown 保存后的查询缓存也需要
|
||||
// 命中真实路径,不能继续读取旧的内存 stub。
|
||||
filepath: useWriteFileStreaming ? filepathFromProps : filepath,
|
||||
enabled: isCodeFile && !useWriteFileStreaming,
|
||||
});
|
||||
|
||||
@@ -458,9 +473,10 @@ export function ArtifactFileDetail({
|
||||
const sandboxDisplayText = useMemo(() => {
|
||||
const raw = displayContent ?? "";
|
||||
if (disableDesensitize) return raw;
|
||||
if (language === "html") return raw;
|
||||
if (streamPerfEnabled && isLiveStreaming) return raw;
|
||||
return desensitize(raw);
|
||||
}, [disableDesensitize, displayContent, isLiveStreaming, streamPerfEnabled]);
|
||||
}, [disableDesensitize, displayContent, isLiveStreaming, language, streamPerfEnabled]);
|
||||
const artifactContentPending =
|
||||
isCodeFile &&
|
||||
!useWriteFileStreaming &&
|
||||
@@ -1690,8 +1706,16 @@ export function ArtifactFileDetail({
|
||||
)}
|
||||
<ArtifactAction
|
||||
icon={DownloadIcon}
|
||||
label={t.common.download}
|
||||
tooltip={t.common.download}
|
||||
label={
|
||||
language === "html" && !useWriteFileStreaming && !onDownloadClick
|
||||
? "下载离线包"
|
||||
: t.common.download
|
||||
}
|
||||
tooltip={
|
||||
language === "html" && !useWriteFileStreaming && !onDownloadClick
|
||||
? "下载包含网页运行库的 ZIP 离线包"
|
||||
: t.common.download
|
||||
}
|
||||
onClick={async () => {
|
||||
if (onDownloadClick) {
|
||||
onDownloadClick();
|
||||
@@ -2205,6 +2229,7 @@ export function ArtifactFilePreview({
|
||||
if (language === "html") {
|
||||
return (
|
||||
<iframe
|
||||
key={htmlPreviewUrl ?? "html-preview"}
|
||||
className={cn(
|
||||
"size-full bg-white",
|
||||
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { DownloadIcon, LoaderIcon, PackageIcon } from "lucide-react";
|
||||
import { useCallback, useState, type ReactNode } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -130,7 +130,9 @@ export function ArtifactFileList({
|
||||
) : (
|
||||
<DownloadIcon className="size-4" />
|
||||
)}
|
||||
{t.common.download}
|
||||
{!onDownloadArtifact && /\.(?:html?|xhtml)$/i.test(getFileName(file))
|
||||
? "下载离线包"
|
||||
: t.common.download}
|
||||
</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { useSidebarSafe } from "@/components/ui/sidebar";
|
||||
import { env } from "@/env";
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { AlertCircleIcon, Loader2Icon, PackageIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import historyChatAvatar from "@/assets/img/chat-history-avatar.png";
|
||||
import historyCloudAvatar from "@/assets/img/chat-history-cloud-avatar.png";
|
||||
import historyDeviceAvatar from "@/assets/img/chat-history-device-avatar.png";
|
||||
|
||||
const CHAT_HISTORY_AVATARS = [
|
||||
historyChatAvatar,
|
||||
historyCloudAvatar,
|
||||
historyDeviceAvatar,
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Conversations do not carry an avatar in persisted state. Derive one from
|
||||
* the stable thread id, so each history row keeps its mark across refreshes
|
||||
* while the list uses varied purple, green, and blue artwork.
|
||||
*/
|
||||
export function historyAvatarForThread(threadId: string): string {
|
||||
let hash = 0;
|
||||
for (let index = 0; index < threadId.length; index += 1) {
|
||||
hash = (hash * 31 + threadId.charCodeAt(index)) | 0;
|
||||
}
|
||||
return CHAT_HISTORY_AVATARS[(hash >>> 0) % CHAT_HISTORY_AVATARS.length]!;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Message } from "@langchain/langgraph-sdk";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { FilesIcon, XIcon } from "lucide-react";
|
||||
import { FilesIcon, GripVertical, XIcon } from "lucide-react";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { GroupImperativeHandle } from "react-resizable-panels";
|
||||
@@ -859,13 +859,48 @@ const ChatBox: React.FC<{
|
||||
</ResizablePanel>
|
||||
<ResizableHandle
|
||||
id={`${resizableIdBase}-separator`}
|
||||
onPointerDownCapture={(event) => {
|
||||
const target = event.target;
|
||||
// The library starts a drag from any pointerdown inside the separator.
|
||||
// Hovering the edge only reveals the grip; the grip is the only drag target.
|
||||
if (!(target instanceof Element) || !target.closest("[data-resize-grip]")) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
"opacity-33 hover:opacity-100",
|
||||
stackArtifactPanel &&
|
||||
"h-px w-full after:inset-x-0 after:inset-y-auto after:top-1/2 after:h-4 after:w-full after:-translate-x-0 after:-translate-y-1/2 after:cursor-row-resize",
|
||||
"group/split z-20",
|
||||
stackArtifactPanel
|
||||
? "h-px w-full opacity-33 hover:opacity-100 after:inset-x-0 after:inset-y-auto after:top-1/2 after:h-4 after:w-full after:-translate-x-0 after:-translate-y-1/2 after:cursor-row-resize"
|
||||
: // The default hit box is a full-height strip and covers both the chat
|
||||
// scrollbar and the panel on the right. The separator itself stays
|
||||
// inert; only the short center grip starts a drag.
|
||||
"pointer-events-none after:pointer-events-none after:w-0",
|
||||
!sidePanelOpen && "pointer-events-none opacity-0",
|
||||
)}
|
||||
>
|
||||
{!stackArtifactPanel && (
|
||||
<>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"absolute inset-y-0 left-0 z-20 w-8 cursor-default",
|
||||
sidePanelOpen ? "pointer-events-auto" : "pointer-events-none",
|
||||
)}
|
||||
/>
|
||||
<span
|
||||
data-resize-grip=""
|
||||
className={cn(
|
||||
"absolute top-1/2 left-1/2 z-30 flex h-16 w-10 -translate-x-1/2 -translate-y-1/2 items-center justify-center",
|
||||
sidePanelOpen ? "pointer-events-auto cursor-col-resize" : "pointer-events-none",
|
||||
)}
|
||||
>
|
||||
<span className="bg-border z-10 flex h-8 w-4 items-center justify-center rounded-sm border shadow-sm opacity-0 transition-opacity group-hover/split:opacity-100 group-focus-visible/split:opacity-100">
|
||||
<GripVertical className="size-3.5" />
|
||||
</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</ResizableHandle>
|
||||
<ResizablePanel
|
||||
className={cn(
|
||||
"bg-background transition-all duration-300 ease-in-out",
|
||||
|
||||
@@ -1,26 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { getWelcomeBrandAsset } from "@/core/branding/brand-assets";
|
||||
import { AppBrandImage } from "@/core/branding/app-brand-image";
|
||||
import { useDisplayDesensitizer } from "@/core/sensitive-words/use-display-desensitizer";
|
||||
import {
|
||||
useAppSystemName,
|
||||
usePageDescriptionsSettings,
|
||||
} from "@/core/system-settings/hooks";
|
||||
import type { GeneralQaPageDescription } from "@/core/system-settings/api";
|
||||
import { readRuntimeFlag } from "@/env";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useDisplayDesensitizer } from "@/core/sensitive-words/use-display-desensitizer";
|
||||
|
||||
/**
|
||||
* 紧凑模式(正常 App)新对话落地页的品牌欢迎块 —— 按 CM-assistant 参考图重画。
|
||||
* 仅展示,无交互。配色走主题 token(--workspace-brand / --primary),红/蓝/深蓝主题自适应。
|
||||
* 非紧凑模式仍用 <Welcome/>,本组件不参与。
|
||||
*/
|
||||
export function CompactWelcome({ className }: { className?: string }) {
|
||||
export function CompactWelcome({
|
||||
className,
|
||||
pageDescription,
|
||||
}: {
|
||||
className?: string;
|
||||
/** The actual interface mode is resolved by ChatPage. */
|
||||
pageDescription?: GeneralQaPageDescription;
|
||||
}) {
|
||||
const desensitizeText = useDisplayDesensitizer();
|
||||
const { theme } = useTheme();
|
||||
const brandTheme = theme;
|
||||
const welcomeLogo = getWelcomeBrandAsset(brandTheme);
|
||||
const [failedWelcomeLogo, setFailedWelcomeLogo] = useState<string | null>(null);
|
||||
const shouldShowWelcomeLogo =
|
||||
Boolean(welcomeLogo) && failedWelcomeLogo !== welcomeLogo;
|
||||
const systemName = useAppSystemName("");
|
||||
const { data: pageDescriptions } = usePageDescriptionsSettings();
|
||||
const configured = pageDescription ?? pageDescriptions?.general_qa.compact;
|
||||
const welcomeTitle =
|
||||
configured?.welcome_title ||
|
||||
(systemName ? `欢迎使用${systemName}` : "欢迎使用CM助手");
|
||||
const welcomeDescription =
|
||||
configured?.welcome_description ||
|
||||
"基于先进深度推理模型,为您提供高效的市场分析、专业报告撰写、调研设计与协同脑暴支持。";
|
||||
const isWelcomeLogoVisible = readRuntimeFlag("VITE_WELCOME_LOGO_VISIBLE");
|
||||
|
||||
return (
|
||||
@@ -30,7 +44,7 @@ export function CompactWelcome({ className }: { className?: string }) {
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* CM logo:浅底圆环 + 主色渐变圆角方块 */}
|
||||
{/* 与全量模式共用同一套系统 Logo;简洁模式仅保留欢迎区的展示容器。 */}
|
||||
{/* Controlled by VITE_WELCOME_LOGO_VISIBLE in runtime-config.js. */}
|
||||
{isWelcomeLogoVisible && (
|
||||
<div
|
||||
@@ -42,35 +56,15 @@ export function CompactWelcome({ className }: { className?: string }) {
|
||||
"1px solid rgb(var(--legacy-workspace-brand-rgb) / 12%)",
|
||||
}}
|
||||
>
|
||||
{shouldShowWelcomeLogo && welcomeLogo ? (
|
||||
<img
|
||||
src={welcomeLogo}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className="size-16 object-contain"
|
||||
onError={() => setFailedWelcomeLogo(welcomeLogo)}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="flex size-14 items-center justify-center rounded-2xl shadow-md"
|
||||
style={{
|
||||
backgroundImage:
|
||||
"linear-gradient(to top right, var(--workspace-brand), var(--brand-200))",
|
||||
}}
|
||||
>
|
||||
<span className="text-2xl font-black tracking-wide text-white italic">
|
||||
{desensitizeText("CM")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<AppBrandImage theme={theme} className="size-16 object-contain" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h1 className="flex items-center justify-center text-2xl font-bold tracking-tight text-foreground/90">
|
||||
{desensitizeText("欢迎使用CM助手")}
|
||||
{desensitizeText(welcomeTitle)}
|
||||
</h1>
|
||||
<p className="text-muted-foreground mx-auto mt-2 max-w-sm text-xs leading-relaxed">
|
||||
基于先进深度推理模型,为您提供高效的市场分析、专业报告撰写、调研设计与协同脑暴支持。
|
||||
{desensitizeText(welcomeDescription)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import { Download } from "lucide-react";
|
||||
import { useCallback } from "react";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { consumerThreadMaterialsDownloadUrl } from "@/core/threads/consumer-thread-values-client";
|
||||
|
||||
import { useThread } from "./messages/context";
|
||||
import { Tooltip } from "./tooltip";
|
||||
|
||||
const MATERIALS_DOWNLOAD_FRAME_ID = "consumer-materials-download-frame";
|
||||
const MATERIALS_DOWNLOAD_FRAME_NAME = "consumer-materials-download-frame";
|
||||
|
||||
function submitDownloadWithoutNavigation(downloadUrl: string): void {
|
||||
let frame = document.getElementById(
|
||||
MATERIALS_DOWNLOAD_FRAME_ID,
|
||||
) as HTMLIFrameElement | null;
|
||||
if (!frame) {
|
||||
frame = document.createElement("iframe");
|
||||
frame.id = MATERIALS_DOWNLOAD_FRAME_ID;
|
||||
frame.name = MATERIALS_DOWNLOAD_FRAME_NAME;
|
||||
frame.title = "资料下载";
|
||||
frame.setAttribute("aria-hidden", "true");
|
||||
frame.style.display = "none";
|
||||
document.body.appendChild(frame);
|
||||
}
|
||||
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = downloadUrl;
|
||||
anchor.target = frame.name;
|
||||
anchor.download = "";
|
||||
anchor.rel = "noopener";
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
}
|
||||
|
||||
/** Downloads the Consumer-maintained source-material workbook for this chat. */
|
||||
export function ConsumerMaterialsExportTrigger({
|
||||
threadId,
|
||||
}: {
|
||||
threadId: string;
|
||||
}) {
|
||||
const { thread } = useThread();
|
||||
const downloadUrl = consumerThreadMaterialsDownloadUrl(threadId);
|
||||
const handleDownload = useCallback(() => {
|
||||
if (!downloadUrl) return;
|
||||
|
||||
// The Consumer URL may be cross-origin, which makes browsers ignore an
|
||||
// anchor's `download` hint and navigate the current document. Route the
|
||||
// native download request through a persistent hidden frame instead, so
|
||||
// the chat never leaves its current route and no extra window is opened.
|
||||
submitDownloadWithoutNavigation(downloadUrl);
|
||||
toast.message("正在准备资料下载…");
|
||||
}, [downloadUrl]);
|
||||
|
||||
if (thread.messages.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Tooltip
|
||||
content={downloadUrl ? "导出本对话检索资料" : "未配置资料导出服务"}
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
variant="ghost"
|
||||
disabled={!downloadUrl}
|
||||
onClick={handleDownload}
|
||||
>
|
||||
<Download className="size-4" aria-hidden="true" />
|
||||
导出资料
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import { useCallback, useState, type ComponentProps } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { copyTextToClipboard } from "@/core/clipboard";
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -162,7 +162,7 @@ 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="agent-composer-tool text-muted-foreground hover:text-foreground hover:bg-muted/70 h-7 w-7 shrink-0 rounded-full"
|
||||
title="管理常用提示词"
|
||||
aria-label="管理常用提示词"
|
||||
onClick={() => setManageOpen(true)}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { Download, FileJson, FileText, FileType2 } from "lucide-react";
|
||||
import { useCallback } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
FileJson,
|
||||
FileText,
|
||||
Loader2,
|
||||
MessageSquare,
|
||||
MoreHorizontal,
|
||||
Pencil,
|
||||
Pin,
|
||||
@@ -39,7 +38,7 @@ import Link from "next/link";
|
||||
import { useParams, usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
import { Select } from "tdesign-react";
|
||||
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
@@ -106,10 +105,12 @@ import { cn } from "@/lib/utils";
|
||||
import { strategyProjectWorkbenchPath } from "@/strategy-selection/project-routes";
|
||||
import {
|
||||
mergeRecentWorkspaceItems,
|
||||
type RecentWorkspaceItem,
|
||||
useRecentStrategyProjects,
|
||||
} from "@/strategy-selection/recent-projects";
|
||||
|
||||
import { agentColor } from "./agent-icon-color";
|
||||
import { historyAvatarForThread } from "./chat-history-avatar";
|
||||
import { SidebarCollapseButton } from "./workspace-header";
|
||||
|
||||
// 智能体图标配色(按 id 稳定散列、分主题)抽到共享模块 ./agent-icon-color,
|
||||
@@ -378,7 +379,6 @@ export function GeneralQaSidebar({
|
||||
// 未搜索时与旧版一致:最多展示 10 条
|
||||
return q ? list : list.slice(0, 10);
|
||||
}, [query, recentItems, t.pages.newChat]);
|
||||
|
||||
const handleNewChatClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.button === 1) return;
|
||||
event.preventDefault();
|
||||
@@ -451,6 +451,176 @@ export function GeneralQaSidebar({
|
||||
|
||||
const isStatic = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
|
||||
|
||||
const renderRecentHistoryItem = (item: RecentWorkspaceItem) => {
|
||||
if (item.kind === "strategy-project") {
|
||||
const { project } = item;
|
||||
const href = strategyProjectWorkbenchPath(
|
||||
"/page/strategy/qa/projects",
|
||||
project.id,
|
||||
);
|
||||
const isActive = href === pathname;
|
||||
return (
|
||||
<div
|
||||
key={`strategy-project:${project.id}`}
|
||||
className="group/item relative flex items-center"
|
||||
>
|
||||
<Link
|
||||
href={href}
|
||||
title={desensitize(project.title)}
|
||||
className={cn(
|
||||
"gq-history-item relative flex min-h-11 min-w-0 flex-1 items-center gap-2 overflow-hidden rounded-xl px-2.5 py-1.5 text-[13px] outline-none transition-[background-color,color,box-shadow] duration-150 focus-visible:ring-2 focus-visible:ring-primary/55",
|
||||
isActive
|
||||
? "gq-history-item--active bg-primary/[0.11] font-medium text-primary shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/22%),0_2px_8px_rgb(var(--legacy-primary-rgb)/7%)] hover:bg-primary/[0.15]"
|
||||
: "text-foreground/80 hover:bg-muted/80 hover:text-foreground hover:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/9%)]",
|
||||
)}
|
||||
>
|
||||
<MyProjectThreadIcon type="strategy" />
|
||||
<span className="min-w-0 flex-1 flex flex-col items-start gap-0.5">
|
||||
<span className="block w-full truncate">{desensitize(project.title)}</span>
|
||||
<MyProjectThreadBadge
|
||||
className="mr-3 max-w-[calc(100%_-_0.75rem)]"
|
||||
projectName={project.title}
|
||||
type="strategy"
|
||||
/>
|
||||
</span>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { thread } = item;
|
||||
const href = buildFullChatNavigationPath(pathForThread(thread), currentSearch);
|
||||
const isActive = href === pathname;
|
||||
const isBoot = isBootstrapThread(thread);
|
||||
const projectInfo = myProjectConversationInfoOfThread(
|
||||
thread,
|
||||
projectThreadNames,
|
||||
);
|
||||
const pinned = isThreadPinned(thread);
|
||||
const favorited = isThreadFavorite(thread);
|
||||
const title = desensitize(titleOfThread(thread, t.pages.newChat));
|
||||
|
||||
return (
|
||||
<div key={`thread:${thread.thread_id}`} className="group/item relative flex items-center">
|
||||
<Link
|
||||
href={href}
|
||||
title={title}
|
||||
className={cn(
|
||||
"gq-history-item relative flex h-9 min-w-0 flex-1 items-center gap-2 overflow-hidden rounded-xl px-2.5 pr-8 text-[13px] outline-none transition-[background-color,color,box-shadow] duration-150 focus-visible:ring-2 focus-visible:ring-primary/55",
|
||||
projectInfo && "h-auto min-h-11 py-1.5",
|
||||
isActive
|
||||
? "gq-history-item--active bg-primary/[0.11] font-medium text-primary shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/22%),0_2px_8px_rgb(var(--legacy-primary-rgb)/7%)] hover:bg-primary/[0.15]"
|
||||
: "text-foreground/80 hover:bg-muted/80 hover:text-foreground hover:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/9%)]",
|
||||
)}
|
||||
>
|
||||
{isBoot ? (
|
||||
<Bot
|
||||
className={cn(
|
||||
"size-3.5 shrink-0",
|
||||
isActive ? "text-primary" : "text-muted-foreground/70",
|
||||
)}
|
||||
aria-label="智能体创建会话"
|
||||
/>
|
||||
) : projectInfo ? (
|
||||
<MyProjectThreadIcon type={projectInfo.type} />
|
||||
) : (
|
||||
<img
|
||||
src={historyAvatarForThread(thread.thread_id)}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
draggable={false}
|
||||
className="size-5 shrink-0 object-contain"
|
||||
/>
|
||||
)}
|
||||
{pinned && (
|
||||
<Pin className="size-3 shrink-0 text-muted-foreground/70" aria-label="已置顶" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"min-w-0 flex-1",
|
||||
projectInfo && "flex flex-col items-start gap-0.5",
|
||||
)}
|
||||
>
|
||||
<span className="block w-full truncate">{title}</span>
|
||||
{projectInfo && (
|
||||
<MyProjectThreadBadge
|
||||
className="mr-3 max-w-[calc(100%_-_0.75rem)]"
|
||||
projectName={projectInfo.projectName}
|
||||
type={projectInfo.type}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</Link>
|
||||
{!isStatic && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${t.common.more}:${title}`}
|
||||
className="absolute right-1 flex size-7 items-center justify-center rounded-lg text-muted-foreground opacity-0 outline-none transition-[opacity,background-color,color] duration-150 hover:bg-background hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-primary/55 group-hover/item:opacity-100 group-focus-within/item:opacity-100 data-[state=open]:bg-background data-[state=open]:text-foreground data-[state=open]:opacity-100"
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-48 rounded-lg" side="right" align="start">
|
||||
<DropdownMenuItem
|
||||
onSelect={() =>
|
||||
handleRenameClick(thread.thread_id, titleOfThread(thread, t.pages.newChat))
|
||||
}
|
||||
>
|
||||
<Pencil className="text-muted-foreground" />
|
||||
<span>{t.common.rename}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => togglePin(thread.thread_id, !pinned)}>
|
||||
{pinned ? (
|
||||
<PinOff className="text-muted-foreground" />
|
||||
) : (
|
||||
<Pin className="text-muted-foreground" />
|
||||
)}
|
||||
<span>{pinned ? t.common.unpin : t.common.pin}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => toggleFavorite(thread.thread_id, !favorited)}>
|
||||
<Star
|
||||
className={
|
||||
favorited
|
||||
? "fill-amber-400 text-amber-400"
|
||||
: "text-muted-foreground"
|
||||
}
|
||||
/>
|
||||
<span>{favorited ? t.common.unfavorite : t.common.favorite}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => setShareThreadId(thread.thread_id)}>
|
||||
<Share2 className="text-muted-foreground" />
|
||||
<span>{t.common.share}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<Download className="text-muted-foreground" />
|
||||
<span>{t.common.export}</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent>
|
||||
<DropdownMenuItem onSelect={() => handleExport(thread, "markdown")}>
|
||||
<FileText className="text-muted-foreground" />
|
||||
<span>{t.common.exportAsMarkdown}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => handleExport(thread, "json")}>
|
||||
<FileJson className="text-muted-foreground" />
|
||||
<span>{t.common.exportAsJSON}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={() => handleDelete(thread.thread_id)}>
|
||||
<Trash2 className="text-muted-foreground" />
|
||||
<span>{t.common.delete}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
// 背景走 sidebar token(浅主题=白、浅蓝主题=浅蓝);深蓝(.dark)主题下由 gq-sidebar
|
||||
// 改为「深蓝主题底图 + 半透明蓝罩」玻璃面板(见 globals.css),与右侧 workspace-chat-bg
|
||||
@@ -710,191 +880,7 @@ export function GeneralQaSidebar({
|
||||
{query ? "没有匹配的会话" : t.chats.noChats}
|
||||
</div>
|
||||
) : (
|
||||
filteredRecentItems.map((item) => {
|
||||
if (item.kind === "strategy-project") {
|
||||
const { project } = item;
|
||||
const href = strategyProjectWorkbenchPath(
|
||||
"/page/strategy/qa/projects",
|
||||
project.id,
|
||||
);
|
||||
const isActive = href === pathname;
|
||||
return (
|
||||
<div
|
||||
key={`strategy-project:${project.id}`}
|
||||
className="group/item relative flex items-center"
|
||||
>
|
||||
<Link
|
||||
href={href}
|
||||
className={cn(
|
||||
"gq-history-item relative flex min-h-12 min-w-0 flex-1 items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] transition-colors",
|
||||
isActive
|
||||
? "gq-history-item--active border border-primary/40 bg-primary/5 font-medium text-primary"
|
||||
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<MyProjectThreadIcon type="strategy" />
|
||||
<span className="min-w-0 flex-1 flex flex-col items-start gap-0.5">
|
||||
<span className="w-full truncate">
|
||||
{desensitize(project.title)}
|
||||
</span>
|
||||
<MyProjectThreadBadge
|
||||
className="mr-4 max-w-[calc(100%_-_1rem)]"
|
||||
projectName={project.title}
|
||||
type="strategy"
|
||||
/>
|
||||
</span>
|
||||
{isActive && (
|
||||
<span className="absolute top-1/2 right-1 h-5 w-1 -translate-y-1/2 rounded-full bg-primary" />
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { thread } = item;
|
||||
const href = buildFullChatNavigationPath(
|
||||
pathForThread(thread),
|
||||
currentSearch,
|
||||
);
|
||||
const isActive = href === pathname;
|
||||
const isBoot = isBootstrapThread(thread);
|
||||
const projectInfo = myProjectConversationInfoOfThread(
|
||||
thread,
|
||||
projectThreadNames,
|
||||
);
|
||||
const pinned = isThreadPinned(thread);
|
||||
const favorited = isThreadFavorite(thread);
|
||||
return (
|
||||
<div
|
||||
key={`thread:${thread.thread_id}`}
|
||||
className="group/item relative flex items-center"
|
||||
>
|
||||
<Link
|
||||
href={href}
|
||||
className={cn(
|
||||
"gq-history-item relative flex h-9 min-w-0 flex-1 items-center gap-2 rounded-lg px-2.5 text-[13px] transition-colors",
|
||||
projectInfo && "h-auto min-h-12 py-1.5",
|
||||
isActive
|
||||
? "gq-history-item--active border border-primary/40 bg-primary/5 font-medium text-primary"
|
||||
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{isBoot ? (
|
||||
<Bot
|
||||
className={cn(
|
||||
"size-3.5 shrink-0",
|
||||
isActive ? "text-primary" : "text-muted-foreground/70",
|
||||
)}
|
||||
aria-label="智能体创建会话"
|
||||
/>
|
||||
) : projectInfo ? (
|
||||
<MyProjectThreadIcon type={projectInfo.type} />
|
||||
) : (
|
||||
<MessageSquare
|
||||
className={cn(
|
||||
"size-3.5 shrink-0",
|
||||
isActive ? "text-primary" : "text-muted-foreground/70",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{pinned && (
|
||||
<Pin className="size-3 shrink-0 text-muted-foreground/70" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"min-w-0 flex-1",
|
||||
projectInfo && "flex flex-col items-start gap-0.5",
|
||||
)}
|
||||
>
|
||||
<span className="w-full truncate">
|
||||
{desensitize(titleOfThread(thread, t.pages.newChat))}
|
||||
</span>
|
||||
{projectInfo && (
|
||||
<MyProjectThreadBadge
|
||||
className="mr-4 max-w-[calc(100%_-_1rem)]"
|
||||
projectName={projectInfo.projectName}
|
||||
type={projectInfo.type}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
{isActive && (
|
||||
<span className="absolute top-1/2 right-1 h-5 w-1 -translate-y-1/2 rounded-full bg-primary" />
|
||||
)}
|
||||
</Link>
|
||||
{!isStatic && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-1 flex size-6 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-background group-hover/item:opacity-100 data-[state=open]:opacity-100"
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
<span className="sr-only">{t.common.more}</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-48 rounded-lg" side="right" align="start">
|
||||
<DropdownMenuItem
|
||||
onSelect={() =>
|
||||
handleRenameClick(
|
||||
thread.thread_id,
|
||||
titleOfThread(thread, t.pages.newChat),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Pencil className="text-muted-foreground" />
|
||||
<span>{t.common.rename}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => togglePin(thread.thread_id, !pinned)}>
|
||||
{pinned ? (
|
||||
<PinOff className="text-muted-foreground" />
|
||||
) : (
|
||||
<Pin className="text-muted-foreground" />
|
||||
)}
|
||||
<span>{pinned ? t.common.unpin : t.common.pin}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onSelect={() => toggleFavorite(thread.thread_id, !favorited)}
|
||||
>
|
||||
<Star
|
||||
className={
|
||||
favorited
|
||||
? "fill-amber-400 text-amber-400"
|
||||
: "text-muted-foreground"
|
||||
}
|
||||
/>
|
||||
<span>{favorited ? t.common.unfavorite : t.common.favorite}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => setShareThreadId(thread.thread_id)}>
|
||||
<Share2 className="text-muted-foreground" />
|
||||
<span>{t.common.share}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<Download className="text-muted-foreground" />
|
||||
<span>{t.common.export}</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent>
|
||||
<DropdownMenuItem onSelect={() => handleExport(thread, "markdown")}>
|
||||
<FileText className="text-muted-foreground" />
|
||||
<span>{t.common.exportAsMarkdown}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => handleExport(thread, "json")}>
|
||||
<FileJson className="text-muted-foreground" />
|
||||
<span>{t.common.exportAsJSON}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={() => handleDelete(thread.thread_id)}>
|
||||
<Trash2 className="text-muted-foreground" />
|
||||
<span>{t.common.delete}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
filteredRecentItems.map(renderRecentHistoryItem)
|
||||
)}
|
||||
{!query && (
|
||||
<Link
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import type { ChatStatus } from "ai";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
import {
|
||||
BookMarkedIcon,
|
||||
BrainCircuitIcon,
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
type CSSProperties,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
|
||||
@@ -63,6 +64,7 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { composerMinHeightCss } from "@/core/settings/composer-width";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import {
|
||||
isDocumentRewriteActiveStage,
|
||||
@@ -138,10 +140,14 @@ export function InputBox({
|
||||
knowledgeRetrieval,
|
||||
knowledgeSuggestedQuestions = [],
|
||||
extraModels = [],
|
||||
placeholder,
|
||||
assistantId,
|
||||
hideAdminRecommendedQuestions,
|
||||
compact,
|
||||
mirrorLandingFrame = false,
|
||||
frameRadius = "default",
|
||||
hideContextTools,
|
||||
composerHeightPercent,
|
||||
...props
|
||||
}: Omit<ComponentProps<typeof PromptInput>, "onSubmit"> & {
|
||||
assistantId?: string | null;
|
||||
@@ -149,9 +155,21 @@ export function InputBox({
|
||||
/** 紧凑模式(正常 App)新对话落地态:去掉旋转彩边、用 CM 参考图的白卡输入框,
|
||||
* 并在推荐问题上方加「试试这些高频业务场景」标题。仅落地态生效,默认 false。 */
|
||||
compact?: boolean;
|
||||
/**
|
||||
* Reuse the non-compact new-chat visual frame for a conversation composer.
|
||||
* This changes only the border shell; conversation behavior remains intact.
|
||||
*/
|
||||
mirrorLandingFrame?: boolean;
|
||||
/** Visual-only radius variant for a mirrored landing frame. */
|
||||
frameRadius?: "default" | "tight";
|
||||
/** 隐藏输入框工具条上的「写作 / 参考文献」上下文开关按钮(任务深链工作区等
|
||||
* 受控场景用;文件/模型等其他按钮不受影响)。 */
|
||||
hideContextTools?: boolean;
|
||||
/**
|
||||
* Appearance height scale. 100 (or omitted) keeps the built-in min-height.
|
||||
* Other values scale the landing / compact-landing / conversation base.
|
||||
*/
|
||||
composerHeightPercent?: number;
|
||||
disabled?: boolean;
|
||||
context: Omit<
|
||||
AgentThreadContext,
|
||||
@@ -219,6 +237,8 @@ export function InputBox({
|
||||
knowledgeSuggestedQuestions?: string[];
|
||||
/** Page-scoped model choices implemented outside the DeerFlow model API. */
|
||||
extraModels?: Model[];
|
||||
/** Page-specific prompt. Omit to keep the localized product default. */
|
||||
placeholder?: string;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [localSettings, setLocalSettings] = useLocalSettings();
|
||||
@@ -706,6 +726,18 @@ export function InputBox({
|
||||
};
|
||||
}, [context.model_name, disabled, followupsEnabled, isMock, selectedSingleRoundRag, status, thread.messages, threadId]);
|
||||
|
||||
const composerMinHeight = composerMinHeightCss(
|
||||
composerHeightPercent ?? 100,
|
||||
compact ? "84px" : isNewThread ? "110px" : "4rem",
|
||||
);
|
||||
const composerHeightStyle: CSSProperties | undefined = composerMinHeight
|
||||
? {
|
||||
minHeight: composerMinHeight,
|
||||
maxHeight: `max(12rem, calc(${composerMinHeight} + 8rem))`,
|
||||
}
|
||||
: undefined;
|
||||
const usesGeminiFrame = !compact && (isNewThread || mirrorLandingFrame);
|
||||
|
||||
return (
|
||||
<div ref={promptRootRef} className="relative flex flex-col gap-6">
|
||||
{extraHeader && (
|
||||
@@ -722,7 +754,7 @@ export function InputBox({
|
||||
<button
|
||||
key={question}
|
||||
type="button"
|
||||
className="max-w-full rounded-full border border-primary/20 bg-primary/5 px-4 py-2 text-left text-sm text-foreground transition-colors hover:bg-primary/10"
|
||||
className="agent-suggested-chip max-w-full rounded-full border px-4 py-2 text-left text-sm text-foreground transition-colors"
|
||||
onClick={() => {
|
||||
fillPromptForEditing(question);
|
||||
}}
|
||||
@@ -798,23 +830,42 @@ export function InputBox({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className={cn(isNewThread && !compact && "gemini-gradient-border gemini-shadow")}>
|
||||
<div
|
||||
className={cn(
|
||||
usesGeminiFrame && "gemini-gradient-border gemini-shadow",
|
||||
// 对话态(含紧凑会话):文心一言式外壳 —— 空闲主题色浅边白卡,
|
||||
// 生成中主题色渐变流光描边(globals.css .composer-shell)。
|
||||
// 落地态(Gemini 彩灯)与紧凑落地白卡维持各自形态。
|
||||
!usesGeminiFrame &&
|
||||
!(compact && isNewThread) &&
|
||||
(composerStatus === "streaming"
|
||||
? "composer-shell composer-shell--streaming"
|
||||
: "composer-shell composer-shell--idle"),
|
||||
)}
|
||||
data-frame-radius={
|
||||
usesGeminiFrame && frameRadius !== "default" ? frameRadius : undefined
|
||||
}
|
||||
>
|
||||
<PromptInput
|
||||
style={
|
||||
composerMinHeight ? { minHeight: composerMinHeight } : undefined
|
||||
}
|
||||
className={cn(
|
||||
"transition-all duration-300 ease-out",
|
||||
// 紧凑落地态(CM 参考图):表单作为白卡,内部 input-group 透明无边框,
|
||||
// 避免双层描边;圆角对齐 2xl。
|
||||
// 内部 input-group:紧凑落地白卡与对话态外壳都去掉自带描边/底色,
|
||||
// 只保留外层一层描边(Gemini 落地态维持现状的双层结构不动)。
|
||||
compact && isNewThread
|
||||
? "*:data-[slot='input-group']:rounded-2xl *:data-[slot='input-group']:border-0 *:data-[slot='input-group']:bg-transparent *:data-[slot='input-group']:shadow-none"
|
||||
: "*:data-[slot='input-group']:rounded-3xl",
|
||||
: usesGeminiFrame
|
||||
? "*:data-[slot='input-group']:rounded-3xl"
|
||||
: "*:data-[slot='input-group']:rounded-3xl *:data-[slot='input-group']:border-0 *:data-[slot='input-group']:bg-transparent *:data-[slot='input-group']:shadow-none",
|
||||
// 紧凑落地态(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-[rgb(var(--legacy-primary-rgb)/35%)] focus-within:ring-4 focus-within:ring-[rgb(var(--legacy-primary-rgb)/5%)] focus-within:shadow-[0_10px_35px_rgb(var(--legacy-primary-rgb)/4%)] dark:border-slate-700 dark:bg-slate-800"
|
||||
: // landing 态:透明,让外层 gemini-gradient-border 提供白卡 + 旋转描边
|
||||
// 对话态:常规白卡 + 中性边框 + 轻阴影
|
||||
isNewThread
|
||||
? "rounded-3xl bg-transparent border-0 shadow-none ring-0"
|
||||
: "rounded-3xl bg-background border border-border shadow-sm transition-shadow hover:shadow-md focus-within:border-ring/40 focus-within:shadow-md focus-within:ring-1 focus-within:ring-ring/20 dark:bg-slate-800 dark:border-slate-700",
|
||||
: // 表单本体一律透明:落地态由外层 gemini-gradient-border 供白卡 +
|
||||
// 旋转彩边,对话态由外层 composer-shell 供边框/底色/阴影,
|
||||
// 避免双层描边。
|
||||
"rounded-3xl bg-transparent border-0 shadow-none ring-0",
|
||||
className,
|
||||
)}
|
||||
disabled={disabled}
|
||||
@@ -832,11 +883,14 @@ export function InputBox({
|
||||
<PromptInputTextarea
|
||||
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]",
|
||||
!composerMinHeight && isNewThread && "min-h-[110px]!",
|
||||
compact && "px-3 pt-3 pb-1 text-[14px]",
|
||||
compact && !composerMinHeight && "min-h-[84px]!",
|
||||
)}
|
||||
data-composer-height={composerMinHeight ? "" : undefined}
|
||||
style={composerHeightStyle}
|
||||
disabled={disabled}
|
||||
placeholder={t.inputBox.placeholder}
|
||||
placeholder={placeholder || t.inputBox.placeholder}
|
||||
autoFocus={autoFocus}
|
||||
defaultValue={initialValue}
|
||||
/>
|
||||
@@ -1219,6 +1273,7 @@ export function InputBox({
|
||||
</PromptInputActionMenuItem>
|
||||
</>
|
||||
)}
|
||||
{/* 多轮 RAG 问答选项暂时下线,需要恢复时取消下面注释即可
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
multiRoundRagActive
|
||||
@@ -1247,6 +1302,7 @@ export function InputBox({
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</PromptInputActionMenuItem>
|
||||
*/}
|
||||
</PromptInputActionMenu>
|
||||
</DropdownMenuGroup>
|
||||
</PromptInputActionMenuContent>
|
||||
@@ -1419,11 +1475,9 @@ export function InputBox({
|
||||
</ModelSelectorContent>
|
||||
</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",
|
||||
compact &&
|
||||
"size-7 rounded-lg border-0 bg-[var(--primary)] text-[var(--button-foreground,var(--primary-foreground))] hover:opacity-90 disabled:bg-muted disabled:text-muted-foreground/40 dark:bg-[var(--primary)] dark:border-0 dark:text-[var(--button-foreground,var(--primary-foreground))] dark:hover:opacity-90 dark:disabled:bg-muted",
|
||||
)}
|
||||
// 皮肤(主题色扁平渐变圆钮 / 流式低对比停止钮)统一由 globals.css 的
|
||||
// .agent-composer-send 提供,这里只保留紧凑落地档的小尺寸。
|
||||
className={cn(compact && "size-7")}
|
||||
disabled={disabled}
|
||||
onClick={(event) => {
|
||||
if (composerStatus !== "streaming") return;
|
||||
@@ -1432,7 +1486,6 @@ export function InputBox({
|
||||
event.preventDefault();
|
||||
handleStopCurrentGeneration();
|
||||
}}
|
||||
variant="outline"
|
||||
status={composerStatus}
|
||||
{...(documentRewriteActive
|
||||
? { "aria-label": "停止 AI 全文改写" }
|
||||
|
||||
@@ -1,102 +1,23 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { BookOpen /* , Database, SearchCheck */ } from "lucide-react";
|
||||
import { BookOpen } from "lucide-react";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
// import { canAccessAssistantKnowledge } from "@/core/llmwiki/assistant-knowledge-access-policy";
|
||||
// import {
|
||||
// useAssistantKnowledgeVisibility,
|
||||
// useUpdateAssistantKnowledgeVisibility,
|
||||
// } from "@/core/system-settings/hooks";
|
||||
import { useLlmWikiRuntime } from "@/strategy-components/api/llmwiki";
|
||||
import {
|
||||
loadOrdinaryKnowledgeLanding,
|
||||
saveOrdinaryKnowledgeLanding,
|
||||
type OrdinaryKnowledgeLanding,
|
||||
} from "@/core/system-settings/api";
|
||||
|
||||
const LANDING_KEY = ["system-settings", "ordinary-knowledge-landing"] as const;
|
||||
|
||||
export function useOrdinaryKnowledgeLanding(enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: LANDING_KEY,
|
||||
queryFn: ({ signal }) => loadOrdinaryKnowledgeLanding(signal),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
export const KNOWLEDGE_NORMAL_VIEW_VALUE = "normal";
|
||||
export const KNOWLEDGE_NORMAL_VIEW_SEARCH = `?view=${KNOWLEDGE_NORMAL_VIEW_VALUE}`;
|
||||
|
||||
export function KnowledgeProductNav() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const client = useQueryClient();
|
||||
// const assistantVisibility = useAssistantKnowledgeVisibility();
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const landing = useOrdinaryKnowledgeLanding(isAdmin);
|
||||
const saveLanding = useMutation({
|
||||
mutationFn: saveOrdinaryKnowledgeLanding,
|
||||
onSuccess: (mode) => { client.setQueryData(LANDING_KEY, mode); toast.success("普通知识库默认页面已更新"); },
|
||||
onError: (error) => toast.error(error.message),
|
||||
});
|
||||
const runtime = useLlmWikiRuntime();
|
||||
const normalAvailable = runtime.data?.provider === "weknora" && Boolean(runtime.data.api_base_url?.trim());
|
||||
// const assistantAllowed = canAccessAssistantKnowledge(
|
||||
// isAdmin,
|
||||
// assistantVisibility.isError ? undefined : assistantVisibility.data,
|
||||
// );
|
||||
// const saveAssistantVisibility = useUpdateAssistantKnowledgeVisibility();
|
||||
const retrievalDebug = location.pathname.includes("/knowledge/retrieval-debug");
|
||||
const assistant = location.pathname.includes("/knowledge/assistant");
|
||||
const ordinary = !assistant && !retrievalDebug;
|
||||
const ordinary = !location.pathname.includes("/knowledge/assistant") && !location.pathname.includes("/knowledge/retrieval-debug");
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2 border-b bg-card px-6 py-2">
|
||||
<Button size="sm" disabled={!normalAvailable} title={normalAvailable ? "普通知识库" : "管理员配置知识服务地址后可用"} variant={ordinary ? "secondary" : "ghost"} onClick={() => navigate(`/page/workspace/knowledge${KNOWLEDGE_NORMAL_VIEW_SEARCH}`)}>
|
||||
<BookOpen />普通知识库
|
||||
</Button>
|
||||
{/* 助手知识库、检索调试暂时隐藏,后续放开时去掉这段注释。
|
||||
{assistantAllowed && (
|
||||
<Button size="sm" variant={assistant ? "secondary" : "ghost"} onClick={() => navigate("/page/workspace/knowledge/assistant")}>
|
||||
<Database />助手知识库
|
||||
</Button>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Button size="sm" variant={retrievalDebug ? "secondary" : "ghost"} onClick={() => navigate("/page/workspace/knowledge/retrieval-debug")}>
|
||||
<SearchCheck />检索调试
|
||||
</Button>
|
||||
)}
|
||||
*/}
|
||||
{isAdmin && (
|
||||
<div className="ml-auto flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
普通知识库默认页面
|
||||
<Select disabled={landing.isLoading || saveLanding.isPending} value={landing.data ?? "wiki"} onValueChange={(value) => saveLanding.mutate(value as OrdinaryKnowledgeLanding)}>
|
||||
<SelectTrigger className="h-8 w-40" aria-label="普通知识库默认页面"><SelectValue /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="wiki">本系统 Wiki 索引</SelectItem><SelectItem value="weknora">知识库管理页面</SelectItem></SelectContent>
|
||||
</Select>
|
||||
{/* 助手知识库日常展示暂时隐藏,和上面两个入口一起放开。
|
||||
助手知识库日常展示
|
||||
<Select
|
||||
disabled={assistantVisibility.isLoading || saveAssistantVisibility.isPending}
|
||||
value={assistantVisibility.data === true ? "visible" : "hidden"}
|
||||
onValueChange={(value) =>
|
||||
saveAssistantVisibility.mutate(value === "visible", {
|
||||
onSuccess: (visible) => toast.success(visible ? "已向普通用户开放助手知识库" : "已隐藏普通用户的助手知识库"),
|
||||
onError: (error) => toast.error(error.message),
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-52" aria-label="助手知识库日常展示"><SelectValue /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="hidden">隐藏(仅管理员可用)</SelectItem><SelectItem value="visible">开放给普通用户</SelectItem></SelectContent>
|
||||
</Select>
|
||||
*/}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { BookMarked } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useKnowledgeActions } from "@/core/knowledge/hooks";
|
||||
|
||||
@@ -608,7 +608,7 @@ export function LlmWikiKnowledgeSelector({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(
|
||||
"h-8 max-w-52 gap-1.5 rounded-full border-0 bg-transparent px-2.5 text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground",
|
||||
"agent-composer-tool h-8 max-w-52 gap-1.5 rounded-full border-0 bg-transparent px-2.5 text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground",
|
||||
selectedCount > 0 && "bg-primary/8 text-primary hover:bg-primary/12 hover:text-primary",
|
||||
className,
|
||||
)}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
ThumbsUpIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Trash2Icon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
XCircleIcon,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ArtifactFileList } from "@/components/workspace/artifacts/artifact-file-list";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FileText, Loader2, MessagesSquare } from "lucide-react";
|
||||
import { useState, type ComponentProps } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -63,6 +63,10 @@ import { useLocalSettings } from "@/core/settings";
|
||||
import { useSkills } from "@/core/skills/hooks";
|
||||
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
|
||||
import { isInternalToolCallName } from "@/core/tools/visibility";
|
||||
import {
|
||||
extractInvokedSkillName,
|
||||
skillInvocationLabel,
|
||||
} from "@/core/tools/skill-invocation";
|
||||
import {
|
||||
applyInlineCitations,
|
||||
buildSkillDisplayMap,
|
||||
@@ -371,6 +375,10 @@ function ToolCall({
|
||||
ragModeEnabled?: boolean;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const invokedSkillName = extractInvokedSkillName(name, args);
|
||||
const invokedSkillLabel = invokedSkillName
|
||||
? skillInvocationLabel(invokedSkillName)
|
||||
: undefined;
|
||||
const displayMatch =
|
||||
result !== undefined && isDisplaySamplePayload(result)
|
||||
? null
|
||||
@@ -566,7 +574,9 @@ function ToolCall({
|
||||
} else if (name === "read_file") {
|
||||
let description: string | undefined = (args as { description: string })
|
||||
?.description;
|
||||
if (!description) {
|
||||
if (invokedSkillLabel) {
|
||||
description = invokedSkillLabel;
|
||||
} else if (!description) {
|
||||
description = t.toolCalls.readFile;
|
||||
}
|
||||
const { path } = args as { path: string; content: string };
|
||||
@@ -598,11 +608,10 @@ function ToolCall({
|
||||
/>
|
||||
);
|
||||
} else if (name === "bash") {
|
||||
const description: string | undefined = (args as { description: string })
|
||||
?.description;
|
||||
if (!description) {
|
||||
return t.toolCalls.executeCommand;
|
||||
}
|
||||
const description =
|
||||
invokedSkillLabel ||
|
||||
(args as { description?: string })?.description ||
|
||||
t.toolCalls.executeCommand;
|
||||
const command: string | undefined = (args as { command: string })?.command;
|
||||
return (
|
||||
<ChainOfThoughtStep
|
||||
@@ -653,7 +662,7 @@ function ToolCall({
|
||||
return (
|
||||
<ChainOfThoughtStep
|
||||
key={id}
|
||||
label={description ?? t.toolCalls.useTool(name)}
|
||||
label={invokedSkillLabel ?? description ?? t.toolCalls.useTool(name)}
|
||||
icon={WrenchIcon}
|
||||
></ChainOfThoughtStep>
|
||||
);
|
||||
|
||||
@@ -38,6 +38,7 @@ import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
|
||||
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
|
||||
import { useSkills } from "@/core/skills/hooks";
|
||||
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
|
||||
import { useRetryKeepPartialSettings } from "@/core/system-settings/hooks";
|
||||
import type { WeKnoraSourceTarget } from "@/core/llmwiki/source-links";
|
||||
import {
|
||||
buildSkillDisplayMap,
|
||||
@@ -489,6 +490,10 @@ export function MessageList({
|
||||
|
||||
const [settings] = useLocalSettings();
|
||||
const { data: citationDisplay } = useCitationDisplaySettings();
|
||||
// 「保留中间正文」管理员开关(默认开启):步骤条执行中吐出的正文不被清空,
|
||||
// 模型静默重试时已流出的半截正文同样保留(后者在 useAgentThread 里处理)。
|
||||
const { data: retryKeepPartialSettings } = useRetryKeepPartialSettings();
|
||||
const keepIntermediateText = retryKeepPartialSettings?.enabled ?? true;
|
||||
const referenceModeEntryEnabled =
|
||||
citationDisplay?.reference_mode_enabled ?? false;
|
||||
const knowledgeReferencesEnabled =
|
||||
@@ -748,7 +753,9 @@ export function MessageList({
|
||||
) : null}
|
||||
{(() => {
|
||||
let didRenderLiveKnowledgeRetrieval = false;
|
||||
const grouped = groupMessages(displayMessages, (group) => {
|
||||
const grouped = groupMessages(
|
||||
displayMessages,
|
||||
(group) => {
|
||||
if (group.type === "human" || group.type === "assistant") {
|
||||
const items = group.messages.map((msg) => {
|
||||
// 深度研究的报告摘要由独立 SSE 作业驱动;把它接入既有 assistant 流式状态,
|
||||
@@ -1189,7 +1196,7 @@ export function MessageList({
|
||||
{speakerShell ? speakerShell(group.messages, processingBody) : processingBody}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
}, { keepIntermediateText });
|
||||
const leftoverRewriteItems = documentRewriteItems.filter(
|
||||
(item) => item.source.kind !== "artifact" || item.operation !== "rewrite",
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ChevronDownIcon, DownloadIcon, EyeIcon, Loader2Icon } from "lucide-react";
|
||||
import { useContext, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -36,6 +36,11 @@ export function ModelNameSelect({
|
||||
title?: string;
|
||||
}) {
|
||||
const { models } = useModels();
|
||||
// 后端约定:配置顺序的第一个模型即默认对话模型(models[0])。
|
||||
const defaultModel = models[0];
|
||||
const defaultModelLabel = defaultModel
|
||||
? `${defaultModel.display_name || defaultModel.name}(默认)`
|
||||
: defaultLabel;
|
||||
return (
|
||||
<Select
|
||||
value={value ?? DEFAULT_VALUE}
|
||||
@@ -46,10 +51,10 @@ export function ModelNameSelect({
|
||||
className={cn("h-8 gap-1.5 text-xs", triggerClassName, className)}
|
||||
title={title}
|
||||
>
|
||||
<SelectValue placeholder={defaultLabel} />
|
||||
<SelectValue placeholder={defaultModelLabel} />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper" side="bottom" sideOffset={4}>
|
||||
<SelectItem value={DEFAULT_VALUE}>{defaultLabel}</SelectItem>
|
||||
<SelectItem value={DEFAULT_VALUE}>{defaultModelLabel}</SelectItem>
|
||||
{models.map((m) => (
|
||||
<SelectItem key={m.name} value={m.name}>
|
||||
{m.display_name || m.name}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
||||
@@ -27,21 +27,146 @@ const PANEL_GUTTER_MARGIN = 24;
|
||||
/** Questions needed before the navigator shows up at all. */
|
||||
const MIN_QUESTIONS = 2;
|
||||
const COLLAPSE_STORAGE_KEY = "deerflow.question-navigator.collapsed";
|
||||
/** Matches `scroll-mt-20` so the target sits below the overlay chat header. */
|
||||
const QUESTION_SCROLL_TOP_OFFSET = 80;
|
||||
/** Re-apply after the drawer overlay unmounts; StickToBottom may snap on resize. */
|
||||
const SHEET_SCROLL_RETRY_MS = 80;
|
||||
|
||||
function verticalOverflow(node: HTMLElement): string {
|
||||
const style = window.getComputedStyle(node);
|
||||
const overflowY = style.overflowY;
|
||||
if (overflowY && overflowY !== "visible") return overflowY;
|
||||
const parts = style.overflow.split(" ");
|
||||
return parts[1] || parts[0] || "";
|
||||
}
|
||||
|
||||
function isVerticallyScrollable(node: HTMLElement): boolean {
|
||||
const overflowY = verticalOverflow(node);
|
||||
return overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay";
|
||||
}
|
||||
|
||||
/** Walk up from a message anchor to the element that actually scrolls. */
|
||||
function findScrollParent(el: HTMLElement | null): HTMLElement | null {
|
||||
let node = el?.parentElement ?? null;
|
||||
while (node) {
|
||||
const overflowY = window.getComputedStyle(node).overflowY;
|
||||
if (
|
||||
(overflowY === "auto" || overflowY === "scroll") &&
|
||||
node.scrollHeight > node.clientHeight
|
||||
) {
|
||||
while (node && node !== document.body) {
|
||||
if (isVerticallyScrollable(node) && node.scrollHeight > node.clientHeight + 1) {
|
||||
return node;
|
||||
}
|
||||
node = node.parentElement;
|
||||
}
|
||||
return null;
|
||||
if (document.scrollingElement instanceof HTMLElement) {
|
||||
return document.scrollingElement;
|
||||
}
|
||||
return document.documentElement;
|
||||
}
|
||||
|
||||
let questionScrollFrame = 0;
|
||||
let questionScrollTarget: { scroller: HTMLElement; top: number } | null = null;
|
||||
|
||||
function prefersReducedMotion(): boolean {
|
||||
try {
|
||||
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Nested-container smooth scroll that Chrome 102 can actually run. */
|
||||
function animateScrollTop(scroller: HTMLElement, top: number): void {
|
||||
if (
|
||||
questionScrollTarget?.scroller === scroller &&
|
||||
Math.abs(questionScrollTarget.top - top) < 8
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (questionScrollFrame) cancelAnimationFrame(questionScrollFrame);
|
||||
const from = scroller.scrollTop;
|
||||
const delta = top - from;
|
||||
questionScrollTarget = { scroller, top };
|
||||
if (Math.abs(delta) < 1 || prefersReducedMotion()) {
|
||||
scroller.scrollTop = top;
|
||||
questionScrollFrame = 0;
|
||||
return;
|
||||
}
|
||||
const duration = Math.min(480, Math.max(240, Math.abs(delta) * 0.45));
|
||||
const start = performance.now();
|
||||
const stopListening = () => {
|
||||
scroller.removeEventListener("wheel", cancelOnUserScroll);
|
||||
scroller.removeEventListener("touchmove", cancelOnUserScroll);
|
||||
};
|
||||
const cancelOnUserScroll = () => {
|
||||
if (questionScrollFrame) cancelAnimationFrame(questionScrollFrame);
|
||||
questionScrollFrame = 0;
|
||||
questionScrollTarget = null;
|
||||
stopListening();
|
||||
};
|
||||
const step = (now: number) => {
|
||||
const t = Math.min(1, (now - start) / duration);
|
||||
const eased = 1 - (1 - t) * (1 - t) * (1 - t);
|
||||
scroller.scrollTop = from + delta * eased;
|
||||
if (t < 1) {
|
||||
questionScrollFrame = requestAnimationFrame(step);
|
||||
return;
|
||||
}
|
||||
questionScrollFrame = 0;
|
||||
stopListening();
|
||||
};
|
||||
scroller.addEventListener("wheel", cancelOnUserScroll, { passive: true });
|
||||
scroller.addEventListener("touchmove", cancelOnUserScroll, { passive: true });
|
||||
questionScrollFrame = requestAnimationFrame(step);
|
||||
}
|
||||
|
||||
function scrollChildIntoParent(
|
||||
el: HTMLElement,
|
||||
parent: HTMLElement,
|
||||
topOffset = 0,
|
||||
): void {
|
||||
const parentRect = parent.getBoundingClientRect();
|
||||
const elRect = el.getBoundingClientRect();
|
||||
const nextTop = parent.scrollTop + (elRect.top - parentRect.top) - topOffset;
|
||||
animateScrollTop(parent, Math.max(0, Math.min(nextTop, maxScrollTop(parent))));
|
||||
}
|
||||
|
||||
function maxScrollTop(parent: HTMLElement): number {
|
||||
return Math.max(0, parent.scrollHeight - parent.clientHeight);
|
||||
}
|
||||
|
||||
/**
|
||||
* Chrome 102 (and other nested-scroller hosts) often no-ops
|
||||
* `scrollIntoView({ behavior: "smooth" })` when the conversation is not the
|
||||
* document. Animate `scrollTop` on the real overflow container instead.
|
||||
*/
|
||||
function scrollElementIntoContainer(el: HTMLElement, topOffset = 0): void {
|
||||
const scroller = findScrollParent(el);
|
||||
if (!scroller || scroller === el) {
|
||||
try {
|
||||
el.scrollIntoView(true);
|
||||
} catch {
|
||||
// ignore hosts that reject the boolean form
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
scroller.dispatchEvent(
|
||||
new WheelEvent("wheel", { deltaY: -1, bubbles: true }),
|
||||
);
|
||||
} catch {
|
||||
// WheelEvent is available on Chrome 102; keep scrollTop even if this fails.
|
||||
}
|
||||
scrollChildIntoParent(el, scroller, topOffset);
|
||||
}
|
||||
|
||||
function scrollItemNearestInParent(
|
||||
item: HTMLElement,
|
||||
parent: HTMLElement,
|
||||
): void {
|
||||
const parentRect = parent.getBoundingClientRect();
|
||||
const itemRect = item.getBoundingClientRect();
|
||||
if (itemRect.top < parentRect.top) {
|
||||
parent.scrollTop += itemRect.top - parentRect.top;
|
||||
} else if (itemRect.bottom > parentRect.bottom) {
|
||||
parent.scrollTop += itemRect.bottom - parentRect.bottom;
|
||||
}
|
||||
}
|
||||
|
||||
function readCollapsedPreference(): boolean {
|
||||
@@ -113,6 +238,7 @@ export function QuestionNavigator({
|
||||
return;
|
||||
}
|
||||
const firstAnchor = document.getElementById(questions[0]!.anchorId);
|
||||
if (!firstAnchor) return;
|
||||
const scroller = findScrollParent(firstAnchor);
|
||||
if (!scroller) return;
|
||||
|
||||
@@ -145,17 +271,20 @@ export function QuestionNavigator({
|
||||
|
||||
const scrollToQuestion = useCallback((anchorId: string) => {
|
||||
const scroll = () => {
|
||||
document
|
||||
.getElementById(anchorId)
|
||||
?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
const el = document.getElementById(anchorId);
|
||||
if (!el) return false;
|
||||
scrollElementIntoContainer(el, QUESTION_SCROLL_TOP_OFFSET);
|
||||
return true;
|
||||
};
|
||||
if (!document.getElementById(anchorId)) {
|
||||
window.dispatchEvent(new Event(REVEAL_CHAT_HISTORY_EVENT));
|
||||
requestAnimationFrame(() => requestAnimationFrame(scroll));
|
||||
} else {
|
||||
scroll();
|
||||
}
|
||||
setActiveId(anchorId);
|
||||
if (scroll()) return;
|
||||
window.dispatchEvent(new Event(REVEAL_CHAT_HISTORY_EVENT));
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (scroll()) return;
|
||||
window.setTimeout(scroll, 50);
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleCollapsed = useCallback(() => {
|
||||
@@ -246,8 +375,12 @@ export function QuestionNavigator({
|
||||
questions={questions}
|
||||
activeId={activeId}
|
||||
onSelect={(anchorId) => {
|
||||
setSheetOpen(false);
|
||||
scrollToQuestion(anchorId);
|
||||
setSheetOpen(false);
|
||||
window.setTimeout(
|
||||
() => scrollToQuestion(anchorId),
|
||||
SHEET_SCROLL_RETRY_MS,
|
||||
);
|
||||
}}
|
||||
className="min-h-0 flex-1"
|
||||
/>
|
||||
@@ -272,17 +405,22 @@ function QuestionCardList({
|
||||
className?: string;
|
||||
}) {
|
||||
const itemRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const navRef = useRef<HTMLElement | null>(null);
|
||||
|
||||
// Keep the active card visible as the chat scrolls. `block: "nearest"` only
|
||||
// nudges this inner list — the card is already inside the on-screen panel,
|
||||
// so no outer container moves.
|
||||
// Keep the active card visible as the chat scrolls. Scroll only this inner
|
||||
// list — `scrollIntoView({ block: "nearest" })` on Chrome 102 also moves
|
||||
// ancestor conversation scrollers, which undoes the jump to the question.
|
||||
useEffect(() => {
|
||||
if (!activeId) return;
|
||||
itemRefs.current.get(activeId)?.scrollIntoView({ block: "nearest" });
|
||||
const item = itemRefs.current.get(activeId);
|
||||
const nav = navRef.current;
|
||||
if (!item || !nav) return;
|
||||
scrollItemNearestInParent(item, nav);
|
||||
}, [activeId]);
|
||||
|
||||
return (
|
||||
<nav
|
||||
ref={navRef}
|
||||
aria-label="问题导航"
|
||||
className={cn("flex flex-col gap-2 overflow-y-auto p-2", className)}
|
||||
>
|
||||
|
||||
@@ -7,19 +7,19 @@ import {
|
||||
Download,
|
||||
FileJson,
|
||||
FileText,
|
||||
MessageSquare,
|
||||
MoreHorizontal,
|
||||
Pencil,
|
||||
Pin,
|
||||
PinOff,
|
||||
Search,
|
||||
Share2,
|
||||
Star,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useParams, usePathname, useRouter } from "next/navigation";
|
||||
import { useCallback, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -91,6 +91,8 @@ import {
|
||||
useRecentStrategyProjects,
|
||||
} from "@/strategy-selection/recent-projects";
|
||||
|
||||
import { historyAvatarForThread } from "./chat-history-avatar";
|
||||
|
||||
export function RecentChatList({
|
||||
compact = false,
|
||||
limit,
|
||||
@@ -137,6 +139,7 @@ export function RecentChatList({
|
||||
|
||||
// Share dialog state — the conversation whose share code is being shown.
|
||||
const [shareThreadId, setShareThreadId] = useState<string | null>(null);
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const handleDelete = useCallback(
|
||||
(threadId: string) => {
|
||||
@@ -218,10 +221,27 @@ export function RecentChatList({
|
||||
recentStrategyProjects,
|
||||
);
|
||||
|
||||
const shownItems = useMemo(() => {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const matchingItems = normalizedQuery
|
||||
? recentItems.filter((item) =>
|
||||
(item.kind === "thread"
|
||||
? titleOfThread(item.thread, t.pages.newChat)
|
||||
: item.project.title
|
||||
)
|
||||
.toLowerCase()
|
||||
.includes(normalizedQuery),
|
||||
)
|
||||
: recentItems;
|
||||
return normalizedQuery || limit == null
|
||||
? matchingItems
|
||||
: matchingItems.slice(0, limit);
|
||||
}, [limit, query, recentItems, t.pages.newChat]);
|
||||
|
||||
if (recentItems.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const shownItems = limit != null ? recentItems.slice(0, limit) : recentItems;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarGroup
|
||||
@@ -259,26 +279,42 @@ export function RecentChatList({
|
||||
}`}
|
||||
>
|
||||
<SidebarMenu>
|
||||
<div className="relative mb-1.5 px-1">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3.5 size-3.5 -translate-y-1/2 text-muted-foreground/60" />
|
||||
<Input
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="搜索历史会话…"
|
||||
aria-label="搜索历史会话"
|
||||
className="h-8 rounded-xl border-border bg-card pl-8 pr-2 text-[12px] shadow-none"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-0.5">
|
||||
{shownItems.map((item) => {
|
||||
{shownItems.length === 0 ? (
|
||||
<div className="px-3 py-4 text-center text-[12px] text-muted-foreground/70">
|
||||
没有匹配的会话
|
||||
</div>
|
||||
) : shownItems.map((item) => {
|
||||
if (item.kind === "strategy-project") {
|
||||
const { project } = item;
|
||||
const href = strategyProjectWorkbenchPath(
|
||||
"/page/strategy/qa/projects",
|
||||
project.id,
|
||||
);
|
||||
const isActive = href === pathname;
|
||||
return (
|
||||
<SidebarMenuItem
|
||||
key={`strategy-project:${project.id}`}
|
||||
className="group/side-menu-item"
|
||||
>
|
||||
<SidebarMenuButton
|
||||
isActive={href === pathname}
|
||||
isActive={isActive}
|
||||
asChild
|
||||
className={cn(
|
||||
"h-auto min-h-11 rounded-lg px-3 py-1.5 text-[13px] text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
|
||||
"data-[active=true]:bg-white data-[active=true]:text-foreground data-[active=true]:shadow-[0_1px_2px_rgba(15,23,42,0.05)]",
|
||||
"dark:data-[active=true]:bg-slate-700/80 dark:data-[active=true]:text-slate-100 dark:data-[active=true]:shadow-none",
|
||||
"gq-history-item relative h-auto min-h-11 overflow-hidden rounded-xl px-3 py-1.5 text-[13px] text-foreground/80 transition-[background-color,color,box-shadow] duration-150 hover:bg-muted/80 hover:text-foreground hover:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/9%)]",
|
||||
isActive && "gq-history-item--active",
|
||||
"data-[active=true]:bg-primary/[0.11] data-[active=true]:font-medium data-[active=true]:text-primary data-[active=true]:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/22%),0_2px_8px_rgb(var(--legacy-primary-rgb)/7%)] data-[active=true]:hover:bg-primary/[0.15]",
|
||||
compact &&
|
||||
"min-h-11 gap-2 rounded-md px-2.5 data-[active=true]:border data-[active=true]:border-border",
|
||||
)}
|
||||
@@ -292,7 +328,7 @@ export function RecentChatList({
|
||||
>
|
||||
<MyProjectThreadIcon type="strategy" />
|
||||
<span className="min-w-0 flex-1 flex flex-col items-start gap-0.5">
|
||||
<span className="w-full truncate">
|
||||
<span className="block w-full truncate">
|
||||
{desensitize(project.title)}
|
||||
</span>
|
||||
<MyProjectThreadBadge
|
||||
@@ -326,9 +362,9 @@ export function RecentChatList({
|
||||
isActive={isActive}
|
||||
asChild
|
||||
className={cn(
|
||||
"h-7 rounded-lg px-3 text-[13px] text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
|
||||
"data-[active=true]:bg-white data-[active=true]:text-foreground data-[active=true]:shadow-[0_1px_2px_rgba(15,23,42,0.05)]",
|
||||
"dark:data-[active=true]:bg-slate-700/80 dark:data-[active=true]:text-slate-100 dark:data-[active=true]:shadow-none",
|
||||
"gq-history-item relative h-9 overflow-hidden rounded-xl px-3 text-[13px] text-foreground/80 transition-[background-color,color,box-shadow] duration-150 hover:bg-muted/80 hover:text-foreground hover:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/9%)]",
|
||||
isActive && "gq-history-item--active",
|
||||
"data-[active=true]:bg-primary/[0.11] data-[active=true]:font-medium data-[active=true]:text-primary data-[active=true]:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/22%),0_2px_8px_rgb(var(--legacy-primary-rgb)/7%)] data-[active=true]:hover:bg-primary/[0.15]",
|
||||
compact &&
|
||||
"h-9 gap-2 rounded-md px-2.5 data-[active=true]:border data-[active=true]:border-border",
|
||||
projectInfo && "h-auto min-h-11 py-1.5",
|
||||
@@ -352,16 +388,13 @@ export function RecentChatList({
|
||||
) : projectInfo ? (
|
||||
<MyProjectThreadIcon type={projectInfo.type} />
|
||||
) : (
|
||||
compact && (
|
||||
<MessageSquare
|
||||
className={
|
||||
"size-3.5 shrink-0 " +
|
||||
(isActive
|
||||
? "text-[var(--primary)]"
|
||||
: "text-muted-foreground/70")
|
||||
}
|
||||
<img
|
||||
src={historyAvatarForThread(thread.thread_id)}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
draggable={false}
|
||||
className="size-5 shrink-0 object-contain"
|
||||
/>
|
||||
)
|
||||
)}
|
||||
{pinned && (
|
||||
<Pin className="size-3 shrink-0 text-muted-foreground/70" />
|
||||
@@ -372,7 +405,7 @@ export function RecentChatList({
|
||||
projectInfo && "flex flex-col items-start gap-0.5",
|
||||
)}
|
||||
>
|
||||
<span className="w-full truncate">
|
||||
<span className="block w-full truncate">
|
||||
{desensitize(titleOfThread(thread, t.pages.newChat))}
|
||||
</span>
|
||||
{projectInfo && (
|
||||
@@ -485,7 +518,7 @@ export function RecentChatList({
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
})}
|
||||
{moreHref && (
|
||||
{moreHref && !query.trim() && (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { confirmAction, toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -92,7 +92,11 @@ export function ShareRoundtableDraftDialog({
|
||||
}
|
||||
|
||||
async function handleRevoke() {
|
||||
if (!share || !window.confirm("撤销后此分享立即失效,确定吗?")) return;
|
||||
if (!share || !(await confirmAction("撤销后此分享立即失效,确定吗?", {
|
||||
title: "撤销分享?",
|
||||
confirmText: "撤销分享",
|
||||
danger: true,
|
||||
}))) return;
|
||||
try {
|
||||
await revokeShare.mutateAsync(share.share_code);
|
||||
toast.success("已撤销分享");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { CopyIcon, LogOutIcon, UserIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -1,64 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { DatabaseIcon, RefreshCwIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Clock3Icon, DatabaseIcon, GlobeIcon, RefreshCwIcon, SaveIcon, SearchIcon } from "lucide-react";
|
||||
import { toast } from "@/core/ui/feedback";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { getAuditRetentionStatus, setAuditRetentionPaused, type AuditRetentionStatus } from "@/core/admin/audit-retention";
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
type CacheCollection = {
|
||||
id: string;
|
||||
label: string;
|
||||
paths: string[];
|
||||
scope: string;
|
||||
enabled: boolean;
|
||||
ttl_seconds: number;
|
||||
};
|
||||
|
||||
type ApiReadCacheStatus = {
|
||||
enabled: boolean;
|
||||
redis_configured: boolean;
|
||||
ttl_seconds: number;
|
||||
max_value_bytes: number;
|
||||
browser_status_enabled: boolean;
|
||||
collections: CacheCollection[];
|
||||
};
|
||||
|
||||
async function loadStatus(): Promise<ApiReadCacheStatus> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/system-settings/api-read-cache`);
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(typeof data.detail === "string" ? data.detail : `读取失败(${response.status})`);
|
||||
type ApiReadCacheUpdate = {
|
||||
enabled?: boolean;
|
||||
ttl_seconds?: number;
|
||||
browser_status_enabled?: boolean;
|
||||
collection_overrides?: Record<string, boolean>;
|
||||
};
|
||||
|
||||
async function requestStatus(update?: ApiReadCacheUpdate): Promise<ApiReadCacheStatus> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/system-settings/api-read-cache`, update ? {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(update),
|
||||
} : undefined);
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(typeof data.detail === "string" ? data.detail : `${update ? "保存" : "读取"}失败(${response.status})`);
|
||||
}
|
||||
return data as ApiReadCacheStatus;
|
||||
}
|
||||
|
||||
async function saveStatus(enabled: boolean): Promise<ApiReadCacheStatus> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/system-settings/api-read-cache`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ enabled }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(typeof data.detail === "string" ? data.detail : `保存失败(${response.status})`);
|
||||
return data as ApiReadCacheStatus;
|
||||
function retentionLabel(status: string) {
|
||||
switch (status) {
|
||||
case "running": return "正在清理";
|
||||
case "pausing": return "正在停止";
|
||||
case "paused": return "已关闭";
|
||||
case "error": return "本轮异常";
|
||||
default: return "等待执行";
|
||||
}
|
||||
}
|
||||
|
||||
function dateTime(value?: string | number | null) {
|
||||
if (!value) return "暂无";
|
||||
const date = new Date(typeof value === "number" ? value * 1000 : value);
|
||||
return Number.isNaN(date.getTime()) ? "暂无" : date.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
|
||||
}
|
||||
|
||||
export function ApiReadCacheSettingsPage() {
|
||||
const [status, setStatus] = useState<ApiReadCacheStatus>();
|
||||
const [retention, setRetention] = useState<AuditRetentionStatus>();
|
||||
const [ttlInput, setTtlInput] = useState("300");
|
||||
const [search, setSearch] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [retentionError, setRetentionError] = useState("");
|
||||
|
||||
const refresh = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setStatus(await loadStatus());
|
||||
const [cacheResult, retentionResult] = await Promise.allSettled([
|
||||
requestStatus(),
|
||||
getAuditRetentionStatus(),
|
||||
]);
|
||||
if (cacheResult.status === "fulfilled") {
|
||||
setStatus(cacheResult.value);
|
||||
setTtlInput(String(cacheResult.value.ttl_seconds));
|
||||
setError("");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "读取设置失败");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
} else {
|
||||
setError(cacheResult.reason instanceof Error ? cacheResult.reason.message : "读取缓存设置失败");
|
||||
}
|
||||
if (retentionResult.status === "fulfilled") {
|
||||
setRetention(retentionResult.value);
|
||||
setRetentionError("");
|
||||
} else {
|
||||
setRetentionError(retentionResult.reason instanceof Error ? retentionResult.reason.message : "读取清理设置失败");
|
||||
}
|
||||
setBusy(false);
|
||||
};
|
||||
|
||||
useEffect(() => { void refresh(); }, []);
|
||||
|
||||
const toggle = async (enabled: boolean) => {
|
||||
const save = async (update: ApiReadCacheUpdate, message: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const saved = await saveStatus(enabled);
|
||||
const saved = await requestStatus(update);
|
||||
setStatus(saved);
|
||||
toast.success(enabled ? "Redis 读取缓存已开启" : "Redis 读取缓存已关闭");
|
||||
if (update.ttl_seconds !== undefined) setTtlInput(String(saved.ttl_seconds));
|
||||
setError("");
|
||||
toast.success(message);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : "保存设置失败");
|
||||
} finally {
|
||||
@@ -66,26 +114,184 @@ export function ApiReadCacheSettingsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const toggleRetention = async (enabled: boolean) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const saved = await setAuditRetentionPaused(!enabled);
|
||||
setRetention(saved);
|
||||
setRetentionError("");
|
||||
toast.success(enabled ? "定时清理已开启" : saved.pause_requested ? "已关闭定时清理,当前批次结束后停止" : "定时清理已关闭");
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : "保存清理设置失败");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const parsedTtl = Number(ttlInput);
|
||||
const validTtl = Number.isInteger(parsedTtl) && parsedTtl >= 1 && parsedTtl <= 3600;
|
||||
const collections = status?.collections ?? [];
|
||||
const searchText = search.trim().toLowerCase();
|
||||
const visibleCollections = collections.filter((item) =>
|
||||
[item.label, item.id, item.scope, ...item.paths].join(" ").toLowerCase().includes(searchText),
|
||||
);
|
||||
const enabledCount = collections.filter((item) => item.enabled).length;
|
||||
|
||||
return (
|
||||
<section className="space-y-5" data-testid="api-read-cache-settings">
|
||||
<section className="space-y-5" data-testid="api-read-cache-settings" aria-busy={busy}>
|
||||
<header className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="flex items-center gap-2 text-xl font-semibold"><DatabaseIcon className="size-5 text-primary" />首页接口 Redis 缓存</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">开关保存在 MySQL,服务重启后仍生效。关闭或 Redis 不可用时,接口自动回到 MySQL 查询。</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border p-4">
|
||||
<div>
|
||||
<p className="font-medium">启用常用读取接口缓存</p>
|
||||
<p className="mt-1 text-sm text-muted-foreground">覆盖智能体、技能、个人偏好、常用提示词和推荐问题列表;缓存按用户隔离,并在数据修改后失效。</p>
|
||||
</div>
|
||||
<Switch checked={status?.enabled ?? false} disabled={!status || busy} onCheckedChange={(value) => void toggle(value)} aria-label="启用 Redis 读取缓存" />
|
||||
<h2 className="flex items-center gap-2 text-xl font-semibold"><DatabaseIcon className="size-5 text-primary" />Redis 与性能管理</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">统一管理接口缓存、浏览器状态查询和历史数据定时清理。</p>
|
||||
</div>
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void refresh()}>
|
||||
<RefreshCwIcon className={`size-4 ${busy ? "animate-spin" : ""}`} />刷新状态
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
{error && <p role="alert" className="rounded-lg border border-destructive/30 p-3 text-sm text-destructive">{error}</p>}
|
||||
{status && <div className="rounded-xl border p-4 text-sm">
|
||||
<p>Redis 连接:<strong>{status.redis_configured ? "已配置" : "未配置"}</strong></p>
|
||||
<p className="mt-1 text-muted-foreground">单条缓存最长保留 {status.ttl_seconds} 秒,超过 {Math.round(status.max_value_bytes / 1024)} KiB 的结果不会写入缓存。</p>
|
||||
{!status.redis_configured && <p className="mt-3 text-amber-700">当前配置没有可用的 Redis 地址。开启后设置会保存,但请求会继续直接查询 MySQL;请先在服务配置中配置 Redis。</p>}
|
||||
|
||||
<div className="overflow-hidden rounded-xl border">
|
||||
<div className="flex items-center justify-between gap-4 bg-muted/30 p-4">
|
||||
<div>
|
||||
<h3 className="font-medium">Redis 读取缓存总开关</h3>
|
||||
<p className="mt-1 text-sm text-muted-foreground">开关和有效期保存在 MySQL,服务重启后仍生效。</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={status?.enabled ?? false}
|
||||
disabled={!status || busy}
|
||||
onCheckedChange={(enabled) => void save({ enabled }, enabled ? "Redis 读取缓存已开启" : "Redis 读取缓存已关闭")}
|
||||
aria-label="启用 Redis 读取缓存"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-3 border-t p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<label htmlFor="api-cache-ttl" className="text-sm font-medium">默认缓存有效期</label>
|
||||
<p id="api-cache-ttl-help" className="mt-1 text-xs text-muted-foreground">1–3600 秒,默认 300 秒;保存后刷新缓存。</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="api-cache-ttl"
|
||||
type="number"
|
||||
min={1}
|
||||
max={3600}
|
||||
step={1}
|
||||
value={ttlInput}
|
||||
disabled={!status || busy}
|
||||
onChange={(event) => setTtlInput(event.target.value)}
|
||||
aria-label="Redis 缓存有效期(秒)"
|
||||
aria-describedby="api-cache-ttl-help"
|
||||
aria-invalid={!validTtl}
|
||||
className="w-24"
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">秒</span>
|
||||
<Button type="button" size="sm" variant="outline" disabled={!status || busy || !validTtl || parsedTtl === status.ttl_seconds} onClick={() => void save({ ttl_seconds: parsedTtl }, "Redis 缓存有效期已保存")}>
|
||||
<SaveIcon className="size-4" />保存有效期
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{status && <div className="flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-muted-foreground">
|
||||
<Badge variant="secondary">Redis 地址{status.redis_configured ? "已配置" : "未配置"}</Badge>
|
||||
<span>单条结果上限 {Math.round(status.max_value_bytes / 1024)} KiB</span>
|
||||
<span>关闭或连接失败时自动使用原查询</span>
|
||||
</div>}
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={() => void refresh()}><RefreshCwIcon className="size-4" />刷新状态</Button>
|
||||
{status && !status.redis_configured && <p className="text-xs text-amber-700 dark:text-amber-400">当前未配置 Redis 地址。可以保存开关,但配置连接后才会使用缓存。</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border p-4" data-testid="browser-status-control">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0">
|
||||
<h3 className="flex items-center gap-2 font-medium"><GlobeIcon className="size-4 text-primary" />允许浏览器状态查询</h3>
|
||||
<p className="mt-1 break-all font-mono text-xs text-muted-foreground">GET /api/browser-context/status</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">控制浏览器插件能否访问状态接口;关闭后,服务器会拒绝该接口的查询。</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={status?.browser_status_enabled ?? false}
|
||||
disabled={!status || busy}
|
||||
onCheckedChange={(enabled) => void save({ browser_status_enabled: enabled }, enabled ? "浏览器状态查询已允许" : "浏览器状态查询已关闭")}
|
||||
aria-label="允许浏览器状态查询"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 rounded-xl border p-4" data-testid="audit-retention-control">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="flex items-center gap-2 font-medium"><Clock3Icon className="size-4 text-primary" />开启历史数据定时清理</h3>
|
||||
<p className="mt-1 text-sm text-muted-foreground">分批清理超过 {retention?.retention_days ?? 90} 天的工具调用、模型调用、已结束任务摘要和排行榜快照。</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={retention ? !retention.paused : false}
|
||||
disabled={!retention || busy}
|
||||
onCheckedChange={(enabled) => void toggleRetention(enabled)}
|
||||
aria-label="开启历史数据定时清理"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">包含 tool_call_metrics、llm_call_metrics;关闭后在当前小批次结束时停止,关闭状态在服务重启后保留。</p>
|
||||
{retentionError && <p role="alert" className="text-sm text-destructive">{retentionError}</p>}
|
||||
{retention && <div className="flex flex-wrap items-center gap-x-4 gap-y-2 rounded-lg bg-muted/40 px-3 py-2 text-xs">
|
||||
<Badge variant={retention.display_status === "error" ? "destructive" : "secondary"}>{retentionLabel(retention.display_status)}</Badge>
|
||||
<span className="text-muted-foreground">间隔 {Math.round((retention.interval_seconds ?? 900) / 60)} 分钟</span>
|
||||
<span className="text-muted-foreground">下次执行:{retention.paused ? "已关闭" : dateTime(retention.next_run_at)}</span>
|
||||
<span className="text-muted-foreground">最近完成:{dateTime(retention.last_sweep?.finished_at)}</span>
|
||||
</div>}
|
||||
{retention?.pause_requested && <p role="status" className="text-sm text-amber-700 dark:text-amber-400">关闭请求已保存,正在等待当前批次结束。可点击“刷新状态”查看结果。</p>}
|
||||
{retention?.last_error && <p role="alert" className="text-sm text-destructive">{retention.last_error}</p>}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3" data-testid="cache-collection-list">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="font-medium">已接入 Redis 的接口</h3>
|
||||
<p className="mt-1 text-xs text-muted-foreground">共 {collections.length} 组,单项开启 {enabledCount} 组;同组接口共用开关。</p>
|
||||
</div>
|
||||
<div className="relative w-full sm:w-56">
|
||||
<SearchIcon className="pointer-events-none absolute top-2.5 left-3 size-4 text-muted-foreground" />
|
||||
<Input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="搜索名称或接口地址" aria-label="搜索缓存接口" className="pl-9" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">每组可独立开关,数据修改后缓存失效。总开关关闭时仍可配置单项,重新开启总开关后生效;各接口实际有效期见列表。</p>
|
||||
{status && !status.enabled && <p className="rounded-lg bg-muted px-3 py-2 text-sm">总开关已关闭,当前所有接口均使用原查询。</p>}
|
||||
<div className="overflow-x-auto rounded-xl border">
|
||||
<table className="w-full table-fixed text-left text-sm">
|
||||
<thead className="bg-muted/40 text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="w-[56%] px-4 py-3 font-medium" scope="col">接口 / 缓存范围</th>
|
||||
<th className="w-[18%] px-2 py-3 font-medium" scope="col">有效期</th>
|
||||
<th className="w-[26%] px-4 py-3 text-right font-medium" scope="col">使用 Redis</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{visibleCollections.map((item) => {
|
||||
const effective = item.enabled && status?.enabled && status.redis_configured;
|
||||
const description = !item.enabled ? "单项已关闭" : !status?.enabled ? "总开关关闭" : !status.redis_configured ? "待配置连接" : "缓存已启用";
|
||||
return <tr key={item.id} data-testid={`cache-collection-${item.id}`}>
|
||||
<td className="px-4 py-3 align-top">
|
||||
<p className="font-medium">{item.label}</p>
|
||||
<div className="mt-1 space-y-1 text-[11px] text-muted-foreground">
|
||||
{item.paths.map((path) => <p key={path} className="break-all font-mono">{path}</p>)}
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{item.scope}</p>
|
||||
</td>
|
||||
<td className="px-2 py-3 align-top text-xs">{item.ttl_seconds} 秒</td>
|
||||
<td className="px-4 py-3 text-right align-top">
|
||||
<Switch
|
||||
checked={item.enabled}
|
||||
disabled={busy}
|
||||
onCheckedChange={(enabled) => void save({ collection_overrides: { [item.id]: enabled } }, `${item.label}缓存${enabled ? "已开启" : "已关闭"}`)}
|
||||
aria-label={`${item.label}使用 Redis 缓存`}
|
||||
/>
|
||||
<p className={`mt-1 text-[11px] ${effective ? "text-primary" : "text-muted-foreground"}`}>{description}</p>
|
||||
</td>
|
||||
</tr>;
|
||||
})}
|
||||
{!visibleCollections.length && <tr><td colSpan={3} className="px-4 py-8 text-center text-muted-foreground">{!status ? error ? "接口列表读取失败,请刷新重试" : "正在读取接口列表…" : searchText ? "没有匹配的接口" : "暂无已接入的接口"}</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||